git.delta.rocks / unique-network / refs/commits / 5985fa11530c

difftreelog

Fix load_spec and is_opal

Daniel Shiposha2022-03-14parent: #89a64dc.patch.diff
in: master

2 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -26,8 +26,17 @@
 
 use unique_runtime_common::types::*;
 
-/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
-pub type ChainSpec = sc_service::GenericChainSpec<unique_runtime::GenesisConfig, Extensions>;
+/// The `ChainSpec` parameterized for the unique runtime.
+#[cfg(feature = "unique-runtime")]
+pub type UniqueChainSpec = sc_service::GenericChainSpec<unique_runtime::GenesisConfig, Extensions>;
+
+/// The `ChainSpec` parameterized for the quartz runtime.
+#[cfg(feature = "quartz-runtime")]
+pub type QuartzChainSpec = sc_service::GenericChainSpec<quartz_runtime::GenesisConfig, Extensions>;
+
+/// The `ChainSpec` parameterized for the opal runtime.
+#[cfg(feature = "opal-runtime")]
+pub type OpalChainSpec = sc_service::GenericChainSpec<opal_runtime::GenesisConfig, Extensions>;
 
 pub trait RuntimeIdentification {
 	fn is_unique(&self) -> bool;
@@ -48,6 +57,8 @@
 
 	fn is_opal(&self) -> bool {
 		self.id().starts_with("opal")
+		|| self.id() == "dev"
+		|| self.id() == "local_testnet"
 	}
 }
 
@@ -85,13 +96,13 @@
 	AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
 }
 
-pub fn development_config() -> ChainSpec {
+pub fn development_config() -> OpalChainSpec {
 	let mut properties = Map::new();
 	properties.insert("tokenSymbol".into(), "OPL".into());
 	properties.insert("tokenDecimals".into(), 15.into());
 	properties.insert("ss58Format".into(), 42.into());
 
-	ChainSpec::from_genesis(
+	OpalChainSpec::from_genesis(
 		// Name
 		"Development",
 		// ID
@@ -130,8 +141,8 @@
 	)
 }
 
-pub fn local_testnet_rococo_config() -> ChainSpec {
-	ChainSpec::from_genesis(
+pub fn local_testnet_rococo_config() -> OpalChainSpec {
+	OpalChainSpec::from_genesis(
 		// Name
 		"Local Testnet",
 		// ID
@@ -180,8 +191,8 @@
 	)
 }
 
-pub fn local_testnet_westend_config() -> ChainSpec {
-	ChainSpec::from_genesis(
+pub fn local_testnet_westend_config() -> OpalChainSpec {
+	OpalChainSpec::from_genesis(
 		// Name
 		"Local Testnet",
 		// ID
@@ -238,8 +249,8 @@
 	initial_authorities: Vec<AuraId>,
 	endowed_accounts: Vec<AccountId>,
 	id: ParaId,
-) -> unique_runtime::GenesisConfig {
-	use unique_runtime::*;
+) -> opal_runtime::GenesisConfig {
+	use opal_runtime::*;
 
 	GenesisConfig {
 		system: SystemConfig {
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, 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;4647#[cfg(feature = "opal-runtime")]48use crate::service::OpalRuntimeExecutor;4950use codec::Encode;51use cumulus_primitives_core::ParaId;52use cumulus_client_service::genesis::generate_genesis_block;53use log::info;54use polkadot_parachain::primitives::AccountIdConversion;55use sc_cli::{56	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,57	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,58};59use sc_service::{60	config::{BasePath, PrometheusConfig},61};62use sp_core::hexdisplay::HexDisplay;63use sp_runtime::traits::Block as BlockT;64use std::{io::Write, net::SocketAddr};6566use unique_runtime_common::types::Block;6768macro_rules! no_runtime_err {69	($chain_spec:expr) => {70		format!(71			"No runtime valid runtime was found, chain id: {}",72			$chain_spec.id()73		)74	};75}7677fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {78	Ok(match id {79		"westend-local" => Box::new(chain_spec::local_testnet_westend_config()),80		"rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),81		"dev" => Box::new(chain_spec::development_config()),82		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),83		path => Box::new(chain_spec::ChainSpec::from_json_file(84			std::path::PathBuf::from(path),85		)?),86	})87}8889impl SubstrateCli for Cli {90	// TODO use args91	fn impl_name() -> String {92		"Unique Node".into()93	}9495	fn impl_version() -> String {96		env!("SUBSTRATE_CLI_IMPL_VERSION").into()97	}98	// TODO use args99	fn description() -> String {100		format!(101			"Unique Node\n\nThe command-line arguments provided first will be \102		passed to the parachain node, while the arguments provided after -- will be passed \103		to the relaychain node.\n\n\104		{} [parachain-args] -- [relaychain-args]",105			Self::executable_name()106		)107	}108109	fn author() -> String {110		env!("CARGO_PKG_AUTHORS").into()111	}112113	//TODO use args114	fn support_url() -> String {115		"support@unique.network".into()116	}117118	fn copyright_start_year() -> i32 {119		2019120	}121122	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {123		load_spec(id)124	}125126	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {127		#[cfg(feature = "unique-runtime")]128		if chain_spec.is_unique() {129			return &unique_runtime::VERSION;130		}131132		#[cfg(feature = "quartz-runtime")]133		if chain_spec.is_quartz() {134			return &quartz_runtime::VERSION;135		}136137		#[cfg(feature = "opal-runtime")]138		if chain_spec.is_opal() {139			return &opal_runtime::VERSION;140		}141142		panic!("{}", no_runtime_err!(chain_spec));143	}144}145146impl SubstrateCli for RelayChainCli {147	// TODO use args148	fn impl_name() -> String {149		"Unique Node".into()150	}151152	fn impl_version() -> String {153		env!("SUBSTRATE_CLI_IMPL_VERSION").into()154	}155	// TODO use args156	fn description() -> String {157		"Unique Node\n\nThe command-line arguments provided first will be \158		passed to the parachain node, while the arguments provided after -- will be passed \159		to the relaychain node.\n\n\160		parachain-collator [parachain-args] -- [relaychain-args]"161			.into()162	}163164	fn author() -> String {165		env!("CARGO_PKG_AUTHORS").into()166	}167	// TODO use args168	fn support_url() -> String {169		"support@unique.network".into()170	}171172	fn copyright_start_year() -> i32 {173		2019174	}175176	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {177		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)178	}179180	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {181		polkadot_cli::Cli::native_runtime_version(chain_spec)182	}183}184185#[allow(clippy::borrowed_box)]186fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {187	let mut storage = chain_spec.build_storage()?;188189	storage190		.top191		.remove(sp_core::storage::well_known_keys::CODE)192		.ok_or_else(|| "Could not find wasm file in genesis state!".into())193}194195macro_rules! construct_async_run {196	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{197		let runner = $cli.create_runner($cmd)?;198199		#[cfg(feature = "unique-runtime")]200		if runner.config().chain_spec.is_unique() {201			return runner.async_run(|$config| {202				let $components = new_partial::<203					unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _204				>(205					&$config,206					crate::service::parachain_build_import_queue,207				)?;208				let task_manager = $components.task_manager;209				{ $( $code )* }.map(|v| (v, task_manager))210			});211		}212213		#[cfg(feature = "quartz-runtime")]214		if runner.config().chain_spec.is_quartz() {215			return runner.async_run(|$config| {216				let $components = new_partial::<217					quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _218				>(219					&$config,220					crate::service::parachain_build_import_queue,221				)?;222				let task_manager = $components.task_manager;223				{ $( $code )* }.map(|v| (v, task_manager))224			});225		}226227		#[cfg(feature = "opal-runtime")]228		if runner.config().chain_spec.is_opal() {229			return runner.async_run(|$config| {230				let $components = new_partial::<231					opal_runtime::RuntimeApi, OpalRuntimeExecutor, _232				>(233					&$config,234					crate::service::parachain_build_import_queue,235				)?;236				let task_manager = $components.task_manager;237				{ $( $code )* }.map(|v| (v, task_manager))238			});239		}240241		Err(no_runtime_err!(runner.config().chain_spec).into())242	}}243}244245/// Parse command line arguments into service configuration.246pub fn run() -> Result<()> {247	let cli = Cli::from_args();248249	match &cli.subcommand {250		Some(Subcommand::BuildSpec(cmd)) => {251			let runner = cli.create_runner(cmd)?;252			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))253		}254		Some(Subcommand::CheckBlock(cmd)) => {255			construct_async_run!(|components, cli, cmd, config| {256				Ok(cmd.run(components.client, components.import_queue))257			})258		}259		Some(Subcommand::ExportBlocks(cmd)) => {260			construct_async_run!(|components, cli, cmd, config| {261				Ok(cmd.run(components.client, config.database))262			})263		}264		Some(Subcommand::ExportState(cmd)) => {265			construct_async_run!(|components, cli, cmd, config| {266				Ok(cmd.run(components.client, config.chain_spec))267			})268		}269		Some(Subcommand::ImportBlocks(cmd)) => {270			construct_async_run!(|components, cli, cmd, config| {271				Ok(cmd.run(components.client, components.import_queue))272			})273		}274		Some(Subcommand::PurgeChain(cmd)) => {275			let runner = cli.create_runner(cmd)?;276277			runner.sync_run(|config| {278				let polkadot_cli = RelayChainCli::new(279					&config,280					[RelayChainCli::executable_name()]281						.iter()282						.chain(cli.relaychain_args.iter()),283				);284285				let polkadot_config = SubstrateCli::create_configuration(286					&polkadot_cli,287					&polkadot_cli,288					config.tokio_handle.clone(),289				)290				.map_err(|err| format!("Relay chain argument error: {}", err))?;291292				cmd.run(config, polkadot_config)293			})294		}295		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {296			Ok(cmd.run(components.client, components.backend))297		}),298		Some(Subcommand::ExportGenesisState(params)) => {299			let mut builder = sc_cli::LoggerBuilder::new("");300			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");301			let _ = builder.init();302303			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;304			let state_version = Cli::native_runtime_version(&spec).state_version();305			let block: Block = generate_genesis_block(&spec, state_version)?;306			let raw_header = block.header().encode();307			let output_buf = if params.raw {308				raw_header309			} else {310				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()311			};312313			if let Some(output) = &params.output {314				std::fs::write(output, output_buf)?;315			} else {316				std::io::stdout().write_all(&output_buf)?;317			}318319			Ok(())320		}321		Some(Subcommand::ExportGenesisWasm(params)) => {322			let mut builder = sc_cli::LoggerBuilder::new("");323			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");324			let _ = builder.init();325326			let raw_wasm_blob =327				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;328			let output_buf = if params.raw {329				raw_wasm_blob330			} else {331				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()332			};333334			if let Some(output) = &params.output {335				std::fs::write(output, output_buf)?;336			} else {337				std::io::stdout().write_all(&output_buf)?;338			}339340			Ok(())341		}342		Some(Subcommand::Benchmark(cmd)) => {343			if cfg!(feature = "runtime-benchmarks") {344				let runner = cli.create_runner(cmd)?;345				runner.sync_run(|config| {346					#[cfg(feature = "unique-runtime")]347					if config.chain_spec.is_unique() {348						return cmd.run::<Block, UniqueRuntimeExecutor>(config);349					}350351					#[cfg(feature = "quartz-runtime")]352					if config.chain_spec.is_quartz() {353						return cmd.run::<Block, QuartzRuntimeExecutor>(config);354					}355356					#[cfg(feature = "opal-runtime")]357					if config.chain_spec.is_opal() {358						return cmd.run::<Block, OpalRuntimeExecutor>(config);359					}360361					Err(no_runtime_err!(config.chain_spec).into())362				})363			} else {364				Err("Benchmarking wasn't enabled when building the node. \365				You can enable it with `--features runtime-benchmarks`."366					.into())367			}368		}369		None => {370			let runner = cli.create_runner(&cli.run.normalize())?;371372			runner.run_node_until_exit(|config| async move {373				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)374					.map(|e| e.para_id)375					.ok_or("Could not find parachain ID in chain-spec.")?;376377				let polkadot_cli = RelayChainCli::new(378					&config,379					[RelayChainCli::executable_name()]380						.iter()381						.chain(cli.relaychain_args.iter()),382				);383384				let id = ParaId::from(para_id);385386				let parachain_account =387					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);388389				let state_version =390					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();391				let block: Block = generate_genesis_block(&config.chain_spec, state_version)392					.map_err(|e| format!("{:?}", e))?;393				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));394				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));395396				let polkadot_config = SubstrateCli::create_configuration(397					&polkadot_cli,398					&polkadot_cli,399					config.tokio_handle.clone(),400				)401				.map_err(|err| format!("Relay chain argument error: {}", err))?;402403				info!("Parachain id: {:?}", id);404				info!("Parachain Account: {}", parachain_account);405				info!("Parachain genesis state: {}", genesis_state);406				info!("Parachain genesis hash: {}", genesis_hash);407				info!(408					"Is collating: {}",409					if config.role.is_authority() {410						"yes"411					} else {412						"no"413					}414				);415416				#[cfg(feature = "unique-runtime")]417				if config.chain_spec.is_unique() {418					return crate::service::start_node::<419						unique_runtime::Runtime,420						unique_runtime::RuntimeApi,421						UniqueRuntimeExecutor,422					>(config, polkadot_config, id)423					.await424					.map(|r| r.0)425					.map_err(Into::into);426				}427428				#[cfg(feature = "quartz-runtime")]429				if config.chain_spec.is_quartz() {430					return crate::service::start_node::<431						quartz_runtime::Runtime,432						quartz_runtime::RuntimeApi,433						QuartzRuntimeExecutor,434					>(config, polkadot_config, id)435					.await436					.map(|r| r.0)437					.map_err(Into::into);438				}439440				#[cfg(feature = "opal-runtime")]441				if config.chain_spec.is_opal() {442					return crate::service::start_node::<443						opal_runtime::Runtime,444						opal_runtime::RuntimeApi,445						OpalRuntimeExecutor,446					>(config, polkadot_config, id)447					.await448					.map(|r| r.0)449					.map_err(Into::into);450				}451452				Err(no_runtime_err!(config.chain_spec).into())453			})454		}455	}456}457458impl DefaultConfigurationValues for RelayChainCli {459	fn p2p_listen_port() -> u16 {460		30334461	}462463	fn rpc_ws_listen_port() -> u16 {464		9945465	}466467	fn rpc_http_listen_port() -> u16 {468		9934469	}470471	fn prometheus_listen_port() -> u16 {472		9616473	}474}475476impl CliConfiguration<Self> for RelayChainCli {477	fn shared_params(&self) -> &SharedParams {478		self.base.base.shared_params()479	}480481	fn import_params(&self) -> Option<&ImportParams> {482		self.base.base.import_params()483	}484485	fn network_params(&self) -> Option<&NetworkParams> {486		self.base.base.network_params()487	}488489	fn keystore_params(&self) -> Option<&KeystoreParams> {490		self.base.base.keystore_params()491	}492493	fn base_path(&self) -> Result<Option<BasePath>> {494		Ok(self495			.shared_params()496			.base_path()497			.or_else(|| self.base_path.clone().map(Into::into)))498	}499500	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {501		self.base.base.rpc_http(default_listen_port)502	}503504	fn rpc_ipc(&self) -> Result<Option<String>> {505		self.base.base.rpc_ipc()506	}507508	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {509		self.base.base.rpc_ws(default_listen_port)510	}511512	fn prometheus_config(513		&self,514		default_listen_port: u16,515		chain_spec: &Box<dyn ChainSpec>,516	) -> Result<Option<PrometheusConfig>> {517		self.base518			.base519			.prometheus_config(default_listen_port, chain_spec)520	}521522	fn init<F>(523		&self,524		_support_url: &String,525		_impl_version: &String,526		_logger_hook: F,527		_config: &sc_service::Configuration,528	) -> Result<()> {529		unreachable!("PolkadotCli is never initialized; qed");530	}531532	fn chain_id(&self, is_dev: bool) -> Result<String> {533		let chain_id = self.base.base.chain_id(is_dev)?;534535		Ok(if chain_id.is_empty() {536			self.chain_id.clone().unwrap_or_default()537		} else {538			chain_id539		})540	}541542	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {543		self.base.base.role(is_dev)544	}545546	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {547		self.base.base.transaction_pool()548	}549550	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {551		self.base.base.state_cache_child_ratio()552	}553554	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {555		self.base.base.rpc_methods()556	}557558	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {559		self.base.base.rpc_ws_max_connections()560	}561562	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {563		self.base.base.rpc_cors(is_dev)564	}565566	fn default_heap_pages(&self) -> Result<Option<u64>> {567		self.base.base.default_heap_pages()568	}569570	fn force_authoring(&self) -> Result<bool> {571		self.base.base.force_authoring()572	}573574	fn disable_grandpa(&self) -> Result<bool> {575		self.base.base.disable_grandpa()576	}577578	fn max_runtime_instances(&self) -> Result<Option<usize>> {579		self.base.base.max_runtime_instances()580	}581582	fn announce_block(&self) -> Result<bool> {583		self.base.base.announce_block()584	}585586	fn telemetry_endpoints(587		&self,588		chain_spec: &Box<dyn ChainSpec>,589	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {590		self.base.base.telemetry_endpoints(chain_spec)591	}592}
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, 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;4647#[cfg(feature = "opal-runtime")]48use crate::service::OpalRuntimeExecutor;4950use codec::Encode;51use cumulus_primitives_core::ParaId;52use cumulus_client_service::genesis::generate_genesis_block;53use log::info;54use polkadot_parachain::primitives::AccountIdConversion;55use sc_cli::{56	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,57	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,58};59use sc_service::{60	config::{BasePath, PrometheusConfig},61};62use sp_core::hexdisplay::HexDisplay;63use sp_runtime::traits::Block as BlockT;64use std::{io::Write, net::SocketAddr};6566use unique_runtime_common::types::Block;6768macro_rules! no_runtime_err {69	($chain_spec:expr) => {70		format!(71			"No runtime valid runtime was found, chain id: {}",72			$chain_spec.id()73		)74	};75}7677fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {78	match id {79		"westend-local" => Ok(Box::new(chain_spec::local_testnet_westend_config())),80		"rococo-local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),81		"dev" => Ok(Box::new(chain_spec::development_config())),82		"" | "local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),83		path => {84			let path = std::path::PathBuf::from(path);85			let chain_spec = Box::new(86				chain_spec::UniqueChainSpec::from_json_file(path.clone())?87			) as Box<dyn sc_service::ChainSpec>;8889			#[cfg(feature = "unique-runtime")]90			if chain_spec.is_unique() {91				return Ok(chain_spec);92			}9394			#[cfg(feature = "quartz-runtime")]95			if chain_spec.is_quartz() {96				let chain_spec = chain_spec::QuartzChainSpec::from_json_file(97					path98				)?;99				return Ok(Box::new(chain_spec));100			}101102			#[cfg(feature = "opal-runtime")]103			if chain_spec.is_opal() {104				let chain_spec = chain_spec::OpalChainSpec::from_json_file(105					path106				)?;107				return Ok(Box::new(chain_spec));108			}109110			Err(no_runtime_err!(chain_spec))111		},112	}113}114115impl SubstrateCli for Cli {116	// TODO use args117	fn impl_name() -> String {118		"Unique Node".into()119	}120121	fn impl_version() -> String {122		env!("SUBSTRATE_CLI_IMPL_VERSION").into()123	}124	// TODO use args125	fn description() -> String {126		format!(127			"Unique Node\n\nThe command-line arguments provided first will be \128		passed to the parachain node, while the arguments provided after -- will be passed \129		to the relaychain node.\n\n\130		{} [parachain-args] -- [relaychain-args]",131			Self::executable_name()132		)133	}134135	fn author() -> String {136		env!("CARGO_PKG_AUTHORS").into()137	}138139	//TODO use args140	fn support_url() -> String {141		"support@unique.network".into()142	}143144	fn copyright_start_year() -> i32 {145		2019146	}147148	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {149		load_spec(id)150	}151152	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {153		#[cfg(feature = "unique-runtime")]154		if chain_spec.is_unique() {155			return &unique_runtime::VERSION;156		}157158		#[cfg(feature = "quartz-runtime")]159		if chain_spec.is_quartz() {160			return &quartz_runtime::VERSION;161		}162163		#[cfg(feature = "opal-runtime")]164		if chain_spec.is_opal() {165			return &opal_runtime::VERSION;166		}167168		panic!("{}", no_runtime_err!(chain_spec));169	}170}171172impl SubstrateCli for RelayChainCli {173	// TODO use args174	fn impl_name() -> String {175		"Unique Node".into()176	}177178	fn impl_version() -> String {179		env!("SUBSTRATE_CLI_IMPL_VERSION").into()180	}181	// TODO use args182	fn description() -> String {183		"Unique Node\n\nThe command-line arguments provided first will be \184		passed to the parachain node, while the arguments provided after -- will be passed \185		to the relaychain node.\n\n\186		parachain-collator [parachain-args] -- [relaychain-args]"187			.into()188	}189190	fn author() -> String {191		env!("CARGO_PKG_AUTHORS").into()192	}193	// TODO use args194	fn support_url() -> String {195		"support@unique.network".into()196	}197198	fn copyright_start_year() -> i32 {199		2019200	}201202	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {203		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)204	}205206	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {207		polkadot_cli::Cli::native_runtime_version(chain_spec)208	}209}210211#[allow(clippy::borrowed_box)]212fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {213	let mut storage = chain_spec.build_storage()?;214215	storage216		.top217		.remove(sp_core::storage::well_known_keys::CODE)218		.ok_or_else(|| "Could not find wasm file in genesis state!".into())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		#[cfg(feature = "unique-runtime")]226		if runner.config().chain_spec.is_unique() {227			return runner.async_run(|$config| {228				let $components = new_partial::<229					unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _230				>(231					&$config,232					crate::service::parachain_build_import_queue,233				)?;234				let task_manager = $components.task_manager;235				{ $( $code )* }.map(|v| (v, task_manager))236			});237		}238239		#[cfg(feature = "quartz-runtime")]240		if runner.config().chain_spec.is_quartz() {241			return runner.async_run(|$config| {242				let $components = new_partial::<243					quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _244				>(245					&$config,246					crate::service::parachain_build_import_queue,247				)?;248				let task_manager = $components.task_manager;249				{ $( $code )* }.map(|v| (v, task_manager))250			});251		}252253		#[cfg(feature = "opal-runtime")]254		if runner.config().chain_spec.is_opal() {255			return runner.async_run(|$config| {256				let $components = new_partial::<257					opal_runtime::RuntimeApi, OpalRuntimeExecutor, _258				>(259					&$config,260					crate::service::parachain_build_import_queue,261				)?;262				let task_manager = $components.task_manager;263				{ $( $code )* }.map(|v| (v, task_manager))264			});265		}266267		Err(no_runtime_err!(runner.config().chain_spec).into())268	}}269}270271/// Parse command line arguments into service configuration.272pub fn run() -> Result<()> {273	let cli = Cli::from_args();274275	match &cli.subcommand {276		Some(Subcommand::BuildSpec(cmd)) => {277			let runner = cli.create_runner(cmd)?;278			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))279		}280		Some(Subcommand::CheckBlock(cmd)) => {281			construct_async_run!(|components, cli, cmd, config| {282				Ok(cmd.run(components.client, components.import_queue))283			})284		}285		Some(Subcommand::ExportBlocks(cmd)) => {286			construct_async_run!(|components, cli, cmd, config| {287				Ok(cmd.run(components.client, config.database))288			})289		}290		Some(Subcommand::ExportState(cmd)) => {291			construct_async_run!(|components, cli, cmd, config| {292				Ok(cmd.run(components.client, config.chain_spec))293			})294		}295		Some(Subcommand::ImportBlocks(cmd)) => {296			construct_async_run!(|components, cli, cmd, config| {297				Ok(cmd.run(components.client, components.import_queue))298			})299		}300		Some(Subcommand::PurgeChain(cmd)) => {301			let runner = cli.create_runner(cmd)?;302303			runner.sync_run(|config| {304				let polkadot_cli = RelayChainCli::new(305					&config,306					[RelayChainCli::executable_name()]307						.iter()308						.chain(cli.relaychain_args.iter()),309				);310311				let polkadot_config = SubstrateCli::create_configuration(312					&polkadot_cli,313					&polkadot_cli,314					config.tokio_handle.clone(),315				)316				.map_err(|err| format!("Relay chain argument error: {}", err))?;317318				cmd.run(config, polkadot_config)319			})320		}321		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {322			Ok(cmd.run(components.client, components.backend))323		}),324		Some(Subcommand::ExportGenesisState(params)) => {325			let mut builder = sc_cli::LoggerBuilder::new("");326			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");327			let _ = builder.init();328329			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;330			let state_version = Cli::native_runtime_version(&spec).state_version();331			let block: Block = generate_genesis_block(&spec, state_version)?;332			let raw_header = block.header().encode();333			let output_buf = if params.raw {334				raw_header335			} else {336				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()337			};338339			if let Some(output) = &params.output {340				std::fs::write(output, output_buf)?;341			} else {342				std::io::stdout().write_all(&output_buf)?;343			}344345			Ok(())346		}347		Some(Subcommand::ExportGenesisWasm(params)) => {348			let mut builder = sc_cli::LoggerBuilder::new("");349			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");350			let _ = builder.init();351352			let raw_wasm_blob =353				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;354			let output_buf = if params.raw {355				raw_wasm_blob356			} else {357				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()358			};359360			if let Some(output) = &params.output {361				std::fs::write(output, output_buf)?;362			} else {363				std::io::stdout().write_all(&output_buf)?;364			}365366			Ok(())367		}368		Some(Subcommand::Benchmark(cmd)) => {369			if cfg!(feature = "runtime-benchmarks") {370				let runner = cli.create_runner(cmd)?;371				runner.sync_run(|config| {372					#[cfg(feature = "unique-runtime")]373					if config.chain_spec.is_unique() {374						return cmd.run::<Block, UniqueRuntimeExecutor>(config);375					}376377					#[cfg(feature = "quartz-runtime")]378					if config.chain_spec.is_quartz() {379						return cmd.run::<Block, QuartzRuntimeExecutor>(config);380					}381382					#[cfg(feature = "opal-runtime")]383					if config.chain_spec.is_opal() {384						return cmd.run::<Block, OpalRuntimeExecutor>(config);385					}386387					Err(no_runtime_err!(config.chain_spec).into())388				})389			} else {390				Err("Benchmarking wasn't enabled when building the node. \391				You can enable it with `--features runtime-benchmarks`."392					.into())393			}394		}395		None => {396			let runner = cli.create_runner(&cli.run.normalize())?;397398			runner.run_node_until_exit(|config| async move {399				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)400					.map(|e| e.para_id)401					.ok_or("Could not find parachain ID in chain-spec.")?;402403				let polkadot_cli = RelayChainCli::new(404					&config,405					[RelayChainCli::executable_name()]406						.iter()407						.chain(cli.relaychain_args.iter()),408				);409410				let id = ParaId::from(para_id);411412				let parachain_account =413					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);414415				let state_version =416					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();417				let block: Block = generate_genesis_block(&config.chain_spec, state_version)418					.map_err(|e| format!("{:?}", e))?;419				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));420				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));421422				let polkadot_config = SubstrateCli::create_configuration(423					&polkadot_cli,424					&polkadot_cli,425					config.tokio_handle.clone(),426				)427				.map_err(|err| format!("Relay chain argument error: {}", err))?;428429				info!("Parachain id: {:?}", id);430				info!("Parachain Account: {}", parachain_account);431				info!("Parachain genesis state: {}", genesis_state);432				info!("Parachain genesis hash: {}", genesis_hash);433				info!(434					"Is collating: {}",435					if config.role.is_authority() {436						"yes"437					} else {438						"no"439					}440				);441442				#[cfg(feature = "unique-runtime")]443				if config.chain_spec.is_unique() {444					return crate::service::start_node::<445						unique_runtime::Runtime,446						unique_runtime::RuntimeApi,447						UniqueRuntimeExecutor,448					>(config, polkadot_config, id)449					.await450					.map(|r| r.0)451					.map_err(Into::into);452				}453454				#[cfg(feature = "quartz-runtime")]455				if config.chain_spec.is_quartz() {456					return crate::service::start_node::<457						quartz_runtime::Runtime,458						quartz_runtime::RuntimeApi,459						QuartzRuntimeExecutor,460					>(config, polkadot_config, id)461					.await462					.map(|r| r.0)463					.map_err(Into::into);464				}465466				#[cfg(feature = "opal-runtime")]467				if config.chain_spec.is_opal() {468					return crate::service::start_node::<469						opal_runtime::Runtime,470						opal_runtime::RuntimeApi,471						OpalRuntimeExecutor,472					>(config, polkadot_config, id)473					.await474					.map(|r| r.0)475					.map_err(Into::into);476				}477478				Err(no_runtime_err!(config.chain_spec).into())479			})480		}481	}482}483484impl DefaultConfigurationValues for RelayChainCli {485	fn p2p_listen_port() -> u16 {486		30334487	}488489	fn rpc_ws_listen_port() -> u16 {490		9945491	}492493	fn rpc_http_listen_port() -> u16 {494		9934495	}496497	fn prometheus_listen_port() -> u16 {498		9616499	}500}501502impl CliConfiguration<Self> for RelayChainCli {503	fn shared_params(&self) -> &SharedParams {504		self.base.base.shared_params()505	}506507	fn import_params(&self) -> Option<&ImportParams> {508		self.base.base.import_params()509	}510511	fn network_params(&self) -> Option<&NetworkParams> {512		self.base.base.network_params()513	}514515	fn keystore_params(&self) -> Option<&KeystoreParams> {516		self.base.base.keystore_params()517	}518519	fn base_path(&self) -> Result<Option<BasePath>> {520		Ok(self521			.shared_params()522			.base_path()523			.or_else(|| self.base_path.clone().map(Into::into)))524	}525526	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {527		self.base.base.rpc_http(default_listen_port)528	}529530	fn rpc_ipc(&self) -> Result<Option<String>> {531		self.base.base.rpc_ipc()532	}533534	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {535		self.base.base.rpc_ws(default_listen_port)536	}537538	fn prometheus_config(539		&self,540		default_listen_port: u16,541		chain_spec: &Box<dyn ChainSpec>,542	) -> Result<Option<PrometheusConfig>> {543		self.base544			.base545			.prometheus_config(default_listen_port, chain_spec)546	}547548	fn init<F>(549		&self,550		_support_url: &String,551		_impl_version: &String,552		_logger_hook: F,553		_config: &sc_service::Configuration,554	) -> Result<()> {555		unreachable!("PolkadotCli is never initialized; qed");556	}557558	fn chain_id(&self, is_dev: bool) -> Result<String> {559		let chain_id = self.base.base.chain_id(is_dev)?;560561		Ok(if chain_id.is_empty() {562			self.chain_id.clone().unwrap_or_default()563		} else {564			chain_id565		})566	}567568	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {569		self.base.base.role(is_dev)570	}571572	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {573		self.base.base.transaction_pool()574	}575576	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {577		self.base.base.state_cache_child_ratio()578	}579580	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {581		self.base.base.rpc_methods()582	}583584	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {585		self.base.base.rpc_ws_max_connections()586	}587588	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {589		self.base.base.rpc_cors(is_dev)590	}591592	fn default_heap_pages(&self) -> Result<Option<u64>> {593		self.base.base.default_heap_pages()594	}595596	fn force_authoring(&self) -> Result<bool> {597		self.base.base.force_authoring()598	}599600	fn disable_grandpa(&self) -> Result<bool> {601		self.base.base.disable_grandpa()602	}603604	fn max_runtime_instances(&self) -> Result<Option<usize>> {605		self.base.base.max_runtime_instances()606	}607608	fn announce_block(&self) -> Result<bool> {609		self.base.base.announce_block()610	}611612	fn telemetry_endpoints(613		&self,614		chain_spec: &Box<dyn ChainSpec>,615	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {616		self.base.base.telemetry_endpoints(chain_spec)617	}618}