1234567891011121314151617181920212223242526272829303132333435use cumulus_primitives_core::ParaId;36use log::info;37use sc_cli::{38 ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,39 NetworkParams, Result, SharedParams, SubstrateCli,40};41use sc_service::config::{BasePath, PrometheusConfig};42use sp_runtime::traits::AccountIdConversion;43use up_common::types::opaque::RuntimeId;4445#[cfg(feature = "runtime-benchmarks")]46use crate::chain_spec::default_runtime;47#[cfg(feature = "runtime-benchmarks")]48use crate::service::DefaultRuntimeExecutor;49#[cfg(feature = "quartz-runtime")]50use crate::service::QuartzRuntimeExecutor;51#[cfg(feature = "unique-runtime")]52use crate::service::UniqueRuntimeExecutor;53use crate::{54 chain_spec::{self, RuntimeIdentification, ServiceId, ServiceIdentification},55 cli::{Cli, RelayChainCli, Subcommand},56 service::{new_partial, start_dev_node, start_node, OpalRuntimeExecutor},57};5859macro_rules! no_runtime_err {60 ($runtime_id:expr) => {61 format!(62 "No runtime valid runtime was found for chain {:#?}",63 $runtime_id64 )65 };66}6768fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {69 Ok(match id {70 "dev" => Box::new(chain_spec::development_config()),71 "" | "local" => Box::new(chain_spec::local_testnet_config()),72 path => {73 let path = std::path::PathBuf::from(path);74 #[allow(clippy::redundant_clone)]75 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)76 as Box<dyn sc_service::ChainSpec>;7778 match chain_spec.runtime_id() {79 #[cfg(feature = "unique-runtime")]80 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),8182 #[cfg(feature = "quartz-runtime")]83 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),8485 RuntimeId::Opal => chain_spec,86 runtime_id => return Err(no_runtime_err!(runtime_id)),87 }88 }89 })90}9192impl SubstrateCli for Cli {93 94 fn impl_name() -> String {95 format!("{} Node", Self::node_name())96 }9798 fn impl_version() -> String {99 env!("SUBSTRATE_CLI_IMPL_VERSION").into()100 }101 102 fn description() -> String {103 format!(104 "{} Node\n\nThe command-line arguments provided first will be \105 passed to the parachain node, while the arguments provided after -- will be passed \106 to the relaychain node.\n\n\107 {} [parachain-args] -- [relaychain-args]",108 Self::node_name(),109 Self::executable_name()110 )111 }112113 fn author() -> String {114 env!("CARGO_PKG_AUTHORS").into()115 }116117 118 fn support_url() -> String {119 "support@unique.network".into()120 }121122 fn copyright_start_year() -> i32 {123 2019124 }125126 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {127 load_spec(id)128 }129}130131impl SubstrateCli for RelayChainCli {132 133 fn impl_name() -> String {134 format!("{} Node", Cli::node_name())135 }136137 fn impl_version() -> String {138 env!("SUBSTRATE_CLI_IMPL_VERSION").into()139 }140 141 fn description() -> String {142 format!(143 "{} Node\n\nThe command-line arguments provided first will be \144 passed to the parachain node, while the arguments provided after -- will be passed \145 to the relaychain node.\n\n\146 parachain-collator [parachain-args] -- [relaychain-args]",147 Cli::node_name()148 )149 }150151 fn author() -> String {152 env!("CARGO_PKG_AUTHORS").into()153 }154 155 fn support_url() -> String {156 "support@unique.network".into()157 }158159 fn copyright_start_year() -> i32 {160 2019161 }162163 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {164 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)165 }166}167168macro_rules! async_run_with_runtime {169 (170 $runtime:path, $runtime_api:path, $executor:path,171 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,172 $( $code:tt )*173 ) => {174 $runner.async_run(|$config| {175 let $components = new_partial::<176 $runtime, $runtime_api, $executor, _177 >(178 &$config,179 crate::service::parachain_build_import_queue::<$runtime, _, _>,180 )?;181 let task_manager = $components.task_manager;182183 { $( $code )* }.map(|v| (v, task_manager))184 })185 };186}187188macro_rules! construct_async_run {189 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{190 let runner = $cli.create_runner($cmd)?;191192 match runner.config().chain_spec.runtime_id() {193 #[cfg(feature = "unique-runtime")]194 RuntimeId::Unique => async_run_with_runtime!(195 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,196 runner, $components, $cli, $cmd, $config, $( $code )*197 ),198199 #[cfg(feature = "quartz-runtime")]200 RuntimeId::Quartz => async_run_with_runtime!(201 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,202 runner, $components, $cli, $cmd, $config, $( $code )*203 ),204205 RuntimeId::Opal => async_run_with_runtime!(206 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,207 runner, $components, $cli, $cmd, $config, $( $code )*208 ),209210 runtime_id => Err(no_runtime_err!(runtime_id).into())211 }212 }}213}214215macro_rules! sync_run_with_runtime {216 (217 $runtime:path, $runtime_api:path, $executor:path,218 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,219 $( $code:tt )*220 ) => {221 $runner.sync_run(|$config| {222 let $components = new_partial::<223 $runtime, $runtime_api, $executor, _224 >(225 &$config,226 crate::service::parachain_build_import_queue::<$runtime, _, _>,227 )?;228229 $( $code )*230 })231 };232}233234macro_rules! construct_sync_run {235 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{236 let runner = $cli.create_runner($cmd)?;237238 match runner.config().chain_spec.runtime_id() {239 #[cfg(feature = "unique-runtime")]240 RuntimeId::Unique => sync_run_with_runtime!(241 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,242 runner, $components, $cli, $cmd, $config, $( $code )*243 ),244245 #[cfg(feature = "quartz-runtime")]246 RuntimeId::Quartz => sync_run_with_runtime!(247 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,248 runner, $components, $cli, $cmd, $config, $( $code )*249 ),250251 RuntimeId::Opal => sync_run_with_runtime!(252 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,253 runner, $components, $cli, $cmd, $config, $( $code )*254 ),255256 runtime_id => Err(no_runtime_err!(runtime_id).into())257 }258 }}259}260261macro_rules! start_node_using_chain_runtime {262 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {263 match $config.chain_spec.runtime_id() {264 #[cfg(feature = "unique-runtime")]265 RuntimeId::Unique => $start_node_fn::<266 unique_runtime::Runtime,267 unique_runtime::RuntimeApi,268 UniqueRuntimeExecutor,269 >($config $(, $($args),+)?) $($code)*,270271 #[cfg(feature = "quartz-runtime")]272 RuntimeId::Quartz => $start_node_fn::<273 quartz_runtime::Runtime,274 quartz_runtime::RuntimeApi,275 QuartzRuntimeExecutor,276 >($config $(, $($args),+)?) $($code)*,277278 RuntimeId::Opal => $start_node_fn::<279 opal_runtime::Runtime,280 opal_runtime::RuntimeApi,281 OpalRuntimeExecutor,282 >($config $(, $($args),+)?) $($code)*,283284 runtime_id => Err(no_runtime_err!(runtime_id).into()),285 }286 };287}288289290pub fn run() -> Result<()> {291 let cli = Cli::from_args();292293 match &cli.subcommand {294 Some(Subcommand::Key(cmd)) => cmd.run(&cli),295 Some(Subcommand::BuildSpec(cmd)) => {296 let runner = cli.create_runner(cmd)?;297 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))298 }299 Some(Subcommand::CheckBlock(cmd)) => {300 construct_async_run!(|components, cli, cmd, config| {301 Ok(cmd.run(components.client, components.import_queue))302 })303 }304 Some(Subcommand::ExportBlocks(cmd)) => {305 construct_async_run!(|components, cli, cmd, config| {306 Ok(cmd.run(components.client, config.database))307 })308 }309 Some(Subcommand::ExportState(cmd)) => {310 construct_async_run!(|components, cli, cmd, config| {311 Ok(cmd.run(components.client, config.chain_spec))312 })313 }314 Some(Subcommand::ImportBlocks(cmd)) => {315 construct_async_run!(|components, cli, cmd, config| {316 Ok(cmd.run(components.client, components.import_queue))317 })318 }319 Some(Subcommand::PurgeChain(cmd)) => {320 let runner = cli.create_runner(cmd)?;321322 runner.sync_run(|config| {323 let polkadot_cli = RelayChainCli::new(324 &config,325 [RelayChainCli::executable_name()]326 .iter()327 .chain(cli.relaychain_args.iter()),328 );329330 let polkadot_config = SubstrateCli::create_configuration(331 &polkadot_cli,332 &polkadot_cli,333 config.tokio_handle.clone(),334 )335 .map_err(|err| format!("Relay chain argument error: {err}"))?;336337 cmd.run(config, polkadot_config)338 })339 }340 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {341 Ok(cmd.run(components.client, components.backend, None))342 }),343 Some(Subcommand::ExportGenesisState(cmd)) => {344 construct_sync_run!(|components, cli, cmd, _config| {345 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;346 cmd.run(&*spec, &*components.client)347 })348 }349 Some(Subcommand::ExportGenesisWasm(cmd)) => {350 construct_sync_run!(|_components, cli, cmd, _config| {351 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;352 cmd.run(&*spec)353 })354 }355 #[cfg(feature = "runtime-benchmarks")]356 Some(Subcommand::Benchmark(cmd)) => {357 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};358 use polkadot_cli::Block;359 use sp_io::SubstrateHostFunctions;360361 let runner = cli.create_runner(cmd)?;362 363 match cmd {364 BenchmarkCmd::Pallet(cmd) => {365 runner.sync_run(|config| cmd.run::<Block, SubstrateHostFunctions>(config))366 }367 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {368 let partials = new_partial::<369 opal_runtime::Runtime,370 opal_runtime::RuntimeApi,371 OpalRuntimeExecutor,372 _,373 >(374 &config,375 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,376 )?;377 cmd.run(partials.client)378 }),379 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {380 let partials = new_partial::<381 opal_runtime::Runtime,382 opal_runtime::RuntimeApi,383 OpalRuntimeExecutor,384 _,385 >(386 &config,387 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,388 )?;389 let db = partials.backend.expose_db();390 let storage = partials.backend.expose_storage();391392 cmd.run(config, partials.client.clone(), db, storage)393 }),394 BenchmarkCmd::Machine(cmd) => {395 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))396 }397 BenchmarkCmd::Overhead(_) | BenchmarkCmd::Extrinsic(_) => {398 Err("Unsupported benchmarking command".into())399 }400 }401 }402 #[cfg(feature = "try-runtime")]403 Some(Subcommand::TryRuntime(cmd)) => {404 use std::{future::Future, pin::Pin};405406 use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};407 use try_runtime_cli::block_building_info::timestamp_with_aura_info;408409 let runner = cli.create_runner(cmd)?;410411 412 let registry = &runner413 .config()414 .prometheus_config415 .as_ref()416 .map(|cfg| &cfg.registry);417 let task_manager =418 sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)419 .map_err(|e| format!("Error: {e:?}"))?;420 let info_provider = Some(timestamp_with_aura_info(12000));421422 runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {423 Ok((424 match config.chain_spec.runtime_id() {425 #[cfg(feature = "unique-runtime")]426 RuntimeId::Unique => Box::pin(cmd.run::<Block, ExtendedHostFunctions<427 sp_io::SubstrateHostFunctions,428 <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,429 >, _>(info_provider)),430431 #[cfg(feature = "quartz-runtime")]432 RuntimeId::Quartz => Box::pin(cmd.run::<Block, ExtendedHostFunctions<433 sp_io::SubstrateHostFunctions,434 <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,435 >, _>(info_provider)),436437 RuntimeId::Opal => Box::pin(cmd.run::<Block, ExtendedHostFunctions<438 sp_io::SubstrateHostFunctions,439 <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,440 >, _>(info_provider)),441 runtime_id => return Err(no_runtime_err!(runtime_id).into()),442 },443 task_manager,444 ))445 })446 }447 #[cfg(not(feature = "try-runtime"))]448 Some(Subcommand::TryRuntime) => {449 Err("Try-runtime must be enabled by `--features try-runtime`.".into())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 mut config = config;476477 config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);478479 return start_node_using_chain_runtime! {480 start_dev_node(config, cli.idle_autoseal_interval, cli.autoseal_finalization_delay, cli.disable_autoseal_on_tx).map_err(Into::into)481 };482 };483484 let para_id = extensions485 .map(|e| e.para_id)486 .ok_or("Could not find parachain ID in chain-spec.")?;487488 let polkadot_cli = RelayChainCli::new(489 &config,490 [RelayChainCli::executable_name()]491 .iter()492 .chain(cli.relaychain_args.iter()),493 );494495 let para_id = ParaId::from(para_id);496497 let parachain_account =498 AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(499 ¶_id,500 );501502 let polkadot_config = SubstrateCli::create_configuration(503 &polkadot_cli,504 &polkadot_cli,505 config.tokio_handle.clone(),506 )507 .map_err(|err| format!("Relay chain argument error: {err}"))?;508509 info!("Parachain id: {:?}", para_id);510 info!("Parachain Account: {}", parachain_account);511 info!(512 "Is collating: {}",513 if config.role.is_authority() {514 "yes"515 } else {516 "no"517 }518 );519520 start_node_using_chain_runtime! {521 start_node(config, polkadot_config, collator_options, para_id, hwbench)522 .await523 .map(|r| r.0)524 .map_err(Into::into)525 }526 })527 }528 }529}530531impl DefaultConfigurationValues for RelayChainCli {532 fn p2p_listen_port() -> u16 {533 30334534 }535536 fn rpc_listen_port() -> u16 {537 9945538 }539540 fn prometheus_listen_port() -> u16 {541 9616542 }543}544545impl CliConfiguration<Self> for RelayChainCli {546 fn shared_params(&self) -> &SharedParams {547 self.base.base.shared_params()548 }549550 fn import_params(&self) -> Option<&ImportParams> {551 self.base.base.import_params()552 }553554 fn network_params(&self) -> Option<&NetworkParams> {555 self.base.base.network_params()556 }557558 fn keystore_params(&self) -> Option<&KeystoreParams> {559 self.base.base.keystore_params()560 }561562 fn base_path(&self) -> Result<Option<BasePath>> {563 Ok(self564 .shared_params()565 .base_path()?566 .or_else(|| Some(self.base_path.clone().into())))567 }568569 fn prometheus_config(570 &self,571 default_listen_port: u16,572 chain_spec: &Box<dyn ChainSpec>,573 ) -> Result<Option<PrometheusConfig>> {574 self.base575 .base576 .prometheus_config(default_listen_port, chain_spec)577 }578579 fn init<F>(580 &self,581 _support_url: &String,582 _impl_version: &String,583 _logger_hook: F,584 _config: &sc_service::Configuration,585 ) -> Result<()> {586 unreachable!("PolkadotCli is never initialized; qed");587 }588589 fn chain_id(&self, is_dev: bool) -> Result<String> {590 let chain_id = self.base.base.chain_id(is_dev)?;591592 Ok(if chain_id.is_empty() {593 self.chain_id.clone().unwrap_or_default()594 } else {595 chain_id596 })597 }598599 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {600 self.base.base.role(is_dev)601 }602603 fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {604 self.base.base.transaction_pool(is_dev)605 }606607 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {608 self.base.base.rpc_methods()609 }610611 fn rpc_max_connections(&self) -> Result<u32> {612 self.base.base.rpc_max_connections()613 }614615 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {616 self.base.base.rpc_cors(is_dev)617 }618619 fn default_heap_pages(&self) -> Result<Option<u64>> {620 self.base.base.default_heap_pages()621 }622623 fn force_authoring(&self) -> Result<bool> {624 self.base.base.force_authoring()625 }626627 fn disable_grandpa(&self) -> Result<bool> {628 self.base.base.disable_grandpa()629 }630631 fn max_runtime_instances(&self) -> Result<Option<usize>> {632 self.base.base.max_runtime_instances()633 }634635 fn announce_block(&self) -> Result<bool> {636 self.base.base.announce_block()637 }638639 fn telemetry_endpoints(640 &self,641 chain_spec: &Box<dyn ChainSpec>,642 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {643 self.base.base.telemetry_endpoints(chain_spec)644 }645}