difftreelog
Add RuntimeId, use match on runtime identification
in: master
2 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -38,25 +38,35 @@
#[cfg(feature = "opal-runtime")]
pub type OpalChainSpec = sc_service::GenericChainSpec<opal_runtime::GenesisConfig, Extensions>;
+pub enum RuntimeId {
+ Unique,
+ Quartz,
+ Opal,
+ Unknown(String),
+}
+
pub trait RuntimeIdentification {
- fn is_unique(&self) -> bool;
-
- fn is_quartz(&self) -> bool;
-
- fn is_opal(&self) -> bool;
+ fn runtime_id(&self) -> RuntimeId;
}
impl RuntimeIdentification for Box<dyn sc_service::ChainSpec> {
- fn is_unique(&self) -> bool {
- self.id().starts_with("unique")
- }
+ fn runtime_id(&self) -> RuntimeId {
+ #[cfg(feature = "unique-runtime")]
+ if self.id().starts_with("unique") {
+ return RuntimeId::Unique;
+ }
- fn is_quartz(&self) -> bool {
- self.id().starts_with("quartz")
- }
+ #[cfg(feature = "quartz-runtime")]
+ if self.id().starts_with("quartz") {
+ return RuntimeId::Quartz;
+ }
+
+ #[cfg(feature = "opal-runtime")]
+ if self.id().starts_with("opal") {
+ return RuntimeId::Opal;
+ }
- fn is_opal(&self) -> bool {
- self.id().starts_with("opal") || self.id() == "dev" || self.id() == "local_testnet"
+ RuntimeId::Unknown(self.id().into())
}
}
node/cli/src/command.rsdiffbeforeafterboth1// 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(¶ms.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) = ¶ms.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(¶ms.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) = ¶ms.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}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, RuntimeId, 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_name:expr) => {70 format!(71 "No runtime valid runtime was found for chain {}",72 $chain_name73 )74 };75}7677fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {78 Ok(match id {79 "westend-local" => Box::new(chain_spec::local_testnet_westend_config()),80 "rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),81 "dev" => Box::new(chain_spec::development_config()),82 "" | "local" => 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(86 path.clone(),87 )?) as Box<dyn sc_service::ChainSpec>;8889 match chain_spec.runtime_id() {90 #[cfg(feature = "unique-runtime")]91 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),9293 #[cfg(feature = "quartz-runtime")]94 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9596 #[cfg(feature = "opal-runtime")]97 RuntimeId::Opal => Box::new(chain_spec::OpalChainSpec::from_json_file(path)?),9899 RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),100 }101 }102 })103}104105impl SubstrateCli for Cli {106 // TODO use args107 fn impl_name() -> String {108 "Unique Node".into()109 }110111 fn impl_version() -> String {112 env!("SUBSTRATE_CLI_IMPL_VERSION").into()113 }114 // TODO use args115 fn description() -> String {116 format!(117 "Unique Node\n\nThe command-line arguments provided first will be \118 passed to the parachain node, while the arguments provided after -- will be passed \119 to the relaychain node.\n\n\120 {} [parachain-args] -- [relaychain-args]",121 Self::executable_name()122 )123 }124125 fn author() -> String {126 env!("CARGO_PKG_AUTHORS").into()127 }128129 //TODO use args130 fn support_url() -> String {131 "support@unique.network".into()132 }133134 fn copyright_start_year() -> i32 {135 2019136 }137138 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {139 load_spec(id)140 }141142 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {143 match chain_spec.runtime_id() {144 #[cfg(feature = "unique-runtime")]145 RuntimeId::Unique => &unique_runtime::VERSION,146147 #[cfg(feature = "quartz-runtime")]148 RuntimeId::Quartz => &quartz_runtime::VERSION,149150 #[cfg(feature = "opal-runtime")]151 RuntimeId::Opal => &opal_runtime::VERSION,152153 RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),154 }155 }156}157158impl SubstrateCli for RelayChainCli {159 // TODO use args160 fn impl_name() -> String {161 "Unique Node".into()162 }163164 fn impl_version() -> String {165 env!("SUBSTRATE_CLI_IMPL_VERSION").into()166 }167 // TODO use args168 fn description() -> String {169 "Unique Node\n\nThe command-line arguments provided first will be \170 passed to the parachain node, while the arguments provided after -- will be passed \171 to the relaychain node.\n\n\172 parachain-collator [parachain-args] -- [relaychain-args]"173 .into()174 }175176 fn author() -> String {177 env!("CARGO_PKG_AUTHORS").into()178 }179 // TODO use args180 fn support_url() -> String {181 "support@unique.network".into()182 }183184 fn copyright_start_year() -> i32 {185 2019186 }187188 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {189 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)190 }191192 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {193 polkadot_cli::Cli::native_runtime_version(chain_spec)194 }195}196197#[allow(clippy::borrowed_box)]198fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {199 let mut storage = chain_spec.build_storage()?;200201 storage202 .top203 .remove(sp_core::storage::well_known_keys::CODE)204 .ok_or_else(|| "Could not find wasm file in genesis state!".into())205}206207macro_rules! async_run_with_runtime {208 (209 $runtime_api:path, $executor:path,210 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,211 $( $code:tt )*212 ) => {213 $runner.async_run(|$config| {214 let $components = new_partial::<215 $runtime_api, $executor, _216 >(217 &$config,218 crate::service::parachain_build_import_queue,219 )?;220 let task_manager = $components.task_manager;221222 { $( $code )* }.map(|v| (v, task_manager))223 })224 };225}226227macro_rules! construct_async_run {228 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{229 let runner = $cli.create_runner($cmd)?;230231 match runner.config().chain_spec.runtime_id() {232 #[cfg(feature = "unique-runtime")]233 RuntimeId::Unique => async_run_with_runtime!(234 unique_runtime::RuntimeApi, UniqueRuntimeExecutor,235 runner, $components, $cli, $cmd, $config, $( $code )*236 ),237238 #[cfg(feature = "quartz-runtime")]239 RuntimeId::Quartz => async_run_with_runtime!(240 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,241 runner, $components, $cli, $cmd, $config, $( $code )*242 ),243244 #[cfg(feature = "opal-runtime")]245 RuntimeId::Opal => async_run_with_runtime!(246 opal_runtime::RuntimeApi, OpalRuntimeExecutor,247 runner, $components, $cli, $cmd, $config, $( $code )*248 ),249250 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())251 }252 }}253}254255/// Parse command line arguments into service configuration.256pub fn run() -> Result<()> {257 let cli = Cli::from_args();258259 match &cli.subcommand {260 Some(Subcommand::BuildSpec(cmd)) => {261 let runner = cli.create_runner(cmd)?;262 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))263 }264 Some(Subcommand::CheckBlock(cmd)) => {265 construct_async_run!(|components, cli, cmd, config| {266 Ok(cmd.run(components.client, components.import_queue))267 })268 }269 Some(Subcommand::ExportBlocks(cmd)) => {270 construct_async_run!(|components, cli, cmd, config| {271 Ok(cmd.run(components.client, config.database))272 })273 }274 Some(Subcommand::ExportState(cmd)) => {275 construct_async_run!(|components, cli, cmd, config| {276 Ok(cmd.run(components.client, config.chain_spec))277 })278 }279 Some(Subcommand::ImportBlocks(cmd)) => {280 construct_async_run!(|components, cli, cmd, config| {281 Ok(cmd.run(components.client, components.import_queue))282 })283 }284 Some(Subcommand::PurgeChain(cmd)) => {285 let runner = cli.create_runner(cmd)?;286287 runner.sync_run(|config| {288 let polkadot_cli = RelayChainCli::new(289 &config,290 [RelayChainCli::executable_name()]291 .iter()292 .chain(cli.relaychain_args.iter()),293 );294295 let polkadot_config = SubstrateCli::create_configuration(296 &polkadot_cli,297 &polkadot_cli,298 config.tokio_handle.clone(),299 )300 .map_err(|err| format!("Relay chain argument error: {}", err))?;301302 cmd.run(config, polkadot_config)303 })304 }305 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {306 Ok(cmd.run(components.client, components.backend))307 }),308 Some(Subcommand::ExportGenesisState(params)) => {309 let mut builder = sc_cli::LoggerBuilder::new("");310 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");311 let _ = builder.init();312313 let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?;314 let state_version = Cli::native_runtime_version(&spec).state_version();315 let block: Block = generate_genesis_block(&spec, state_version)?;316 let raw_header = block.header().encode();317 let output_buf = if params.raw {318 raw_header319 } else {320 format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()321 };322323 if let Some(output) = ¶ms.output {324 std::fs::write(output, output_buf)?;325 } else {326 std::io::stdout().write_all(&output_buf)?;327 }328329 Ok(())330 }331 Some(Subcommand::ExportGenesisWasm(params)) => {332 let mut builder = sc_cli::LoggerBuilder::new("");333 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");334 let _ = builder.init();335336 let raw_wasm_blob =337 extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?;338 let output_buf = if params.raw {339 raw_wasm_blob340 } else {341 format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()342 };343344 if let Some(output) = ¶ms.output {345 std::fs::write(output, output_buf)?;346 } else {347 std::io::stdout().write_all(&output_buf)?;348 }349350 Ok(())351 }352 Some(Subcommand::Benchmark(cmd)) => {353 if cfg!(feature = "runtime-benchmarks") {354 let runner = cli.create_runner(cmd)?;355 runner.sync_run(|config| match config.chain_spec.runtime_id() {356 #[cfg(feature = "unique-runtime")]357 RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),358359 #[cfg(feature = "quartz-runtime")]360 RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),361362 #[cfg(feature = "opal-runtime")]363 RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),364365 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),366 })367 } else {368 Err("Benchmarking wasn't enabled when building the node. \369 You can enable it with `--features runtime-benchmarks`."370 .into())371 }372 }373 None => {374 let runner = cli.create_runner(&cli.run.normalize())?;375376 runner.run_node_until_exit(|config| async move {377 let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)378 .map(|e| e.para_id)379 .ok_or("Could not find parachain ID in chain-spec.")?;380381 let polkadot_cli = RelayChainCli::new(382 &config,383 [RelayChainCli::executable_name()]384 .iter()385 .chain(cli.relaychain_args.iter()),386 );387388 let id = ParaId::from(para_id);389390 let parachain_account =391 AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);392393 let state_version =394 RelayChainCli::native_runtime_version(&config.chain_spec).state_version();395 let block: Block = generate_genesis_block(&config.chain_spec, state_version)396 .map_err(|e| format!("{:?}", e))?;397 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));398 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));399400 let polkadot_config = SubstrateCli::create_configuration(401 &polkadot_cli,402 &polkadot_cli,403 config.tokio_handle.clone(),404 )405 .map_err(|err| format!("Relay chain argument error: {}", err))?;406407 info!("Parachain id: {:?}", id);408 info!("Parachain Account: {}", parachain_account);409 info!("Parachain genesis state: {}", genesis_state);410 info!("Parachain genesis hash: {}", genesis_hash);411 info!(412 "Is collating: {}",413 if config.role.is_authority() {414 "yes"415 } else {416 "no"417 }418 );419420 match config.chain_spec.runtime_id() {421 #[cfg(feature = "unique-runtime")]422 RuntimeId::Unique => crate::service::start_node::<423 unique_runtime::Runtime,424 unique_runtime::RuntimeApi,425 UniqueRuntimeExecutor,426 >(config, polkadot_config, id)427 .await428 .map(|r| r.0)429 .map_err(Into::into),430431 #[cfg(feature = "quartz-runtime")]432 RuntimeId::Quartz => crate::service::start_node::<433 quartz_runtime::Runtime,434 quartz_runtime::RuntimeApi,435 QuartzRuntimeExecutor,436 >(config, polkadot_config, id)437 .await438 .map(|r| r.0)439 .map_err(Into::into),440441 #[cfg(feature = "opal-runtime")]442 RuntimeId::Opal => crate::service::start_node::<443 opal_runtime::Runtime,444 opal_runtime::RuntimeApi,445 OpalRuntimeExecutor,446 >(config, polkadot_config, id)447 .await448 .map(|r| r.0)449 .map_err(Into::into),450451 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),452 }453 })454 }455 }456}457458impl DefaultConfigurationValues for RelayChainCli {459 fn p2p_listen_port() -> u16 {460 30334461 }462463 fn rpc_ws_listen_port() -> u16 {464 9945465 }466467 fn rpc_http_listen_port() -> u16 {468 9934469 }470471 fn prometheus_listen_port() -> u16 {472 9616473 }474}475476impl CliConfiguration<Self> for RelayChainCli {477 fn shared_params(&self) -> &SharedParams {478 self.base.base.shared_params()479 }480481 fn import_params(&self) -> Option<&ImportParams> {482 self.base.base.import_params()483 }484485 fn network_params(&self) -> Option<&NetworkParams> {486 self.base.base.network_params()487 }488489 fn keystore_params(&self) -> Option<&KeystoreParams> {490 self.base.base.keystore_params()491 }492493 fn base_path(&self) -> Result<Option<BasePath>> {494 Ok(self495 .shared_params()496 .base_path()497 .or_else(|| self.base_path.clone().map(Into::into)))498 }499500 fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {501 self.base.base.rpc_http(default_listen_port)502 }503504 fn rpc_ipc(&self) -> Result<Option<String>> {505 self.base.base.rpc_ipc()506 }507508 fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {509 self.base.base.rpc_ws(default_listen_port)510 }511512 fn prometheus_config(513 &self,514 default_listen_port: u16,515 chain_spec: &Box<dyn ChainSpec>,516 ) -> Result<Option<PrometheusConfig>> {517 self.base518 .base519 .prometheus_config(default_listen_port, chain_spec)520 }521522 fn init<F>(523 &self,524 _support_url: &String,525 _impl_version: &String,526 _logger_hook: F,527 _config: &sc_service::Configuration,528 ) -> Result<()> {529 unreachable!("PolkadotCli is never initialized; qed");530 }531532 fn chain_id(&self, is_dev: bool) -> Result<String> {533 let chain_id = self.base.base.chain_id(is_dev)?;534535 Ok(if chain_id.is_empty() {536 self.chain_id.clone().unwrap_or_default()537 } else {538 chain_id539 })540 }541542 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {543 self.base.base.role(is_dev)544 }545546 fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {547 self.base.base.transaction_pool()548 }549550 fn state_cache_child_ratio(&self) -> Result<Option<usize>> {551 self.base.base.state_cache_child_ratio()552 }553554 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {555 self.base.base.rpc_methods()556 }557558 fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {559 self.base.base.rpc_ws_max_connections()560 }561562 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {563 self.base.base.rpc_cors(is_dev)564 }565566 fn default_heap_pages(&self) -> Result<Option<u64>> {567 self.base.base.default_heap_pages()568 }569570 fn force_authoring(&self) -> Result<bool> {571 self.base.base.force_authoring()572 }573574 fn disable_grandpa(&self) -> Result<bool> {575 self.base.base.disable_grandpa()576 }577578 fn max_runtime_instances(&self) -> Result<Option<usize>> {579 self.base.base.max_runtime_instances()580 }581582 fn announce_block(&self) -> Result<bool> {583 self.base.base.announce_block()584 }585586 fn telemetry_endpoints(587 &self,588 chain_spec: &Box<dyn ChainSpec>,589 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {590 self.base.base.telemetry_endpoints(chain_spec)591 }592}