git.delta.rocks / unique-network / refs/commits / 7e0ba1d9645e

difftreelog

source

node/cli/src/command.rs13.4 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		format!("{} Node", runtime::RUNTIME_NAME)83	}8485	fn impl_version() -> String {86		env!("SUBSTRATE_CLI_IMPL_VERSION").into()87	}88	// TODO use args89	fn description() -> String {90		format!(91			"{} 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			runtime::RUNTIME_NAME,96			Self::executable_name()97		)98	}99100	fn author() -> String {101		env!("CARGO_PKG_AUTHORS").into()102	}103104	//TODO use args105	fn support_url() -> String {106		"support@unique.network".into()107	}108109	fn copyright_start_year() -> i32 {110		2019111	}112113	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {114		load_spec(id)115	}116117	fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {118		&runtime::VERSION119	}120}121122impl SubstrateCli for RelayChainCli {123	// TODO use args124	fn impl_name() -> String {125		format!("{} Node", runtime::RUNTIME_NAME)126	}127128	fn impl_version() -> String {129		env!("SUBSTRATE_CLI_IMPL_VERSION").into()130	}131	// TODO use args132	fn description() -> String {133		format!(134			"{} Node\n\nThe command-line arguments provided first will be \135		passed to the parachain node, while the arguments provided after -- will be passed \136		to the relaychain node.\n\n\137		parachain-collator [parachain-args] -- [relaychain-args]",138			runtime::RUNTIME_NAME139		)140	}141142	fn author() -> String {143		env!("CARGO_PKG_AUTHORS").into()144	}145	// TODO use args146	fn support_url() -> String {147		"support@unique.network".into()148	}149150	fn copyright_start_year() -> i32 {151		2019152	}153154	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {155		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)156	}157158	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {159		polkadot_cli::Cli::native_runtime_version(chain_spec)160	}161}162163#[allow(clippy::borrowed_box)]164fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {165	let mut storage = chain_spec.build_storage()?;166167	storage168		.top169		.remove(sp_core::storage::well_known_keys::CODE)170		.ok_or_else(|| "Could not find wasm file in genesis state!".into())171}172173macro_rules! construct_async_run {174	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{175		let runner = $cli.create_runner($cmd)?;176		runner.async_run(|$config| {177			let $components = new_partial::<178				_179			>(180				&$config,181				crate::service::parachain_build_import_queue,182			)?;183			let task_manager = $components.task_manager;184			{ $( $code )* }.map(|v| (v, task_manager))185		})186	}}187}188189/// Parse command line arguments into service configuration.190pub fn run() -> Result<()> {191	let cli = Cli::from_args();192193	match &cli.subcommand {194		Some(Subcommand::BuildSpec(cmd)) => {195			let runner = cli.create_runner(cmd)?;196			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))197		}198		Some(Subcommand::CheckBlock(cmd)) => {199			construct_async_run!(|components, cli, cmd, config| {200				Ok(cmd.run(components.client, components.import_queue))201			})202		}203		Some(Subcommand::ExportBlocks(cmd)) => {204			construct_async_run!(|components, cli, cmd, config| {205				Ok(cmd.run(components.client, config.database))206			})207		}208		Some(Subcommand::ExportState(cmd)) => {209			construct_async_run!(|components, cli, cmd, config| {210				Ok(cmd.run(components.client, config.chain_spec))211			})212		}213		Some(Subcommand::ImportBlocks(cmd)) => {214			construct_async_run!(|components, cli, cmd, config| {215				Ok(cmd.run(components.client, components.import_queue))216			})217		}218		Some(Subcommand::PurgeChain(cmd)) => {219			let runner = cli.create_runner(cmd)?;220221			runner.sync_run(|config| {222				let polkadot_cli = RelayChainCli::new(223					&config,224					[RelayChainCli::executable_name()]225						.iter()226						.chain(cli.relaychain_args.iter()),227				);228229				let polkadot_config = SubstrateCli::create_configuration(230					&polkadot_cli,231					&polkadot_cli,232					config.tokio_handle.clone(),233				)234				.map_err(|err| format!("Relay chain argument error: {}", err))?;235236				cmd.run(config, polkadot_config)237			})238		}239		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {240			Ok(cmd.run(components.client, components.backend))241		}),242		Some(Subcommand::ExportGenesisState(params)) => {243			let mut builder = sc_cli::LoggerBuilder::new("");244			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");245			let _ = builder.init();246247			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;248			let state_version = Cli::native_runtime_version(&spec).state_version();249			let block: Block = generate_genesis_block(&spec, state_version)?;250			let raw_header = block.header().encode();251			let output_buf = if params.raw {252				raw_header253			} else {254				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()255			};256257			if let Some(output) = &params.output {258				std::fs::write(output, output_buf)?;259			} else {260				std::io::stdout().write_all(&output_buf)?;261			}262263			Ok(())264		}265		Some(Subcommand::ExportGenesisWasm(params)) => {266			let mut builder = sc_cli::LoggerBuilder::new("");267			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");268			let _ = builder.init();269270			let raw_wasm_blob =271				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;272			let output_buf = if params.raw {273				raw_wasm_blob274			} else {275				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()276			};277278			if let Some(output) = &params.output {279				std::fs::write(output, output_buf)?;280			} else {281				std::io::stdout().write_all(&output_buf)?;282			}283284			Ok(())285		}286		Some(Subcommand::Benchmark(cmd)) => {287			if cfg!(feature = "runtime-benchmarks") {288				let runner = cli.create_runner(cmd)?;289290				runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))291			} else {292				Err("Benchmarking wasn't enabled when building the node. \293				You can enable it with `--features runtime-benchmarks`."294					.into())295			}296		}297		None => {298			let runner = cli.create_runner(&cli.run.normalize())?;299300			runner.run_node_until_exit(|config| async move {301				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)302					.map(|e| e.para_id)303					.ok_or("Could not find parachain ID in chain-spec.")?;304305				let polkadot_cli = RelayChainCli::new(306					&config,307					[RelayChainCli::executable_name()]308						.iter()309						.chain(cli.relaychain_args.iter()),310				);311312				let id = ParaId::from(para_id);313314				let parachain_account =315					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);316317				let state_version =318					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();319				let block: Block = generate_genesis_block(&config.chain_spec, state_version)320					.map_err(|e| format!("{:?}", e))?;321				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));322				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));323324				let polkadot_config = SubstrateCli::create_configuration(325					&polkadot_cli,326					&polkadot_cli,327					config.tokio_handle.clone(),328				)329				.map_err(|err| format!("Relay chain argument error: {}", err))?;330331				info!("Parachain id: {:?}", id);332				info!("Parachain Account: {}", parachain_account);333				info!("Parachain genesis state: {}", genesis_state);334				info!("Parachain genesis hash: {}", genesis_hash);335				info!(336					"Is collating: {}",337					if config.role.is_authority() {338						"yes"339					} else {340						"no"341					}342				);343344				crate::service::start_node(config, polkadot_config, id)345					.await346					.map(|r| r.0)347					.map_err(Into::into)348			})349		}350	}351}352353impl DefaultConfigurationValues for RelayChainCli {354	fn p2p_listen_port() -> u16 {355		30334356	}357358	fn rpc_ws_listen_port() -> u16 {359		9945360	}361362	fn rpc_http_listen_port() -> u16 {363		9934364	}365366	fn prometheus_listen_port() -> u16 {367		9616368	}369}370371impl CliConfiguration<Self> for RelayChainCli {372	fn shared_params(&self) -> &SharedParams {373		self.base.base.shared_params()374	}375376	fn import_params(&self) -> Option<&ImportParams> {377		self.base.base.import_params()378	}379380	fn network_params(&self) -> Option<&NetworkParams> {381		self.base.base.network_params()382	}383384	fn keystore_params(&self) -> Option<&KeystoreParams> {385		self.base.base.keystore_params()386	}387388	fn base_path(&self) -> Result<Option<BasePath>> {389		Ok(self390			.shared_params()391			.base_path()392			.or_else(|| self.base_path.clone().map(Into::into)))393	}394395	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {396		self.base.base.rpc_http(default_listen_port)397	}398399	fn rpc_ipc(&self) -> Result<Option<String>> {400		self.base.base.rpc_ipc()401	}402403	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {404		self.base.base.rpc_ws(default_listen_port)405	}406407	fn prometheus_config(408		&self,409		default_listen_port: u16,410		chain_spec: &Box<dyn ChainSpec>,411	) -> Result<Option<PrometheusConfig>> {412		self.base413			.base414			.prometheus_config(default_listen_port, chain_spec)415	}416417	fn init<F>(418		&self,419		_support_url: &String,420		_impl_version: &String,421		_logger_hook: F,422		_config: &sc_service::Configuration,423	) -> Result<()> {424		unreachable!("PolkadotCli is never initialized; qed");425	}426427	fn chain_id(&self, is_dev: bool) -> Result<String> {428		let chain_id = self.base.base.chain_id(is_dev)?;429430		Ok(if chain_id.is_empty() {431			self.chain_id.clone().unwrap_or_default()432		} else {433			chain_id434		})435	}436437	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {438		self.base.base.role(is_dev)439	}440441	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {442		self.base.base.transaction_pool()443	}444445	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {446		self.base.base.state_cache_child_ratio()447	}448449	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {450		self.base.base.rpc_methods()451	}452453	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {454		self.base.base.rpc_ws_max_connections()455	}456457	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {458		self.base.base.rpc_cors(is_dev)459	}460461	fn default_heap_pages(&self) -> Result<Option<u64>> {462		self.base.base.default_heap_pages()463	}464465	fn force_authoring(&self) -> Result<bool> {466		self.base.base.force_authoring()467	}468469	fn disable_grandpa(&self) -> Result<bool> {470		self.base.base.disable_grandpa()471	}472473	fn max_runtime_instances(&self) -> Result<Option<usize>> {474		self.base.base.max_runtime_instances()475	}476477	fn announce_block(&self) -> Result<bool> {478		self.base.base.announce_block()479	}480481	fn telemetry_endpoints(482		&self,483		chain_spec: &Box<dyn ChainSpec>,484	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {485		self.base.base.telemetry_endpoints(chain_spec)486	}487}