git.delta.rocks / unique-network / refs/commits / 4657e257e343

difftreelog

source

node/cli/src/command.rs13.3 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license18// This file is part of Substrate.1920// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use crate::{36	chain_spec,37	cli::{Cli, RelayChainCli, Subcommand},38	service::{new_partial, ParachainRuntimeExecutor},39};40use codec::Encode;41use cumulus_primitives_core::ParaId;42use cumulus_client_service::genesis::generate_genesis_block;43use log::info;44use polkadot_parachain::primitives::AccountIdConversion;45use sc_cli::{46	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,47	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,48};49use sc_service::{50	config::{BasePath, PrometheusConfig},51};52use sp_core::hexdisplay::HexDisplay;53use sp_runtime::traits::Block as BlockT;54use std::{io::Write, net::SocketAddr};5556#[cfg(feature = "unique-runtime")]57use unique_runtime as runtime;5859#[cfg(feature = "quartz-runtime")]60use quartz_runtime as runtime;6162#[cfg(feature = "opal-runtime")]63use opal_runtime as runtime;6465use runtime::Block;6667fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {68	Ok(match id {69		"westend-local" => Box::new(chain_spec::local_testnet_westend_config()),70		"rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),71		"dev" => Box::new(chain_spec::development_config()),72		"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),73		path => Box::new(chain_spec::ChainSpec::from_json_file(74			std::path::PathBuf::from(path),75		)?),76	})77}7879impl SubstrateCli for Cli {80	// TODO use args81	fn impl_name() -> String {82		"Opal Node".into()83	}8485	fn impl_version() -> String {86		env!("SUBSTRATE_CLI_IMPL_VERSION").into()87	}88	// TODO use args89	fn description() -> String {90		format!(91			"Opal Node\n\nThe command-line arguments provided first will be \92		passed to the parachain node, while the arguments provided after -- will be passed \93		to the relaychain node.\n\n\94		{} [parachain-args] -- [relaychain-args]",95			Self::executable_name()96		)97	}9899	fn author() -> String {100		env!("CARGO_PKG_AUTHORS").into()101	}102103	//TODO use args104	fn support_url() -> String {105		"support@unique.network".into()106	}107108	fn copyright_start_year() -> i32 {109		2019110	}111112	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {113		load_spec(id)114	}115116	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {117		&runtime::VERSION118	}119}120121impl SubstrateCli for RelayChainCli {122	// TODO use args123	fn impl_name() -> String {124		"Opal Node".into()125	}126127	fn impl_version() -> String {128		env!("SUBSTRATE_CLI_IMPL_VERSION").into()129	}130	// TODO use args131	fn description() -> String {132		"Opal Node\n\nThe command-line arguments provided first will be \133		passed to the parachain node, while the arguments provided after -- will be passed \134		to the relaychain node.\n\n\135		parachain-collator [parachain-args] -- [relaychain-args]"136			.into()137	}138139	fn author() -> String {140		env!("CARGO_PKG_AUTHORS").into()141	}142	// TODO use args143	fn support_url() -> String {144		"support@unique.network".into()145	}146147	fn copyright_start_year() -> i32 {148		2019149	}150151	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {152		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)153	}154155	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {156		polkadot_cli::Cli::native_runtime_version(chain_spec)157	}158}159160#[allow(clippy::borrowed_box)]161fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {162	let mut storage = chain_spec.build_storage()?;163164	storage165		.top166		.remove(sp_core::storage::well_known_keys::CODE)167		.ok_or_else(|| "Could not find wasm file in genesis state!".into())168}169170macro_rules! construct_async_run {171	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{172		let runner = $cli.create_runner($cmd)?;173		runner.async_run(|$config| {174			let $components = new_partial::<175				_176			>(177				&$config,178				crate::service::parachain_build_import_queue,179			)?;180			let task_manager = $components.task_manager;181			{ $( $code )* }.map(|v| (v, task_manager))182		})183	}}184}185186/// Parse command line arguments into service configuration.187pub fn run() -> Result<()> {188	let cli = Cli::from_args();189190	match &cli.subcommand {191		Some(Subcommand::BuildSpec(cmd)) => {192			let runner = cli.create_runner(cmd)?;193			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))194		}195		Some(Subcommand::CheckBlock(cmd)) => {196			construct_async_run!(|components, cli, cmd, config| {197				Ok(cmd.run(components.client, components.import_queue))198			})199		}200		Some(Subcommand::ExportBlocks(cmd)) => {201			construct_async_run!(|components, cli, cmd, config| {202				Ok(cmd.run(components.client, config.database))203			})204		}205		Some(Subcommand::ExportState(cmd)) => {206			construct_async_run!(|components, cli, cmd, config| {207				Ok(cmd.run(components.client, config.chain_spec))208			})209		}210		Some(Subcommand::ImportBlocks(cmd)) => {211			construct_async_run!(|components, cli, cmd, config| {212				Ok(cmd.run(components.client, components.import_queue))213			})214		}215		Some(Subcommand::PurgeChain(cmd)) => {216			let runner = cli.create_runner(cmd)?;217218			runner.sync_run(|config| {219				let polkadot_cli = RelayChainCli::new(220					&config,221					[RelayChainCli::executable_name()]222						.iter()223						.chain(cli.relaychain_args.iter()),224				);225226				let polkadot_config = SubstrateCli::create_configuration(227					&polkadot_cli,228					&polkadot_cli,229					config.tokio_handle.clone(),230				)231				.map_err(|err| format!("Relay chain argument error: {}", err))?;232233				cmd.run(config, polkadot_config)234			})235		}236		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {237			Ok(cmd.run(components.client, components.backend))238		}),239		Some(Subcommand::ExportGenesisState(params)) => {240			let mut builder = sc_cli::LoggerBuilder::new("");241			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");242			let _ = builder.init();243244			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;245			let state_version = Cli::native_runtime_version(&spec).state_version();246			let block: Block = generate_genesis_block(&spec, state_version)?;247			let raw_header = block.header().encode();248			let output_buf = if params.raw {249				raw_header250			} else {251				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()252			};253254			if let Some(output) = &params.output {255				std::fs::write(output, output_buf)?;256			} else {257				std::io::stdout().write_all(&output_buf)?;258			}259260			Ok(())261		}262		Some(Subcommand::ExportGenesisWasm(params)) => {263			let mut builder = sc_cli::LoggerBuilder::new("");264			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");265			let _ = builder.init();266267			let raw_wasm_blob =268				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;269			let output_buf = if params.raw {270				raw_wasm_blob271			} else {272				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()273			};274275			if let Some(output) = &params.output {276				std::fs::write(output, output_buf)?;277			} else {278				std::io::stdout().write_all(&output_buf)?;279			}280281			Ok(())282		}283		Some(Subcommand::Benchmark(cmd)) => {284			if cfg!(feature = "runtime-benchmarks") {285				let runner = cli.create_runner(cmd)?;286287				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))288			} else {289				Err("Benchmarking wasn't enabled when building the node. \290				You can enable it with `--features runtime-benchmarks`."291					.into())292			}293		}294		None => {295			let runner = cli.create_runner(&cli.run.normalize())?;296297			runner.run_node_until_exit(|config| async move {298				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)299					.map(|e| e.para_id)300					.ok_or("Could not find parachain ID in chain-spec.")?;301302				let polkadot_cli = RelayChainCli::new(303					&config,304					[RelayChainCli::executable_name()]305						.iter()306						.chain(cli.relaychain_args.iter()),307				);308309				let id = ParaId::from(para_id);310311				let parachain_account =312					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);313314				let state_version =315					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();316				let block: Block = generate_genesis_block(&config.chain_spec, state_version)317					.map_err(|e| format!("{:?}", e))?;318				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));319				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));320321				let polkadot_config = SubstrateCli::create_configuration(322					&polkadot_cli,323					&polkadot_cli,324					config.tokio_handle.clone(),325				)326				.map_err(|err| format!("Relay chain argument error: {}", err))?;327328				info!("Parachain id: {:?}", id);329				info!("Parachain Account: {}", parachain_account);330				info!("Parachain genesis state: {}", genesis_state);331				info!("Parachain genesis hash: {}", genesis_hash);332				info!(333					"Is collating: {}",334					if config.role.is_authority() {335						"yes"336					} else {337						"no"338					}339				);340341				crate::service::start_node(config, polkadot_config, id)342					.await343					.map(|r| r.0)344					.map_err(Into::into)345			})346		}347	}348}349350impl DefaultConfigurationValues for RelayChainCli {351	fn p2p_listen_port() -> u16 {352		30334353	}354355	fn rpc_ws_listen_port() -> u16 {356		9945357	}358359	fn rpc_http_listen_port() -> u16 {360		9934361	}362363	fn prometheus_listen_port() -> u16 {364		9616365	}366}367368impl CliConfiguration<Self> for RelayChainCli {369	fn shared_params(&self) -> &SharedParams {370		self.base.base.shared_params()371	}372373	fn import_params(&self) -> Option<&ImportParams> {374		self.base.base.import_params()375	}376377	fn network_params(&self) -> Option<&NetworkParams> {378		self.base.base.network_params()379	}380381	fn keystore_params(&self) -> Option<&KeystoreParams> {382		self.base.base.keystore_params()383	}384385	fn base_path(&self) -> Result<Option<BasePath>> {386		Ok(self387			.shared_params()388			.base_path()389			.or_else(|| self.base_path.clone().map(Into::into)))390	}391392	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {393		self.base.base.rpc_http(default_listen_port)394	}395396	fn rpc_ipc(&self) -> Result<Option<String>> {397		self.base.base.rpc_ipc()398	}399400	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {401		self.base.base.rpc_ws(default_listen_port)402	}403404	fn prometheus_config(405		&self,406		default_listen_port: u16,407		chain_spec: &Box<dyn ChainSpec>,408	) -> Result<Option<PrometheusConfig>> {409		self.base410			.base411			.prometheus_config(default_listen_port, chain_spec)412	}413414	fn init<F>(415		&self,416		_support_url: &String,417		_impl_version: &String,418		_logger_hook: F,419		_config: &sc_service::Configuration,420	) -> Result<()> {421		unreachable!("PolkadotCli is never initialized; qed");422	}423424	fn chain_id(&self, is_dev: bool) -> Result<String> {425		let chain_id = self.base.base.chain_id(is_dev)?;426427		Ok(if chain_id.is_empty() {428			self.chain_id.clone().unwrap_or_default()429		} else {430			chain_id431		})432	}433434	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {435		self.base.base.role(is_dev)436	}437438	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {439		self.base.base.transaction_pool()440	}441442	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {443		self.base.base.state_cache_child_ratio()444	}445446	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {447		self.base.base.rpc_methods()448	}449450	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {451		self.base.base.rpc_ws_max_connections()452	}453454	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {455		self.base.base.rpc_cors(is_dev)456	}457458	fn default_heap_pages(&self) -> Result<Option<u64>> {459		self.base.base.default_heap_pages()460	}461462	fn force_authoring(&self) -> Result<bool> {463		self.base.base.force_authoring()464	}465466	fn disable_grandpa(&self) -> Result<bool> {467		self.base.base.disable_grandpa()468	}469470	fn max_runtime_instances(&self) -> Result<Option<usize>> {471		self.base.base.max_runtime_instances()472	}473474	fn announce_block(&self) -> Result<bool> {475		self.base.base.announce_block()476	}477478	fn telemetry_endpoints(479		&self,480		chain_spec: &Box<dyn ChainSpec>,481	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {482		self.base.base.telemetry_endpoints(chain_spec)483	}484}