git.delta.rocks / unique-network / refs/commits / 186cd5e51d7b

difftreelog

source

node/cli/src/command.rs16.8 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::{self, RuntimeIdentification},37	cli::{Cli, RelayChainCli, Subcommand},38	service::new_partial,39};4041#[cfg(feature = "unique-runtime")]42use crate::service::UniqueRuntimeExecutor;4344#[cfg(feature = "quartz-runtime")]45use crate::service::QuartzRuntimeExecutor;4647#[cfg(feature = "opal-runtime")]48use crate::service::OpalRuntimeExecutor;4950use codec::Encode;51use cumulus_primitives_core::ParaId;52use cumulus_client_service::genesis::generate_genesis_block;53use log::info;54use polkadot_parachain::primitives::AccountIdConversion;55use sc_cli::{56	ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,57	NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,58};59use sc_service::{60	config::{BasePath, PrometheusConfig},61};62use sp_core::hexdisplay::HexDisplay;63use sp_runtime::traits::Block as BlockT;64use std::{io::Write, net::SocketAddr};6566use unique_runtime_common::types::Block;6768macro_rules! no_runtime_err {69	($chain_spec:expr) => {70		format!(71			"No runtime valid runtime was found, chain id: {}",72			$chain_spec.id()73		)74	};75}7677fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {78	match id {79		"westend-local" => Ok(Box::new(chain_spec::local_testnet_westend_config())),80		"rococo-local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),81		"dev" => Ok(Box::new(chain_spec::development_config())),82		"" | "local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),83		path => {84			let path = std::path::PathBuf::from(path);85			let chain_spec = Box::new(sc_service::GenericChainSpec::<()>::from_json_file(path.clone())?)86				as Box<dyn sc_service::ChainSpec>;8788			#[cfg(feature = "unique-runtime")]89			if chain_spec.is_unique() {90				let chain_spec = chain_spec::UniqueChainSpec::from_json_file(path)?;91				return Ok(Box::new(chain_spec));92			}9394			#[cfg(feature = "quartz-runtime")]95			if chain_spec.is_quartz() {96				let chain_spec = chain_spec::QuartzChainSpec::from_json_file(path)?;97				return Ok(Box::new(chain_spec));98			}99100			#[cfg(feature = "opal-runtime")]101			if chain_spec.is_opal() {102				let chain_spec = chain_spec::OpalChainSpec::from_json_file(path)?;103				return Ok(Box::new(chain_spec));104			}105106			Err(no_runtime_err!(chain_spec))107		}108	}109}110111impl SubstrateCli for Cli {112	// TODO use args113	fn impl_name() -> String {114		"Unique Node".into()115	}116117	fn impl_version() -> String {118		env!("SUBSTRATE_CLI_IMPL_VERSION").into()119	}120	// TODO use args121	fn description() -> String {122		format!(123			"Unique Node\n\nThe command-line arguments provided first will be \124		passed to the parachain node, while the arguments provided after -- will be passed \125		to the relaychain node.\n\n\126		{} [parachain-args] -- [relaychain-args]",127			Self::executable_name()128		)129	}130131	fn author() -> String {132		env!("CARGO_PKG_AUTHORS").into()133	}134135	//TODO use args136	fn support_url() -> String {137		"support@unique.network".into()138	}139140	fn copyright_start_year() -> i32 {141		2019142	}143144	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {145		load_spec(id)146	}147148	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {149		#[cfg(feature = "unique-runtime")]150		if chain_spec.is_unique() {151			return &unique_runtime::VERSION;152		}153154		#[cfg(feature = "quartz-runtime")]155		if chain_spec.is_quartz() {156			return &quartz_runtime::VERSION;157		}158159		#[cfg(feature = "opal-runtime")]160		if chain_spec.is_opal() {161			return &opal_runtime::VERSION;162		}163164		panic!("{}", no_runtime_err!(chain_spec));165	}166}167168impl SubstrateCli for RelayChainCli {169	// TODO use args170	fn impl_name() -> String {171		"Unique Node".into()172	}173174	fn impl_version() -> String {175		env!("SUBSTRATE_CLI_IMPL_VERSION").into()176	}177	// TODO use args178	fn description() -> String {179		"Unique Node\n\nThe command-line arguments provided first will be \180		passed to the parachain node, while the arguments provided after -- will be passed \181		to the relaychain node.\n\n\182		parachain-collator [parachain-args] -- [relaychain-args]"183			.into()184	}185186	fn author() -> String {187		env!("CARGO_PKG_AUTHORS").into()188	}189	// TODO use args190	fn support_url() -> String {191		"support@unique.network".into()192	}193194	fn copyright_start_year() -> i32 {195		2019196	}197198	fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {199		polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)200	}201202	fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {203		polkadot_cli::Cli::native_runtime_version(chain_spec)204	}205}206207#[allow(clippy::borrowed_box)]208fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {209	let mut storage = chain_spec.build_storage()?;210211	storage212		.top213		.remove(sp_core::storage::well_known_keys::CODE)214		.ok_or_else(|| "Could not find wasm file in genesis state!".into())215}216217macro_rules! construct_async_run {218	(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{219		let runner = $cli.create_runner($cmd)?;220221		#[cfg(feature = "unique-runtime")]222		if runner.config().chain_spec.is_unique() {223			return runner.async_run(|$config| {224				let $components = new_partial::<225					unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _226				>(227					&$config,228					crate::service::parachain_build_import_queue,229				)?;230				let task_manager = $components.task_manager;231				{ $( $code )* }.map(|v| (v, task_manager))232			});233		}234235		#[cfg(feature = "quartz-runtime")]236		if runner.config().chain_spec.is_quartz() {237			return runner.async_run(|$config| {238				let $components = new_partial::<239					quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _240				>(241					&$config,242					crate::service::parachain_build_import_queue,243				)?;244				let task_manager = $components.task_manager;245				{ $( $code )* }.map(|v| (v, task_manager))246			});247		}248249		#[cfg(feature = "opal-runtime")]250		if runner.config().chain_spec.is_opal() {251			return runner.async_run(|$config| {252				let $components = new_partial::<253					opal_runtime::RuntimeApi, OpalRuntimeExecutor, _254				>(255					&$config,256					crate::service::parachain_build_import_queue,257				)?;258				let task_manager = $components.task_manager;259				{ $( $code )* }.map(|v| (v, task_manager))260			});261		}262263		Err(no_runtime_err!(runner.config().chain_spec).into())264	}}265}266267/// Parse command line arguments into service configuration.268pub fn run() -> Result<()> {269	let cli = Cli::from_args();270271	match &cli.subcommand {272		Some(Subcommand::BuildSpec(cmd)) => {273			let runner = cli.create_runner(cmd)?;274			runner.sync_run(|config| cmd.run(config.chain_spec, config.network))275		}276		Some(Subcommand::CheckBlock(cmd)) => {277			construct_async_run!(|components, cli, cmd, config| {278				Ok(cmd.run(components.client, components.import_queue))279			})280		}281		Some(Subcommand::ExportBlocks(cmd)) => {282			construct_async_run!(|components, cli, cmd, config| {283				Ok(cmd.run(components.client, config.database))284			})285		}286		Some(Subcommand::ExportState(cmd)) => {287			construct_async_run!(|components, cli, cmd, config| {288				Ok(cmd.run(components.client, config.chain_spec))289			})290		}291		Some(Subcommand::ImportBlocks(cmd)) => {292			construct_async_run!(|components, cli, cmd, config| {293				Ok(cmd.run(components.client, components.import_queue))294			})295		}296		Some(Subcommand::PurgeChain(cmd)) => {297			let runner = cli.create_runner(cmd)?;298299			runner.sync_run(|config| {300				let polkadot_cli = RelayChainCli::new(301					&config,302					[RelayChainCli::executable_name()]303						.iter()304						.chain(cli.relaychain_args.iter()),305				);306307				let polkadot_config = SubstrateCli::create_configuration(308					&polkadot_cli,309					&polkadot_cli,310					config.tokio_handle.clone(),311				)312				.map_err(|err| format!("Relay chain argument error: {}", err))?;313314				cmd.run(config, polkadot_config)315			})316		}317		Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {318			Ok(cmd.run(components.client, components.backend))319		}),320		Some(Subcommand::ExportGenesisState(params)) => {321			let mut builder = sc_cli::LoggerBuilder::new("");322			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");323			let _ = builder.init();324325			let spec = load_spec(&params.chain.clone().unwrap_or_default())?;326			let state_version = Cli::native_runtime_version(&spec).state_version();327			let block: Block = generate_genesis_block(&spec, state_version)?;328			let raw_header = block.header().encode();329			let output_buf = if params.raw {330				raw_header331			} else {332				format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()333			};334335			if let Some(output) = &params.output {336				std::fs::write(output, output_buf)?;337			} else {338				std::io::stdout().write_all(&output_buf)?;339			}340341			Ok(())342		}343		Some(Subcommand::ExportGenesisWasm(params)) => {344			let mut builder = sc_cli::LoggerBuilder::new("");345			builder.with_profiling(sc_tracing::TracingReceiver::Log, "");346			let _ = builder.init();347348			let raw_wasm_blob =349				extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?;350			let output_buf = if params.raw {351				raw_wasm_blob352			} else {353				format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()354			};355356			if let Some(output) = &params.output {357				std::fs::write(output, output_buf)?;358			} else {359				std::io::stdout().write_all(&output_buf)?;360			}361362			Ok(())363		}364		Some(Subcommand::Benchmark(cmd)) => {365			if cfg!(feature = "runtime-benchmarks") {366				let runner = cli.create_runner(cmd)?;367				runner.sync_run(|config| {368					#[cfg(feature = "unique-runtime")]369					if config.chain_spec.is_unique() {370						return cmd.run::<Block, UniqueRuntimeExecutor>(config);371					}372373					#[cfg(feature = "quartz-runtime")]374					if config.chain_spec.is_quartz() {375						return cmd.run::<Block, QuartzRuntimeExecutor>(config);376					}377378					#[cfg(feature = "opal-runtime")]379					if config.chain_spec.is_opal() {380						return cmd.run::<Block, OpalRuntimeExecutor>(config);381					}382383					Err(no_runtime_err!(config.chain_spec).into())384				})385			} else {386				Err("Benchmarking wasn't enabled when building the node. \387				You can enable it with `--features runtime-benchmarks`."388					.into())389			}390		}391		None => {392			let runner = cli.create_runner(&cli.run.normalize())?;393394			runner.run_node_until_exit(|config| async move {395				let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)396					.map(|e| e.para_id)397					.ok_or("Could not find parachain ID in chain-spec.")?;398399				let polkadot_cli = RelayChainCli::new(400					&config,401					[RelayChainCli::executable_name()]402						.iter()403						.chain(cli.relaychain_args.iter()),404				);405406				let id = ParaId::from(para_id);407408				let parachain_account =409					AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);410411				let state_version =412					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();413				let block: Block = generate_genesis_block(&config.chain_spec, state_version)414					.map_err(|e| format!("{:?}", e))?;415				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));416				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));417418				let polkadot_config = SubstrateCli::create_configuration(419					&polkadot_cli,420					&polkadot_cli,421					config.tokio_handle.clone(),422				)423				.map_err(|err| format!("Relay chain argument error: {}", err))?;424425				info!("Parachain id: {:?}", id);426				info!("Parachain Account: {}", parachain_account);427				info!("Parachain genesis state: {}", genesis_state);428				info!("Parachain genesis hash: {}", genesis_hash);429				info!(430					"Is collating: {}",431					if config.role.is_authority() {432						"yes"433					} else {434						"no"435					}436				);437438				#[cfg(feature = "unique-runtime")]439				if config.chain_spec.is_unique() {440					return crate::service::start_node::<441						unique_runtime::Runtime,442						unique_runtime::RuntimeApi,443						UniqueRuntimeExecutor,444					>(config, polkadot_config, id)445					.await446					.map(|r| r.0)447					.map_err(Into::into);448				}449450				#[cfg(feature = "quartz-runtime")]451				if config.chain_spec.is_quartz() {452					return crate::service::start_node::<453						quartz_runtime::Runtime,454						quartz_runtime::RuntimeApi,455						QuartzRuntimeExecutor,456					>(config, polkadot_config, id)457					.await458					.map(|r| r.0)459					.map_err(Into::into);460				}461462				#[cfg(feature = "opal-runtime")]463				if config.chain_spec.is_opal() {464					return crate::service::start_node::<465						opal_runtime::Runtime,466						opal_runtime::RuntimeApi,467						OpalRuntimeExecutor,468					>(config, polkadot_config, id)469					.await470					.map(|r| r.0)471					.map_err(Into::into);472				}473474				Err(no_runtime_err!(config.chain_spec).into())475			})476		}477	}478}479480impl DefaultConfigurationValues for RelayChainCli {481	fn p2p_listen_port() -> u16 {482		30334483	}484485	fn rpc_ws_listen_port() -> u16 {486		9945487	}488489	fn rpc_http_listen_port() -> u16 {490		9934491	}492493	fn prometheus_listen_port() -> u16 {494		9616495	}496}497498impl CliConfiguration<Self> for RelayChainCli {499	fn shared_params(&self) -> &SharedParams {500		self.base.base.shared_params()501	}502503	fn import_params(&self) -> Option<&ImportParams> {504		self.base.base.import_params()505	}506507	fn network_params(&self) -> Option<&NetworkParams> {508		self.base.base.network_params()509	}510511	fn keystore_params(&self) -> Option<&KeystoreParams> {512		self.base.base.keystore_params()513	}514515	fn base_path(&self) -> Result<Option<BasePath>> {516		Ok(self517			.shared_params()518			.base_path()519			.or_else(|| self.base_path.clone().map(Into::into)))520	}521522	fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {523		self.base.base.rpc_http(default_listen_port)524	}525526	fn rpc_ipc(&self) -> Result<Option<String>> {527		self.base.base.rpc_ipc()528	}529530	fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {531		self.base.base.rpc_ws(default_listen_port)532	}533534	fn prometheus_config(535		&self,536		default_listen_port: u16,537		chain_spec: &Box<dyn ChainSpec>,538	) -> Result<Option<PrometheusConfig>> {539		self.base540			.base541			.prometheus_config(default_listen_port, chain_spec)542	}543544	fn init<F>(545		&self,546		_support_url: &String,547		_impl_version: &String,548		_logger_hook: F,549		_config: &sc_service::Configuration,550	) -> Result<()> {551		unreachable!("PolkadotCli is never initialized; qed");552	}553554	fn chain_id(&self, is_dev: bool) -> Result<String> {555		let chain_id = self.base.base.chain_id(is_dev)?;556557		Ok(if chain_id.is_empty() {558			self.chain_id.clone().unwrap_or_default()559		} else {560			chain_id561		})562	}563564	fn role(&self, is_dev: bool) -> Result<sc_service::Role> {565		self.base.base.role(is_dev)566	}567568	fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {569		self.base.base.transaction_pool()570	}571572	fn state_cache_child_ratio(&self) -> Result<Option<usize>> {573		self.base.base.state_cache_child_ratio()574	}575576	fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {577		self.base.base.rpc_methods()578	}579580	fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {581		self.base.base.rpc_ws_max_connections()582	}583584	fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {585		self.base.base.rpc_cors(is_dev)586	}587588	fn default_heap_pages(&self) -> Result<Option<u64>> {589		self.base.base.default_heap_pages()590	}591592	fn force_authoring(&self) -> Result<bool> {593		self.base.base.force_authoring()594	}595596	fn disable_grandpa(&self) -> Result<bool> {597		self.base.base.disable_grandpa()598	}599600	fn max_runtime_instances(&self) -> Result<Option<usize>> {601		self.base.base.max_runtime_instances()602	}603604	fn announce_block(&self) -> Result<bool> {605		self.base.base.announce_block()606	}607608	fn telemetry_endpoints(609		&self,610		chain_spec: &Box<dyn ChainSpec>,611	) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {612		self.base.base.telemetry_endpoints(chain_spec)613	}614}