git.delta.rocks / unique-network / refs/commits / 0bee999418d1

difftreelog

source

node/cli/src/command.rs16.7 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license18// This file is part of Substrate.1920// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use crate::{36	chain_spec::{self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification},37	cli::{Cli, RelayChainCli, Subcommand},38	service::{new_partial, start_node, start_dev_node},39};4041#[cfg(feature = "unique-runtime")]42use crate::service::UniqueRuntimeExecutor;4344#[cfg(feature = "quartz-runtime")]45use crate::service::QuartzRuntimeExecutor;4647use crate::service::OpalRuntimeExecutor;4849use codec::Encode;50use cumulus_primitives_core::ParaId;51use cumulus_client_service::genesis::generate_genesis_block;52use log::info;53use polkadot_parachain::primitives::AccountIdConversion;54use sc_cli::{55	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,56	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,57};58use sc_service::{59	config::{BasePath, PrometheusConfig},60};61use sp_core::hexdisplay::HexDisplay;62use sp_runtime::traits::Block as BlockT;63use std::{io::Write, net::SocketAddr};6465use unique_runtime_common::types::Block;6667macro_rules! no_runtime_err {68	($chain_name:expr) => {69		format!(70			"No runtime valid runtime was found for chain {}",71			$chain_name72		)73	};74}7576fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {77	Ok(match id {78		"dev" => Box::new(chain_spec::development_config()),79		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),80		path => {81			let path = std::path::PathBuf::from(path);82			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)83				as Box<dyn sc_service::ChainSpec>;8485			match chain_spec.runtime_id() {86				#[cfg(feature = "unique-runtime")]87				RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),8889				#[cfg(feature = "quartz-runtime")]90				RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9192				RuntimeId::Opal => chain_spec,93				RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),94			}95		}96	})97}9899impl SubstrateCli for Cli {100	// TODO use args101	fn impl_name() -> String {102		"Unique Node".into()103	}104105	fn impl_version() -> String {106		env!("SUBSTRATE_CLI_IMPL_VERSION").into()107	}108	// TODO use args109	fn description() -> String {110		format!(111			"Unique Node\n\nThe command-line arguments provided first will be \112		passed to the parachain node, while the arguments provided after -- will be passed \113		to the relaychain node.\n\n\114		{} [parachain-args] -- [relaychain-args]",115			Self::executable_name()116		)117	}118119	fn author() -> String {120		env!("CARGO_PKG_AUTHORS").into()121	}122123	//TODO use args124	fn support_url() -> String {125		"support@unique.network".into()126	}127128	fn copyright_start_year() -> i32 {129		2019130	}131132	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {133		load_spec(id)134	}135136	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {137		match chain_spec.runtime_id() {138			#[cfg(feature = "unique-runtime")]139			RuntimeId::Unique => &unique_runtime::VERSION,140141			#[cfg(feature = "quartz-runtime")]142			RuntimeId::Quartz => &quartz_runtime::VERSION,143144			RuntimeId::Opal => &opal_runtime::VERSION,145			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),146		}147	}148}149150impl SubstrateCli for RelayChainCli {151	// TODO use args152	fn impl_name() -> String {153		"Unique Node".into()154	}155156	fn impl_version() -> String {157		env!("SUBSTRATE_CLI_IMPL_VERSION").into()158	}159	// TODO use args160	fn description() -> String {161		"Unique Node\n\nThe command-line arguments provided first will be \162		passed to the parachain node, while the arguments provided after -- will be passed \163		to the relaychain node.\n\n\164		parachain-collator [parachain-args] -- [relaychain-args]"165			.into()166	}167168	fn author() -> String {169		env!("CARGO_PKG_AUTHORS").into()170	}171	// TODO use args172	fn support_url() -> String {173		"support@unique.network".into()174	}175176	fn copyright_start_year() -> i32 {177		2019178	}179180	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {181		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)182	}183184	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {185		polkadot_cli::Cli::native_runtime_version(chain_spec)186	}187}188189#[allow(clippy::borrowed_box)]190fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {191	let mut storage = chain_spec.build_storage()?;192193	storage194		.top195		.remove(sp_core::storage::well_known_keys::CODE)196		.ok_or_else(|| "Could not find wasm file in genesis state!".into())197}198199macro_rules! async_run_with_runtime {200	(201		$runtime_api:path, $executor:path,202		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,203		$( $code:tt )*204	) => {205		$runner.async_run(|$config| {206			let $components = new_partial::<207				$runtime_api, $executor, _208			>(209				&$config,210				crate::service::parachain_build_import_queue,211			)?;212			let task_manager = $components.task_manager;213214			{ $( $code )* }.map(|v| (v, task_manager))215		})216	};217}218219macro_rules! construct_async_run {220	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{221		let runner = $cli.create_runner($cmd)?;222223		match runner.config().chain_spec.runtime_id() {224			#[cfg(feature = "unique-runtime")]225			RuntimeId::Unique => async_run_with_runtime!(226				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,227				runner, $components, $cli, $cmd, $config, $( $code )*228			),229230			#[cfg(feature = "quartz-runtime")]231			RuntimeId::Quartz => async_run_with_runtime!(232				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,233				runner, $components, $cli, $cmd, $config, $( $code )*234			),235236			RuntimeId::Opal => async_run_with_runtime!(237				opal_runtime::RuntimeApi, OpalRuntimeExecutor,238				runner, $components, $cli, $cmd, $config, $( $code )*239			),240241			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())242		}243	}}244}245246macro_rules! start_node_using_chain_runtime {247	($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {248		match $config.chain_spec.runtime_id() {249			#[cfg(feature = "unique-runtime")]250			RuntimeId::Unique => $start_node_fn::<251				unique_runtime::Runtime,252				unique_runtime::RuntimeApi,253				UniqueRuntimeExecutor,254			>($config $(, $($args),+)?) $($code)*,255256			#[cfg(feature = "quartz-runtime")]257			RuntimeId::Quartz => $start_node_fn::<258				quartz_runtime::Runtime,259				quartz_runtime::RuntimeApi,260				QuartzRuntimeExecutor,261			>($config $(, $($args),+)?) $($code)*,262263			RuntimeId::Opal => $start_node_fn::<264				opal_runtime::Runtime,265				opal_runtime::RuntimeApi,266				OpalRuntimeExecutor,267			>($config $(, $($args),+)?) $($code)*,268269			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),270		}271	};272}273274/// Parse command line arguments into service configuration.275pub fn run() -> Result<()> {276	let cli = Cli::from_args();277278	match &cli.subcommand {279		Some(Subcommand::BuildSpec(cmd)) => {280			let runner = cli.create_runner(cmd)?;281			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))282		}283		Some(Subcommand::CheckBlock(cmd)) => {284			construct_async_run!(|components, cli, cmd, config| {285				Ok(cmd.run(components.client, components.import_queue))286			})287		}288		Some(Subcommand::ExportBlocks(cmd)) => {289			construct_async_run!(|components, cli, cmd, config| {290				Ok(cmd.run(components.client, config.database))291			})292		}293		Some(Subcommand::ExportState(cmd)) => {294			construct_async_run!(|components, cli, cmd, config| {295				Ok(cmd.run(components.client, config.chain_spec))296			})297		}298		Some(Subcommand::ImportBlocks(cmd)) => {299			construct_async_run!(|components, cli, cmd, config| {300				Ok(cmd.run(components.client, components.import_queue))301			})302		}303		Some(Subcommand::PurgeChain(cmd)) => {304			let runner = cli.create_runner(cmd)?;305306			runner.sync_run(|config| {307				let polkadot_cli = RelayChainCli::new(308					&config,309					[RelayChainCli::executable_name()]310						.iter()311						.chain(cli.relaychain_args.iter()),312				);313314				let polkadot_config = SubstrateCli::create_configuration(315					&polkadot_cli,316					&polkadot_cli,317					config.tokio_handle.clone(),318				)319				.map_err(|err| format!("Relay chain argument error: {}", err))?;320321				cmd.run(config, polkadot_config)322			})323		}324		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {325			Ok(cmd.run(components.client, components.backend))326		}),327		Some(Subcommand::ExportGenesisState(params)) => {328			let mut builder = sc_cli::LoggerBuilder::new("");329			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");330			let _ = builder.init();331332			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;333			let state_version = Cli::native_runtime_version(&spec).state_version();334			let block: Block = generate_genesis_block(&spec, state_version)?;335			let raw_header = block.header().encode();336			let output_buf = if params.raw {337				raw_header338			} else {339				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()340			};341342			if let Some(output) = &params.output {343				std::fs::write(output, output_buf)?;344			} else {345				std::io::stdout().write_all(&output_buf)?;346			}347348			Ok(())349		}350		Some(Subcommand::ExportGenesisWasm(params)) => {351			let mut builder = sc_cli::LoggerBuilder::new("");352			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");353			let _ = builder.init();354355			let raw_wasm_blob =356				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;357			let output_buf = if params.raw {358				raw_wasm_blob359			} else {360				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()361			};362363			if let Some(output) = &params.output {364				std::fs::write(output, output_buf)?;365			} else {366				std::io::stdout().write_all(&output_buf)?;367			}368369			Ok(())370		}371		Some(Subcommand::Benchmark(cmd)) => {372			if cfg!(feature = "runtime-benchmarks") {373				let runner = cli.create_runner(cmd)?;374				runner.sync_run(|config| match config.chain_spec.runtime_id() {375					#[cfg(feature = "unique-runtime")]376					RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),377378					#[cfg(feature = "quartz-runtime")]379					RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),380381					RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),382					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),383				})384			} else {385				Err("Benchmarking wasn't enabled when building the node. \386				You can enable it with `--features runtime-benchmarks`."387					.into())388			}389		}390		None => {391			let runner = cli.create_runner(&cli.run.normalize())?;392393			runner.run_node_until_exit(|config| async move {394				let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);395396				let service_id = config.chain_spec.service_id();397				let relay_chain_id = extensions.map(|e| e.relay_chain.clone());398				let is_dev_service = matches![service_id, ServiceId::Dev]399					|| relay_chain_id == Some("dev-service".into());400401				if is_dev_service {402					info!("Running Dev service");403404					return start_node_using_chain_runtime! {405						start_dev_node(config).map_err(Into::into)406					};407				};408409				let para_id = extensions410					.map(|e| e.para_id)411					.ok_or("Could not find parachain ID in chain-spec.")?;412413				let polkadot_cli = RelayChainCli::new(414					&config,415					[RelayChainCli::executable_name()]416						.iter()417						.chain(cli.relaychain_args.iter()),418				);419420				let para_id = ParaId::from(para_id);421422				let parachain_account =423					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(424						&para_id,425					);426427				let state_version =428					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();429				let block: Block = generate_genesis_block(&config.chain_spec, state_version)430					.map_err(|e| format!("{:?}", e))?;431				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));432				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));433434				let polkadot_config = SubstrateCli::create_configuration(435					&polkadot_cli,436					&polkadot_cli,437					config.tokio_handle.clone(),438				)439				.map_err(|err| format!("Relay chain argument error: {}", err))?;440441				info!("Parachain id: {:?}", para_id);442				info!("Parachain Account: {}", parachain_account);443				info!("Parachain genesis state: {}", genesis_state);444				info!("Parachain genesis hash: {}", genesis_hash);445				info!(446					"Is collating: {}",447					if config.role.is_authority() {448						"yes"449					} else {450						"no"451					}452				);453454				start_node_using_chain_runtime! {455					start_node(config, polkadot_config, para_id)456						.await457						.map(|r| r.0)458						.map_err(Into::into)459				}460			})461		}462	}463}464465impl DefaultConfigurationValues for RelayChainCli {466	fn p2p_listen_port() -> u16 {467		30334468	}469470	fn rpc_ws_listen_port() -> u16 {471		9945472	}473474	fn rpc_http_listen_port() -> u16 {475		9934476	}477478	fn prometheus_listen_port() -> u16 {479		9616480	}481}482483impl CliConfiguration<Self> for RelayChainCli {484	fn shared_params(&self) -> &SharedParams {485		self.base.base.shared_params()486	}487488	fn import_params(&self) -> Option<&ImportParams> {489		self.base.base.import_params()490	}491492	fn network_params(&self) -> Option<&NetworkParams> {493		self.base.base.network_params()494	}495496	fn keystore_params(&self) -> Option<&KeystoreParams> {497		self.base.base.keystore_params()498	}499500	fn base_path(&self) -> Result<Option<BasePath>> {501		Ok(self502			.shared_params()503			.base_path()504			.or_else(|| self.base_path.clone().map(Into::into)))505	}506507	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {508		self.base.base.rpc_http(default_listen_port)509	}510511	fn rpc_ipc(&self) -> Result<Option<String>> {512		self.base.base.rpc_ipc()513	}514515	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {516		self.base.base.rpc_ws(default_listen_port)517	}518519	fn prometheus_config(520		&self,521		default_listen_port: u16,522		chain_spec: &Box<dyn ChainSpec>,523	) -> Result<Option<PrometheusConfig>> {524		self.base525			.base526			.prometheus_config(default_listen_port, chain_spec)527	}528529	fn init<F>(530		&self,531		_support_url: &String,532		_impl_version: &String,533		_logger_hook: F,534		_config: &sc_service::Configuration,535	) -> Result<()> {536		unreachable!("PolkadotCli is never initialized; qed");537	}538539	fn chain_id(&self, is_dev: bool) -> Result<String> {540		let chain_id = self.base.base.chain_id(is_dev)?;541542		Ok(if chain_id.is_empty() {543			self.chain_id.clone().unwrap_or_default()544		} else {545			chain_id546		})547	}548549	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {550		self.base.base.role(is_dev)551	}552553	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {554		self.base.base.transaction_pool()555	}556557	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {558		self.base.base.state_cache_child_ratio()559	}560561	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {562		self.base.base.rpc_methods()563	}564565	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {566		self.base.base.rpc_ws_max_connections()567	}568569	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {570		self.base.base.rpc_cors(is_dev)571	}572573	fn default_heap_pages(&self) -> Result<Option<u64>> {574		self.base.base.default_heap_pages()575	}576577	fn force_authoring(&self) -> Result<bool> {578		self.base.base.force_authoring()579	}580581	fn disable_grandpa(&self) -> Result<bool> {582		self.base.base.disable_grandpa()583	}584585	fn max_runtime_instances(&self) -> Result<Option<usize>> {586		self.base.base.max_runtime_instances()587	}588589	fn announce_block(&self) -> Result<bool> {590		self.base.base.announce_block()591	}592593	fn telemetry_endpoints(594		&self,595		chain_spec: &Box<dyn ChainSpec>,596	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {597		self.base.base.telemetry_endpoints(chain_spec)598	}599}