difftreelog
cargo fmt
in: master
2 files changed
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, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification, default_runtime},37 cli::{Cli, RelayChainCli, Subcommand},38 service::{new_partial, start_node, start_dev_node},39};4041#[cfg(feature = "unique-runtime")]42use crate::service::UniqueRuntimeExecutor;4344#[cfg(feature = "quartz-runtime")]45use crate::service::QuartzRuntimeExecutor;4647use crate::service::{OpalRuntimeExecutor, DefaultRuntimeExecutor};4849use codec::Encode;50use cumulus_primitives_core::ParaId;51use cumulus_client_service::genesis::generate_genesis_block;52use std::{future::Future, pin::Pin};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, time::Duration};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 "dev" => Box::new(chain_spec::development_config()),80 "" | "local" => Box::new(chain_spec::local_testnet_config()),81 path => {82 let path = std::path::PathBuf::from(path);83 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)84 as Box<dyn sc_service::ChainSpec>;8586 match chain_spec.runtime_id() {87 #[cfg(feature = "unique-runtime")]88 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),8990 #[cfg(feature = "quartz-runtime")]91 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9293 RuntimeId::Opal => chain_spec,94 RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),95 }96 }97 })98}99100impl SubstrateCli for Cli {101 // TODO use args102 fn impl_name() -> String {103 format!("{} Node", Self::node_name())104 }105106 fn impl_version() -> String {107 env!("SUBSTRATE_CLI_IMPL_VERSION").into()108 }109 // TODO use args110 fn description() -> String {111 format!(112 "{} Node\n\nThe command-line arguments provided first will be \113 passed to the parachain node, while the arguments provided after -- will be passed \114 to the relaychain node.\n\n\115 {} [parachain-args] -- [relaychain-args]",116 Self::node_name(),117 Self::executable_name()118 )119 }120121 fn author() -> String {122 env!("CARGO_PKG_AUTHORS").into()123 }124125 //TODO use args126 fn support_url() -> String {127 "support@unique.network".into()128 }129130 fn copyright_start_year() -> i32 {131 2019132 }133134 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {135 load_spec(id)136 }137138 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {139 match chain_spec.runtime_id() {140 #[cfg(feature = "unique-runtime")]141 RuntimeId::Unique => &unique_runtime::VERSION,142143 #[cfg(feature = "quartz-runtime")]144 RuntimeId::Quartz => &quartz_runtime::VERSION,145146 RuntimeId::Opal => &opal_runtime::VERSION,147 RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),148 }149 }150}151152impl SubstrateCli for RelayChainCli {153 // TODO use args154 fn impl_name() -> String {155 format!("{} Node", Cli::node_name())156 }157158 fn impl_version() -> String {159 env!("SUBSTRATE_CLI_IMPL_VERSION").into()160 }161 // TODO use args162 fn description() -> String {163 format!(164 "{} Node\n\nThe command-line arguments provided first will be \165 passed to the parachain node, while the arguments provided after -- will be passed \166 to the relaychain node.\n\n\167 parachain-collator [parachain-args] -- [relaychain-args]",168 Cli::node_name()169 )170 }171172 fn author() -> String {173 env!("CARGO_PKG_AUTHORS").into()174 }175 // TODO use args176 fn support_url() -> String {177 "support@unique.network".into()178 }179180 fn copyright_start_year() -> i32 {181 2019182 }183184 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {185 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)186 }187188 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {189 polkadot_cli::Cli::native_runtime_version(chain_spec)190 }191}192193#[allow(clippy::borrowed_box)]194fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {195 let mut storage = chain_spec.build_storage()?;196197 storage198 .top199 .remove(sp_core::storage::well_known_keys::CODE)200 .ok_or_else(|| "Could not find wasm file in genesis state!".into())201}202203macro_rules! async_run_with_runtime {204 (205 $runtime_api:path, $executor:path,206 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,207 $( $code:tt )*208 ) => {209 $runner.async_run(|$config| {210 let $components = new_partial::<211 $runtime_api, $executor, _212 >(213 &$config,214 crate::service::parachain_build_import_queue,215 )?;216 let task_manager = $components.task_manager;217218 { $( $code )* }.map(|v| (v, task_manager))219 })220 };221}222223macro_rules! construct_async_run {224 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{225 let runner = $cli.create_runner($cmd)?;226227 match runner.config().chain_spec.runtime_id() {228 #[cfg(feature = "unique-runtime")]229 RuntimeId::Unique => async_run_with_runtime!(230 unique_runtime::RuntimeApi, UniqueRuntimeExecutor,231 runner, $components, $cli, $cmd, $config, $( $code )*232 ),233234 #[cfg(feature = "quartz-runtime")]235 RuntimeId::Quartz => async_run_with_runtime!(236 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,237 runner, $components, $cli, $cmd, $config, $( $code )*238 ),239240 RuntimeId::Opal => async_run_with_runtime!(241 opal_runtime::RuntimeApi, OpalRuntimeExecutor,242 runner, $components, $cli, $cmd, $config, $( $code )*243 ),244245 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())246 }247 }}248}249250macro_rules! start_node_using_chain_runtime {251 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {252 match $config.chain_spec.runtime_id() {253 #[cfg(feature = "unique-runtime")]254 RuntimeId::Unique => $start_node_fn::<255 unique_runtime::Runtime,256 unique_runtime::RuntimeApi,257 UniqueRuntimeExecutor,258 >($config $(, $($args),+)?) $($code)*,259260 #[cfg(feature = "quartz-runtime")]261 RuntimeId::Quartz => $start_node_fn::<262 quartz_runtime::Runtime,263 quartz_runtime::RuntimeApi,264 QuartzRuntimeExecutor,265 >($config $(, $($args),+)?) $($code)*,266267 RuntimeId::Opal => $start_node_fn::<268 opal_runtime::Runtime,269 opal_runtime::RuntimeApi,270 OpalRuntimeExecutor,271 >($config $(, $($args),+)?) $($code)*,272273 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),274 }275 };276}277278/// Parse command line arguments into service configuration.279pub fn run() -> Result<()> {280 let cli = Cli::from_args();281282 match &cli.subcommand {283 Some(Subcommand::BuildSpec(cmd)) => {284 let runner = cli.create_runner(cmd)?;285 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))286 }287 Some(Subcommand::CheckBlock(cmd)) => {288 construct_async_run!(|components, cli, cmd, config| {289 Ok(cmd.run(components.client, components.import_queue))290 })291 }292 Some(Subcommand::ExportBlocks(cmd)) => {293 construct_async_run!(|components, cli, cmd, config| {294 Ok(cmd.run(components.client, config.database))295 })296 }297 Some(Subcommand::ExportState(cmd)) => {298 construct_async_run!(|components, cli, cmd, config| {299 Ok(cmd.run(components.client, config.chain_spec))300 })301 }302 Some(Subcommand::ImportBlocks(cmd)) => {303 construct_async_run!(|components, cli, cmd, config| {304 Ok(cmd.run(components.client, components.import_queue))305 })306 }307 Some(Subcommand::PurgeChain(cmd)) => {308 let runner = cli.create_runner(cmd)?;309310 runner.sync_run(|config| {311 let polkadot_cli = RelayChainCli::new(312 &config,313 [RelayChainCli::executable_name()]314 .iter()315 .chain(cli.relaychain_args.iter()),316 );317318 let polkadot_config = SubstrateCli::create_configuration(319 &polkadot_cli,320 &polkadot_cli,321 config.tokio_handle.clone(),322 )323 .map_err(|err| format!("Relay chain argument error: {}", err))?;324325 cmd.run(config, polkadot_config)326 })327 }328 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {329 Ok(cmd.run(components.client, components.backend, None))330 }),331 Some(Subcommand::ExportGenesisState(params)) => {332 let mut builder = sc_cli::LoggerBuilder::new("");333 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");334 let _ = builder.init();335336 let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?;337 let state_version = Cli::native_runtime_version(&spec).state_version();338 let block: Block = generate_genesis_block(&spec, state_version)?;339 let raw_header = block.header().encode();340 let output_buf = if params.raw {341 raw_header342 } else {343 format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()344 };345346 if let Some(output) = ¶ms.output {347 std::fs::write(output, output_buf)?;348 } else {349 std::io::stdout().write_all(&output_buf)?;350 }351352 Ok(())353 }354 Some(Subcommand::ExportGenesisWasm(params)) => {355 let mut builder = sc_cli::LoggerBuilder::new("");356 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");357 let _ = builder.init();358359 let raw_wasm_blob =360 extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?;361 let output_buf = if params.raw {362 raw_wasm_blob363 } else {364 format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()365 };366367 if let Some(output) = ¶ms.output {368 std::fs::write(output, output_buf)?;369 } else {370 std::io::stdout().write_all(&output_buf)?;371 }372373 Ok(())374 }375 Some(Subcommand::Benchmark(cmd)) => {376 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};377 let runner = cli.create_runner(cmd)?;378 // Switch on the concrete benchmark sub-command-379 match cmd {380 BenchmarkCmd::Pallet(cmd) => {381 if cfg!(feature = "runtime-benchmarks") {382 runner.sync_run(|config| cmd.run::<Block, DefaultRuntimeExecutor>(config))383 } else {384 Err("Benchmarking wasn't enabled when building the node. \385 You can enable it with `--features runtime-benchmarks`."386 .into())387 }388 }389 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {390 let partials = new_partial::<391 default_runtime::RuntimeApi,392 DefaultRuntimeExecutor,393 _,394 >(&config, crate::service::parachain_build_import_queue)?;395 cmd.run(partials.client)396 }),397 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {398 let partials = new_partial::<399 default_runtime::RuntimeApi,400 DefaultRuntimeExecutor,401 _,402 >(&config, crate::service::parachain_build_import_queue)?;403 let db = partials.backend.expose_db();404 let storage = partials.backend.expose_storage();405406 cmd.run(config, partials.client.clone(), db, storage)407 }),408 BenchmarkCmd::Machine(cmd) => {409 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))410 }411 BenchmarkCmd::Overhead(_) => Err("Unsupported benchmarking command".into()),412 }413 }414 Some(Subcommand::TryRuntime(cmd)) => {415 if cfg!(feature = "try-runtime") {416 let runner = cli.create_runner(cmd)?;417418 // grab the task manager.419 let registry = &runner420 .config()421 .prometheus_config422 .as_ref()423 .map(|cfg| &cfg.registry);424 let task_manager =425 sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)426 .map_err(|e| format!("Error: {:?}", e))?;427428 runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {429 Ok((430 match config.chain_spec.runtime_id() {431 #[cfg(feature = "unique-runtime")]432 RuntimeId::Unique => Box::pin(cmd.run::<Block, UniqueRuntimeExecutor>(config)),433434 #[cfg(feature = "quartz-runtime")]435 RuntimeId::Quartz => Box::pin(cmd.run::<Block, QuartzRuntimeExecutor>(config)),436437 RuntimeId::Opal => {438 Box::pin(cmd.run::<Block, OpalRuntimeExecutor>(config))439 }440 RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),441 },442 task_manager,443 ))444 })445 } else {446 Err("Try-runtime must be enabled by `--features try-runtime`.".into())447 }448 }449 None => {450 let runner = cli.create_runner(&cli.run.normalize())?;451 let collator_options = cli.run.collator_options();452453 runner.run_node_until_exit(|config| async move {454 let hwbench = if !cli.no_hardware_benchmarks {455 config.database.path().map(|database_path| {456 let _ = std::fs::create_dir_all(&database_path);457 sc_sysinfo::gather_hwbench(Some(database_path))458 })459 } else {460 None461 };462463 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);464465 let service_id = config.chain_spec.service_id();466 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());467 let is_dev_service = matches![service_id, ServiceId::Dev]468 || relay_chain_id == Some("dev-service".into());469470 if is_dev_service {471 info!("Running Dev service");472473 let autoseal_interval = Duration::from_millis(cli.idle_autoseal_interval);474475 return start_node_using_chain_runtime! {476 start_dev_node(config, autoseal_interval).map_err(Into::into)477 };478 };479480 let para_id = extensions481 .map(|e| e.para_id)482 .ok_or("Could not find parachain ID in chain-spec.")?;483484 let polkadot_cli = RelayChainCli::new(485 &config,486 [RelayChainCli::executable_name()]487 .iter()488 .chain(cli.relaychain_args.iter()),489 );490491 let para_id = ParaId::from(para_id);492493 let parachain_account =494 AccountIdConversion::<polkadot_primitives::v2::AccountId>::into_account(495 ¶_id,496 );497498 let state_version =499 RelayChainCli::native_runtime_version(&config.chain_spec).state_version();500 let block: Block = generate_genesis_block(&config.chain_spec, state_version)501 .map_err(|e| format!("{:?}", e))?;502 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));503 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));504505 let polkadot_config = SubstrateCli::create_configuration(506 &polkadot_cli,507 &polkadot_cli,508 config.tokio_handle.clone(),509 )510 .map_err(|err| format!("Relay chain argument error: {}", err))?;511512 info!("Parachain id: {:?}", para_id);513 info!("Parachain Account: {}", parachain_account);514 info!("Parachain genesis state: {}", genesis_state);515 info!("Parachain genesis hash: {}", genesis_hash);516 info!(517 "Is collating: {}",518 if config.role.is_authority() {519 "yes"520 } else {521 "no"522 }523 );524525 start_node_using_chain_runtime! {526 start_node(config, polkadot_config, collator_options, para_id, hwbench)527 .await528 .map(|r| r.0)529 .map_err(Into::into)530 }531 })532 }533 }534}535536impl DefaultConfigurationValues for RelayChainCli {537 fn p2p_listen_port() -> u16 {538 30334539 }540541 fn rpc_ws_listen_port() -> u16 {542 9945543 }544545 fn rpc_http_listen_port() -> u16 {546 9934547 }548549 fn prometheus_listen_port() -> u16 {550 9616551 }552}553554impl CliConfiguration<Self> for RelayChainCli {555 fn shared_params(&self) -> &SharedParams {556 self.base.base.shared_params()557 }558559 fn import_params(&self) -> Option<&ImportParams> {560 self.base.base.import_params()561 }562563 fn network_params(&self) -> Option<&NetworkParams> {564 self.base.base.network_params()565 }566567 fn keystore_params(&self) -> Option<&KeystoreParams> {568 self.base.base.keystore_params()569 }570571 fn base_path(&self) -> Result<Option<BasePath>> {572 Ok(self573 .shared_params()574 .base_path()575 .or_else(|| self.base_path.clone().map(Into::into)))576 }577578 fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {579 self.base.base.rpc_http(default_listen_port)580 }581582 fn rpc_ipc(&self) -> Result<Option<String>> {583 self.base.base.rpc_ipc()584 }585586 fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {587 self.base.base.rpc_ws(default_listen_port)588 }589590 fn prometheus_config(591 &self,592 default_listen_port: u16,593 chain_spec: &Box<dyn ChainSpec>,594 ) -> Result<Option<PrometheusConfig>> {595 self.base596 .base597 .prometheus_config(default_listen_port, chain_spec)598 }599600 fn init<F>(601 &self,602 _support_url: &String,603 _impl_version: &String,604 _logger_hook: F,605 _config: &sc_service::Configuration,606 ) -> Result<()> {607 unreachable!("PolkadotCli is never initialized; qed");608 }609610 fn chain_id(&self, is_dev: bool) -> Result<String> {611 let chain_id = self.base.base.chain_id(is_dev)?;612613 Ok(if chain_id.is_empty() {614 self.chain_id.clone().unwrap_or_default()615 } else {616 chain_id617 })618 }619620 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {621 self.base.base.role(is_dev)622 }623624 fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {625 self.base.base.transaction_pool()626 }627628 fn state_cache_child_ratio(&self) -> Result<Option<usize>> {629 self.base.base.state_cache_child_ratio()630 }631632 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {633 self.base.base.rpc_methods()634 }635636 fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {637 self.base.base.rpc_ws_max_connections()638 }639640 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {641 self.base.base.rpc_cors(is_dev)642 }643644 fn default_heap_pages(&self) -> Result<Option<u64>> {645 self.base.base.default_heap_pages()646 }647648 fn force_authoring(&self) -> Result<bool> {649 self.base.base.force_authoring()650 }651652 fn disable_grandpa(&self) -> Result<bool> {653 self.base.base.disable_grandpa()654 }655656 fn max_runtime_instances(&self) -> Result<Option<usize>> {657 self.base.base.max_runtime_instances()658 }659660 fn announce_block(&self) -> Result<bool> {661 self.base.base.announce_block()662 }663664 fn telemetry_endpoints(665 &self,666 chain_spec: &Box<dyn ChainSpec>,667 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {668 self.base.base.telemetry_endpoints(chain_spec)669 }670}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 self, RuntimeId, RuntimeIdentification, ServiceId, ServiceIdentification, default_runtime,38 },39 cli::{Cli, RelayChainCli, Subcommand},40 service::{new_partial, start_node, start_dev_node},41};4243#[cfg(feature = "unique-runtime")]44use crate::service::UniqueRuntimeExecutor;4546#[cfg(feature = "quartz-runtime")]47use crate::service::QuartzRuntimeExecutor;4849use crate::service::{OpalRuntimeExecutor, DefaultRuntimeExecutor};5051use codec::Encode;52use cumulus_primitives_core::ParaId;53use cumulus_client_service::genesis::generate_genesis_block;54use std::{future::Future, pin::Pin};55use log::info;56use polkadot_parachain::primitives::AccountIdConversion;57use sc_cli::{58 ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,59 NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,60};61use sc_service::{62 config::{BasePath, PrometheusConfig},63};64use sp_core::hexdisplay::HexDisplay;65use sp_runtime::traits::Block as BlockT;66use std::{io::Write, net::SocketAddr, time::Duration};6768use unique_runtime_common::types::Block;6970macro_rules! no_runtime_err {71 ($chain_name:expr) => {72 format!(73 "No runtime valid runtime was found for chain {}",74 $chain_name75 )76 };77}7879fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {80 Ok(match id {81 "dev" => Box::new(chain_spec::development_config()),82 "" | "local" => Box::new(chain_spec::local_testnet_config()),83 path => {84 let path = std::path::PathBuf::from(path);85 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)86 as Box<dyn sc_service::ChainSpec>;8788 match chain_spec.runtime_id() {89 #[cfg(feature = "unique-runtime")]90 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),9192 #[cfg(feature = "quartz-runtime")]93 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),9495 RuntimeId::Opal => chain_spec,96 RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),97 }98 }99 })100}101102impl SubstrateCli for Cli {103 // TODO use args104 fn impl_name() -> String {105 format!("{} Node", Self::node_name())106 }107108 fn impl_version() -> String {109 env!("SUBSTRATE_CLI_IMPL_VERSION").into()110 }111 // TODO use args112 fn description() -> String {113 format!(114 "{} Node\n\nThe command-line arguments provided first will be \115 passed to the parachain node, while the arguments provided after -- will be passed \116 to the relaychain node.\n\n\117 {} [parachain-args] -- [relaychain-args]",118 Self::node_name(),119 Self::executable_name()120 )121 }122123 fn author() -> String {124 env!("CARGO_PKG_AUTHORS").into()125 }126127 //TODO use args128 fn support_url() -> String {129 "support@unique.network".into()130 }131132 fn copyright_start_year() -> i32 {133 2019134 }135136 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {137 load_spec(id)138 }139140 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {141 match chain_spec.runtime_id() {142 #[cfg(feature = "unique-runtime")]143 RuntimeId::Unique => &unique_runtime::VERSION,144145 #[cfg(feature = "quartz-runtime")]146 RuntimeId::Quartz => &quartz_runtime::VERSION,147148 RuntimeId::Opal => &opal_runtime::VERSION,149 RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),150 }151 }152}153154impl SubstrateCli for RelayChainCli {155 // TODO use args156 fn impl_name() -> String {157 format!("{} Node", Cli::node_name())158 }159160 fn impl_version() -> String {161 env!("SUBSTRATE_CLI_IMPL_VERSION").into()162 }163 // TODO use args164 fn description() -> String {165 format!(166 "{} Node\n\nThe command-line arguments provided first will be \167 passed to the parachain node, while the arguments provided after -- will be passed \168 to the relaychain node.\n\n\169 parachain-collator [parachain-args] -- [relaychain-args]",170 Cli::node_name()171 )172 }173174 fn author() -> String {175 env!("CARGO_PKG_AUTHORS").into()176 }177 // TODO use args178 fn support_url() -> String {179 "support@unique.network".into()180 }181182 fn copyright_start_year() -> i32 {183 2019184 }185186 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {187 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)188 }189190 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {191 polkadot_cli::Cli::native_runtime_version(chain_spec)192 }193}194195#[allow(clippy::borrowed_box)]196fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {197 let mut storage = chain_spec.build_storage()?;198199 storage200 .top201 .remove(sp_core::storage::well_known_keys::CODE)202 .ok_or_else(|| "Could not find wasm file in genesis state!".into())203}204205macro_rules! async_run_with_runtime {206 (207 $runtime_api:path, $executor:path,208 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,209 $( $code:tt )*210 ) => {211 $runner.async_run(|$config| {212 let $components = new_partial::<213 $runtime_api, $executor, _214 >(215 &$config,216 crate::service::parachain_build_import_queue,217 )?;218 let task_manager = $components.task_manager;219220 { $( $code )* }.map(|v| (v, task_manager))221 })222 };223}224225macro_rules! construct_async_run {226 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{227 let runner = $cli.create_runner($cmd)?;228229 match runner.config().chain_spec.runtime_id() {230 #[cfg(feature = "unique-runtime")]231 RuntimeId::Unique => async_run_with_runtime!(232 unique_runtime::RuntimeApi, UniqueRuntimeExecutor,233 runner, $components, $cli, $cmd, $config, $( $code )*234 ),235236 #[cfg(feature = "quartz-runtime")]237 RuntimeId::Quartz => async_run_with_runtime!(238 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,239 runner, $components, $cli, $cmd, $config, $( $code )*240 ),241242 RuntimeId::Opal => async_run_with_runtime!(243 opal_runtime::RuntimeApi, OpalRuntimeExecutor,244 runner, $components, $cli, $cmd, $config, $( $code )*245 ),246247 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())248 }249 }}250}251252macro_rules! start_node_using_chain_runtime {253 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {254 match $config.chain_spec.runtime_id() {255 #[cfg(feature = "unique-runtime")]256 RuntimeId::Unique => $start_node_fn::<257 unique_runtime::Runtime,258 unique_runtime::RuntimeApi,259 UniqueRuntimeExecutor,260 >($config $(, $($args),+)?) $($code)*,261262 #[cfg(feature = "quartz-runtime")]263 RuntimeId::Quartz => $start_node_fn::<264 quartz_runtime::Runtime,265 quartz_runtime::RuntimeApi,266 QuartzRuntimeExecutor,267 >($config $(, $($args),+)?) $($code)*,268269 RuntimeId::Opal => $start_node_fn::<270 opal_runtime::Runtime,271 opal_runtime::RuntimeApi,272 OpalRuntimeExecutor,273 >($config $(, $($args),+)?) $($code)*,274275 RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),276 }277 };278}279280/// Parse command line arguments into service configuration.281pub fn run() -> Result<()> {282 let cli = Cli::from_args();283284 match &cli.subcommand {285 Some(Subcommand::BuildSpec(cmd)) => {286 let runner = cli.create_runner(cmd)?;287 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))288 }289 Some(Subcommand::CheckBlock(cmd)) => {290 construct_async_run!(|components, cli, cmd, config| {291 Ok(cmd.run(components.client, components.import_queue))292 })293 }294 Some(Subcommand::ExportBlocks(cmd)) => {295 construct_async_run!(|components, cli, cmd, config| {296 Ok(cmd.run(components.client, config.database))297 })298 }299 Some(Subcommand::ExportState(cmd)) => {300 construct_async_run!(|components, cli, cmd, config| {301 Ok(cmd.run(components.client, config.chain_spec))302 })303 }304 Some(Subcommand::ImportBlocks(cmd)) => {305 construct_async_run!(|components, cli, cmd, config| {306 Ok(cmd.run(components.client, components.import_queue))307 })308 }309 Some(Subcommand::PurgeChain(cmd)) => {310 let runner = cli.create_runner(cmd)?;311312 runner.sync_run(|config| {313 let polkadot_cli = RelayChainCli::new(314 &config,315 [RelayChainCli::executable_name()]316 .iter()317 .chain(cli.relaychain_args.iter()),318 );319320 let polkadot_config = SubstrateCli::create_configuration(321 &polkadot_cli,322 &polkadot_cli,323 config.tokio_handle.clone(),324 )325 .map_err(|err| format!("Relay chain argument error: {}", err))?;326327 cmd.run(config, polkadot_config)328 })329 }330 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {331 Ok(cmd.run(components.client, components.backend, None))332 }),333 Some(Subcommand::ExportGenesisState(params)) => {334 let mut builder = sc_cli::LoggerBuilder::new("");335 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");336 let _ = builder.init();337338 let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?;339 let state_version = Cli::native_runtime_version(&spec).state_version();340 let block: Block = generate_genesis_block(&spec, state_version)?;341 let raw_header = block.header().encode();342 let output_buf = if params.raw {343 raw_header344 } else {345 format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()346 };347348 if let Some(output) = ¶ms.output {349 std::fs::write(output, output_buf)?;350 } else {351 std::io::stdout().write_all(&output_buf)?;352 }353354 Ok(())355 }356 Some(Subcommand::ExportGenesisWasm(params)) => {357 let mut builder = sc_cli::LoggerBuilder::new("");358 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");359 let _ = builder.init();360361 let raw_wasm_blob =362 extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?;363 let output_buf = if params.raw {364 raw_wasm_blob365 } else {366 format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()367 };368369 if let Some(output) = ¶ms.output {370 std::fs::write(output, output_buf)?;371 } else {372 std::io::stdout().write_all(&output_buf)?;373 }374375 Ok(())376 }377 Some(Subcommand::Benchmark(cmd)) => {378 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};379 let runner = cli.create_runner(cmd)?;380 // Switch on the concrete benchmark sub-command-381 match cmd {382 BenchmarkCmd::Pallet(cmd) => {383 if cfg!(feature = "runtime-benchmarks") {384 runner.sync_run(|config| cmd.run::<Block, DefaultRuntimeExecutor>(config))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 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {392 let partials = new_partial::<393 default_runtime::RuntimeApi,394 DefaultRuntimeExecutor,395 _,396 >(&config, crate::service::parachain_build_import_queue)?;397 cmd.run(partials.client)398 }),399 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {400 let partials = new_partial::<401 default_runtime::RuntimeApi,402 DefaultRuntimeExecutor,403 _,404 >(&config, crate::service::parachain_build_import_queue)?;405 let db = partials.backend.expose_db();406 let storage = partials.backend.expose_storage();407408 cmd.run(config, partials.client.clone(), db, storage)409 }),410 BenchmarkCmd::Machine(cmd) => {411 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))412 }413 BenchmarkCmd::Overhead(_) => Err("Unsupported benchmarking command".into()),414 }415 }416 Some(Subcommand::TryRuntime(cmd)) => {417 if cfg!(feature = "try-runtime") {418 let runner = cli.create_runner(cmd)?;419420 // grab the task manager.421 let registry = &runner422 .config()423 .prometheus_config424 .as_ref()425 .map(|cfg| &cfg.registry);426 let task_manager =427 sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)428 .map_err(|e| format!("Error: {:?}", e))?;429430 runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {431 Ok((432 match config.chain_spec.runtime_id() {433 #[cfg(feature = "unique-runtime")]434 RuntimeId::Unique => Box::pin(cmd.run::<Block, UniqueRuntimeExecutor>(config)),435436 #[cfg(feature = "quartz-runtime")]437 RuntimeId::Quartz => Box::pin(cmd.run::<Block, QuartzRuntimeExecutor>(config)),438439 RuntimeId::Opal => {440 Box::pin(cmd.run::<Block, OpalRuntimeExecutor>(config))441 }442 RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),443 },444 task_manager,445 ))446 })447 } else {448 Err("Try-runtime must be enabled by `--features try-runtime`.".into())449 }450 }451 None => {452 let runner = cli.create_runner(&cli.run.normalize())?;453 let collator_options = cli.run.collator_options();454455 runner.run_node_until_exit(|config| async move {456 let hwbench = if !cli.no_hardware_benchmarks {457 config.database.path().map(|database_path| {458 let _ = std::fs::create_dir_all(&database_path);459 sc_sysinfo::gather_hwbench(Some(database_path))460 })461 } else {462 None463 };464465 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);466467 let service_id = config.chain_spec.service_id();468 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());469 let is_dev_service = matches![service_id, ServiceId::Dev]470 || relay_chain_id == Some("dev-service".into());471472 if is_dev_service {473 info!("Running Dev service");474475 let autoseal_interval = Duration::from_millis(cli.idle_autoseal_interval);476477 return start_node_using_chain_runtime! {478 start_dev_node(config, autoseal_interval).map_err(Into::into)479 };480 };481482 let para_id = extensions483 .map(|e| e.para_id)484 .ok_or("Could not find parachain ID in chain-spec.")?;485486 let polkadot_cli = RelayChainCli::new(487 &config,488 [RelayChainCli::executable_name()]489 .iter()490 .chain(cli.relaychain_args.iter()),491 );492493 let para_id = ParaId::from(para_id);494495 let parachain_account =496 AccountIdConversion::<polkadot_primitives::v2::AccountId>::into_account(497 ¶_id,498 );499500 let state_version =501 RelayChainCli::native_runtime_version(&config.chain_spec).state_version();502 let block: Block = generate_genesis_block(&config.chain_spec, state_version)503 .map_err(|e| format!("{:?}", e))?;504 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));505 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));506507 let polkadot_config = SubstrateCli::create_configuration(508 &polkadot_cli,509 &polkadot_cli,510 config.tokio_handle.clone(),511 )512 .map_err(|err| format!("Relay chain argument error: {}", err))?;513514 info!("Parachain id: {:?}", para_id);515 info!("Parachain Account: {}", parachain_account);516 info!("Parachain genesis state: {}", genesis_state);517 info!("Parachain genesis hash: {}", genesis_hash);518 info!(519 "Is collating: {}",520 if config.role.is_authority() {521 "yes"522 } else {523 "no"524 }525 );526527 start_node_using_chain_runtime! {528 start_node(config, polkadot_config, collator_options, para_id, hwbench)529 .await530 .map(|r| r.0)531 .map_err(Into::into)532 }533 })534 }535 }536}537538impl DefaultConfigurationValues for RelayChainCli {539 fn p2p_listen_port() -> u16 {540 30334541 }542543 fn rpc_ws_listen_port() -> u16 {544 9945545 }546547 fn rpc_http_listen_port() -> u16 {548 9934549 }550551 fn prometheus_listen_port() -> u16 {552 9616553 }554}555556impl CliConfiguration<Self> for RelayChainCli {557 fn shared_params(&self) -> &SharedParams {558 self.base.base.shared_params()559 }560561 fn import_params(&self) -> Option<&ImportParams> {562 self.base.base.import_params()563 }564565 fn network_params(&self) -> Option<&NetworkParams> {566 self.base.base.network_params()567 }568569 fn keystore_params(&self) -> Option<&KeystoreParams> {570 self.base.base.keystore_params()571 }572573 fn base_path(&self) -> Result<Option<BasePath>> {574 Ok(self575 .shared_params()576 .base_path()577 .or_else(|| self.base_path.clone().map(Into::into)))578 }579580 fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {581 self.base.base.rpc_http(default_listen_port)582 }583584 fn rpc_ipc(&self) -> Result<Option<String>> {585 self.base.base.rpc_ipc()586 }587588 fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> {589 self.base.base.rpc_ws(default_listen_port)590 }591592 fn prometheus_config(593 &self,594 default_listen_port: u16,595 chain_spec: &Box<dyn ChainSpec>,596 ) -> Result<Option<PrometheusConfig>> {597 self.base598 .base599 .prometheus_config(default_listen_port, chain_spec)600 }601602 fn init<F>(603 &self,604 _support_url: &String,605 _impl_version: &String,606 _logger_hook: F,607 _config: &sc_service::Configuration,608 ) -> Result<()> {609 unreachable!("PolkadotCli is never initialized; qed");610 }611612 fn chain_id(&self, is_dev: bool) -> Result<String> {613 let chain_id = self.base.base.chain_id(is_dev)?;614615 Ok(if chain_id.is_empty() {616 self.chain_id.clone().unwrap_or_default()617 } else {618 chain_id619 })620 }621622 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {623 self.base.base.role(is_dev)624 }625626 fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> {627 self.base.base.transaction_pool()628 }629630 fn state_cache_child_ratio(&self) -> Result<Option<usize>> {631 self.base.base.state_cache_child_ratio()632 }633634 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {635 self.base.base.rpc_methods()636 }637638 fn rpc_ws_max_connections(&self) -> Result<Option<usize>> {639 self.base.base.rpc_ws_max_connections()640 }641642 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {643 self.base.base.rpc_cors(is_dev)644 }645646 fn default_heap_pages(&self) -> Result<Option<u64>> {647 self.base.base.default_heap_pages()648 }649650 fn force_authoring(&self) -> Result<bool> {651 self.base.base.force_authoring()652 }653654 fn disable_grandpa(&self) -> Result<bool> {655 self.base.base.disable_grandpa()656 }657658 fn max_runtime_instances(&self) -> Result<Option<usize>> {659 self.base.base.max_runtime_instances()660 }661662 fn announce_block(&self) -> Result<bool> {663 self.base.base.announce_block()664 }665666 fn telemetry_endpoints(667 &self,668 chain_spec: &Box<dyn ChainSpec>,669 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {670 self.base.base.telemetry_endpoints(chain_spec)671 }672}runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -74,9 +74,8 @@
CollectionStats, RpcCollection,
mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
TokenChild, RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo,
- RmrkBaseInfo, RmrkPartType, RmrkTheme, RmrkThemeName, RmrkCollectionId,
- RmrkNftId, RmrkNftChild, RmrkPropertyKey,
- RmrkResourceId, RmrkBaseId,
+ RmrkBaseInfo, RmrkPartType, RmrkTheme, RmrkThemeName, RmrkCollectionId, RmrkNftId,
+ RmrkNftChild, RmrkPropertyKey, RmrkResourceId, RmrkBaseId,
};
// use pallet_contracts::weights::WeightInfo;