git.delta.rocks / unique-network / refs/commits / d6d871a1e073

difftreelog

source

node/cli/src/command.rs19.1 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::{37		self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification, default_runtime,38	},39	cli::{Cli, RelayChainCli, Subcommand},40	service::{new_partial, start_node, start_dev_node},41};4243#[cfg(feature = "unique-runtime")]44use crate::service::UniqueRuntimeExecutor;4546#[cfg(feature = "quartz-runtime")]47use crate::service::QuartzRuntimeExecutor;4849use crate::service::{OpalRuntimeExecutor, DefaultRuntimeExecutor};5051use codec::Encode;52use cumulus_primitives_core::ParaId;53use cumulus_client_service::genesis::generate_genesis_block;54use std::{future::Future, pin::Pin};55use log::info;56use polkadot_parachain::primitives::AccountIdConversion;57use sc_cli::{58	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,59	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,60};61use sc_service::{62	config::{BasePath, PrometheusConfig},63};64use sp_core::hexdisplay::HexDisplay;65use sp_runtime::traits::Block as BlockT;66use std::{io::Write, net::SocketAddr, time::Duration};6768use unique_runtime_common::types::Block;6970macro_rules! no_runtime_err {71	($chain_name:expr) => {72		format!(73			"No runtime valid runtime was found for chain {}",74			$chain_name75		)76	};77}7879fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {80	Ok(match id {81		"dev" => Box::new(chain_spec::development_config()),82		"" | "local" => Box::new(chain_spec::local_testnet_config()),83		path => {84			let path = std::path::PathBuf::from(path);85			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(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 => chain_spec,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		format!("{} Node", Self::node_name())106	}107108	fn impl_version() -> String {109		env!("SUBSTRATE_CLI_IMPL_VERSION").into()110	}111	// TODO use args112	fn description() -> String {113		format!(114			"{} 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::node_name(),119			Self::executable_name()120		)121	}122123	fn author() -> String {124		env!("CARGO_PKG_AUTHORS").into()125	}126127	//TODO use args128	fn support_url() -> String {129		"support@unique.network".into()130	}131132	fn copyright_start_year() -> i32 {133		2019134	}135136	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {137		load_spec(id)138	}139140	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {141		match chain_spec.runtime_id() {142			#[cfg(feature = "unique-runtime")]143			RuntimeId::Unique => &unique_runtime::VERSION,144145			#[cfg(feature = "quartz-runtime")]146			RuntimeId::Quartz => &quartz_runtime::VERSION,147148			RuntimeId::Opal => &opal_runtime::VERSION,149			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),150		}151	}152}153154impl SubstrateCli for RelayChainCli {155	// TODO use args156	fn impl_name() -> String {157		format!("{} Node", Cli::node_name())158	}159160	fn impl_version() -> String {161		env!("SUBSTRATE_CLI_IMPL_VERSION").into()162	}163	// TODO use args164	fn description() -> String {165		format!(166			"{} Node\n\nThe command-line arguments provided first will be \167			passed to the parachain node, while the arguments provided after -- will be passed \168			to the relaychain node.\n\n\169			parachain-collator [parachain-args] -- [relaychain-args]",170			Cli::node_name()171		)172	}173174	fn author() -> String {175		env!("CARGO_PKG_AUTHORS").into()176	}177	// TODO use args178	fn support_url() -> String {179		"support@unique.network".into()180	}181182	fn copyright_start_year() -> i32 {183		2019184	}185186	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {187		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)188	}189190	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {191		polkadot_cli::Cli::native_runtime_version(chain_spec)192	}193}194195#[allow(clippy::borrowed_box)]196fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {197	let mut storage = chain_spec.build_storage()?;198199	storage200		.top201		.remove(sp_core::storage::well_known_keys::CODE)202		.ok_or_else(|| "Could not find wasm file in genesis state!".into())203}204205macro_rules! async_run_with_runtime {206	(207		$runtime_api:path, $executor:path,208		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,209		$( $code:tt )*210	) => {211		$runner.async_run(|$config| {212			let $components = new_partial::<213				$runtime_api, $executor, _214			>(215				&$config,216				crate::service::parachain_build_import_queue,217			)?;218			let task_manager = $components.task_manager;219220			{ $( $code )* }.map(|v| (v, task_manager))221		})222	};223}224225macro_rules! construct_async_run {226	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{227		let runner = $cli.create_runner($cmd)?;228229		match runner.config().chain_spec.runtime_id() {230			#[cfg(feature = "unique-runtime")]231			RuntimeId::Unique => async_run_with_runtime!(232				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,233				runner, $components, $cli, $cmd, $config, $( $code )*234			),235236			#[cfg(feature = "quartz-runtime")]237			RuntimeId::Quartz => async_run_with_runtime!(238				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,239				runner, $components, $cli, $cmd, $config, $( $code )*240			),241242			RuntimeId::Opal => async_run_with_runtime!(243				opal_runtime::RuntimeApi, OpalRuntimeExecutor,244				runner, $components, $cli, $cmd, $config, $( $code )*245			),246247			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())248		}249	}}250}251252macro_rules! start_node_using_chain_runtime {253	($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {254		match $config.chain_spec.runtime_id() {255			#[cfg(feature = "unique-runtime")]256			RuntimeId::Unique => $start_node_fn::<257				unique_runtime::Runtime,258				unique_runtime::RuntimeApi,259				UniqueRuntimeExecutor,260			>($config $(, $($args),+)?) $($code)*,261262			#[cfg(feature = "quartz-runtime")]263			RuntimeId::Quartz => $start_node_fn::<264				quartz_runtime::Runtime,265				quartz_runtime::RuntimeApi,266				QuartzRuntimeExecutor,267			>($config $(, $($args),+)?) $($code)*,268269			RuntimeId::Opal => $start_node_fn::<270				opal_runtime::Runtime,271				opal_runtime::RuntimeApi,272				OpalRuntimeExecutor,273			>($config $(, $($args),+)?) $($code)*,274275			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),276		}277	};278}279280/// Parse command line arguments into service configuration.281pub fn run() -> Result<()> {282	let cli = Cli::from_args();283284	match &cli.subcommand {285		Some(Subcommand::BuildSpec(cmd)) => {286			let runner = cli.create_runner(cmd)?;287			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))288		}289		Some(Subcommand::CheckBlock(cmd)) => {290			construct_async_run!(|components, cli, cmd, config| {291				Ok(cmd.run(components.client, components.import_queue))292			})293		}294		Some(Subcommand::ExportBlocks(cmd)) => {295			construct_async_run!(|components, cli, cmd, config| {296				Ok(cmd.run(components.client, config.database))297			})298		}299		Some(Subcommand::ExportState(cmd)) => {300			construct_async_run!(|components, cli, cmd, config| {301				Ok(cmd.run(components.client, config.chain_spec))302			})303		}304		Some(Subcommand::ImportBlocks(cmd)) => {305			construct_async_run!(|components, cli, cmd, config| {306				Ok(cmd.run(components.client, components.import_queue))307			})308		}309		Some(Subcommand::PurgeChain(cmd)) => {310			let runner = cli.create_runner(cmd)?;311312			runner.sync_run(|config| {313				let polkadot_cli = RelayChainCli::new(314					&config,315					[RelayChainCli::executable_name()]316						.iter()317						.chain(cli.relaychain_args.iter()),318				);319320				let polkadot_config = SubstrateCli::create_configuration(321					&polkadot_cli,322					&polkadot_cli,323					config.tokio_handle.clone(),324				)325				.map_err(|err| format!("Relay chain argument error: {}", err))?;326327				cmd.run(config, polkadot_config)328			})329		}330		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {331			Ok(cmd.run(components.client, components.backend, None))332		}),333		Some(Subcommand::ExportGenesisState(params)) => {334			let mut builder = sc_cli::LoggerBuilder::new("");335			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");336			let _ = builder.init();337338			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;339			let state_version = Cli::native_runtime_version(&spec).state_version();340			let block: Block = generate_genesis_block(&spec, state_version)?;341			let raw_header = block.header().encode();342			let output_buf = if params.raw {343				raw_header344			} else {345				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()346			};347348			if let Some(output) = &params.output {349				std::fs::write(output, output_buf)?;350			} else {351				std::io::stdout().write_all(&output_buf)?;352			}353354			Ok(())355		}356		Some(Subcommand::ExportGenesisWasm(params)) => {357			let mut builder = sc_cli::LoggerBuilder::new("");358			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");359			let _ = builder.init();360361			let raw_wasm_blob =362				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;363			let output_buf = if params.raw {364				raw_wasm_blob365			} else {366				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()367			};368369			if let Some(output) = &params.output {370				std::fs::write(output, output_buf)?;371			} else {372				std::io::stdout().write_all(&output_buf)?;373			}374375			Ok(())376		}377		Some(Subcommand::Benchmark(cmd)) => {378			use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};379			let runner = cli.create_runner(cmd)?;380			// Switch on the concrete benchmark sub-command-381			match cmd {382				BenchmarkCmd::Pallet(cmd) => {383					if cfg!(feature = "runtime-benchmarks") {384						runner.sync_run(|config| cmd.run::<Block, DefaultRuntimeExecutor>(config))385					} else {386						Err("Benchmarking wasn't enabled when building the node. \387					You can enable it with `--features runtime-benchmarks`."388							.into())389					}390				}391				BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {392					let partials = new_partial::<393						default_runtime::RuntimeApi,394						DefaultRuntimeExecutor,395						_,396					>(&config, crate::service::parachain_build_import_queue)?;397					cmd.run(partials.client)398				}),399				BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {400					let partials = new_partial::<401						default_runtime::RuntimeApi,402						DefaultRuntimeExecutor,403						_,404					>(&config, crate::service::parachain_build_import_queue)?;405					let db = partials.backend.expose_db();406					let storage = partials.backend.expose_storage();407408					cmd.run(config, partials.client.clone(), db, storage)409				}),410				BenchmarkCmd::Machine(cmd) => {411					runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))412				}413				BenchmarkCmd::Overhead(_) => Err("Unsupported benchmarking command".into()),414			}415		}416		Some(Subcommand::TryRuntime(cmd)) => {417			if cfg!(feature = "try-runtime") {418				let runner = cli.create_runner(cmd)?;419420				// grab the task manager.421				let registry = &runner422					.config()423					.prometheus_config424					.as_ref()425					.map(|cfg| &cfg.registry);426				let task_manager =427					sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)428						.map_err(|e| format!("Error: {:?}", e))?;429430				runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {431					Ok((432						match config.chain_spec.runtime_id() {433							#[cfg(feature = "unique-runtime")]434							RuntimeId::Unique => Box::pin(cmd.run::<Block, UniqueRuntimeExecutor>(config)),435436							#[cfg(feature = "quartz-runtime")]437							RuntimeId::Quartz => Box::pin(cmd.run::<Block, QuartzRuntimeExecutor>(config)),438439							RuntimeId::Opal => {440								Box::pin(cmd.run::<Block, OpalRuntimeExecutor>(config))441							}442							RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),443						},444						task_manager,445					))446				})447			} else {448				Err("Try-runtime must be enabled by `--features try-runtime`.".into())449			}450		}451		None => {452			let runner = cli.create_runner(&cli.run.normalize())?;453			let collator_options = cli.run.collator_options();454455			runner.run_node_until_exit(|config| async move {456				let hwbench = if !cli.no_hardware_benchmarks {457					config.database.path().map(|database_path| {458						let _ = std::fs::create_dir_all(&database_path);459						sc_sysinfo::gather_hwbench(Some(database_path))460					})461				} else {462					None463				};464465				let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);466467				let service_id = config.chain_spec.service_id();468				let relay_chain_id = extensions.map(|e| e.relay_chain.clone());469				let is_dev_service = matches![service_id, ServiceId::Dev]470					|| relay_chain_id == Some("dev-service".into());471472				if is_dev_service {473					info!("Running Dev service");474475					let autoseal_interval = Duration::from_millis(cli.idle_autoseal_interval);476477					return start_node_using_chain_runtime! {478						start_dev_node(config, autoseal_interval).map_err(Into::into)479					};480				};481482				let para_id = extensions483					.map(|e| e.para_id)484					.ok_or("Could not find parachain ID in chain-spec.")?;485486				let polkadot_cli = RelayChainCli::new(487					&config,488					[RelayChainCli::executable_name()]489						.iter()490						.chain(cli.relaychain_args.iter()),491				);492493				let para_id = ParaId::from(para_id);494495				let parachain_account =496					AccountIdConversion::<polkadot_primitives::v2::AccountId>::into_account(497						&para_id,498					);499500				let state_version =501					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();502				let block: Block = generate_genesis_block(&config.chain_spec, state_version)503					.map_err(|e| format!("{:?}", e))?;504				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));505				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));506507				let polkadot_config = SubstrateCli::create_configuration(508					&polkadot_cli,509					&polkadot_cli,510					config.tokio_handle.clone(),511				)512				.map_err(|err| format!("Relay chain argument error: {}", err))?;513514				info!("Parachain id: {:?}", para_id);515				info!("Parachain Account: {}", parachain_account);516				info!("Parachain genesis state: {}", genesis_state);517				info!("Parachain genesis hash: {}", genesis_hash);518				info!(519					"Is collating: {}",520					if config.role.is_authority() {521						"yes"522					} else {523						"no"524					}525				);526527				start_node_using_chain_runtime! {528					start_node(config, polkadot_config, collator_options, para_id, hwbench)529						.await530						.map(|r| r.0)531						.map_err(Into::into)532				}533			})534		}535	}536}537538impl DefaultConfigurationValues for RelayChainCli {539	fn p2p_listen_port() -> u16 {540		30334541	}542543	fn rpc_ws_listen_port() -> u16 {544		9945545	}546547	fn rpc_http_listen_port() -> u16 {548		9934549	}550551	fn prometheus_listen_port() -> u16 {552		9616553	}554}555556impl CliConfiguration<Self> for RelayChainCli {557	fn shared_params(&self) -> &SharedParams {558		self.base.base.shared_params()559	}560561	fn import_params(&self) -> Option<&ImportParams> {562		self.base.base.import_params()563	}564565	fn network_params(&self) -> Option<&NetworkParams> {566		self.base.base.network_params()567	}568569	fn keystore_params(&self) -> Option<&KeystoreParams> {570		self.base.base.keystore_params()571	}572573	fn base_path(&self) -> Result<Option<BasePath>> {574		Ok(self575			.shared_params()576			.base_path()577			.or_else(|| self.base_path.clone().map(Into::into)))578	}579580	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {581		self.base.base.rpc_http(default_listen_port)582	}583584	fn rpc_ipc(&self) -> Result<Option<String>> {585		self.base.base.rpc_ipc()586	}587588	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {589		self.base.base.rpc_ws(default_listen_port)590	}591592	fn prometheus_config(593		&self,594		default_listen_port: u16,595		chain_spec: &Box<dyn ChainSpec>,596	) -> Result<Option<PrometheusConfig>> {597		self.base598			.base599			.prometheus_config(default_listen_port, chain_spec)600	}601602	fn init<F>(603		&self,604		_support_url: &String,605		_impl_version: &String,606		_logger_hook: F,607		_config: &sc_service::Configuration,608	) -> Result<()> {609		unreachable!("PolkadotCli is never initialized; qed");610	}611612	fn chain_id(&self, is_dev: bool) -> Result<String> {613		let chain_id = self.base.base.chain_id(is_dev)?;614615		Ok(if chain_id.is_empty() {616			self.chain_id.clone().unwrap_or_default()617		} else {618			chain_id619		})620	}621622	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {623		self.base.base.role(is_dev)624	}625626	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {627		self.base.base.transaction_pool()628	}629630	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {631		self.base.base.state_cache_child_ratio()632	}633634	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {635		self.base.base.rpc_methods()636	}637638	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {639		self.base.base.rpc_ws_max_connections()640	}641642	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {643		self.base.base.rpc_cors(is_dev)644	}645646	fn default_heap_pages(&self) -> Result<Option<u64>> {647		self.base.base.default_heap_pages()648	}649650	fn force_authoring(&self) -> Result<bool> {651		self.base.base.force_authoring()652	}653654	fn disable_grandpa(&self) -> Result<bool> {655		self.base.base.disable_grandpa()656	}657658	fn max_runtime_instances(&self) -> Result<Option<usize>> {659		self.base.base.max_runtime_instances()660	}661662	fn announce_block(&self) -> Result<bool> {663		self.base.base.announce_block()664	}665666	fn telemetry_endpoints(667		&self,668		chain_spec: &Box<dyn ChainSpec>,669	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {670		self.base.base.telemetry_endpoints(chain_spec)671	}672}