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

difftreelog

source

node/cli/src/command.rs12.1 KiBsourcehistory
1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718use crate::{19	chain_spec,20	cli::{Cli, RelayChainCli, Subcommand},21	service::{new_partial, ParachainRuntimeExecutor},22};23use codec::Encode;24use cumulus_primitives_core::ParaId;25use cumulus_client_service::genesis::generate_genesis_block;26use log::info;27use unique_runtime::Block;28use polkadot_parachain::primitives::AccountIdConversion;29use sc_cli::{30	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,31	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,32};33use sc_service::{34	config::{BasePath, PrometheusConfig},35};36use sp_core::hexdisplay::HexDisplay;37use sp_runtime::traits::Block as BlockT;38use std::{io::Write, net::SocketAddr};3940fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {41	Ok(match id {42		"westend-local" => Box::new(chain_spec::local_testnet_westend_config()),43		"dev" => Box::new(chain_spec::development_config()),44		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),45		path => Box::new(chain_spec::ChainSpec::from_json_file(46			std::path::PathBuf::from(path),47		)?),48	})49}5051impl SubstrateCli for Cli {52	// TODO use args53	fn impl_name() -> String {54		"Opal Node".into()55	}5657	fn impl_version() -> String {58		env!("SUBSTRATE_CLI_IMPL_VERSION").into()59	}60	// TODO use args61	fn description() -> String {62		format!(63			"Opal Node\n\nThe command-line arguments provided first will be \64		passed to the parachain node, while the arguments provided after -- will be passed \65		to the relaychain node.\n\n\66		{} [parachain-args] -- [relaychain-args]",67			Self::executable_name()68		)69	}7071	fn author() -> String {72		env!("CARGO_PKG_AUTHORS").into()73	}7475	//TODO use args76	fn support_url() -> String {77		"support@unique.network".into()78	}7980	fn copyright_start_year() -> i32 {81		201982	}8384	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {85		load_spec(id)86	}8788	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {89		&unique_runtime::VERSION90	}91}9293impl SubstrateCli for RelayChainCli {94	// TODO use args95	fn impl_name() -> String {96		"Opal Node".into()97	}9899	fn impl_version() -> String {100		env!("SUBSTRATE_CLI_IMPL_VERSION").into()101	}102	// TODO use args103	fn description() -> String {104		"Opal Node\n\nThe command-line arguments provided first will be \105		passed to the parachain node, while the arguments provided after -- will be passed \106		to the relaychain node.\n\n\107		parachain-collator [parachain-args] -- [relaychain-args]"108			.into()109	}110111	fn author() -> String {112		env!("CARGO_PKG_AUTHORS").into()113	}114	// TODO use args115	fn support_url() -> String {116		"support@unique.network".into()117	}118119	fn copyright_start_year() -> i32 {120		2019121	}122123	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {124		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)125	}126127	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {128		polkadot_cli::Cli::native_runtime_version(chain_spec)129	}130}131132#[allow(clippy::borrowed_box)]133fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {134	let mut storage = chain_spec.build_storage()?;135136	storage137		.top138		.remove(sp_core::storage::well_known_keys::CODE)139		.ok_or_else(|| "Could not find wasm file in genesis state!".into())140}141142macro_rules! construct_async_run {143	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{144		let runner = $cli.create_runner($cmd)?;145		runner.async_run(|$config| {146			let $components = new_partial::<147				_148			>(149				&$config,150				crate::service::parachain_build_import_queue,151			)?;152			let task_manager = $components.task_manager;153			{ $( $code )* }.map(|v| (v, task_manager))154		})155	}}156}157158/// Parse command line arguments into service configuration.159pub fn run() -> Result<()> {160	let cli = Cli::from_args();161162	match &cli.subcommand {163		Some(Subcommand::BuildSpec(cmd)) => {164			let runner = cli.create_runner(cmd)?;165			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))166		}167		Some(Subcommand::CheckBlock(cmd)) => {168			construct_async_run!(|components, cli, cmd, config| {169				Ok(cmd.run(components.client, components.import_queue))170			})171		}172		Some(Subcommand::ExportBlocks(cmd)) => {173			construct_async_run!(|components, cli, cmd, config| {174				Ok(cmd.run(components.client, config.database))175			})176		}177		Some(Subcommand::ExportState(cmd)) => {178			construct_async_run!(|components, cli, cmd, config| {179				Ok(cmd.run(components.client, config.chain_spec))180			})181		}182		Some(Subcommand::ImportBlocks(cmd)) => {183			construct_async_run!(|components, cli, cmd, config| {184				Ok(cmd.run(components.client, components.import_queue))185			})186		}187		Some(Subcommand::PurgeChain(cmd)) => {188			let runner = cli.create_runner(cmd)?;189190			runner.sync_run(|config| {191				let polkadot_cli = RelayChainCli::new(192					&config,193					[RelayChainCli::executable_name()]194						.iter()195						.chain(cli.relaychain_args.iter()),196				);197198				let polkadot_config = SubstrateCli::create_configuration(199					&polkadot_cli,200					&polkadot_cli,201					config.tokio_handle.clone(),202				)203				.map_err(|err| format!("Relay chain argument error: {}", err))?;204205				cmd.run(config, polkadot_config)206			})207		}208		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {209			Ok(cmd.run(components.client, components.backend))210		}),211		Some(Subcommand::ExportGenesisState(params)) => {212			let mut builder = sc_cli::LoggerBuilder::new("");213			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");214			let _ = builder.init();215216			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;217			let state_version = Cli::native_runtime_version(&spec).state_version();218			let block: Block = generate_genesis_block(&spec, state_version)?;219			let raw_header = block.header().encode();220			let output_buf = if params.raw {221				raw_header222			} else {223				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()224			};225226			if let Some(output) = &params.output {227				std::fs::write(output, output_buf)?;228			} else {229				std::io::stdout().write_all(&output_buf)?;230			}231232			Ok(())233		}234		Some(Subcommand::ExportGenesisWasm(params)) => {235			let mut builder = sc_cli::LoggerBuilder::new("");236			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");237			let _ = builder.init();238239			let raw_wasm_blob =240				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;241			let output_buf = if params.raw {242				raw_wasm_blob243			} else {244				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()245			};246247			if let Some(output) = &params.output {248				std::fs::write(output, output_buf)?;249			} else {250				std::io::stdout().write_all(&output_buf)?;251			}252253			Ok(())254		}255		Some(Subcommand::Benchmark(cmd)) => {256			if cfg!(feature = "runtime-benchmarks") {257				let runner = cli.create_runner(cmd)?;258259				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))260			} else {261				Err("Benchmarking wasn't enabled when building the node. \262				You can enable it with `--features runtime-benchmarks`."263					.into())264			}265		}266		None => {267			let runner = cli.create_runner(&cli.run.normalize())?;268269			runner.run_node_until_exit(|config| async move {270				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)271					.map(|e| e.para_id)272					.ok_or("Could not find parachain ID in chain-spec.")?;273274				let polkadot_cli = RelayChainCli::new(275					&config,276					[RelayChainCli::executable_name()]277						.iter()278						.chain(cli.relaychain_args.iter()),279				);280281				let id = ParaId::from(para_id);282283				let parachain_account =284					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);285286				let state_version =287					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();288				let block: Block = generate_genesis_block(&config.chain_spec, state_version)289					.map_err(|e| format!("{:?}", e))?;290				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));291292				let polkadot_config = SubstrateCli::create_configuration(293					&polkadot_cli,294					&polkadot_cli,295					config.tokio_handle.clone(),296				)297				.map_err(|err| format!("Relay chain argument error: {}", err))?;298299				info!("Parachain id: {:?}", id);300				info!("Parachain Account: {}", parachain_account);301				info!("Parachain genesis state: {}", genesis_state);302				info!(303					"Is collating: {}",304					if config.role.is_authority() {305						"yes"306					} else {307						"no"308					}309				);310311				crate::service::start_node(config, polkadot_config, id)312					.await313					.map(|r| r.0)314					.map_err(Into::into)315			})316		}317	}318}319320impl DefaultConfigurationValues for RelayChainCli {321	fn p2p_listen_port() -> u16 {322		30334323	}324325	fn rpc_ws_listen_port() -> u16 {326		9945327	}328329	fn rpc_http_listen_port() -> u16 {330		9934331	}332333	fn prometheus_listen_port() -> u16 {334		9616335	}336}337338impl CliConfiguration<Self> for RelayChainCli {339	fn shared_params(&self) -> &SharedParams {340		self.base.base.shared_params()341	}342343	fn import_params(&self) -> Option<&ImportParams> {344		self.base.base.import_params()345	}346347	fn network_params(&self) -> Option<&NetworkParams> {348		self.base.base.network_params()349	}350351	fn keystore_params(&self) -> Option<&KeystoreParams> {352		self.base.base.keystore_params()353	}354355	fn base_path(&self) -> Result<Option<BasePath>> {356		Ok(self357			.shared_params()358			.base_path()359			.or_else(|| self.base_path.clone().map(Into::into)))360	}361362	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {363		self.base.base.rpc_http(default_listen_port)364	}365366	fn rpc_ipc(&self) -> Result<Option<String>> {367		self.base.base.rpc_ipc()368	}369370	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {371		self.base.base.rpc_ws(default_listen_port)372	}373374	fn prometheus_config(375		&self,376		default_listen_port: u16,377		chain_spec: &Box<dyn ChainSpec>,378	) -> Result<Option<PrometheusConfig>> {379		self.base380			.base381			.prometheus_config(default_listen_port, chain_spec)382	}383384	fn init<F>(385		&self,386		_support_url: &String,387		_impl_version: &String,388		_logger_hook: F,389		_config: &sc_service::Configuration,390	) -> Result<()> {391		unreachable!("PolkadotCli is never initialized; qed");392	}393394	fn chain_id(&self, is_dev: bool) -> Result<String> {395		let chain_id = self.base.base.chain_id(is_dev)?;396397		Ok(if chain_id.is_empty() {398			self.chain_id.clone().unwrap_or_default()399		} else {400			chain_id401		})402	}403404	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {405		self.base.base.role(is_dev)406	}407408	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {409		self.base.base.transaction_pool()410	}411412	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {413		self.base.base.state_cache_child_ratio()414	}415416	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {417		self.base.base.rpc_methods()418	}419420	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {421		self.base.base.rpc_ws_max_connections()422	}423424	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {425		self.base.base.rpc_cors(is_dev)426	}427428	fn default_heap_pages(&self) -> Result<Option<u64>> {429		self.base.base.default_heap_pages()430	}431432	fn force_authoring(&self) -> Result<bool> {433		self.base.base.force_authoring()434	}435436	fn disable_grandpa(&self) -> Result<bool> {437		self.base.base.disable_grandpa()438	}439440	fn max_runtime_instances(&self) -> Result<Option<usize>> {441		self.base.base.max_runtime_instances()442	}443444	fn announce_block(&self) -> Result<bool> {445		self.base.base.announce_block()446	}447448	fn telemetry_endpoints(449		&self,450		chain_spec: &Box<dyn ChainSpec>,451	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {452		self.base.base.telemetry_endpoints(chain_spec)453	}454}