git.delta.rocks / unique-network / refs/commits / 6b7300defa13

difftreelog

source

node/cli/src/command.rs16.3 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license18// This file is part of Substrate.1920// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use crate::{36	chain_spec::{self, RuntimeId, RuntimeIdentification},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}