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

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, 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}