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

difftreelog

source

node/cli/src/command.rs12.3 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		"rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),44		"dev" => Box::new(chain_spec::development_config()),45		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),46		path => Box::new(chain_spec::ChainSpec::from_json_file(47			std::path::PathBuf::from(path),48		)?),49	})50}5152impl SubstrateCli for Cli {53	// TODO use args54	fn impl_name() -> String {55		"Opal Node".into()56	}5758	fn impl_version() -> String {59		env!("SUBSTRATE_CLI_IMPL_VERSION").into()60	}61	// TODO use args62	fn description() -> String {63		format!(64			"Opal Node\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	//TODO use args77	fn support_url() -> String {78		"support@unique.network".into()79	}8081	fn copyright_start_year() -> i32 {82		201983	}8485	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {86		load_spec(id)87	}8889	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {90		&unique_runtime::VERSION91	}92}9394impl SubstrateCli for RelayChainCli {95	// TODO use args96	fn impl_name() -> String {97		"Opal Node".into()98	}99100	fn impl_version() -> String {101		env!("SUBSTRATE_CLI_IMPL_VERSION").into()102	}103	// TODO use args104	fn description() -> String {105		"Opal Node\n\nThe command-line arguments provided first will be \106		passed to the parachain node, while the arguments provided after -- will be passed \107		to the relaychain node.\n\n\108		parachain-collator [parachain-args] -- [relaychain-args]"109			.into()110	}111112	fn author() -> String {113		env!("CARGO_PKG_AUTHORS").into()114	}115	// TODO use args116	fn support_url() -> String {117		"support@unique.network".into()118	}119120	fn copyright_start_year() -> i32 {121		2019122	}123124	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {125		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)126	}127128	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {129		polkadot_cli::Cli::native_runtime_version(chain_spec)130	}131}132133#[allow(clippy::borrowed_box)]134fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {135	let mut storage = chain_spec.build_storage()?;136137	storage138		.top139		.remove(sp_core::storage::well_known_keys::CODE)140		.ok_or_else(|| "Could not find wasm file in genesis state!".into())141}142143macro_rules! construct_async_run {144	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{145		let runner = $cli.create_runner($cmd)?;146		runner.async_run(|$config| {147			let $components = new_partial::<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()]195						.iter()196						.chain(cli.relaychain_args.iter()),197				);198199				let polkadot_config = SubstrateCli::create_configuration(200					&polkadot_cli,201					&polkadot_cli,202					config.tokio_handle.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 spec = load_spec(&params.chain.clone().unwrap_or_default())?;218			let state_version = Cli::native_runtime_version(&spec).state_version();219			let block: Block = generate_genesis_block(&spec, state_version)?;220			let raw_header = block.header().encode();221			let output_buf = if params.raw {222				raw_header223			} else {224				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()225			};226227			if let Some(output) = &params.output {228				std::fs::write(output, output_buf)?;229			} else {230				std::io::stdout().write_all(&output_buf)?;231			}232233			Ok(())234		}235		Some(Subcommand::ExportGenesisWasm(params)) => {236			let mut builder = sc_cli::LoggerBuilder::new("");237			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");238			let _ = builder.init();239240			let raw_wasm_blob =241				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;242			let output_buf = if params.raw {243				raw_wasm_blob244			} else {245				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()246			};247248			if let Some(output) = &params.output {249				std::fs::write(output, output_buf)?;250			} else {251				std::io::stdout().write_all(&output_buf)?;252			}253254			Ok(())255		}256		Some(Subcommand::Benchmark(cmd)) => {257			if cfg!(feature = "runtime-benchmarks") {258				let runner = cli.create_runner(cmd)?;259260				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))261			} else {262				Err("Benchmarking wasn't enabled when building the node. \263				You can enable it with `--features runtime-benchmarks`."264					.into())265			}266		}267		None => {268			let runner = cli.create_runner(&cli.run.normalize())?;269270			runner.run_node_until_exit(|config| async move {271				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)272					.map(|e| e.para_id)273					.ok_or("Could not find parachain ID in chain-spec.")?;274275				let polkadot_cli = RelayChainCli::new(276					&config,277					[RelayChainCli::executable_name()]278						.iter()279						.chain(cli.relaychain_args.iter()),280				);281282				let id = ParaId::from(para_id);283284				let parachain_account =285					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);286287				let state_version =288					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();289				let block: Block = generate_genesis_block(&config.chain_spec, state_version)290					.map_err(|e| format!("{:?}", e))?;291				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));292				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));293294				let polkadot_config = SubstrateCli::create_configuration(295					&polkadot_cli,296					&polkadot_cli,297					config.tokio_handle.clone(),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!("Parachain genesis hash: {}", genesis_hash);305				info!(306					"Is collating: {}",307					if config.role.is_authority() {308						"yes"309					} else {310						"no"311					}312				);313314				crate::service::start_node(config, polkadot_config, id)315					.await316					.map(|r| r.0)317					.map_err(Into::into)318			})319		}320	}321}322323impl DefaultConfigurationValues for RelayChainCli {324	fn p2p_listen_port() -> u16 {325		30334326	}327328	fn rpc_ws_listen_port() -> u16 {329		9945330	}331332	fn rpc_http_listen_port() -> u16 {333		9934334	}335336	fn prometheus_listen_port() -> u16 {337		9616338	}339}340341impl CliConfiguration<Self> for RelayChainCli {342	fn shared_params(&self) -> &SharedParams {343		self.base.base.shared_params()344	}345346	fn import_params(&self) -> Option<&ImportParams> {347		self.base.base.import_params()348	}349350	fn network_params(&self) -> Option<&NetworkParams> {351		self.base.base.network_params()352	}353354	fn keystore_params(&self) -> Option<&KeystoreParams> {355		self.base.base.keystore_params()356	}357358	fn base_path(&self) -> Result<Option<BasePath>> {359		Ok(self360			.shared_params()361			.base_path()362			.or_else(|| self.base_path.clone().map(Into::into)))363	}364365	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {366		self.base.base.rpc_http(default_listen_port)367	}368369	fn rpc_ipc(&self) -> Result<Option<String>> {370		self.base.base.rpc_ipc()371	}372373	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {374		self.base.base.rpc_ws(default_listen_port)375	}376377	fn prometheus_config(378		&self,379		default_listen_port: u16,380		chain_spec: &Box<dyn ChainSpec>,381	) -> Result<Option<PrometheusConfig>> {382		self.base383			.base384			.prometheus_config(default_listen_port, chain_spec)385	}386387	fn init<F>(388		&self,389		_support_url: &String,390		_impl_version: &String,391		_logger_hook: F,392		_config: &sc_service::Configuration,393	) -> Result<()> {394		unreachable!("PolkadotCli is never initialized; qed");395	}396397	fn chain_id(&self, is_dev: bool) -> Result<String> {398		let chain_id = self.base.base.chain_id(is_dev)?;399400		Ok(if chain_id.is_empty() {401			self.chain_id.clone().unwrap_or_default()402		} else {403			chain_id404		})405	}406407	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {408		self.base.base.role(is_dev)409	}410411	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {412		self.base.base.transaction_pool()413	}414415	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {416		self.base.base.state_cache_child_ratio()417	}418419	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {420		self.base.base.rpc_methods()421	}422423	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {424		self.base.base.rpc_ws_max_connections()425	}426427	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {428		self.base.base.rpc_cors(is_dev)429	}430431	fn default_heap_pages(&self) -> Result<Option<u64>> {432		self.base.base.default_heap_pages()433	}434435	fn force_authoring(&self) -> Result<bool> {436		self.base.base.force_authoring()437	}438439	fn disable_grandpa(&self) -> Result<bool> {440		self.base.base.disable_grandpa()441	}442443	fn max_runtime_instances(&self) -> Result<Option<usize>> {444		self.base.base.max_runtime_instances()445	}446447	fn announce_block(&self) -> Result<bool> {448		self.base.base.announce_block()449	}450451	fn telemetry_endpoints(452		&self,453		chain_spec: &Box<dyn ChainSpec>,454	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {455		self.base.base.telemetry_endpoints(chain_spec)456	}457}