difftreelog
fix use ChainSpecBuilder
in: master
8 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6380,6 +6380,7 @@
"sp-block-builder",
"sp-consensus-aura",
"sp-core",
+ "sp-genesis-builder",
"sp-inherents",
"sp-io",
"sp-offchain",
@@ -10261,6 +10262,7 @@
"sp-block-builder",
"sp-consensus-aura",
"sp-core",
+ "sp-genesis-builder",
"sp-inherents",
"sp-io",
"sp-offchain",
@@ -15134,6 +15136,7 @@
"sp-block-builder",
"sp-consensus-aura",
"sp-core",
+ "sp-genesis-builder",
"sp-inherents",
"sp-io",
"sp-offchain",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -181,6 +181,7 @@
sp-trie = { default-features = false, version = "32.0.0" }
sp-version = { default-features = false, version = "32.0.0" }
sp-weights = { default-features = false, version = "30.0.0" }
+sp-genesis-builder = { default-features = false, version = "0.10.0" }
staging-parachain-info = { default-features = false, version = "0.10.0" }
staging-xcm = { default-features = false, version = "10.0.0" }
staging-xcm-builder = { default-features = false, version = "10.0.0" }
@@ -217,4 +218,5 @@
log = { version = "0.4.20", default-features = false }
num_enum = { version = "0.7.0", default-features = false }
serde = { default-features = false, features = ['derive'], version = "1.0.188" }
+serde_json = "1"
smallvec = "1.11.1"
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use std::collections::BTreeMap;
-
use default_runtime::WASM_BINARY;
#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]
pub use opal_runtime as default_runtime;
@@ -24,7 +22,7 @@
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
use sc_service::ChainType;
use serde::{Deserialize, Serialize};
-use serde_json::map::Map;
+use serde_json::{json, map::Map};
use sp_core::{sr25519, Pair, Public};
use sp_runtime::traits::{IdentifyAccount, Verify};
#[cfg(feature = "unique-runtime")]
@@ -142,184 +140,102 @@
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
}
-#[cfg(not(feature = "unique-runtime"))]
-macro_rules! testnet_genesis {
- (
- $runtime:path,
- $root_key:expr,
- $initial_invulnerables:expr,
- $endowed_accounts:expr,
- $id:expr
- ) => {{
- use $runtime::*;
-
- RuntimeGenesisConfig {
- system: Default::default(),
- balances: BalancesConfig {
- balances: $endowed_accounts
- .iter()
- .cloned()
- // 1e13 UNQ
- .map(|k| (k, 1 << 100))
- .collect(),
- },
- sudo: SudoConfig {
- key: Some($root_key),
- },
-
- vesting: VestingConfig { vesting: vec![] },
- parachain_info: ParachainInfoConfig {
- parachain_id: $id.into(),
- ..Default::default()
- },
- collator_selection: CollatorSelectionConfig {
- invulnerables: $initial_invulnerables
- .iter()
- .cloned()
- .map(|(acc, _)| acc)
- .collect(),
- },
- session: SessionConfig {
- keys: $initial_invulnerables
- .into_iter()
- .map(|(acc, aura)| {
- (
- acc.clone(), // account id
- acc, // validator id
- SessionKeys { aura }, // session keys
- )
- })
- .collect(),
- },
- evm: EVMConfig {
- accounts: BTreeMap::new(),
- ..Default::default()
- },
- ..Default::default()
+pub fn test_config(chain_id: &str, relay_chain: &str) -> DefaultChainSpec {
+ DefaultChainSpec::builder(
+ WASM_BINARY.expect("WASM binary was not build, please build it!"),
+ Extensions {
+ relay_chain: relay_chain.into(),
+ para_id: PARA_ID,
+ },
+ )
+ .with_id(&format!(
+ "{}_{}",
+ default_runtime::VERSION.spec_name,
+ chain_id
+ ))
+ .with_name(&format!(
+ "{}{}",
+ default_runtime::VERSION.spec_name.to_uppercase(),
+ if cfg!(feature = "unique-runtime") {
+ ""
+ } else {
+ " by UNIQUE"
}
- }};
+ ))
+ .with_properties(chain_properties())
+ .with_chain_type(ChainType::Development)
+ .with_genesis_config_patch(genesis_patch())
+ .build()
}
-#[cfg(feature = "unique-runtime")]
-macro_rules! testnet_genesis {
- (
- $runtime:path,
- $root_key:expr,
- $initial_invulnerables:expr,
- $endowed_accounts:expr,
- $id:expr
- ) => {{
- use $runtime::*;
+fn genesis_patch() -> serde_json::Value {
+ use default_runtime::*;
- RuntimeGenesisConfig {
- system: Default::default(),
- balances: BalancesConfig {
- balances: $endowed_accounts
- .iter()
- .cloned()
- // 1e13 UNQ
- .map(|k| (k, 1 << 100))
- .collect(),
- },
- sudo: SudoConfig {
- key: Some($root_key),
- },
- vesting: VestingConfig { vesting: vec![] },
- parachain_info: ParachainInfoConfig {
- parachain_id: $id.into(),
- ..Default::default()
- },
- aura: AuraConfig {
- authorities: $initial_invulnerables
- .into_iter()
- .map(|(_, aura)| aura)
- .collect(),
- },
- evm: EVMConfig {
- accounts: BTreeMap::new(),
- ..Default::default()
- },
- ..Default::default()
- }
- }};
-}
+ let invulnerables = ["Alice", "Bob"];
-pub fn development_config() -> DefaultChainSpec {
- let mut properties = Map::new();
- properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
- properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
- properties.insert(
- "ss58Format".into(),
- default_runtime::SS58Prefix::get().into(),
- );
+ #[allow(unused_mut)]
+ let mut patch = json!({
+ "parachainInfo": {
+ "parachainId": PARA_ID,
+ },
- DefaultChainSpec::from_genesis(
- // Name
- format!(
- "{}{}",
- default_runtime::VERSION.spec_name.to_uppercase(),
- if cfg!(feature = "unique-runtime") {
- ""
- } else {
- " by UNIQUE"
- }
- )
- .as_str(),
- // ID
- format!("{}_dev", default_runtime::VERSION.spec_name).as_str(),
- ChainType::Local,
- move || {
- testnet_genesis!(
- default_runtime,
- // Sudo account
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- [
+ "aura": {
+ "authorities": invulnerables.into_iter()
+ .map(|name| get_from_seed::<AuraId>(name))
+ .collect::<Vec<_>>(),
+ },
+
+ "session": {
+ "keys": invulnerables.into_iter()
+ .map(|name| {
+ let account = get_account_id_from_seed::<sr25519::Public>(name);
+ let aura = get_from_seed::<AuraId>(name);
+
(
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- get_from_seed::<AuraId>("Alice"),
- ),
- (
- get_account_id_from_seed::<sr25519::Public>("Bob"),
- get_from_seed::<AuraId>("Bob"),
- ),
- ],
- // Pre-funded accounts
- vec![
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- get_account_id_from_seed::<sr25519::Public>("Bob"),
- get_account_id_from_seed::<sr25519::Public>("Charlie"),
- get_account_id_from_seed::<sr25519::Public>("Dave"),
- get_account_id_from_seed::<sr25519::Public>("Eve"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie"),
- get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
- get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
- get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
- get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
- get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
- ],
- PARA_ID
- )
+ /* account id: */ account.clone(),
+ /* validator id: */ account,
+ /* session keys: */ SessionKeys { aura },
+ )
+ })
+ .collect::<Vec<_>>()
+ },
+
+ "sudo": {
+ "key": get_account_id_from_seed::<sr25519::Public>("Alice"),
},
- // Bootnodes
- vec![],
- // Telemetry
- None,
- // Protocol ID
- None,
- None,
- // Properties
- Some(properties),
- // Extensions
- Extensions {
- relay_chain: "rococo-dev".into(),
- para_id: PARA_ID,
+
+ "balances": {
+ "balances": &[
+ get_account_id_from_seed::<sr25519::Public>("Alice"),
+ get_account_id_from_seed::<sr25519::Public>("Bob"),
+ get_account_id_from_seed::<sr25519::Public>("Charlie"),
+ get_account_id_from_seed::<sr25519::Public>("Dave"),
+ get_account_id_from_seed::<sr25519::Public>("Eve"),
+ get_account_id_from_seed::<sr25519::Public>("Ferdie"),
+ get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
+ get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
+ ].into_iter()
+ .map(|k| (k, /* ~1.2e+12 UNQ */ 1u128 << 100))
+ .collect::<Vec<_>>(),
},
- WASM_BINARY.expect("WASM binary was not build, please build it!"),
- )
+ });
+
+ #[cfg(feature = "unique-runtime")]
+ {
+ patch
+ .as_object_mut()
+ .expect("the genesis patch is always an object; qed")
+ .remove("session");
+ }
+
+ patch
}
-pub fn local_testnet_config() -> DefaultChainSpec {
+fn chain_properties() -> sc_chain_spec::Properties {
let mut properties = Map::new();
properties.insert("tokenSymbol".into(), default_runtime::TOKEN_SYMBOL.into());
properties.insert("tokenDecimals".into(), default_runtime::DECIMALS.into());
@@ -328,68 +244,5 @@
default_runtime::SS58Prefix::get().into(),
);
- DefaultChainSpec::from_genesis(
- // Name
- format!(
- "{}{}",
- default_runtime::VERSION.impl_name.to_uppercase(),
- if cfg!(feature = "unique-runtime") {
- ""
- } else {
- " by UNIQUE"
- }
- )
- .as_str(),
- // ID
- format!("{}_local", default_runtime::VERSION.spec_name).as_str(),
- ChainType::Local,
- move || {
- testnet_genesis!(
- default_runtime,
- // Sudo account
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- [
- (
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- get_from_seed::<AuraId>("Alice"),
- ),
- (
- get_account_id_from_seed::<sr25519::Public>("Bob"),
- get_from_seed::<AuraId>("Bob"),
- ),
- ],
- // Pre-funded accounts
- vec![
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- get_account_id_from_seed::<sr25519::Public>("Bob"),
- get_account_id_from_seed::<sr25519::Public>("Charlie"),
- get_account_id_from_seed::<sr25519::Public>("Dave"),
- get_account_id_from_seed::<sr25519::Public>("Eve"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie"),
- get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
- get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
- get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
- get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
- get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
- ],
- PARA_ID
- )
- },
- // Bootnodes
- vec![],
- // Telemetry
- None,
- // Protocol ID
- None,
- None,
- // Properties
- Some(properties),
- // Extensions
- Extensions {
- relay_chain: "westend-local".into(),
- para_id: PARA_ID,
- },
- WASM_BINARY.expect("WASM binary was not build, please build it!"),
- )
+ properties
}
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 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 = "quartz-runtime")]46use crate::service::QuartzRuntimeExecutor;47#[cfg(feature = "unique-runtime")]48use crate::service::UniqueRuntimeExecutor;49use crate::{50 chain_spec::{self, RuntimeIdentification, ServiceId, ServiceIdentification},51 cli::{Cli, RelayChainCli, Subcommand},52 service::{53 new_partial, start_dev_node, start_node, OpalRuntimeExecutor, ParachainHostFunctions,54 },55};5657macro_rules! no_runtime_err {58 ($runtime_id:expr) => {59 format!(60 "No runtime valid runtime was found for chain {:#?}",61 $runtime_id62 )63 };64}6566fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {67 Ok(match id {68 "dev" => Box::new(chain_spec::development_config()),69 "" | "local" => Box::new(chain_spec::local_testnet_config()),70 path => {71 let path = std::path::PathBuf::from(path);72 #[allow(clippy::redundant_clone)]73 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)74 as Box<dyn sc_service::ChainSpec>;7576 match chain_spec.runtime_id() {77 #[cfg(feature = "unique-runtime")]78 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),7980 #[cfg(feature = "quartz-runtime")]81 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),8283 RuntimeId::Opal => chain_spec,84 runtime_id => return Err(no_runtime_err!(runtime_id)),85 }86 }87 })88}8990impl SubstrateCli for Cli {91 // TODO use args92 fn impl_name() -> String {93 format!("{} Node", Self::node_name())94 }9596 fn impl_version() -> String {97 env!("SUBSTRATE_CLI_IMPL_VERSION").into()98 }99 // TODO use args100 fn description() -> String {101 format!(102 "{} Node\n\nThe command-line arguments provided first will be \103 passed to the parachain node, while the arguments provided after -- will be passed \104 to the relaychain node.\n\n\105 {} [parachain-args] -- [relaychain-args]",106 Self::node_name(),107 Self::executable_name()108 )109 }110111 fn author() -> String {112 env!("CARGO_PKG_AUTHORS").into()113 }114115 //TODO use args116 fn support_url() -> String {117 "support@unique.network".into()118 }119120 fn copyright_start_year() -> i32 {121 2019122 }123124 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {125 load_spec(id)126 }127}128129impl SubstrateCli for RelayChainCli {130 // TODO use args131 fn impl_name() -> String {132 format!("{} Node", Cli::node_name())133 }134135 fn impl_version() -> String {136 env!("SUBSTRATE_CLI_IMPL_VERSION").into()137 }138 // TODO use args139 fn description() -> String {140 format!(141 "{} Node\n\nThe command-line arguments provided first will be \142 passed to the parachain node, while the arguments provided after -- will be passed \143 to the relaychain node.\n\n\144 parachain-collator [parachain-args] -- [relaychain-args]",145 Cli::node_name()146 )147 }148149 fn author() -> String {150 env!("CARGO_PKG_AUTHORS").into()151 }152 // TODO use args153 fn support_url() -> String {154 "support@unique.network".into()155 }156157 fn copyright_start_year() -> i32 {158 2019159 }160161 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {162 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)163 }164}165166macro_rules! async_run_with_runtime {167 (168 $runtime:path, $runtime_api:path, $executor:path,169 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,170 $( $code:tt )*171 ) => {172 $runner.async_run(|$config| {173 let $components = new_partial::<174 $runtime, $runtime_api, $executor, _175 >(176 &$config,177 crate::service::parachain_build_import_queue::<$runtime, _, _>,178 )?;179 let task_manager = $components.task_manager;180181 { $( $code )* }.map(|v| (v, task_manager))182 })183 };184}185186macro_rules! construct_async_run {187 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{188 let runner = $cli.create_runner($cmd)?;189190 match runner.config().chain_spec.runtime_id() {191 #[cfg(feature = "unique-runtime")]192 RuntimeId::Unique => async_run_with_runtime!(193 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,194 runner, $components, $cli, $cmd, $config, $( $code )*195 ),196197 #[cfg(feature = "quartz-runtime")]198 RuntimeId::Quartz => async_run_with_runtime!(199 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,200 runner, $components, $cli, $cmd, $config, $( $code )*201 ),202203 RuntimeId::Opal => async_run_with_runtime!(204 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,205 runner, $components, $cli, $cmd, $config, $( $code )*206 ),207208 runtime_id => Err(no_runtime_err!(runtime_id).into())209 }210 }}211}212213macro_rules! sync_run_with_runtime {214 (215 $runtime:path, $runtime_api:path, $executor:path,216 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,217 $( $code:tt )*218 ) => {219 $runner.sync_run(|$config| {220 let $components = new_partial::<221 $runtime, $runtime_api, $executor, _222 >(223 &$config,224 crate::service::parachain_build_import_queue::<$runtime, _, _>,225 )?;226227 $( $code )*228 })229 };230}231232macro_rules! construct_sync_run {233 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{234 let runner = $cli.create_runner($cmd)?;235236 match runner.config().chain_spec.runtime_id() {237 #[cfg(feature = "unique-runtime")]238 RuntimeId::Unique => sync_run_with_runtime!(239 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,240 runner, $components, $cli, $cmd, $config, $( $code )*241 ),242243 #[cfg(feature = "quartz-runtime")]244 RuntimeId::Quartz => sync_run_with_runtime!(245 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,246 runner, $components, $cli, $cmd, $config, $( $code )*247 ),248249 RuntimeId::Opal => sync_run_with_runtime!(250 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,251 runner, $components, $cli, $cmd, $config, $( $code )*252 ),253254 runtime_id => Err(no_runtime_err!(runtime_id).into())255 }256 }}257}258259macro_rules! start_node_using_chain_runtime {260 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {261 match $config.chain_spec.runtime_id() {262 #[cfg(feature = "unique-runtime")]263 RuntimeId::Unique => $start_node_fn::<264 unique_runtime::Runtime,265 unique_runtime::RuntimeApi,266 UniqueRuntimeExecutor,267 >($config $(, $($args),+)?) $($code)*,268269 #[cfg(feature = "quartz-runtime")]270 RuntimeId::Quartz => $start_node_fn::<271 quartz_runtime::Runtime,272 quartz_runtime::RuntimeApi,273 QuartzRuntimeExecutor,274 >($config $(, $($args),+)?) $($code)*,275276 RuntimeId::Opal => $start_node_fn::<277 opal_runtime::Runtime,278 opal_runtime::RuntimeApi,279 OpalRuntimeExecutor,280 >($config $(, $($args),+)?) $($code)*,281282 runtime_id => Err(no_runtime_err!(runtime_id).into()),283 }284 };285}286287/// Parse command line arguments into service configuration.288pub fn run() -> Result<()> {289 let cli = Cli::from_args();290291 match &cli.subcommand {292 Some(Subcommand::Key(cmd)) => cmd.run(&cli),293 Some(Subcommand::BuildSpec(cmd)) => {294 let runner = cli.create_runner(cmd)?;295 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))296 }297 Some(Subcommand::CheckBlock(cmd)) => {298 construct_async_run!(|components, cli, cmd, config| {299 Ok(cmd.run(components.client, components.import_queue))300 })301 }302 Some(Subcommand::ExportBlocks(cmd)) => {303 construct_async_run!(|components, cli, cmd, config| {304 Ok(cmd.run(components.client, config.database))305 })306 }307 Some(Subcommand::ExportState(cmd)) => {308 construct_async_run!(|components, cli, cmd, config| {309 Ok(cmd.run(components.client, config.chain_spec))310 })311 }312 Some(Subcommand::ImportBlocks(cmd)) => {313 construct_async_run!(|components, cli, cmd, config| {314 Ok(cmd.run(components.client, components.import_queue))315 })316 }317 Some(Subcommand::PurgeChain(cmd)) => {318 let runner = cli.create_runner(cmd)?;319320 runner.sync_run(|config| {321 let polkadot_cli = RelayChainCli::new(322 &config,323 [RelayChainCli::executable_name()]324 .iter()325 .chain(cli.relaychain_args.iter()),326 );327328 let polkadot_config = SubstrateCli::create_configuration(329 &polkadot_cli,330 &polkadot_cli,331 config.tokio_handle.clone(),332 )333 .map_err(|err| format!("Relay chain argument error: {err}"))?;334335 cmd.run(config, polkadot_config)336 })337 }338 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {339 Ok(cmd.run(components.client, components.backend, None))340 }),341 Some(Subcommand::ExportGenesisState(cmd)) => {342 construct_sync_run!(|components, cli, cmd, _config| cmd.run(components.client))343 }344 Some(Subcommand::ExportGenesisWasm(cmd)) => {345 construct_sync_run!(|_components, cli, cmd, _config| {346 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;347 cmd.run(&*spec)348 })349 }350 #[cfg(feature = "runtime-benchmarks")]351 Some(Subcommand::Benchmark(cmd)) => {352 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};353 use polkadot_cli::Block;354355 type Header = <Block as sp_runtime::traits::Block>::Header;356 type Hasher = <Header as sp_runtime::traits::Header>::Hashing;357358 let runner = cli.create_runner(cmd)?;359 // Switch on the concrete benchmark sub-command-360 match cmd {361 BenchmarkCmd::Pallet(cmd) => {362 runner.sync_run(|config| cmd.run::<Hasher, ParachainHostFunctions>(config))363 }364 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {365 let partials = new_partial::<366 opal_runtime::Runtime,367 opal_runtime::RuntimeApi,368 OpalRuntimeExecutor,369 _,370 >(371 &config,372 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,373 )?;374 cmd.run(partials.client)375 }),376 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {377 let partials = new_partial::<378 opal_runtime::Runtime,379 opal_runtime::RuntimeApi,380 OpalRuntimeExecutor,381 _,382 >(383 &config,384 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,385 )?;386 let db = partials.backend.expose_db();387 let storage = partials.backend.expose_storage();388389 cmd.run(config, partials.client.clone(), db, storage)390 }),391 BenchmarkCmd::Machine(cmd) => {392 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))393 }394 BenchmarkCmd::Overhead(_) | BenchmarkCmd::Extrinsic(_) => {395 Err("Unsupported benchmarking command".into())396 }397 }398 }399 #[cfg(feature = "try-runtime")]400 // embedded try-runtime cli will be removed soon.401 #[allow(deprecated)]402 Some(Subcommand::TryRuntime(cmd)) => {403 use std::{future::Future, pin::Pin};404405 use polkadot_cli::Block;406 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 // grab the task manager.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(427 cmd428 .run::<Block, <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(429 info_provider,430 ),431 ),432433 #[cfg(feature = "quartz-runtime")]434 RuntimeId::Quartz => Box::pin(435 cmd436 .run::<Block, <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(437 info_provider,438 ),439 ),440441 RuntimeId::Opal => Box::pin(442 cmd443 .run::<Block, <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(444 info_provider,445 ),446 ),447 runtime_id => return Err(no_runtime_err!(runtime_id).into()),448 },449 task_manager,450 ))451 })452 }453 #[cfg(not(feature = "try-runtime"))]454 Some(Subcommand::TryRuntime) => {455 Err("Try-runtime must be enabled by `--features try-runtime`.".into())456 }457 None => {458 let runner = cli.create_runner(&cli.run.normalize())?;459 let collator_options = cli.run.collator_options();460461 runner.run_node_until_exit(|config| async move {462 let hwbench = if !cli.no_hardware_benchmarks {463 config.database.path().map(|database_path| {464 let _ = std::fs::create_dir_all(database_path);465 sc_sysinfo::gather_hwbench(Some(database_path))466 })467 } else {468 None469 };470471 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);472473 let service_id = config.chain_spec.service_id();474 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());475 let is_dev_service = matches![service_id, ServiceId::Dev]476 || relay_chain_id == Some("dev-service".into());477478 if is_dev_service {479 info!("Running Dev service");480481 let mut config = config;482483 config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);484485 return start_node_using_chain_runtime! {486 start_dev_node(config, cli.idle_autoseal_interval, cli.autoseal_finalization_delay, cli.disable_autoseal_on_tx).map_err(Into::into)487 };488 };489490 let para_id = extensions491 .map(|e| e.para_id)492 .ok_or("Could not find parachain ID in chain-spec.")?;493494 let polkadot_cli = RelayChainCli::new(495 &config,496 [RelayChainCli::executable_name()]497 .iter()498 .chain(cli.relaychain_args.iter()),499 );500501 let para_id = ParaId::from(para_id);502503 let parachain_account =504 AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(505 ¶_id,506 );507508 let polkadot_config = SubstrateCli::create_configuration(509 &polkadot_cli,510 &polkadot_cli,511 config.tokio_handle.clone(),512 )513 .map_err(|err| format!("Relay chain argument error: {err}"))?;514515 info!("Parachain id: {:?}", para_id);516 info!("Parachain Account: {}", parachain_account);517 info!(518 "Is collating: {}",519 if config.role.is_authority() {520 "yes"521 } else {522 "no"523 }524 );525526 start_node_using_chain_runtime! {527 start_node(config, polkadot_config, collator_options, para_id, hwbench)528 .await529 .map(|r| r.0)530 .map_err(Into::into)531 }532 })533 }534 }535}536537impl DefaultConfigurationValues for RelayChainCli {538 fn p2p_listen_port() -> u16 {539 30334540 }541542 fn rpc_listen_port() -> u16 {543 9945544 }545546 fn prometheus_listen_port() -> u16 {547 9616548 }549}550551impl CliConfiguration<Self> for RelayChainCli {552 fn shared_params(&self) -> &SharedParams {553 self.base.base.shared_params()554 }555556 fn import_params(&self) -> Option<&ImportParams> {557 self.base.base.import_params()558 }559560 fn network_params(&self) -> Option<&NetworkParams> {561 self.base.base.network_params()562 }563564 fn keystore_params(&self) -> Option<&KeystoreParams> {565 self.base.base.keystore_params()566 }567568 fn base_path(&self) -> Result<Option<BasePath>> {569 Ok(self570 .shared_params()571 .base_path()?572 .or_else(|| Some(self.base_path.clone().into())))573 }574575 fn prometheus_config(576 &self,577 default_listen_port: u16,578 chain_spec: &Box<dyn ChainSpec>,579 ) -> Result<Option<PrometheusConfig>> {580 self.base581 .base582 .prometheus_config(default_listen_port, chain_spec)583 }584585 fn init<F>(586 &self,587 _support_url: &String,588 _impl_version: &String,589 _logger_hook: F,590 _config: &sc_service::Configuration,591 ) -> Result<()> {592 unreachable!("PolkadotCli is never initialized; qed");593 }594595 fn chain_id(&self, is_dev: bool) -> Result<String> {596 let chain_id = self.base.base.chain_id(is_dev)?;597598 Ok(if chain_id.is_empty() {599 self.chain_id.clone().unwrap_or_default()600 } else {601 chain_id602 })603 }604605 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {606 self.base.base.role(is_dev)607 }608609 fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {610 self.base.base.transaction_pool(is_dev)611 }612613 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {614 self.base.base.rpc_methods()615 }616617 fn rpc_max_connections(&self) -> Result<u32> {618 self.base.base.rpc_max_connections()619 }620621 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {622 self.base.base.rpc_cors(is_dev)623 }624625 fn default_heap_pages(&self) -> Result<Option<u64>> {626 self.base.base.default_heap_pages()627 }628629 fn force_authoring(&self) -> Result<bool> {630 self.base.base.force_authoring()631 }632633 fn disable_grandpa(&self) -> Result<bool> {634 self.base.base.disable_grandpa()635 }636637 fn max_runtime_instances(&self) -> Result<Option<usize>> {638 self.base.base.max_runtime_instances()639 }640641 fn announce_block(&self) -> Result<bool> {642 self.base.base.announce_block()643 }644645 fn telemetry_endpoints(646 &self,647 chain_spec: &Box<dyn ChainSpec>,648 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {649 self.base.base.telemetry_endpoints(chain_spec)650 }651}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 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 = "quartz-runtime")]46use crate::service::QuartzRuntimeExecutor;47#[cfg(feature = "unique-runtime")]48use crate::service::UniqueRuntimeExecutor;49use crate::{50 chain_spec::{self, RuntimeIdentification, ServiceId, ServiceIdentification},51 cli::{Cli, RelayChainCli, Subcommand},52 service::{new_partial, start_dev_node, start_node, OpalRuntimeExecutor},53};5455macro_rules! no_runtime_err {56 ($runtime_id:expr) => {57 format!(58 "No runtime valid runtime was found for chain {:#?}",59 $runtime_id60 )61 };62}6364fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {65 Ok(match id {66 "dev" => Box::new(chain_spec::test_config("dev", "rococo-dev")),67 "" | "local" => Box::new(chain_spec::test_config("local", "westend-local")),68 path => {69 let path = std::path::PathBuf::from(path);70 #[allow(clippy::redundant_clone)]71 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)72 as Box<dyn sc_service::ChainSpec>;7374 match chain_spec.runtime_id() {75 #[cfg(feature = "unique-runtime")]76 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),7778 #[cfg(feature = "quartz-runtime")]79 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),8081 RuntimeId::Opal => chain_spec,82 runtime_id => return Err(no_runtime_err!(runtime_id)),83 }84 }85 })86}8788impl SubstrateCli for Cli {89 // TODO use args90 fn impl_name() -> String {91 format!("{} Node", Self::node_name())92 }9394 fn impl_version() -> String {95 env!("SUBSTRATE_CLI_IMPL_VERSION").into()96 }97 // TODO use args98 fn description() -> String {99 format!(100 "{} Node\n\nThe command-line arguments provided first will be \101 passed to the parachain node, while the arguments provided after -- will be passed \102 to the relaychain node.\n\n\103 {} [parachain-args] -- [relaychain-args]",104 Self::node_name(),105 Self::executable_name()106 )107 }108109 fn author() -> String {110 env!("CARGO_PKG_AUTHORS").into()111 }112113 //TODO use args114 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 }125}126127impl SubstrateCli for RelayChainCli {128 // TODO use args129 fn impl_name() -> String {130 format!("{} Node", Cli::node_name())131 }132133 fn impl_version() -> String {134 env!("SUBSTRATE_CLI_IMPL_VERSION").into()135 }136 // TODO use args137 fn description() -> String {138 format!(139 "{} Node\n\nThe command-line arguments provided first will be \140 passed to the parachain node, while the arguments provided after -- will be passed \141 to the relaychain node.\n\n\142 parachain-collator [parachain-args] -- [relaychain-args]",143 Cli::node_name()144 )145 }146147 fn author() -> String {148 env!("CARGO_PKG_AUTHORS").into()149 }150 // TODO use args151 fn support_url() -> String {152 "support@unique.network".into()153 }154155 fn copyright_start_year() -> i32 {156 2019157 }158159 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {160 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)161 }162}163164macro_rules! async_run_with_runtime {165 (166 $runtime:path, $runtime_api:path, $executor:path,167 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,168 $( $code:tt )*169 ) => {170 $runner.async_run(|$config| {171 let $components = new_partial::<172 $runtime, $runtime_api, $executor, _173 >(174 &$config,175 crate::service::parachain_build_import_queue::<$runtime, _, _>,176 )?;177 let task_manager = $components.task_manager;178179 { $( $code )* }.map(|v| (v, task_manager))180 })181 };182}183184macro_rules! construct_async_run {185 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{186 let runner = $cli.create_runner($cmd)?;187188 match runner.config().chain_spec.runtime_id() {189 #[cfg(feature = "unique-runtime")]190 RuntimeId::Unique => async_run_with_runtime!(191 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,192 runner, $components, $cli, $cmd, $config, $( $code )*193 ),194195 #[cfg(feature = "quartz-runtime")]196 RuntimeId::Quartz => async_run_with_runtime!(197 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,198 runner, $components, $cli, $cmd, $config, $( $code )*199 ),200201 RuntimeId::Opal => async_run_with_runtime!(202 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,203 runner, $components, $cli, $cmd, $config, $( $code )*204 ),205206 runtime_id => Err(no_runtime_err!(runtime_id).into())207 }208 }}209}210211macro_rules! sync_run_with_runtime {212 (213 $runtime:path, $runtime_api:path, $executor:path,214 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,215 $( $code:tt )*216 ) => {217 $runner.sync_run(|$config| {218 let $components = new_partial::<219 $runtime, $runtime_api, $executor, _220 >(221 &$config,222 crate::service::parachain_build_import_queue::<$runtime, _, _>,223 )?;224225 $( $code )*226 })227 };228}229230macro_rules! construct_sync_run {231 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{232 let runner = $cli.create_runner($cmd)?;233234 match runner.config().chain_spec.runtime_id() {235 #[cfg(feature = "unique-runtime")]236 RuntimeId::Unique => sync_run_with_runtime!(237 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,238 runner, $components, $cli, $cmd, $config, $( $code )*239 ),240241 #[cfg(feature = "quartz-runtime")]242 RuntimeId::Quartz => sync_run_with_runtime!(243 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,244 runner, $components, $cli, $cmd, $config, $( $code )*245 ),246247 RuntimeId::Opal => sync_run_with_runtime!(248 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,249 runner, $components, $cli, $cmd, $config, $( $code )*250 ),251252 runtime_id => Err(no_runtime_err!(runtime_id).into())253 }254 }}255}256257macro_rules! start_node_using_chain_runtime {258 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {259 match $config.chain_spec.runtime_id() {260 #[cfg(feature = "unique-runtime")]261 RuntimeId::Unique => $start_node_fn::<262 unique_runtime::Runtime,263 unique_runtime::RuntimeApi,264 UniqueRuntimeExecutor,265 >($config $(, $($args),+)?) $($code)*,266267 #[cfg(feature = "quartz-runtime")]268 RuntimeId::Quartz => $start_node_fn::<269 quartz_runtime::Runtime,270 quartz_runtime::RuntimeApi,271 QuartzRuntimeExecutor,272 >($config $(, $($args),+)?) $($code)*,273274 RuntimeId::Opal => $start_node_fn::<275 opal_runtime::Runtime,276 opal_runtime::RuntimeApi,277 OpalRuntimeExecutor,278 >($config $(, $($args),+)?) $($code)*,279280 runtime_id => Err(no_runtime_err!(runtime_id).into()),281 }282 };283}284285/// Parse command line arguments into service configuration.286pub fn run() -> Result<()> {287 let cli = Cli::from_args();288289 match &cli.subcommand {290 Some(Subcommand::Key(cmd)) => cmd.run(&cli),291 Some(Subcommand::BuildSpec(cmd)) => {292 let runner = cli.create_runner(cmd)?;293 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))294 }295 Some(Subcommand::CheckBlock(cmd)) => {296 construct_async_run!(|components, cli, cmd, config| {297 Ok(cmd.run(components.client, components.import_queue))298 })299 }300 Some(Subcommand::ExportBlocks(cmd)) => {301 construct_async_run!(|components, cli, cmd, config| {302 Ok(cmd.run(components.client, config.database))303 })304 }305 Some(Subcommand::ExportState(cmd)) => {306 construct_async_run!(|components, cli, cmd, config| {307 Ok(cmd.run(components.client, config.chain_spec))308 })309 }310 Some(Subcommand::ImportBlocks(cmd)) => {311 construct_async_run!(|components, cli, cmd, config| {312 Ok(cmd.run(components.client, components.import_queue))313 })314 }315 Some(Subcommand::PurgeChain(cmd)) => {316 let runner = cli.create_runner(cmd)?;317318 runner.sync_run(|config| {319 let polkadot_cli = RelayChainCli::new(320 &config,321 [RelayChainCli::executable_name()]322 .iter()323 .chain(cli.relaychain_args.iter()),324 );325326 let polkadot_config = SubstrateCli::create_configuration(327 &polkadot_cli,328 &polkadot_cli,329 config.tokio_handle.clone(),330 )331 .map_err(|err| format!("Relay chain argument error: {err}"))?;332333 cmd.run(config, polkadot_config)334 })335 }336 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {337 Ok(cmd.run(components.client, components.backend, None))338 }),339 Some(Subcommand::ExportGenesisState(cmd)) => {340 construct_sync_run!(|components, cli, cmd, _config| cmd.run(components.client))341 }342 Some(Subcommand::ExportGenesisWasm(cmd)) => {343 construct_sync_run!(|_components, cli, cmd, _config| {344 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;345 cmd.run(&*spec)346 })347 }348 #[cfg(feature = "runtime-benchmarks")]349 Some(Subcommand::Benchmark(cmd)) => {350 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};351 use polkadot_cli::Block;352353 use crate::service::ParachainHostFunctions;354355 type Header = <Block as sp_runtime::traits::Block>::Header;356 type Hasher = <Header as sp_runtime::traits::Header>::Hashing;357358 let runner = cli.create_runner(cmd)?;359 // Switch on the concrete benchmark sub-command-360 match cmd {361 BenchmarkCmd::Pallet(cmd) => {362 runner.sync_run(|config| cmd.run::<Hasher, ParachainHostFunctions>(config))363 }364 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {365 let partials = new_partial::<366 opal_runtime::Runtime,367 opal_runtime::RuntimeApi,368 OpalRuntimeExecutor,369 _,370 >(371 &config,372 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,373 )?;374 cmd.run(partials.client)375 }),376 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {377 let partials = new_partial::<378 opal_runtime::Runtime,379 opal_runtime::RuntimeApi,380 OpalRuntimeExecutor,381 _,382 >(383 &config,384 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,385 )?;386 let db = partials.backend.expose_db();387 let storage = partials.backend.expose_storage();388389 cmd.run(config, partials.client.clone(), db, storage)390 }),391 BenchmarkCmd::Machine(cmd) => {392 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))393 }394 BenchmarkCmd::Overhead(_) | BenchmarkCmd::Extrinsic(_) => {395 Err("Unsupported benchmarking command".into())396 }397 }398 }399 #[cfg(feature = "try-runtime")]400 // embedded try-runtime cli will be removed soon.401 #[allow(deprecated)]402 Some(Subcommand::TryRuntime(cmd)) => {403 use std::{future::Future, pin::Pin};404405 use polkadot_cli::Block;406 use sc_executor::NativeExecutionDispatch;407 use try_runtime_cli::block_building_info::timestamp_with_aura_info;408409 let runner = cli.create_runner(cmd)?;410411 // grab the task manager.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(427 cmd428 .run::<Block, <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(429 info_provider,430 ),431 ),432433 #[cfg(feature = "quartz-runtime")]434 RuntimeId::Quartz => Box::pin(435 cmd436 .run::<Block, <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(437 info_provider,438 ),439 ),440441 RuntimeId::Opal => Box::pin(442 cmd443 .run::<Block, <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions, _>(444 info_provider,445 ),446 ),447 runtime_id => return Err(no_runtime_err!(runtime_id).into()),448 },449 task_manager,450 ))451 })452 }453 #[cfg(not(feature = "try-runtime"))]454 Some(Subcommand::TryRuntime) => {455 Err("Try-runtime must be enabled by `--features try-runtime`.".into())456 }457 None => {458 let runner = cli.create_runner(&cli.run.normalize())?;459 let collator_options = cli.run.collator_options();460461 runner.run_node_until_exit(|config| async move {462 let hwbench = if !cli.no_hardware_benchmarks {463 config.database.path().map(|database_path| {464 let _ = std::fs::create_dir_all(database_path);465 sc_sysinfo::gather_hwbench(Some(database_path))466 })467 } else {468 None469 };470471 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);472473 let service_id = config.chain_spec.service_id();474 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());475 let is_dev_service = matches![service_id, ServiceId::Dev]476 || relay_chain_id == Some("dev-service".into());477478 if is_dev_service {479 info!("Running Dev service");480481 let mut config = config;482483 config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);484485 return start_node_using_chain_runtime! {486 start_dev_node(config, cli.idle_autoseal_interval, cli.autoseal_finalization_delay, cli.disable_autoseal_on_tx).map_err(Into::into)487 };488 };489490 let para_id = extensions491 .map(|e| e.para_id)492 .ok_or("Could not find parachain ID in chain-spec.")?;493494 let polkadot_cli = RelayChainCli::new(495 &config,496 [RelayChainCli::executable_name()]497 .iter()498 .chain(cli.relaychain_args.iter()),499 );500501 let para_id = ParaId::from(para_id);502503 let parachain_account =504 AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(505 ¶_id,506 );507508 let polkadot_config = SubstrateCli::create_configuration(509 &polkadot_cli,510 &polkadot_cli,511 config.tokio_handle.clone(),512 )513 .map_err(|err| format!("Relay chain argument error: {err}"))?;514515 info!("Parachain id: {:?}", para_id);516 info!("Parachain Account: {}", parachain_account);517 info!(518 "Is collating: {}",519 if config.role.is_authority() {520 "yes"521 } else {522 "no"523 }524 );525526 start_node_using_chain_runtime! {527 start_node(config, polkadot_config, collator_options, para_id, hwbench)528 .await529 .map(|r| r.0)530 .map_err(Into::into)531 }532 })533 }534 }535}536537impl DefaultConfigurationValues for RelayChainCli {538 fn p2p_listen_port() -> u16 {539 30334540 }541542 fn rpc_listen_port() -> u16 {543 9945544 }545546 fn prometheus_listen_port() -> u16 {547 9616548 }549}550551impl CliConfiguration<Self> for RelayChainCli {552 fn shared_params(&self) -> &SharedParams {553 self.base.base.shared_params()554 }555556 fn import_params(&self) -> Option<&ImportParams> {557 self.base.base.import_params()558 }559560 fn network_params(&self) -> Option<&NetworkParams> {561 self.base.base.network_params()562 }563564 fn keystore_params(&self) -> Option<&KeystoreParams> {565 self.base.base.keystore_params()566 }567568 fn base_path(&self) -> Result<Option<BasePath>> {569 Ok(self570 .shared_params()571 .base_path()?572 .or_else(|| Some(self.base_path.clone().into())))573 }574575 fn prometheus_config(576 &self,577 default_listen_port: u16,578 chain_spec: &Box<dyn ChainSpec>,579 ) -> Result<Option<PrometheusConfig>> {580 self.base581 .base582 .prometheus_config(default_listen_port, chain_spec)583 }584585 fn init<F>(586 &self,587 _support_url: &String,588 _impl_version: &String,589 _logger_hook: F,590 _config: &sc_service::Configuration,591 ) -> Result<()> {592 unreachable!("PolkadotCli is never initialized; qed");593 }594595 fn chain_id(&self, is_dev: bool) -> Result<String> {596 let chain_id = self.base.base.chain_id(is_dev)?;597598 Ok(if chain_id.is_empty() {599 self.chain_id.clone().unwrap_or_default()600 } else {601 chain_id602 })603 }604605 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {606 self.base.base.role(is_dev)607 }608609 fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {610 self.base.base.transaction_pool(is_dev)611 }612613 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {614 self.base.base.rpc_methods()615 }616617 fn rpc_max_connections(&self) -> Result<u32> {618 self.base.base.rpc_max_connections()619 }620621 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {622 self.base.base.rpc_cors(is_dev)623 }624625 fn default_heap_pages(&self) -> Result<Option<u64>> {626 self.base.base.default_heap_pages()627 }628629 fn force_authoring(&self) -> Result<bool> {630 self.base.base.force_authoring()631 }632633 fn disable_grandpa(&self) -> Result<bool> {634 self.base.base.disable_grandpa()635 }636637 fn max_runtime_instances(&self) -> Result<Option<usize>> {638 self.base.base.max_runtime_instances()639 }640641 fn announce_block(&self) -> Result<bool> {642 self.base.base.announce_block()643 }644645 fn telemetry_endpoints(646 &self,647 chain_spec: &Box<dyn ChainSpec>,648 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {649 self.base.base.telemetry_endpoints(chain_spec)650 }651}runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -43,6 +43,7 @@
ApplyExtrinsicResult, DispatchError, ExtrinsicInclusionMode,
};
use frame_support::{
+ genesis_builder_helper::{build_config, create_default_config},
pallet_prelude::Weight,
traits::OnFinalize,
};
@@ -710,6 +711,16 @@
)
}
}
+
+ impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
+ fn create_default_config() -> Vec<u8> {
+ create_default_config::<RuntimeGenesisConfig>()
+ }
+
+ fn build_config(config: Vec<u8>) -> sp_genesis_builder::Result {
+ build_config::<RuntimeGenesisConfig>(config)
+ }
+ }
}
}
}
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -146,6 +146,7 @@
'sp-storage/std',
'sp-transaction-pool/std',
'sp-version/std',
+ 'sp-genesis-builder/std',
'staging-parachain-info/std',
'staging-xcm-builder/std',
'staging-xcm-executor/std',
@@ -295,6 +296,7 @@
sp-storage = { workspace = true }
sp-transaction-pool = { workspace = true }
sp-version = { workspace = true }
+sp-genesis-builder = { workspace = true }
staging-parachain-info = { workspace = true }
staging-xcm = { workspace = true }
staging-xcm-builder = { workspace = true }
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -145,6 +145,7 @@
'sp-std/std',
'sp-transaction-pool/std',
'sp-version/std',
+ 'sp-genesis-builder/std',
'staging-parachain-info/std',
'staging-xcm-builder/std',
'staging-xcm-executor/std',
@@ -283,6 +284,7 @@
sp-storage = { workspace = true }
sp-transaction-pool = { workspace = true }
sp-version = { workspace = true }
+sp-genesis-builder = { workspace = true }
staging-parachain-info = { workspace = true }
staging-xcm = { workspace = true }
staging-xcm-builder = { workspace = true }
runtime/unique/Cargo.tomldiffbeforeafterboth--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -143,6 +143,7 @@
'sp-std/std',
'sp-transaction-pool/std',
'sp-version/std',
+ 'sp-genesis-builder/std',
'staging-parachain-info/std',
'staging-xcm-builder/std',
'staging-xcm-executor/std',
@@ -287,6 +288,7 @@
sp-storage = { workspace = true }
sp-transaction-pool = { workspace = true }
sp-version = { workspace = true }
+sp-genesis-builder = { workspace = true }
staging-parachain-info = { workspace = true }
staging-xcm = { workspace = true }
staging-xcm-builder = { workspace = true }