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

difftreelog

source

node/src/command.rs12.2 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::{RuntimeApi, 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	fn impl_name() -> String {55		"Parachain Collator Template".into()56	}5758	fn impl_version() -> String {59		env!("SUBSTRATE_CLI_IMPL_VERSION").into()60	}6162	fn description() -> String {63		format!(64			"Parachain Collator Template\n\nThe command-line arguments provided first will be \65		passed to the parachain node, while the arguments provided after -- will be passed \66		to the relaychain node.\n\n\67		{} [parachain-args] -- [relaychain-args]",68			Self::executable_name()69		)70	}7172	fn author() -> String {73		env!("CARGO_PKG_AUTHORS").into()74	}7576	fn support_url() -> String {77		"https://github.com/substrate-developer-hub/substrate-parachain-template/issues/new".into()78	}7980	fn copyright_start_year() -> i32 {81		201782	}8384	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {85		load_spec(id, self.run.parachain_id.unwrap_or(200).into())86	}8788	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {89		&nft_runtime::VERSION90	}91}9293impl SubstrateCli for RelayChainCli {94	fn impl_name() -> String {95		"Parachain Collator Template".into()96	}9798	fn impl_version() -> String {99		env!("SUBSTRATE_CLI_IMPL_VERSION").into()100	}101102	fn description() -> String {103		"Parachain Collator Template\n\nThe command-line arguments provided first will be \104		passed to the parachain node, while the arguments provided after -- will be passed \105		to the relaychain node.\n\n\106		parachain-collator [parachain-args] -- [relaychain-args]"107			.into()108	}109110	fn author() -> String {111		env!("CARGO_PKG_AUTHORS").into()112	}113114	fn support_url() -> String {115		"https://github.com/substrate-developer-hub/substrate-parachain-template/issues/new".into()116	}117118	fn copyright_start_year() -> i32 {119		2017120	}121122	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {123		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter())124			.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}131132fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {133	let mut storage = chain_spec.build_storage()?;134135	storage136		.top137		.remove(sp_core::storage::well_known_keys::CODE)138		.ok_or_else(|| "Could not find wasm file in genesis state!".into())139}140141macro_rules! construct_async_run {142	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{143		let runner = $cli.create_runner($cmd)?;144		runner.async_run(|$config| {145			let $components = new_partial::<146				RuntimeApi,147				ParachainRuntimeExecutor,148				_149			>(150				&$config,151				crate::service::parachain_build_import_queue,152			)?;153			let task_manager = $components.task_manager;154			{ $( $code )* }.map(|v| (v, task_manager))155		})156	}}157}158159/// Parse command line arguments into service configuration.160pub fn run() -> Result<()> {161	let cli = Cli::from_args();162163	match &cli.subcommand {164		Some(Subcommand::BuildSpec(cmd)) => {165			let runner = cli.create_runner(cmd)?;166			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))167		}168		Some(Subcommand::CheckBlock(cmd)) => {169			construct_async_run!(|components, cli, cmd, config| {170				Ok(cmd.run(components.client, components.import_queue))171			})172		}173		Some(Subcommand::ExportBlocks(cmd)) => {174			construct_async_run!(|components, cli, cmd, config| {175				Ok(cmd.run(components.client, config.database))176			})177		}178		Some(Subcommand::ExportState(cmd)) => {179			construct_async_run!(|components, cli, cmd, config| {180				Ok(cmd.run(components.client, config.chain_spec))181			})182		}183		Some(Subcommand::ImportBlocks(cmd)) => {184			construct_async_run!(|components, cli, cmd, config| {185				Ok(cmd.run(components.client, components.import_queue))186			})187		}188		Some(Subcommand::PurgeChain(cmd)) => {189			let runner = cli.create_runner(cmd)?;190191			runner.sync_run(|config| {192				let polkadot_cli = RelayChainCli::new(193					&config,194					[RelayChainCli::executable_name().to_string()]195						.iter()196						.chain(cli.relaychain_args.iter()),197				);198199				let polkadot_config = SubstrateCli::create_configuration(200					&polkadot_cli,201					&polkadot_cli,202					config.task_executor.clone(),203				)204				.map_err(|err| format!("Relay chain argument error: {}", err))?;205206				cmd.run(config, polkadot_config)207			})208		}209		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {210			Ok(cmd.run(components.client, components.backend))211		}),212		Some(Subcommand::ExportGenesisState(params)) => {213			let mut builder = sc_cli::LoggerBuilder::new("");214			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");215			let _ = builder.init();216217			let block: Block = generate_genesis_block(&load_spec(218				&params.chain.clone().unwrap_or_default(),219				params.parachain_id.unwrap_or(200).into(),220			)?)?;221			let raw_header = block.header().encode();222			let output_buf = if params.raw {223				raw_header224			} else {225				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()226			};227228			if let Some(output) = &params.output {229				std::fs::write(output, output_buf)?;230			} else {231				std::io::stdout().write_all(&output_buf)?;232			}233234			Ok(())235		}236		Some(Subcommand::ExportGenesisWasm(params)) => {237			let mut builder = sc_cli::LoggerBuilder::new("");238			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");239			let _ = builder.init();240241			let raw_wasm_blob =242				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;243			let output_buf = if params.raw {244				raw_wasm_blob245			} else {246				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()247			};248249			if let Some(output) = &params.output {250				std::fs::write(output, output_buf)?;251			} else {252				std::io::stdout().write_all(&output_buf)?;253			}254255			Ok(())256		},257		Some(Subcommand::Benchmark(cmd)) => {258			if cfg!(feature = "runtime-benchmarks") {259				let runner = cli.create_runner(cmd)?;260261				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))262			} else {263				Err("Benchmarking wasn't enabled when building the node. \264				You can enable it with `--features runtime-benchmarks`.".into())265			}266		},267		None => {268			let runner = cli.create_runner(&cli.run.normalize())?;269270			runner.run_node_until_exit(|config| async move {271				// TODO272				let key = sp_core::Pair::generate().0;273274				let para_id =275					chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id);276277				let polkadot_cli = RelayChainCli::new(278					&config,279					[RelayChainCli::executable_name().to_string()]280						.iter()281						.chain(cli.relaychain_args.iter()),282				);283284				let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(200));285286				let parachain_account =287					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);288289				let block: Block =290					generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?;291				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));292293				let task_executor = config.task_executor.clone();294				let polkadot_config = SubstrateCli::create_configuration(295					&polkadot_cli,296					&polkadot_cli,297					task_executor,298				)299				.map_err(|err| format!("Relay chain argument error: {}", err))?;300301				info!("Parachain id: {:?}", id);302				info!("Parachain Account: {}", parachain_account);303				info!("Parachain genesis state: {}", genesis_state);304				info!(305					"Is collating: {}",306					if config.role.is_authority() {307						"yes"308					} else {309						"no"310					}311				);312313				crate::service::start_node(config, key, polkadot_config, id)314					.await315					.map(|r| r.0)316					.map_err(Into::into)317			})318		}319	}320}321322impl DefaultConfigurationValues for RelayChainCli {323	fn p2p_listen_port() -> u16 {324		30334325	}326327	fn rpc_ws_listen_port() -> u16 {328		9945329	}330331	fn rpc_http_listen_port() -> u16 {332		9934333	}334335	fn prometheus_listen_port() -> u16 {336		9616337	}338}339340impl CliConfiguration<Self> for RelayChainCli {341	fn shared_params(&self) -> &SharedParams {342		self.base.base.shared_params()343	}344345	fn import_params(&self) -> Option<&ImportParams> {346		self.base.base.import_params()347	}348349	fn network_params(&self) -> Option<&NetworkParams> {350		self.base.base.network_params()351	}352353	fn keystore_params(&self) -> Option<&KeystoreParams> {354		self.base.base.keystore_params()355	}356357	fn base_path(&self) -> Result<Option<BasePath>> {358		Ok(self359			.shared_params()360			.base_path()361			.or_else(|| self.base_path.clone().map(Into::into)))362	}363364	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {365		self.base.base.rpc_http(default_listen_port)366	}367368	fn rpc_ipc(&self) -> Result<Option<String>> {369		self.base.base.rpc_ipc()370	}371372	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {373		self.base.base.rpc_ws(default_listen_port)374	}375376	fn prometheus_config(&self, default_listen_port: u16) -> Result<Option<PrometheusConfig>> {377		self.base.base.prometheus_config(default_listen_port)378	}379380	fn init<C: SubstrateCli>(&self) -> Result<()> {381		unreachable!("PolkadotCli is never initialized; qed");382	}383384	fn chain_id(&self, is_dev: bool) -> Result<String> {385		let chain_id = self.base.base.chain_id(is_dev)?;386387		Ok(if chain_id.is_empty() {388			self.chain_id.clone().unwrap_or_default()389		} else {390			chain_id391		})392	}393394	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {395		self.base.base.role(is_dev)396	}397398	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {399		self.base.base.transaction_pool()400	}401402	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {403		self.base.base.state_cache_child_ratio()404	}405406	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {407		self.base.base.rpc_methods()408	}409410	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {411		self.base.base.rpc_ws_max_connections()412	}413414	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {415		self.base.base.rpc_cors(is_dev)416	}417418	fn telemetry_external_transport(&self) -> Result<Option<sc_service::config::ExtTransport>> {419		self.base.base.telemetry_external_transport()420	}421422	fn default_heap_pages(&self) -> Result<Option<u64>> {423		self.base.base.default_heap_pages()424	}425426	fn force_authoring(&self) -> Result<bool> {427		self.base.base.force_authoring()428	}429430	fn disable_grandpa(&self) -> Result<bool> {431		self.base.base.disable_grandpa()432	}433434	fn max_runtime_instances(&self) -> Result<Option<usize>> {435		self.base.base.max_runtime_instances()436	}437438	fn announce_block(&self) -> Result<bool> {439		self.base.base.announce_block()440	}441442	fn telemetry_endpoints(443		&self,444		chain_spec: &Box<dyn ChainSpec>,445	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {446		self.base.base.telemetry_endpoints(chain_spec)447	}448}