1234567891011121314151617181920212223242526272829303132333435use 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 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 => Box::new(chain_spec::ChainSpec::from_json_file(84 std::path::PathBuf::from(path),85 )?),86 })87}8889impl SubstrateCli for Cli {90 91 fn impl_name() -> String {92 "Unique Node".into()93 }9495 fn impl_version() -> String {96 env!("SUBSTRATE_CLI_IMPL_VERSION").into()97 }98 99 fn description() -> String {100 format!(101 "Unique Node\n\nThe command-line arguments provided first will be \102 passed to the parachain node, while the arguments provided after -- will be passed \103 to the relaychain node.\n\n\104 {} [parachain-args] -- [relaychain-args]",105 Self::executable_name()106 )107 }108109 fn author() -> String {110 env!("CARGO_PKG_AUTHORS").into()111 }112113 114 fn support_url() -> String {115 "support@unique.network".into()116 }117118 fn copyright_start_year() -> i32 {119 2019120 }121122 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {123 load_spec(id)124 }125126 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {127 #[cfg(feature = "unique-runtime")]128 if chain_spec.is_unique() {129 return &unique_runtime::VERSION;130 }131132 #[cfg(feature = "quartz-runtime")]133 if chain_spec.is_quartz() {134 return &quartz_runtime::VERSION;135 }136137 #[cfg(feature = "opal-runtime")]138 if chain_spec.is_opal() {139 return &opal_runtime::VERSION;140 }141142 panic!("{}", no_runtime_err!(chain_spec));143 }144}145146impl SubstrateCli for RelayChainCli {147 148 fn impl_name() -> String {149 "Unique Node".into()150 }151152 fn impl_version() -> String {153 env!("SUBSTRATE_CLI_IMPL_VERSION").into()154 }155 156 fn description() -> String {157 "Unique Node\n\nThe command-line arguments provided first will be \158 passed to the parachain node, while the arguments provided after -- will be passed \159 to the relaychain node.\n\n\160 parachain-collator [parachain-args] -- [relaychain-args]"161 .into()162 }163164 fn author() -> String {165 env!("CARGO_PKG_AUTHORS").into()166 }167 168 fn support_url() -> String {169 "support@unique.network".into()170 }171172 fn copyright_start_year() -> i32 {173 2019174 }175176 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {177 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)178 }179180 fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {181 polkadot_cli::Cli::native_runtime_version(chain_spec)182 }183}184185#[allow(clippy::borrowed_box)]186fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {187 let mut storage = chain_spec.build_storage()?;188189 storage190 .top191 .remove(sp_core::storage::well_known_keys::CODE)192 .ok_or_else(|| "Could not find wasm file in genesis state!".into())193}194195macro_rules! construct_async_run {196 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{197 let runner = $cli.create_runner($cmd)?;198199 #[cfg(feature = "unique-runtime")]200 if runner.config().chain_spec.is_unique() {201 return runner.async_run(|$config| {202 let $components = new_partial::<203 unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _204 >(205 &$config,206 crate::service::parachain_build_import_queue,207 )?;208 let task_manager = $components.task_manager;209 { $( $code )* }.map(|v| (v, task_manager))210 });211 }212213 #[cfg(feature = "quartz-runtime")]214 if runner.config().chain_spec.is_quartz() {215 return runner.async_run(|$config| {216 let $components = new_partial::<217 quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _218 >(219 &$config,220 crate::service::parachain_build_import_queue,221 )?;222 let task_manager = $components.task_manager;223 { $( $code )* }.map(|v| (v, task_manager))224 });225 }226227 #[cfg(feature = "opal-runtime")]228 if runner.config().chain_spec.is_opal() {229 return runner.async_run(|$config| {230 let $components = new_partial::<231 opal_runtime::RuntimeApi, OpalRuntimeExecutor, _232 >(233 &$config,234 crate::service::parachain_build_import_queue,235 )?;236 let task_manager = $components.task_manager;237 { $( $code )* }.map(|v| (v, task_manager))238 });239 }240241 Err(no_runtime_err!(runner.config().chain_spec).into())242 }}243}244245246pub fn run() -> Result<()> {247 let cli = Cli::from_args();248249 match &cli.subcommand {250 Some(Subcommand::BuildSpec(cmd)) => {251 let runner = cli.create_runner(cmd)?;252 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))253 }254 Some(Subcommand::CheckBlock(cmd)) => {255 construct_async_run!(|components, cli, cmd, config| {256 Ok(cmd.run(components.client, components.import_queue))257 })258 }259 Some(Subcommand::ExportBlocks(cmd)) => {260 construct_async_run!(|components, cli, cmd, config| {261 Ok(cmd.run(components.client, config.database))262 })263 }264 Some(Subcommand::ExportState(cmd)) => {265 construct_async_run!(|components, cli, cmd, config| {266 Ok(cmd.run(components.client, config.chain_spec))267 })268 }269 Some(Subcommand::ImportBlocks(cmd)) => {270 construct_async_run!(|components, cli, cmd, config| {271 Ok(cmd.run(components.client, components.import_queue))272 })273 }274 Some(Subcommand::PurgeChain(cmd)) => {275 let runner = cli.create_runner(cmd)?;276277 runner.sync_run(|config| {278 let polkadot_cli = RelayChainCli::new(279 &config,280 [RelayChainCli::executable_name()]281 .iter()282 .chain(cli.relaychain_args.iter()),283 );284285 let polkadot_config = SubstrateCli::create_configuration(286 &polkadot_cli,287 &polkadot_cli,288 config.tokio_handle.clone(),289 )290 .map_err(|err| format!("Relay chain argument error: {}", err))?;291292 cmd.run(config, polkadot_config)293 })294 }295 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {296 Ok(cmd.run(components.client, components.backend))297 }),298 Some(Subcommand::ExportGenesisState(params)) => {299 let mut builder = sc_cli::LoggerBuilder::new("");300 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");301 let _ = builder.init();302303 let spec = load_spec(¶ms.chain.clone().unwrap_or_default())?;304 let state_version = Cli::native_runtime_version(&spec).state_version();305 let block: Block = generate_genesis_block(&spec, state_version)?;306 let raw_header = block.header().encode();307 let output_buf = if params.raw {308 raw_header309 } else {310 format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes()311 };312313 if let Some(output) = ¶ms.output {314 std::fs::write(output, output_buf)?;315 } else {316 std::io::stdout().write_all(&output_buf)?;317 }318319 Ok(())320 }321 Some(Subcommand::ExportGenesisWasm(params)) => {322 let mut builder = sc_cli::LoggerBuilder::new("");323 builder.with_profiling(sc_tracing::TracingReceiver::Log, "");324 let _ = builder.init();325326 let raw_wasm_blob =327 extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?;328 let output_buf = if params.raw {329 raw_wasm_blob330 } else {331 format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes()332 };333334 if let Some(output) = ¶ms.output {335 std::fs::write(output, output_buf)?;336 } else {337 std::io::stdout().write_all(&output_buf)?;338 }339340 Ok(())341 }342 Some(Subcommand::Benchmark(cmd)) => {343 if cfg!(feature = "runtime-benchmarks") {344 let runner = cli.create_runner(cmd)?;345 runner.sync_run(|config| {346 #[cfg(feature = "unique-runtime")]347 if config.chain_spec.is_unique() {348 return cmd.run::<Block, UniqueRuntimeExecutor>(config);349 }350351 #[cfg(feature = "quartz-runtime")]352 if config.chain_spec.is_quartz() {353 return cmd.run::<Block, QuartzRuntimeExecutor>(config);354 }355356 #[cfg(feature = "opal-runtime")]357 if config.chain_spec.is_opal() {358 return cmd.run::<Block, OpalRuntimeExecutor>(config);359 }360361 Err(no_runtime_err!(config.chain_spec).into())362 })363 } else {364 Err("Benchmarking wasn't enabled when building the node. \365 You can enable it with `--features runtime-benchmarks`."366 .into())367 }368 }369 None => {370 let runner = cli.create_runner(&cli.run.normalize())?;371372 runner.run_node_until_exit(|config| async move {373 let para_id = chain_spec::Extensions::try_get(&*config.chain_spec)374 .map(|e| e.para_id)375 .ok_or("Could not find parachain ID in chain-spec.")?;376377 let polkadot_cli = RelayChainCli::new(378 &config,379 [RelayChainCli::executable_name()]380 .iter()381 .chain(cli.relaychain_args.iter()),382 );383384 let id = ParaId::from(para_id);385386 let parachain_account =387 AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id);388389 let state_version =390 RelayChainCli::native_runtime_version(&config.chain_spec).state_version();391 let block: Block = generate_genesis_block(&config.chain_spec, state_version)392 .map_err(|e| format!("{:?}", e))?;393 let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));394 let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));395396 let polkadot_config = SubstrateCli::create_configuration(397 &polkadot_cli,398 &polkadot_cli,399 config.tokio_handle.clone(),400 )401 .map_err(|err| format!("Relay chain argument error: {}", err))?;402403 info!("Parachain id: {:?}", id);404 info!("Parachain Account: {}", parachain_account);405 info!("Parachain genesis state: {}", genesis_state);406 info!("Parachain genesis hash: {}", genesis_hash);407 info!(408 "Is collating: {}",409 if config.role.is_authority() {410 "yes"411 } else {412 "no"413 }414 );415416 #[cfg(feature = "unique-runtime")]417 if config.chain_spec.is_unique() {418 return crate::service::start_node::<419 unique_runtime::Runtime,420 unique_runtime::RuntimeApi,421 UniqueRuntimeExecutor,422 >(config, polkadot_config, id)423 .await424 .map(|r| r.0)425 .map_err(Into::into);426 }427428 #[cfg(feature = "quartz-runtime")]429 if config.chain_spec.is_quartz() {430 return crate::service::start_node::<431 quartz_runtime::Runtime,432 quartz_runtime::RuntimeApi,433 QuartzRuntimeExecutor,434 >(config, polkadot_config, id)435 .await436 .map(|r| r.0)437 .map_err(Into::into);438 }439440 #[cfg(feature = "opal-runtime")]441 if config.chain_spec.is_opal() {442 return 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);450 }451452 Err(no_runtime_err!(config.chain_spec).into())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}