git.delta.rocks / unique-network / refs/commits / 8484aa77f543

difftreelog

source

node/cli/src/command.rs12.0 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 nft_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(41	id: &str,42	para_id: ParaId,43) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {44	Ok(match id {45		"dev" => Box::new(chain_spec::development_config(para_id)),46		"" | "local" => Box::new(chain_spec::local_testnet_config(para_id)),47		path => Box::new(chain_spec::ChainSpec::from_json_file(48			std::path::PathBuf::from(path),49		)?),50	})51}5253impl SubstrateCli for Cli {54	// TODO use args55	fn impl_name() -> String {56		"Opal Node".into()57	}5859	fn impl_version() -> String {60		env!("SUBSTRATE_CLI_IMPL_VERSION").into()61	}62	// TODO use args63	fn description() -> String {64		format!(65			"Opal Node\n\nThe command-line arguments provided first will be \66		passed to the parachain node, while the arguments provided after -- will be passed \67		to the relaychain node.\n\n\68		{} [parachain-args] -- [relaychain-args]",69			Self::executable_name()70		)71	}7273	fn author() -> String {74		env!("CARGO_PKG_AUTHORS").into()75	}7677	//TODO use args78	fn support_url() -> String {79		"mailto:support@unique.network".into()80	}8182	fn copyright_start_year() -> i32 {83		202184	}8586	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {87		load_spec(id, self.run.parachain_id.unwrap_or(200).into())88	}8990	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {91		&nft_runtime::VERSION92	}93}9495impl SubstrateCli for RelayChainCli {96	// TODO use args97	fn impl_name() -> String {98		"Opal Node".into()99	}100101	fn impl_version() -> String {102		env!("SUBSTRATE_CLI_IMPL_VERSION").into()103	}104	// TODO use args105	fn description() -> String {106		"Opal Node\n\nThe command-line arguments provided first will be \107		passed to the parachain node, while the arguments provided after -- will be passed \108		to the relaychain node.\n\n\109		parachain-collator [parachain-args] -- [relaychain-args]"110			.into()111	}112113	fn author() -> String {114		env!("CARGO_PKG_AUTHORS").into()115	}116	// TODO use args117	fn support_url() -> String {118		"mailto:support@unique.network".into()119	}120121	fn copyright_start_year() -> i32 {122		2021123	}124125	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {126		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)127	}128129	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {130		polkadot_cli::Cli::native_runtime_version(chain_spec)131	}132}133134#[allow(clippy::borrowed_box)]135fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {136	let mut storage = chain_spec.build_storage()?;137138	storage139		.top140		.remove(sp_core::storage::well_known_keys::CODE)141		.ok_or_else(|| "Could not find wasm file in genesis state!".into())142}143144macro_rules! construct_async_run {145	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{146		let runner = $cli.create_runner($cmd)?;147		runner.async_run(|$config| {148			let $components = new_partial::<149				_150			>(151				&$config,152				crate::service::parachain_build_import_queue,153			)?;154			let task_manager = $components.task_manager;155			{ $( $code )* }.map(|v| (v, task_manager))156		})157	}}158}159160/// Parse command line arguments into service configuration.161pub fn run() -> Result<()> {162	let cli = Cli::from_args();163164	match &cli.subcommand {165		Some(Subcommand::BuildSpec(cmd)) => {166			let runner = cli.create_runner(cmd)?;167			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))168		}169		Some(Subcommand::CheckBlock(cmd)) => {170			construct_async_run!(|components, cli, cmd, config| {171				Ok(cmd.run(components.client, components.import_queue))172			})173		}174		Some(Subcommand::ExportBlocks(cmd)) => {175			construct_async_run!(|components, cli, cmd, config| {176				Ok(cmd.run(components.client, config.database))177			})178		}179		Some(Subcommand::ExportState(cmd)) => {180			construct_async_run!(|components, cli, cmd, config| {181				Ok(cmd.run(components.client, config.chain_spec))182			})183		}184		Some(Subcommand::ImportBlocks(cmd)) => {185			construct_async_run!(|components, cli, cmd, config| {186				Ok(cmd.run(components.client, components.import_queue))187			})188		}189		Some(Subcommand::PurgeChain(cmd)) => {190			let runner = cli.create_runner(cmd)?;191192			runner.sync_run(|config| {193				let polkadot_cli = RelayChainCli::new(194					&config,195					[RelayChainCli::executable_name()]196						.iter()197						.chain(cli.relaychain_args.iter()),198				);199200				let polkadot_config = SubstrateCli::create_configuration(201					&polkadot_cli,202					&polkadot_cli,203					config.task_executor.clone(),204				)205				.map_err(|err| format!("Relay chain argument error: {}", err))?;206207				cmd.run(config, polkadot_config)208			})209		}210		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {211			Ok(cmd.run(components.client, components.backend))212		}),213		Some(Subcommand::ExportGenesisState(params)) => {214			let mut builder = sc_cli::LoggerBuilder::new("");215			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");216			let _ = builder.init();217218			let block: Block = generate_genesis_block(&load_spec(219				&params.chain.clone().unwrap_or_default(),220				params.parachain_id.unwrap_or(200).into(),221			)?)?;222			let raw_header = block.header().encode();223			let output_buf = if params.raw {224				raw_header225			} else {226				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()227			};228229			if let Some(output) = &params.output {230				std::fs::write(output, output_buf)?;231			} else {232				std::io::stdout().write_all(&output_buf)?;233			}234235			Ok(())236		}237		Some(Subcommand::ExportGenesisWasm(params)) => {238			let mut builder = sc_cli::LoggerBuilder::new("");239			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");240			let _ = builder.init();241242			let raw_wasm_blob =243				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;244			let output_buf = if params.raw {245				raw_wasm_blob246			} else {247				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()248			};249250			if let Some(output) = &params.output {251				std::fs::write(output, output_buf)?;252			} else {253				std::io::stdout().write_all(&output_buf)?;254			}255256			Ok(())257		}258		Some(Subcommand::Benchmark(cmd)) => {259			if cfg!(feature = "runtime-benchmarks") {260				let runner = cli.create_runner(cmd)?;261262				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))263			} else {264				Err("Benchmarking wasn't enabled when building the node. \265				You can enable it with `--features runtime-benchmarks`."266					.into())267			}268		}269		None => {270			let runner = cli.create_runner(&cli.run.normalize())?;271272			runner.run_node_until_exit(|config| async move {273				let para_id =274					chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id);275276				let polkadot_cli = RelayChainCli::new(277					&config,278					[RelayChainCli::executable_name()]279						.iter()280						.chain(cli.relaychain_args.iter()),281				);282283				let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(200));284285				let parachain_account =286					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);287288				let block: Block =289					generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?;290				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));291292				let task_executor = config.task_executor.clone();293				let polkadot_config =294					SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, task_executor)295						.map_err(|err| format!("Relay chain argument error: {}", err))?;296297				info!("Parachain id: {:?}", id);298				info!("Parachain Account: {}", parachain_account);299				info!("Parachain genesis state: {}", genesis_state);300				info!(301					"Is collating: {}",302					if config.role.is_authority() {303						"yes"304					} else {305						"no"306					}307				);308309				crate::service::start_node(config, polkadot_config, id)310					.await311					.map(|r| r.0)312					.map_err(Into::into)313			})314		}315	}316}317318impl DefaultConfigurationValues for RelayChainCli {319	fn p2p_listen_port() -> u16 {320		30334321	}322323	fn rpc_ws_listen_port() -> u16 {324		9945325	}326327	fn rpc_http_listen_port() -> u16 {328		9934329	}330331	fn prometheus_listen_port() -> u16 {332		9616333	}334}335336impl CliConfiguration<Self> for RelayChainCli {337	fn shared_params(&self) -> &SharedParams {338		self.base.base.shared_params()339	}340341	fn import_params(&self) -> Option<&ImportParams> {342		self.base.base.import_params()343	}344345	fn network_params(&self) -> Option<&NetworkParams> {346		self.base.base.network_params()347	}348349	fn keystore_params(&self) -> Option<&KeystoreParams> {350		self.base.base.keystore_params()351	}352353	fn base_path(&self) -> Result<Option<BasePath>> {354		Ok(self355			.shared_params()356			.base_path()357			.or_else(|| self.base_path.clone().map(Into::into)))358	}359360	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {361		self.base.base.rpc_http(default_listen_port)362	}363364	fn rpc_ipc(&self) -> Result<Option<String>> {365		self.base.base.rpc_ipc()366	}367368	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {369		self.base.base.rpc_ws(default_listen_port)370	}371372	fn prometheus_config(&self, default_listen_port: u16) -> Result<Option<PrometheusConfig>> {373		self.base.base.prometheus_config(default_listen_port)374	}375376	fn init<C: SubstrateCli>(&self) -> Result<()> {377		unreachable!("PolkadotCli is never initialized; qed");378	}379380	fn chain_id(&self, is_dev: bool) -> Result<String> {381		let chain_id = self.base.base.chain_id(is_dev)?;382383		Ok(if chain_id.is_empty() {384			self.chain_id.clone().unwrap_or_default()385		} else {386			chain_id387		})388	}389390	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {391		self.base.base.role(is_dev)392	}393394	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {395		self.base.base.transaction_pool()396	}397398	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {399		self.base.base.state_cache_child_ratio()400	}401402	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {403		self.base.base.rpc_methods()404	}405406	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {407		self.base.base.rpc_ws_max_connections()408	}409410	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {411		self.base.base.rpc_cors(is_dev)412	}413414	fn telemetry_external_transport(&self) -> Result<Option<sc_service::config::ExtTransport>> {415		self.base.base.telemetry_external_transport()416	}417418	fn default_heap_pages(&self) -> Result<Option<u64>> {419		self.base.base.default_heap_pages()420	}421422	fn force_authoring(&self) -> Result<bool> {423		self.base.base.force_authoring()424	}425426	fn disable_grandpa(&self) -> Result<bool> {427		self.base.base.disable_grandpa()428	}429430	fn max_runtime_instances(&self) -> Result<Option<usize>> {431		self.base.base.max_runtime_instances()432	}433434	fn announce_block(&self) -> Result<bool> {435		self.base.base.announce_block()436	}437438	fn telemetry_endpoints(439		&self,440		chain_spec: &Box<dyn ChainSpec>,441	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {442		self.base.base.telemetry_endpoints(chain_spec)443	}444}