1234567891011121314151617181920212223242526272829303132333435use 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 107 fn impl_name() -> String {108 "Unique Node".into()109 }110111 fn impl_version() -> String {112 env!("SUBSTRATE_CLI_IMPL_VERSION").into()113 }114 115 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 130 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 160 fn impl_name() -> String {161 "Unique Node".into()162 }163164 fn impl_version() -> String {165 env!("SUBSTRATE_CLI_IMPL_VERSION").into()166 }167 168 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 180 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}254255256pub 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}