git.delta.rocks / unique-network / refs/commits / 0a9dcd573876

difftreelog

source

node/cli/src/command.rs11.9 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(41	id: &str,42	para_id: ParaId,43) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {44	Ok(match id {45		"westend-local" => Box::new(chain_spec::local_testnet_westend_config(para_id)),46		"dev" => Box::new(chain_spec::development_config(para_id)),47		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config(para_id)),48		path => Box::new(chain_spec::ChainSpec::from_json_file(49			std::path::PathBuf::from(path),50		)?),51	})52}5354impl SubstrateCli for Cli {55	// TODO use args56	fn impl_name() -> String {57		"Opal Node".into()58	}5960	fn impl_version() -> String {61		env!("SUBSTRATE_CLI_IMPL_VERSION").into()62	}63	// TODO use args64	fn description() -> String {65		format!(66			"Opal Node\n\nThe command-line arguments provided first will be \67		passed to the parachain node, while the arguments provided after -- will be passed \68		to the relaychain node.\n\n\69		{} [parachain-args] -- [relaychain-args]",70			Self::executable_name()71		)72	}7374	fn author() -> String {75		env!("CARGO_PKG_AUTHORS").into()76	}7778	//TODO use args79	fn support_url() -> String {80		"support@unique.network".into()81	}8283	fn copyright_start_year() -> i32 {84		201985	}8687	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {88		load_spec(id, self.run.parachain_id.unwrap_or(2000).into())89	}9091	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {92		&unique_runtime::VERSION93	}94}9596impl SubstrateCli for RelayChainCli {97	// TODO use args98	fn impl_name() -> String {99		"Opal Node".into()100	}101102	fn impl_version() -> String {103		env!("SUBSTRATE_CLI_IMPL_VERSION").into()104	}105	// TODO use args106	fn description() -> String {107		"Opal Node\n\nThe command-line arguments provided first will be \108		passed to the parachain node, while the arguments provided after -- will be passed \109		to the relaychain node.\n\n\110		parachain-collator [parachain-args] -- [relaychain-args]"111			.into()112	}113114	fn author() -> String {115		env!("CARGO_PKG_AUTHORS").into()116	}117	// TODO use args118	fn support_url() -> String {119		"support@unique.network".into()120	}121122	fn copyright_start_year() -> i32 {123		2019124	}125126	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {127		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)128	}129130	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {131		polkadot_cli::Cli::native_runtime_version(chain_spec)132	}133}134135#[allow(clippy::borrowed_box)]136fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {137	let mut storage = chain_spec.build_storage()?;138139	storage140		.top141		.remove(sp_core::storage::well_known_keys::CODE)142		.ok_or_else(|| "Could not find wasm file in genesis state!".into())143}144145macro_rules! construct_async_run {146	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{147		let runner = $cli.create_runner($cmd)?;148		runner.async_run(|$config| {149			let $components = new_partial::<150				_151			>(152				&$config,153				crate::service::parachain_build_import_queue,154			)?;155			let task_manager = $components.task_manager;156			{ $( $code )* }.map(|v| (v, task_manager))157		})158	}}159}160161/// Parse command line arguments into service configuration.162pub fn run() -> Result<()> {163	let cli = Cli::from_args();164165	match &cli.subcommand {166		Some(Subcommand::BuildSpec(cmd)) => {167			let runner = cli.create_runner(cmd)?;168			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))169		}170		Some(Subcommand::CheckBlock(cmd)) => {171			construct_async_run!(|components, cli, cmd, config| {172				Ok(cmd.run(components.client, components.import_queue))173			})174		}175		Some(Subcommand::ExportBlocks(cmd)) => {176			construct_async_run!(|components, cli, cmd, config| {177				Ok(cmd.run(components.client, config.database))178			})179		}180		Some(Subcommand::ExportState(cmd)) => {181			construct_async_run!(|components, cli, cmd, config| {182				Ok(cmd.run(components.client, config.chain_spec))183			})184		}185		Some(Subcommand::ImportBlocks(cmd)) => {186			construct_async_run!(|components, cli, cmd, config| {187				Ok(cmd.run(components.client, components.import_queue))188			})189		}190		Some(Subcommand::PurgeChain(cmd)) => {191			let runner = cli.create_runner(cmd)?;192193			runner.sync_run(|config| {194				let polkadot_cli = RelayChainCli::new(195					&config,196					[RelayChainCli::executable_name()]197						.iter()198						.chain(cli.relaychain_args.iter()),199				);200201				let polkadot_config = SubstrateCli::create_configuration(202					&polkadot_cli,203					&polkadot_cli,204					config.tokio_handle.clone(),205				)206				.map_err(|err| format!("Relay chain argument error: {}", err))?;207208				cmd.run(config, polkadot_config)209			})210		}211		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {212			Ok(cmd.run(components.client, components.backend))213		}),214		Some(Subcommand::ExportGenesisState(params)) => {215			let mut builder = sc_cli::LoggerBuilder::new("");216			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");217			let _ = builder.init();218219			let block: Block = generate_genesis_block(&load_spec(220				&params.chain.clone().unwrap_or_default(),221				params.parachain_id.unwrap_or(2000).into(),222			)?)?;223			let raw_header = block.header().encode();224			let output_buf = if params.raw {225				raw_header226			} else {227				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()228			};229230			if let Some(output) = &params.output {231				std::fs::write(output, output_buf)?;232			} else {233				std::io::stdout().write_all(&output_buf)?;234			}235236			Ok(())237		}238		Some(Subcommand::ExportGenesisWasm(params)) => {239			let mut builder = sc_cli::LoggerBuilder::new("");240			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");241			let _ = builder.init();242243			let raw_wasm_blob =244				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;245			let output_buf = if params.raw {246				raw_wasm_blob247			} else {248				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()249			};250251			if let Some(output) = &params.output {252				std::fs::write(output, output_buf)?;253			} else {254				std::io::stdout().write_all(&output_buf)?;255			}256257			Ok(())258		}259		Some(Subcommand::Benchmark(cmd)) => {260			if cfg!(feature = "runtime-benchmarks") {261				let runner = cli.create_runner(cmd)?;262263				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))264			} else {265				Err("Benchmarking wasn't enabled when building the node. \266				You can enable it with `--features runtime-benchmarks`."267					.into())268			}269		}270		None => {271			let runner = cli.create_runner(&cli.run.normalize())?;272273			runner.run_node_until_exit(|config| async move {274				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()]280						.iter()281						.chain(cli.relaychain_args.iter()),282				);283284				let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(2000));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 polkadot_config = SubstrateCli::create_configuration(294					&polkadot_cli,295					&polkadot_cli,296					config.tokio_handle.clone(),297				)298				.map_err(|err| format!("Relay chain argument error: {}", err))?;299300				info!("Parachain id: {:?}", id);301				info!("Parachain Account: {}", parachain_account);302				info!("Parachain genesis state: {}", genesis_state);303				info!(304					"Is collating: {}",305					if config.role.is_authority() {306						"yes"307					} else {308						"no"309					}310				);311312				crate::service::start_node(config, polkadot_config, id)313					.await314					.map(|r| r.0)315					.map_err(Into::into)316			})317		}318	}319}320321impl DefaultConfigurationValues for RelayChainCli {322	fn p2p_listen_port() -> u16 {323		30334324	}325326	fn rpc_ws_listen_port() -> u16 {327		9945328	}329330	fn rpc_http_listen_port() -> u16 {331		9934332	}333334	fn prometheus_listen_port() -> u16 {335		9616336	}337}338339impl CliConfiguration<Self> for RelayChainCli {340	fn shared_params(&self) -> &SharedParams {341		self.base.base.shared_params()342	}343344	fn import_params(&self) -> Option<&ImportParams> {345		self.base.base.import_params()346	}347348	fn network_params(&self) -> Option<&NetworkParams> {349		self.base.base.network_params()350	}351352	fn keystore_params(&self) -> Option<&KeystoreParams> {353		self.base.base.keystore_params()354	}355356	fn base_path(&self) -> Result<Option<BasePath>> {357		Ok(self358			.shared_params()359			.base_path()360			.or_else(|| self.base_path.clone().map(Into::into)))361	}362363	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {364		self.base.base.rpc_http(default_listen_port)365	}366367	fn rpc_ipc(&self) -> Result<Option<String>> {368		self.base.base.rpc_ipc()369	}370371	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {372		self.base.base.rpc_ws(default_listen_port)373	}374375	fn prometheus_config(&self, default_listen_port: u16) -> Result<Option<PrometheusConfig>> {376		self.base.base.prometheus_config(default_listen_port)377	}378379	fn init<C: SubstrateCli>(&self) -> Result<()> {380		unreachable!("PolkadotCli is never initialized; qed");381	}382383	fn chain_id(&self, is_dev: bool) -> Result<String> {384		let chain_id = self.base.base.chain_id(is_dev)?;385386		Ok(if chain_id.is_empty() {387			self.chain_id.clone().unwrap_or_default()388		} else {389			chain_id390		})391	}392393	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {394		self.base.base.role(is_dev)395	}396397	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {398		self.base.base.transaction_pool()399	}400401	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {402		self.base.base.state_cache_child_ratio()403	}404405	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {406		self.base.base.rpc_methods()407	}408409	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {410		self.base.base.rpc_ws_max_connections()411	}412413	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {414		self.base.base.rpc_cors(is_dev)415	}416417	fn default_heap_pages(&self) -> Result<Option<u64>> {418		self.base.base.default_heap_pages()419	}420421	fn force_authoring(&self) -> Result<bool> {422		self.base.base.force_authoring()423	}424425	fn disable_grandpa(&self) -> Result<bool> {426		self.base.base.disable_grandpa()427	}428429	fn max_runtime_instances(&self) -> Result<Option<usize>> {430		self.base.base.max_runtime_instances()431	}432433	fn announce_block(&self) -> Result<bool> {434		self.base.base.announce_block()435	}436437	fn telemetry_endpoints(438		&self,439		chain_spec: &Box<dyn ChainSpec>,440	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {441		self.base.base.telemetry_endpoints(chain_spec)442	}443}