git.delta.rocks / unique-network / refs/commits / 8a5f501c3ec3

difftreelog

Fix code style

Daniel Shiposha2022-03-14parent: #6b7300d.patch.diff
in: master

1 file changed

modifiednode/cli/src/command.rsdiffbeforeafterboth
before · node/cli/src/command.rs
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},37	cli::{Cli, RelayChainCli, Subcommand},38	service::new_partial,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		"westend-local" => Box::new(chain_spec::local_testnet_westend_config()),79		"rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),80		"dev" => Box::new(chain_spec::development_config()),81		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),82		path => {83			let path = std::path::PathBuf::from(path);84			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(85				path.clone(),86			)?) as Box<dyn sc_service::ChainSpec>;8788			match chain_spec.runtime_id() {89				#[cfg(feature = "unique-runtime")]90				RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),9192				#[cfg(feature = "quartz-runtime")]93				RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9495				RuntimeId::Opal => Box::new(chain_spec::OpalChainSpec::from_json_file(path)?),96				RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),97			}98		}99	})100}101102impl SubstrateCli for Cli {103	// TODO use args104	fn impl_name() -> String {105		"Unique Node".into()106	}107108	fn impl_version() -> String {109		env!("SUBSTRATE_CLI_IMPL_VERSION").into()110	}111	// TODO use args112	fn description() -> String {113		format!(114			"Unique Node\n\nThe command-line arguments provided first will be \115		passed to the parachain node, while the arguments provided after -- will be passed \116		to the relaychain node.\n\n\117		{} [parachain-args] -- [relaychain-args]",118			Self::executable_name()119		)120	}121122	fn author() -> String {123		env!("CARGO_PKG_AUTHORS").into()124	}125126	//TODO use args127	fn support_url() -> String {128		"support@unique.network".into()129	}130131	fn copyright_start_year() -> i32 {132		2019133	}134135	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {136		load_spec(id)137	}138139	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {140		match chain_spec.runtime_id() {141			#[cfg(feature = "unique-runtime")]142			RuntimeId::Unique => &unique_runtime::VERSION,143144			#[cfg(feature = "quartz-runtime")]145			RuntimeId::Quartz => &quartz_runtime::VERSION,146147			RuntimeId::Opal => &opal_runtime::VERSION,148			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),149		}150	}151}152153impl SubstrateCli for RelayChainCli {154	// TODO use args155	fn impl_name() -> String {156		"Unique Node".into()157	}158159	fn impl_version() -> String {160		env!("SUBSTRATE_CLI_IMPL_VERSION").into()161	}162	// TODO use args163	fn description() -> String {164		"Unique Node\n\nThe command-line arguments provided first will be \165		passed to the parachain node, while the arguments provided after -- will be passed \166		to the relaychain node.\n\n\167		parachain-collator [parachain-args] -- [relaychain-args]"168			.into()169	}170171	fn author() -> String {172		env!("CARGO_PKG_AUTHORS").into()173	}174	// TODO use args175	fn support_url() -> String {176		"support@unique.network".into()177	}178179	fn copyright_start_year() -> i32 {180		2019181	}182183	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {184		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)185	}186187	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {188		polkadot_cli::Cli::native_runtime_version(chain_spec)189	}190}191192#[allow(clippy::borrowed_box)]193fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {194	let mut storage = chain_spec.build_storage()?;195196	storage197		.top198		.remove(sp_core::storage::well_known_keys::CODE)199		.ok_or_else(|| "Could not find wasm file in genesis state!".into())200}201202macro_rules! async_run_with_runtime {203	(204		$runtime_api:path, $executor:path,205		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,206		$( $code:tt )*207	) => {208		$runner.async_run(|$config| {209			let $components = new_partial::<210				$runtime_api, $executor, _211			>(212				&$config,213				crate::service::parachain_build_import_queue,214			)?;215			let task_manager = $components.task_manager;216217			{ $( $code )* }.map(|v| (v, task_manager))218		})219	};220}221222macro_rules! construct_async_run {223	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{224		let runner = $cli.create_runner($cmd)?;225226		match runner.config().chain_spec.runtime_id() {227			#[cfg(feature = "unique-runtime")]228			RuntimeId::Unique => async_run_with_runtime!(229				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,230				runner, $components, $cli, $cmd, $config, $( $code )*231			),232233			#[cfg(feature = "quartz-runtime")]234			RuntimeId::Quartz => async_run_with_runtime!(235				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,236				runner, $components, $cli, $cmd, $config, $( $code )*237			),238239			RuntimeId::Opal => async_run_with_runtime!(240				opal_runtime::RuntimeApi, OpalRuntimeExecutor,241				runner, $components, $cli, $cmd, $config, $( $code )*242			),243244			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())245		}246	}}247}248249/// Parse command line arguments into service configuration.250pub fn run() -> Result<()> {251	let cli = Cli::from_args();252253	match &cli.subcommand {254		Some(Subcommand::BuildSpec(cmd)) => {255			let runner = cli.create_runner(cmd)?;256			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))257		}258		Some(Subcommand::CheckBlock(cmd)) => {259			construct_async_run!(|components, cli, cmd, config| {260				Ok(cmd.run(components.client, components.import_queue))261			})262		}263		Some(Subcommand::ExportBlocks(cmd)) => {264			construct_async_run!(|components, cli, cmd, config| {265				Ok(cmd.run(components.client, config.database))266			})267		}268		Some(Subcommand::ExportState(cmd)) => {269			construct_async_run!(|components, cli, cmd, config| {270				Ok(cmd.run(components.client, config.chain_spec))271			})272		}273		Some(Subcommand::ImportBlocks(cmd)) => {274			construct_async_run!(|components, cli, cmd, config| {275				Ok(cmd.run(components.client, components.import_queue))276			})277		}278		Some(Subcommand::PurgeChain(cmd)) => {279			let runner = cli.create_runner(cmd)?;280281			runner.sync_run(|config| {282				let polkadot_cli = RelayChainCli::new(283					&config,284					[RelayChainCli::executable_name()]285						.iter()286						.chain(cli.relaychain_args.iter()),287				);288289				let polkadot_config = SubstrateCli::create_configuration(290					&polkadot_cli,291					&polkadot_cli,292					config.tokio_handle.clone(),293				)294				.map_err(|err| format!("Relay chain argument error: {}", err))?;295296				cmd.run(config, polkadot_config)297			})298		}299		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {300			Ok(cmd.run(components.client, components.backend))301		}),302		Some(Subcommand::ExportGenesisState(params)) => {303			let mut builder = sc_cli::LoggerBuilder::new("");304			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");305			let _ = builder.init();306307			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;308			let state_version = Cli::native_runtime_version(&spec).state_version();309			let block: Block = generate_genesis_block(&spec, state_version)?;310			let raw_header = block.header().encode();311			let output_buf = if params.raw {312				raw_header313			} else {314				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()315			};316317			if let Some(output) = &params.output {318				std::fs::write(output, output_buf)?;319			} else {320				std::io::stdout().write_all(&output_buf)?;321			}322323			Ok(())324		}325		Some(Subcommand::ExportGenesisWasm(params)) => {326			let mut builder = sc_cli::LoggerBuilder::new("");327			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");328			let _ = builder.init();329330			let raw_wasm_blob =331				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;332			let output_buf = if params.raw {333				raw_wasm_blob334			} else {335				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()336			};337338			if let Some(output) = &params.output {339				std::fs::write(output, output_buf)?;340			} else {341				std::io::stdout().write_all(&output_buf)?;342			}343344			Ok(())345		}346		Some(Subcommand::Benchmark(cmd)) => {347			if cfg!(feature = "runtime-benchmarks") {348				let runner = cli.create_runner(cmd)?;349				runner.sync_run(|config| match config.chain_spec.runtime_id() {350					#[cfg(feature = "unique-runtime")]351					RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),352353					#[cfg(feature = "quartz-runtime")]354					RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),355356					RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),357					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),358				})359			} else {360				Err("Benchmarking wasn't enabled when building the node. \361				You can enable it with `--features runtime-benchmarks`."362					.into())363			}364		}365		None => {366			let runner = cli.create_runner(&cli.run.normalize())?;367368			runner.run_node_until_exit(|config| async move {369				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)370					.map(|e| e.para_id)371					.ok_or("Could not find parachain ID in chain-spec.")?;372373				let polkadot_cli = RelayChainCli::new(374					&config,375					[RelayChainCli::executable_name()]376						.iter()377						.chain(cli.relaychain_args.iter()),378				);379380				let id = ParaId::from(para_id);381382				let parachain_account =383					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);384385				let state_version =386					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();387				let block: Block = generate_genesis_block(&config.chain_spec, state_version)388					.map_err(|e| format!("{:?}", e))?;389				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));390				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));391392				let polkadot_config = SubstrateCli::create_configuration(393					&polkadot_cli,394					&polkadot_cli,395					config.tokio_handle.clone(),396				)397				.map_err(|err| format!("Relay chain argument error: {}", err))?;398399				info!("Parachain id: {:?}", id);400				info!("Parachain Account: {}", parachain_account);401				info!("Parachain genesis state: {}", genesis_state);402				info!("Parachain genesis hash: {}", genesis_hash);403				info!(404					"Is collating: {}",405					if config.role.is_authority() {406						"yes"407					} else {408						"no"409					}410				);411412				match config.chain_spec.runtime_id() {413					#[cfg(feature = "unique-runtime")]414					RuntimeId::Unique => crate::service::start_node::<415						unique_runtime::Runtime,416						unique_runtime::RuntimeApi,417						UniqueRuntimeExecutor,418					>(config, polkadot_config, id)419					.await420					.map(|r| r.0)421					.map_err(Into::into),422423					#[cfg(feature = "quartz-runtime")]424					RuntimeId::Quartz => crate::service::start_node::<425						quartz_runtime::Runtime,426						quartz_runtime::RuntimeApi,427						QuartzRuntimeExecutor,428					>(config, polkadot_config, id)429					.await430					.map(|r| r.0)431					.map_err(Into::into),432433					RuntimeId::Opal => crate::service::start_node::<434						opal_runtime::Runtime,435						opal_runtime::RuntimeApi,436						OpalRuntimeExecutor,437					>(config, polkadot_config, id)438					.await439					.map(|r| r.0)440					.map_err(Into::into),441442					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),443				}444			})445		}446	}447}448449impl DefaultConfigurationValues for RelayChainCli {450	fn p2p_listen_port() -> u16 {451		30334452	}453454	fn rpc_ws_listen_port() -> u16 {455		9945456	}457458	fn rpc_http_listen_port() -> u16 {459		9934460	}461462	fn prometheus_listen_port() -> u16 {463		9616464	}465}466467impl CliConfiguration<Self> for RelayChainCli {468	fn shared_params(&self) -> &SharedParams {469		self.base.base.shared_params()470	}471472	fn import_params(&self) -> Option<&ImportParams> {473		self.base.base.import_params()474	}475476	fn network_params(&self) -> Option<&NetworkParams> {477		self.base.base.network_params()478	}479480	fn keystore_params(&self) -> Option<&KeystoreParams> {481		self.base.base.keystore_params()482	}483484	fn base_path(&self) -> Result<Option<BasePath>> {485		Ok(self486			.shared_params()487			.base_path()488			.or_else(|| self.base_path.clone().map(Into::into)))489	}490491	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {492		self.base.base.rpc_http(default_listen_port)493	}494495	fn rpc_ipc(&self) -> Result<Option<String>> {496		self.base.base.rpc_ipc()497	}498499	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {500		self.base.base.rpc_ws(default_listen_port)501	}502503	fn prometheus_config(504		&self,505		default_listen_port: u16,506		chain_spec: &Box<dyn ChainSpec>,507	) -> Result<Option<PrometheusConfig>> {508		self.base509			.base510			.prometheus_config(default_listen_port, chain_spec)511	}512513	fn init<F>(514		&self,515		_support_url: &String,516		_impl_version: &String,517		_logger_hook: F,518		_config: &sc_service::Configuration,519	) -> Result<()> {520		unreachable!("PolkadotCli is never initialized; qed");521	}522523	fn chain_id(&self, is_dev: bool) -> Result<String> {524		let chain_id = self.base.base.chain_id(is_dev)?;525526		Ok(if chain_id.is_empty() {527			self.chain_id.clone().unwrap_or_default()528		} else {529			chain_id530		})531	}532533	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {534		self.base.base.role(is_dev)535	}536537	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {538		self.base.base.transaction_pool()539	}540541	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {542		self.base.base.state_cache_child_ratio()543	}544545	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {546		self.base.base.rpc_methods()547	}548549	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {550		self.base.base.rpc_ws_max_connections()551	}552553	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {554		self.base.base.rpc_cors(is_dev)555	}556557	fn default_heap_pages(&self) -> Result<Option<u64>> {558		self.base.base.default_heap_pages()559	}560561	fn force_authoring(&self) -> Result<bool> {562		self.base.base.force_authoring()563	}564565	fn disable_grandpa(&self) -> Result<bool> {566		self.base.base.disable_grandpa()567	}568569	fn max_runtime_instances(&self) -> Result<Option<usize>> {570		self.base.base.max_runtime_instances()571	}572573	fn announce_block(&self) -> Result<bool> {574		self.base.base.announce_block()575	}576577	fn telemetry_endpoints(578		&self,579		chain_spec: &Box<dyn ChainSpec>,580	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {581		self.base.base.telemetry_endpoints(chain_spec)582	}583}
after · node/cli/src/command.rs
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},37	cli::{Cli, RelayChainCli, Subcommand},38	service::new_partial,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		"westend-local" => Box::new(chain_spec::local_testnet_westend_config()),79		"rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),80		"dev" => Box::new(chain_spec::development_config()),81		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),82		path => {83			let path = std::path::PathBuf::from(path);84			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)85				as Box<dyn sc_service::ChainSpec>;8687			match chain_spec.runtime_id() {88				#[cfg(feature = "unique-runtime")]89				RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),9091				#[cfg(feature = "quartz-runtime")]92				RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9394				RuntimeId::Opal => Box::new(chain_spec::OpalChainSpec::from_json_file(path)?),95				RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),96			}97		}98	})99}100101impl SubstrateCli for Cli {102	// TODO use args103	fn impl_name() -> String {104		"Unique Node".into()105	}106107	fn impl_version() -> String {108		env!("SUBSTRATE_CLI_IMPL_VERSION").into()109	}110	// TODO use args111	fn description() -> String {112		format!(113			"Unique Node\n\nThe command-line arguments provided first will be \114		passed to the parachain node, while the arguments provided after -- will be passed \115		to the relaychain node.\n\n\116		{} [parachain-args] -- [relaychain-args]",117			Self::executable_name()118		)119	}120121	fn author() -> String {122		env!("CARGO_PKG_AUTHORS").into()123	}124125	//TODO use args126	fn support_url() -> String {127		"support@unique.network".into()128	}129130	fn copyright_start_year() -> i32 {131		2019132	}133134	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {135		load_spec(id)136	}137138	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {139		match chain_spec.runtime_id() {140			#[cfg(feature = "unique-runtime")]141			RuntimeId::Unique => &unique_runtime::VERSION,142143			#[cfg(feature = "quartz-runtime")]144			RuntimeId::Quartz => &quartz_runtime::VERSION,145146			RuntimeId::Opal => &opal_runtime::VERSION,147			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),148		}149	}150}151152impl SubstrateCli for RelayChainCli {153	// TODO use args154	fn impl_name() -> String {155		"Unique Node".into()156	}157158	fn impl_version() -> String {159		env!("SUBSTRATE_CLI_IMPL_VERSION").into()160	}161	// TODO use args162	fn description() -> String {163		"Unique Node\n\nThe command-line arguments provided first will be \164		passed to the parachain node, while the arguments provided after -- will be passed \165		to the relaychain node.\n\n\166		parachain-collator [parachain-args] -- [relaychain-args]"167			.into()168	}169170	fn author() -> String {171		env!("CARGO_PKG_AUTHORS").into()172	}173	// TODO use args174	fn support_url() -> String {175		"support@unique.network".into()176	}177178	fn copyright_start_year() -> i32 {179		2019180	}181182	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {183		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)184	}185186	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {187		polkadot_cli::Cli::native_runtime_version(chain_spec)188	}189}190191#[allow(clippy::borrowed_box)]192fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {193	let mut storage = chain_spec.build_storage()?;194195	storage196		.top197		.remove(sp_core::storage::well_known_keys::CODE)198		.ok_or_else(|| "Could not find wasm file in genesis state!".into())199}200201macro_rules! async_run_with_runtime {202	(203		$runtime_api:path, $executor:path,204		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,205		$( $code:tt )*206	) => {207		$runner.async_run(|$config| {208			let $components = new_partial::<209				$runtime_api, $executor, _210			>(211				&$config,212				crate::service::parachain_build_import_queue,213			)?;214			let task_manager = $components.task_manager;215216			{ $( $code )* }.map(|v| (v, task_manager))217		})218	};219}220221macro_rules! construct_async_run {222	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{223		let runner = $cli.create_runner($cmd)?;224225		match runner.config().chain_spec.runtime_id() {226			#[cfg(feature = "unique-runtime")]227			RuntimeId::Unique => async_run_with_runtime!(228				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,229				runner, $components, $cli, $cmd, $config, $( $code )*230			),231232			#[cfg(feature = "quartz-runtime")]233			RuntimeId::Quartz => async_run_with_runtime!(234				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,235				runner, $components, $cli, $cmd, $config, $( $code )*236			),237238			RuntimeId::Opal => async_run_with_runtime!(239				opal_runtime::RuntimeApi, OpalRuntimeExecutor,240				runner, $components, $cli, $cmd, $config, $( $code )*241			),242243			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())244		}245	}}246}247248/// Parse command line arguments into service configuration.249pub fn run() -> Result<()> {250	let cli = Cli::from_args();251252	match &cli.subcommand {253		Some(Subcommand::BuildSpec(cmd)) => {254			let runner = cli.create_runner(cmd)?;255			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))256		}257		Some(Subcommand::CheckBlock(cmd)) => {258			construct_async_run!(|components, cli, cmd, config| {259				Ok(cmd.run(components.client, components.import_queue))260			})261		}262		Some(Subcommand::ExportBlocks(cmd)) => {263			construct_async_run!(|components, cli, cmd, config| {264				Ok(cmd.run(components.client, config.database))265			})266		}267		Some(Subcommand::ExportState(cmd)) => {268			construct_async_run!(|components, cli, cmd, config| {269				Ok(cmd.run(components.client, config.chain_spec))270			})271		}272		Some(Subcommand::ImportBlocks(cmd)) => {273			construct_async_run!(|components, cli, cmd, config| {274				Ok(cmd.run(components.client, components.import_queue))275			})276		}277		Some(Subcommand::PurgeChain(cmd)) => {278			let runner = cli.create_runner(cmd)?;279280			runner.sync_run(|config| {281				let polkadot_cli = RelayChainCli::new(282					&config,283					[RelayChainCli::executable_name()]284						.iter()285						.chain(cli.relaychain_args.iter()),286				);287288				let polkadot_config = SubstrateCli::create_configuration(289					&polkadot_cli,290					&polkadot_cli,291					config.tokio_handle.clone(),292				)293				.map_err(|err| format!("Relay chain argument error: {}", err))?;294295				cmd.run(config, polkadot_config)296			})297		}298		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {299			Ok(cmd.run(components.client, components.backend))300		}),301		Some(Subcommand::ExportGenesisState(params)) => {302			let mut builder = sc_cli::LoggerBuilder::new("");303			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");304			let _ = builder.init();305306			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;307			let state_version = Cli::native_runtime_version(&spec).state_version();308			let block: Block = generate_genesis_block(&spec, state_version)?;309			let raw_header = block.header().encode();310			let output_buf = if params.raw {311				raw_header312			} else {313				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()314			};315316			if let Some(output) = &params.output {317				std::fs::write(output, output_buf)?;318			} else {319				std::io::stdout().write_all(&output_buf)?;320			}321322			Ok(())323		}324		Some(Subcommand::ExportGenesisWasm(params)) => {325			let mut builder = sc_cli::LoggerBuilder::new("");326			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");327			let _ = builder.init();328329			let raw_wasm_blob =330				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;331			let output_buf = if params.raw {332				raw_wasm_blob333			} else {334				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()335			};336337			if let Some(output) = &params.output {338				std::fs::write(output, output_buf)?;339			} else {340				std::io::stdout().write_all(&output_buf)?;341			}342343			Ok(())344		}345		Some(Subcommand::Benchmark(cmd)) => {346			if cfg!(feature = "runtime-benchmarks") {347				let runner = cli.create_runner(cmd)?;348				runner.sync_run(|config| match config.chain_spec.runtime_id() {349					#[cfg(feature = "unique-runtime")]350					RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),351352					#[cfg(feature = "quartz-runtime")]353					RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),354355					RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),356					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),357				})358			} else {359				Err("Benchmarking wasn't enabled when building the node. \360				You can enable it with `--features runtime-benchmarks`."361					.into())362			}363		}364		None => {365			let runner = cli.create_runner(&cli.run.normalize())?;366367			runner.run_node_until_exit(|config| async move {368				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)369					.map(|e| e.para_id)370					.ok_or("Could not find parachain ID in chain-spec.")?;371372				let polkadot_cli = RelayChainCli::new(373					&config,374					[RelayChainCli::executable_name()]375						.iter()376						.chain(cli.relaychain_args.iter()),377				);378379				let id = ParaId::from(para_id);380381				let parachain_account =382					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);383384				let state_version =385					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();386				let block: Block = generate_genesis_block(&config.chain_spec, state_version)387					.map_err(|e| format!("{:?}", e))?;388				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));389				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));390391				let polkadot_config = SubstrateCli::create_configuration(392					&polkadot_cli,393					&polkadot_cli,394					config.tokio_handle.clone(),395				)396				.map_err(|err| format!("Relay chain argument error: {}", err))?;397398				info!("Parachain id: {:?}", id);399				info!("Parachain Account: {}", parachain_account);400				info!("Parachain genesis state: {}", genesis_state);401				info!("Parachain genesis hash: {}", genesis_hash);402				info!(403					"Is collating: {}",404					if config.role.is_authority() {405						"yes"406					} else {407						"no"408					}409				);410411				match config.chain_spec.runtime_id() {412					#[cfg(feature = "unique-runtime")]413					RuntimeId::Unique => crate::service::start_node::<414						unique_runtime::Runtime,415						unique_runtime::RuntimeApi,416						UniqueRuntimeExecutor,417					>(config, polkadot_config, id)418					.await419					.map(|r| r.0)420					.map_err(Into::into),421422					#[cfg(feature = "quartz-runtime")]423					RuntimeId::Quartz => crate::service::start_node::<424						quartz_runtime::Runtime,425						quartz_runtime::RuntimeApi,426						QuartzRuntimeExecutor,427					>(config, polkadot_config, id)428					.await429					.map(|r| r.0)430					.map_err(Into::into),431432					RuntimeId::Opal => crate::service::start_node::<433						opal_runtime::Runtime,434						opal_runtime::RuntimeApi,435						OpalRuntimeExecutor,436					>(config, polkadot_config, id)437					.await438					.map(|r| r.0)439					.map_err(Into::into),440441					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),442				}443			})444		}445	}446}447448impl DefaultConfigurationValues for RelayChainCli {449	fn p2p_listen_port() -> u16 {450		30334451	}452453	fn rpc_ws_listen_port() -> u16 {454		9945455	}456457	fn rpc_http_listen_port() -> u16 {458		9934459	}460461	fn prometheus_listen_port() -> u16 {462		9616463	}464}465466impl CliConfiguration<Self> for RelayChainCli {467	fn shared_params(&self) -> &SharedParams {468		self.base.base.shared_params()469	}470471	fn import_params(&self) -> Option<&ImportParams> {472		self.base.base.import_params()473	}474475	fn network_params(&self) -> Option<&NetworkParams> {476		self.base.base.network_params()477	}478479	fn keystore_params(&self) -> Option<&KeystoreParams> {480		self.base.base.keystore_params()481	}482483	fn base_path(&self) -> Result<Option<BasePath>> {484		Ok(self485			.shared_params()486			.base_path()487			.or_else(|| self.base_path.clone().map(Into::into)))488	}489490	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {491		self.base.base.rpc_http(default_listen_port)492	}493494	fn rpc_ipc(&self) -> Result<Option<String>> {495		self.base.base.rpc_ipc()496	}497498	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {499		self.base.base.rpc_ws(default_listen_port)500	}501502	fn prometheus_config(503		&self,504		default_listen_port: u16,505		chain_spec: &Box<dyn ChainSpec>,506	) -> Result<Option<PrometheusConfig>> {507		self.base508			.base509			.prometheus_config(default_listen_port, chain_spec)510	}511512	fn init<F>(513		&self,514		_support_url: &String,515		_impl_version: &String,516		_logger_hook: F,517		_config: &sc_service::Configuration,518	) -> Result<()> {519		unreachable!("PolkadotCli is never initialized; qed");520	}521522	fn chain_id(&self, is_dev: bool) -> Result<String> {523		let chain_id = self.base.base.chain_id(is_dev)?;524525		Ok(if chain_id.is_empty() {526			self.chain_id.clone().unwrap_or_default()527		} else {528			chain_id529		})530	}531532	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {533		self.base.base.role(is_dev)534	}535536	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {537		self.base.base.transaction_pool()538	}539540	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {541		self.base.base.state_cache_child_ratio()542	}543544	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {545		self.base.base.rpc_methods()546	}547548	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {549		self.base.base.rpc_ws_max_connections()550	}551552	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {553		self.base.base.rpc_cors(is_dev)554	}555556	fn default_heap_pages(&self) -> Result<Option<u64>> {557		self.base.base.default_heap_pages()558	}559560	fn force_authoring(&self) -> Result<bool> {561		self.base.base.force_authoring()562	}563564	fn disable_grandpa(&self) -> Result<bool> {565		self.base.base.disable_grandpa()566	}567568	fn max_runtime_instances(&self) -> Result<Option<usize>> {569		self.base.base.max_runtime_instances()570	}571572	fn announce_block(&self) -> Result<bool> {573		self.base.base.announce_block()574	}575576	fn telemetry_endpoints(577		&self,578		chain_spec: &Box<dyn ChainSpec>,579	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {580		self.base.base.telemetry_endpoints(chain_spec)581	}582}