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 polkadot_cli::Block;358 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};359 let runner = cli.create_runner(cmd)?;360 361 match cmd {362 BenchmarkCmd::Pallet(cmd) => {363 runner.sync_run(|config| cmd.run::<Block, DefaultRuntimeExecutor>(config))364 }365 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {366 let partials = new_partial::<367 _,368 default_runtime::RuntimeApi,369 DefaultRuntimeExecutor,370 _,371 >(&config, crate::service::parachain_build_import_queue)?;372 cmd.run(partials.client)373 }),374 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {375 let partials = new_partial::<376 _,377 default_runtime::RuntimeApi,378 DefaultRuntimeExecutor,379 _,380 >(&config, crate::service::parachain_build_import_queue)?;381 let db = partials.backend.expose_db();382 let storage = partials.backend.expose_storage();383384 cmd.run(config, partials.client.clone(), db, storage)385 }),386 BenchmarkCmd::Machine(cmd) => {387 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))388 }389 BenchmarkCmd::Overhead(_) | BenchmarkCmd::Extrinsic(_) => {390 Err("Unsupported benchmarking command".into())391 }392 }393 }394 #[cfg(feature = "try-runtime")]395 Some(Subcommand::TryRuntime(cmd)) => {396 use std::{future::Future, pin::Pin};397398 use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};399 use try_runtime_cli::block_building_info::timestamp_with_aura_info;400401 let runner = cli.create_runner(cmd)?;402403 404 let registry = &runner405 .config()406 .prometheus_config407 .as_ref()408 .map(|cfg| &cfg.registry);409 let task_manager =410 sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)411 .map_err(|e| format!("Error: {e:?}"))?;412 let info_provider = Some(timestamp_with_aura_info(12000));413414 runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {415 Ok((416 match config.chain_spec.runtime_id() {417 #[cfg(feature = "unique-runtime")]418 RuntimeId::Unique => Box::pin(cmd.run::<Block, ExtendedHostFunctions<419 sp_io::SubstrateHostFunctions,420 <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,421 >, _>(info_provider)),422423 #[cfg(feature = "quartz-runtime")]424 RuntimeId::Quartz => Box::pin(cmd.run::<Block, ExtendedHostFunctions<425 sp_io::SubstrateHostFunctions,426 <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,427 >, _>(info_provider)),428429 RuntimeId::Opal => Box::pin(cmd.run::<Block, ExtendedHostFunctions<430 sp_io::SubstrateHostFunctions,431 <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,432 >, _>(info_provider)),433 runtime_id => return Err(no_runtime_err!(runtime_id).into()),434 },435 task_manager,436 ))437 })438 }439 #[cfg(not(feature = "try-runtime"))]440 Some(Subcommand::TryRuntime) => {441 Err("Try-runtime must be enabled by `--features try-runtime`.".into())442 }443 None => {444 let runner = cli.create_runner(&cli.run.normalize())?;445 let collator_options = cli.run.collator_options();446447 runner.run_node_until_exit(|config| async move {448 let hwbench = if !cli.no_hardware_benchmarks {449 config.database.path().map(|database_path| {450 let _ = std::fs::create_dir_all(database_path);451 sc_sysinfo::gather_hwbench(Some(database_path))452 })453 } else {454 None455 };456457 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);458459 let service_id = config.chain_spec.service_id();460 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());461 let is_dev_service = matches![service_id, ServiceId::Dev]462 || relay_chain_id == Some("dev-service".into());463464 if is_dev_service {465 info!("Running Dev service");466467 let mut config = config;468469 config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);470471 return start_node_using_chain_runtime! {472 start_dev_node(config, cli.idle_autoseal_interval, cli.autoseal_finalization_delay, cli.disable_autoseal_on_tx).map_err(Into::into)473 };474 };475476 let para_id = extensions477 .map(|e| e.para_id)478 .ok_or("Could not find parachain ID in chain-spec.")?;479480 let polkadot_cli = RelayChainCli::new(481 &config,482 [RelayChainCli::executable_name()]483 .iter()484 .chain(cli.relaychain_args.iter()),485 );486487 let para_id = ParaId::from(para_id);488489 let parachain_account =490 AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(491 ¶_id,492 );493494 let polkadot_config = SubstrateCli::create_configuration(495 &polkadot_cli,496 &polkadot_cli,497 config.tokio_handle.clone(),498 )499 .map_err(|err| format!("Relay chain argument error: {err}"))?;500501 info!("Parachain id: {:?}", para_id);502 info!("Parachain Account: {}", parachain_account);503 info!(504 "Is collating: {}",505 if config.role.is_authority() {506 "yes"507 } else {508 "no"509 }510 );511512 start_node_using_chain_runtime! {513 start_node(config, polkadot_config, collator_options, para_id, hwbench)514 .await515 .map(|r| r.0)516 .map_err(Into::into)517 }518 })519 }520 }521}522523impl DefaultConfigurationValues for RelayChainCli {524 fn p2p_listen_port() -> u16 {525 30334526 }527528 fn rpc_listen_port() -> u16 {529 9945530 }531532 fn prometheus_listen_port() -> u16 {533 9616534 }535}536537impl CliConfiguration<Self> for RelayChainCli {538 fn shared_params(&self) -> &SharedParams {539 self.base.base.shared_params()540 }541542 fn import_params(&self) -> Option<&ImportParams> {543 self.base.base.import_params()544 }545546 fn network_params(&self) -> Option<&NetworkParams> {547 self.base.base.network_params()548 }549550 fn keystore_params(&self) -> Option<&KeystoreParams> {551 self.base.base.keystore_params()552 }553554 fn base_path(&self) -> Result<Option<BasePath>> {555 Ok(self556 .shared_params()557 .base_path()?558 .or_else(|| Some(self.base_path.clone().into())))559 }560561 fn prometheus_config(562 &self,563 default_listen_port: u16,564 chain_spec: &Box<dyn ChainSpec>,565 ) -> Result<Option<PrometheusConfig>> {566 self.base567 .base568 .prometheus_config(default_listen_port, chain_spec)569 }570571 fn init<F>(572 &self,573 _support_url: &String,574 _impl_version: &String,575 _logger_hook: F,576 _config: &sc_service::Configuration,577 ) -> Result<()> {578 unreachable!("PolkadotCli is never initialized; qed");579 }580581 fn chain_id(&self, is_dev: bool) -> Result<String> {582 let chain_id = self.base.base.chain_id(is_dev)?;583584 Ok(if chain_id.is_empty() {585 self.chain_id.clone().unwrap_or_default()586 } else {587 chain_id588 })589 }590591 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {592 self.base.base.role(is_dev)593 }594595 fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {596 self.base.base.transaction_pool(is_dev)597 }598599 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {600 self.base.base.rpc_methods()601 }602603 fn rpc_max_connections(&self) -> Result<u32> {604 self.base.base.rpc_max_connections()605 }606607 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {608 self.base.base.rpc_cors(is_dev)609 }610611 fn default_heap_pages(&self) -> Result<Option<u64>> {612 self.base.base.default_heap_pages()613 }614615 fn force_authoring(&self) -> Result<bool> {616 self.base.base.force_authoring()617 }618619 fn disable_grandpa(&self) -> Result<bool> {620 self.base.base.disable_grandpa()621 }622623 fn max_runtime_instances(&self) -> Result<Option<usize>> {624 self.base.base.max_runtime_instances()625 }626627 fn announce_block(&self) -> Result<bool> {628 self.base.base.announce_block()629 }630631 fn telemetry_endpoints(632 &self,633 chain_spec: &Box<dyn ChainSpec>,634 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {635 self.base.base.telemetry_endpoints(chain_spec)636 }637}