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

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(path.clone())?)85				as Box<dyn sc_service::ChainSpec>;8687			match chain_spec.runtime_id() {88				#[cfg(feature = "unique-runtime")]89				RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),9091				#[cfg(feature = "quartz-runtime")]92				RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9394				RuntimeId::Opal => chain_spec,95				RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),96			}97		}98	})99}100101impl SubstrateCli for Cli {102	// TODO use args103	fn impl_name() -> String {104		"Unique Node".into()105	}106107	fn impl_version() -> String {108		env!("SUBSTRATE_CLI_IMPL_VERSION").into()109	}110	// TODO use args111	fn description() -> String {112		format!(113			"Unique Node\n\nThe command-line arguments provided first will be \114		passed to the parachain node, while the arguments provided after -- will be passed \115		to the relaychain node.\n\n\116		{} [parachain-args] -- [relaychain-args]",117			Self::executable_name()118		)119	}120121	fn author() -> String {122		env!("CARGO_PKG_AUTHORS").into()123	}124125	//TODO use args126	fn support_url() -> String {127		"support@unique.network".into()128	}129130	fn copyright_start_year() -> i32 {131		2019132	}133134	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {135		load_spec(id)136	}137138	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {139		match chain_spec.runtime_id() {140			#[cfg(feature = "unique-runtime")]141			RuntimeId::Unique => &unique_runtime::VERSION,142143			#[cfg(feature = "quartz-runtime")]144			RuntimeId::Quartz => &quartz_runtime::VERSION,145146			RuntimeId::Opal => &opal_runtime::VERSION,147			RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),148		}149	}150}151152impl SubstrateCli for RelayChainCli {153	// TODO use args154	fn impl_name() -> String {155		"Unique Node".into()156	}157158	fn impl_version() -> String {159		env!("SUBSTRATE_CLI_IMPL_VERSION").into()160	}161	// TODO use args162	fn description() -> String {163		"Unique Node\n\nThe command-line arguments provided first will be \164		passed to the parachain node, while the arguments provided after -- will be passed \165		to the relaychain node.\n\n\166		parachain-collator [parachain-args] -- [relaychain-args]"167			.into()168	}169170	fn author() -> String {171		env!("CARGO_PKG_AUTHORS").into()172	}173	// TODO use args174	fn support_url() -> String {175		"support@unique.network".into()176	}177178	fn copyright_start_year() -> i32 {179		2019180	}181182	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {183		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)184	}185186	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {187		polkadot_cli::Cli::native_runtime_version(chain_spec)188	}189}190191#[allow(clippy::borrowed_box)]192fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {193	let mut storage = chain_spec.build_storage()?;194195	storage196		.top197		.remove(sp_core::storage::well_known_keys::CODE)198		.ok_or_else(|| "Could not find wasm file in genesis state!".into())199}200201macro_rules! async_run_with_runtime {202	(203		$runtime_api:path, $executor:path,204		$runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,205		$( $code:tt )*206	) => {207		$runner.async_run(|$config| {208			let $components = new_partial::<209				$runtime_api, $executor, _210			>(211				&$config,212				crate::service::parachain_build_import_queue,213			)?;214			let task_manager = $components.task_manager;215216			{ $( $code )* }.map(|v| (v, task_manager))217		})218	};219}220221macro_rules! construct_async_run {222	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{223		let runner = $cli.create_runner($cmd)?;224225		match runner.config().chain_spec.runtime_id() {226			#[cfg(feature = "unique-runtime")]227			RuntimeId::Unique => async_run_with_runtime!(228				unique_runtime::RuntimeApi, UniqueRuntimeExecutor,229				runner, $components, $cli, $cmd, $config, $( $code )*230			),231232			#[cfg(feature = "quartz-runtime")]233			RuntimeId::Quartz => async_run_with_runtime!(234				quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,235				runner, $components, $cli, $cmd, $config, $( $code )*236			),237238			RuntimeId::Opal => async_run_with_runtime!(239				opal_runtime::RuntimeApi, OpalRuntimeExecutor,240				runner, $components, $cli, $cmd, $config, $( $code )*241			),242243			RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())244		}245	}}246}247248/// Parse command line arguments into service configuration.249pub fn run() -> Result<()> {250	let cli = Cli::from_args();251252	match &cli.subcommand {253		Some(Subcommand::BuildSpec(cmd)) => {254			let runner = cli.create_runner(cmd)?;255			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))256		}257		Some(Subcommand::CheckBlock(cmd)) => {258			construct_async_run!(|components, cli, cmd, config| {259				Ok(cmd.run(components.client, components.import_queue))260			})261		}262		Some(Subcommand::ExportBlocks(cmd)) => {263			construct_async_run!(|components, cli, cmd, config| {264				Ok(cmd.run(components.client, config.database))265			})266		}267		Some(Subcommand::ExportState(cmd)) => {268			construct_async_run!(|components, cli, cmd, config| {269				Ok(cmd.run(components.client, config.chain_spec))270			})271		}272		Some(Subcommand::ImportBlocks(cmd)) => {273			construct_async_run!(|components, cli, cmd, config| {274				Ok(cmd.run(components.client, components.import_queue))275			})276		}277		Some(Subcommand::PurgeChain(cmd)) => {278			let runner = cli.create_runner(cmd)?;279280			runner.sync_run(|config| {281				let polkadot_cli = RelayChainCli::new(282					&config,283					[RelayChainCli::executable_name()]284						.iter()285						.chain(cli.relaychain_args.iter()),286				);287288				let polkadot_config = SubstrateCli::create_configuration(289					&polkadot_cli,290					&polkadot_cli,291					config.tokio_handle.clone(),292				)293				.map_err(|err| format!("Relay chain argument error: {}", err))?;294295				cmd.run(config, polkadot_config)296			})297		}298		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {299			Ok(cmd.run(components.client, components.backend))300		}),301		Some(Subcommand::ExportGenesisState(params)) => {302			let mut builder = sc_cli::LoggerBuilder::new("");303			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");304			let _ = builder.init();305306			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;307			let state_version = Cli::native_runtime_version(&spec).state_version();308			let block: Block = generate_genesis_block(&spec, state_version)?;309			let raw_header = block.header().encode();310			let output_buf = if params.raw {311				raw_header312			} else {313				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()314			};315316			if let Some(output) = &params.output {317				std::fs::write(output, output_buf)?;318			} else {319				std::io::stdout().write_all(&output_buf)?;320			}321322			Ok(())323		}324		Some(Subcommand::ExportGenesisWasm(params)) => {325			let mut builder = sc_cli::LoggerBuilder::new("");326			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");327			let _ = builder.init();328329			let raw_wasm_blob =330				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;331			let output_buf = if params.raw {332				raw_wasm_blob333			} else {334				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()335			};336337			if let Some(output) = &params.output {338				std::fs::write(output, output_buf)?;339			} else {340				std::io::stdout().write_all(&output_buf)?;341			}342343			Ok(())344		}345		Some(Subcommand::Benchmark(cmd)) => {346			if cfg!(feature = "runtime-benchmarks") {347				let runner = cli.create_runner(cmd)?;348				runner.sync_run(|config| match config.chain_spec.runtime_id() {349					#[cfg(feature = "unique-runtime")]350					RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),351352					#[cfg(feature = "quartz-runtime")]353					RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),354355					RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),356					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),357				})358			} else {359				Err("Benchmarking wasn't enabled when building the node. \360				You can enable it with `--features runtime-benchmarks`."361					.into())362			}363		}364		None => {365			let runner = cli.create_runner(&cli.run.normalize())?;366367			runner.run_node_until_exit(|config| async move {368				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)369					.map(|e| e.para_id)370					.ok_or("Could not find parachain ID in chain-spec.")?;371372				let polkadot_cli = RelayChainCli::new(373					&config,374					[RelayChainCli::executable_name()]375						.iter()376						.chain(cli.relaychain_args.iter()),377				);378379				let id = ParaId::from(para_id);380381				let parachain_account =382					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);383384				let state_version =385					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();386				let block: Block = generate_genesis_block(&config.chain_spec, state_version)387					.map_err(|e| format!("{:?}", e))?;388				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));389				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));390391				let polkadot_config = SubstrateCli::create_configuration(392					&polkadot_cli,393					&polkadot_cli,394					config.tokio_handle.clone(),395				)396				.map_err(|err| format!("Relay chain argument error: {}", err))?;397398				info!("Parachain id: {:?}", id);399				info!("Parachain Account: {}", parachain_account);400				info!("Parachain genesis state: {}", genesis_state);401				info!("Parachain genesis hash: {}", genesis_hash);402				info!(403					"Is collating: {}",404					if config.role.is_authority() {405						"yes"406					} else {407						"no"408					}409				);410411				match config.chain_spec.runtime_id() {412					#[cfg(feature = "unique-runtime")]413					RuntimeId::Unique => crate::service::start_node::<414						unique_runtime::Runtime,415						unique_runtime::RuntimeApi,416						UniqueRuntimeExecutor,417					>(config, polkadot_config, id)418					.await419					.map(|r| r.0)420					.map_err(Into::into),421422					#[cfg(feature = "quartz-runtime")]423					RuntimeId::Quartz => crate::service::start_node::<424						quartz_runtime::Runtime,425						quartz_runtime::RuntimeApi,426						QuartzRuntimeExecutor,427					>(config, polkadot_config, id)428					.await429					.map(|r| r.0)430					.map_err(Into::into),431432					RuntimeId::Opal => crate::service::start_node::<433						opal_runtime::Runtime,434						opal_runtime::RuntimeApi,435						OpalRuntimeExecutor,436					>(config, polkadot_config, id)437					.await438					.map(|r| r.0)439					.map_err(Into::into),440441					RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),442				}443			})444		}445	}446}447448impl DefaultConfigurationValues for RelayChainCli {449	fn p2p_listen_port() -> u16 {450		30334451	}452453	fn rpc_ws_listen_port() -> u16 {454		9945455	}456457	fn rpc_http_listen_port() -> u16 {458		9934459	}460461	fn prometheus_listen_port() -> u16 {462		9616463	}464}465466impl CliConfiguration<Self> for RelayChainCli {467	fn shared_params(&self) -> &SharedParams {468		self.base.base.shared_params()469	}470471	fn import_params(&self) -> Option<&ImportParams> {472		self.base.base.import_params()473	}474475	fn network_params(&self) -> Option<&NetworkParams> {476		self.base.base.network_params()477	}478479	fn keystore_params(&self) -> Option<&KeystoreParams> {480		self.base.base.keystore_params()481	}482483	fn base_path(&self) -> Result<Option<BasePath>> {484		Ok(self485			.shared_params()486			.base_path()487			.or_else(|| self.base_path.clone().map(Into::into)))488	}489490	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {491		self.base.base.rpc_http(default_listen_port)492	}493494	fn rpc_ipc(&self) -> Result<Option<String>> {495		self.base.base.rpc_ipc()496	}497498	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {499		self.base.base.rpc_ws(default_listen_port)500	}501502	fn prometheus_config(503		&self,504		default_listen_port: u16,505		chain_spec: &Box<dyn ChainSpec>,506	) -> Result<Option<PrometheusConfig>> {507		self.base508			.base509			.prometheus_config(default_listen_port, chain_spec)510	}511512	fn init<F>(513		&self,514		_support_url: &String,515		_impl_version: &String,516		_logger_hook: F,517		_config: &sc_service::Configuration,518	) -> Result<()> {519		unreachable!("PolkadotCli is never initialized; qed");520	}521522	fn chain_id(&self, is_dev: bool) -> Result<String> {523		let chain_id = self.base.base.chain_id(is_dev)?;524525		Ok(if chain_id.is_empty() {526			self.chain_id.clone().unwrap_or_default()527		} else {528			chain_id529		})530	}531532	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {533		self.base.base.role(is_dev)534	}535536	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {537		self.base.base.transaction_pool()538	}539540	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {541		self.base.base.state_cache_child_ratio()542	}543544	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {545		self.base.base.rpc_methods()546	}547548	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {549		self.base.base.rpc_ws_max_connections()550	}551552	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {553		self.base.base.rpc_cors(is_dev)554	}555556	fn default_heap_pages(&self) -> Result<Option<u64>> {557		self.base.base.default_heap_pages()558	}559560	fn force_authoring(&self) -> Result<bool> {561		self.base.base.force_authoring()562	}563564	fn disable_grandpa(&self) -> Result<bool> {565		self.base.base.disable_grandpa()566	}567568	fn max_runtime_instances(&self) -> Result<Option<usize>> {569		self.base.base.max_runtime_instances()570	}571572	fn announce_block(&self) -> Result<bool> {573		self.base.base.announce_block()574	}575576	fn telemetry_endpoints(577		&self,578		chain_spec: &Box<dyn ChainSpec>,579	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {580		self.base.base.telemetry_endpoints(chain_spec)581	}582}