difftreelog
Add RuntimeId, use match on runtime identification
in: master
2 files changed
node/cli/src/chain_spec.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/>.1617use cumulus_primitives_core::ParaId;18use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};19use sc_service::ChainType;20use sp_core::{sr25519, Pair, Public};21use sp_runtime::traits::{IdentifyAccount, Verify};22use std::collections::BTreeMap;2324use serde::{Deserialize, Serialize};25use serde_json::map::Map;2627use unique_runtime_common::types::*;2829/// The `ChainSpec` parameterized for the unique runtime.30#[cfg(feature = "unique-runtime")]31pub type UniqueChainSpec = sc_service::GenericChainSpec<unique_runtime::GenesisConfig, Extensions>;3233/// The `ChainSpec` parameterized for the quartz runtime.34#[cfg(feature = "quartz-runtime")]35pub type QuartzChainSpec = sc_service::GenericChainSpec<quartz_runtime::GenesisConfig, Extensions>;3637/// The `ChainSpec` parameterized for the opal runtime.38#[cfg(feature = "opal-runtime")]39pub type OpalChainSpec = sc_service::GenericChainSpec<opal_runtime::GenesisConfig, Extensions>;4041pub trait RuntimeIdentification {42 fn is_unique(&self) -> bool;4344 fn is_quartz(&self) -> bool;4546 fn is_opal(&self) -> bool;47}4849impl RuntimeIdentification for Box<dyn sc_service::ChainSpec> {50 fn is_unique(&self) -> bool {51 self.id().starts_with("unique")52 }5354 fn is_quartz(&self) -> bool {55 self.id().starts_with("quartz")56 }5758 fn is_opal(&self) -> bool {59 self.id().starts_with("opal") || self.id() == "dev" || self.id() == "local_testnet"60 }61}6263/// Helper function to generate a crypto pair from seed64pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {65 TPublic::Pair::from_string(&format!("//{}", seed), None)66 .expect("static values are valid; qed")67 .public()68}6970/// The extensions for the [`ChainSpec`].71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]72#[serde(deny_unknown_fields)]73pub struct Extensions {74 /// The relay chain of the Parachain.75 pub relay_chain: String,76 /// The id of the Parachain.77 pub para_id: u32,78}7980impl Extensions {81 /// Try to get the extension from the given `ChainSpec`.82 pub fn try_get(chain_spec: &dyn sc_service::ChainSpec) -> Option<&Self> {83 sc_chain_spec::get_extension(chain_spec.extensions())84 }85}8687type AccountPublic = <Signature as Verify>::Signer;8889/// Helper function to generate an account ID from seed90pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId91where92 AccountPublic: From<<TPublic::Pair as Pair>::Public>,93{94 AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()95}9697pub fn development_config() -> OpalChainSpec {98 let mut properties = Map::new();99 properties.insert("tokenSymbol".into(), "OPL".into());100 properties.insert("tokenDecimals".into(), 15.into());101 properties.insert("ss58Format".into(), 42.into());102103 OpalChainSpec::from_genesis(104 // Name105 "Development",106 // ID107 "dev",108 ChainType::Local,109 move || {110 testnet_genesis(111 // Sudo account112 get_account_id_from_seed::<sr25519::Public>("Alice"),113 vec![114 get_from_seed::<AuraId>("Alice"),115 get_from_seed::<AuraId>("Bob"),116 ],117 // Pre-funded accounts118 vec![119 get_account_id_from_seed::<sr25519::Public>("Alice"),120 get_account_id_from_seed::<sr25519::Public>("Bob"),121 ],122 1000.into(),123 )124 },125 // Bootnodes126 vec![],127 // Telemetry128 None,129 // Protocol ID130 None,131 None,132 // Properties133 Some(properties),134 // Extensions135 Extensions {136 relay_chain: "rococo-dev".into(),137 para_id: 1000,138 },139 )140}141142pub fn local_testnet_rococo_config() -> OpalChainSpec {143 OpalChainSpec::from_genesis(144 // Name145 "Local Testnet",146 // ID147 "local_testnet",148 ChainType::Local,149 move || {150 testnet_genesis(151 // Sudo account152 get_account_id_from_seed::<sr25519::Public>("Alice"),153 vec![154 get_from_seed::<AuraId>("Alice"),155 get_from_seed::<AuraId>("Bob"),156 ],157 // Pre-funded accounts158 vec![159 get_account_id_from_seed::<sr25519::Public>("Alice"),160 get_account_id_from_seed::<sr25519::Public>("Bob"),161 get_account_id_from_seed::<sr25519::Public>("Charlie"),162 get_account_id_from_seed::<sr25519::Public>("Dave"),163 get_account_id_from_seed::<sr25519::Public>("Eve"),164 get_account_id_from_seed::<sr25519::Public>("Ferdie"),165 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),166 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),167 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),168 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),169 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),170 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),171 ],172 1000.into(),173 )174 },175 // Bootnodes176 vec![],177 // Telemetry178 None,179 // Protocol ID180 None,181 None,182 // Properties183 None,184 // Extensions185 Extensions {186 relay_chain: "rococo-local".into(),187 para_id: 1000,188 },189 )190}191192pub fn local_testnet_westend_config() -> OpalChainSpec {193 OpalChainSpec::from_genesis(194 // Name195 "Local Testnet",196 // ID197 "local_testnet",198 ChainType::Local,199 move || {200 testnet_genesis(201 // Sudo account202 get_account_id_from_seed::<sr25519::Public>("Alice"),203 vec![204 get_from_seed::<AuraId>("Alice"),205 get_from_seed::<AuraId>("Bob"),206 get_from_seed::<AuraId>("Charlie"),207 get_from_seed::<AuraId>("Dave"),208 get_from_seed::<AuraId>("Eve"),209 ],210 // Pre-funded accounts211 vec![212 get_account_id_from_seed::<sr25519::Public>("Alice"),213 get_account_id_from_seed::<sr25519::Public>("Bob"),214 get_account_id_from_seed::<sr25519::Public>("Charlie"),215 get_account_id_from_seed::<sr25519::Public>("Dave"),216 get_account_id_from_seed::<sr25519::Public>("Eve"),217 get_account_id_from_seed::<sr25519::Public>("Ferdie"),218 get_account_id_from_seed::<sr25519::Public>("Alice//stash"),219 get_account_id_from_seed::<sr25519::Public>("Bob//stash"),220 get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),221 get_account_id_from_seed::<sr25519::Public>("Dave//stash"),222 get_account_id_from_seed::<sr25519::Public>("Eve//stash"),223 get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),224 ],225 1000.into(),226 )227 },228 // Bootnodes229 vec![],230 // Telemetry231 None,232 // Protocol ID233 None,234 None,235 // Properties236 None,237 // Extensions238 Extensions {239 relay_chain: "westend-local".into(),240 para_id: 1000,241 },242 )243}244245fn testnet_genesis(246 root_key: AccountId,247 initial_authorities: Vec<AuraId>,248 endowed_accounts: Vec<AccountId>,249 id: ParaId,250) -> opal_runtime::GenesisConfig {251 use opal_runtime::*;252253 GenesisConfig {254 system: SystemConfig {255 code: WASM_BINARY256 .expect("WASM binary was not build, please build it!")257 .to_vec(),258 },259 balances: BalancesConfig {260 balances: endowed_accounts261 .iter()262 .cloned()263 // 1e13 UNQ264 .map(|k| (k, 1 << 100))265 .collect(),266 },267 treasury: Default::default(),268 sudo: SudoConfig {269 key: Some(root_key),270 },271 vesting: VestingConfig { vesting: vec![] },272 parachain_info: ParachainInfoConfig { parachain_id: id },273 parachain_system: Default::default(),274 aura: AuraConfig {275 authorities: initial_authorities,276 },277 aura_ext: Default::default(),278 evm: EVMConfig {279 accounts: BTreeMap::new(),280 },281 ethereum: EthereumConfig {},282 }283}node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -33,7 +33,7 @@
// limitations under the License.
use crate::{
- chain_spec::{self, RuntimeIdentification},
+ chain_spec::{self, RuntimeId, RuntimeIdentification},
cli::{Cli, RelayChainCli, Subcommand},
service::new_partial,
};
@@ -66,46 +66,40 @@
use unique_runtime_common::types::Block;
macro_rules! no_runtime_err {
- ($chain_spec:expr) => {
+ ($chain_name:expr) => {
format!(
- "No runtime valid runtime was found, chain id: {}",
- $chain_spec.id()
+ "No runtime valid runtime was found for chain {}",
+ $chain_name
)
};
}
fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
- match id {
- "westend-local" => Ok(Box::new(chain_spec::local_testnet_westend_config())),
- "rococo-local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),
- "dev" => Ok(Box::new(chain_spec::development_config())),
- "" | "local" => Ok(Box::new(chain_spec::local_testnet_rococo_config())),
+ Ok(match id {
+ "westend-local" => Box::new(chain_spec::local_testnet_westend_config()),
+ "rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),
+ "dev" => Box::new(chain_spec::development_config()),
+ "" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),
path => {
let path = std::path::PathBuf::from(path);
- let chain_spec = Box::new(sc_service::GenericChainSpec::<()>::from_json_file(path.clone())?)
- as Box<dyn sc_service::ChainSpec>;
+ let chain_spec = Box::new(sc_service::GenericChainSpec::<()>::from_json_file(
+ path.clone(),
+ )?) as Box<dyn sc_service::ChainSpec>;
- #[cfg(feature = "unique-runtime")]
- if chain_spec.is_unique() {
- let chain_spec = chain_spec::UniqueChainSpec::from_json_file(path)?;
- return Ok(Box::new(chain_spec));
- }
+ match chain_spec.runtime_id() {
+ #[cfg(feature = "unique-runtime")]
+ RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),
+
+ #[cfg(feature = "quartz-runtime")]
+ RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),
- #[cfg(feature = "quartz-runtime")]
- if chain_spec.is_quartz() {
- let chain_spec = chain_spec::QuartzChainSpec::from_json_file(path)?;
- return Ok(Box::new(chain_spec));
- }
+ #[cfg(feature = "opal-runtime")]
+ RuntimeId::Opal => Box::new(chain_spec::OpalChainSpec::from_json_file(path)?),
- #[cfg(feature = "opal-runtime")]
- if chain_spec.is_opal() {
- let chain_spec = chain_spec::OpalChainSpec::from_json_file(path)?;
- return Ok(Box::new(chain_spec));
+ RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain)),
}
-
- Err(no_runtime_err!(chain_spec))
}
- }
+ })
}
impl SubstrateCli for Cli {
@@ -146,22 +140,18 @@
}
fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
- #[cfg(feature = "unique-runtime")]
- if chain_spec.is_unique() {
- return &unique_runtime::VERSION;
- }
+ match chain_spec.runtime_id() {
+ #[cfg(feature = "unique-runtime")]
+ RuntimeId::Unique => &unique_runtime::VERSION,
+
+ #[cfg(feature = "quartz-runtime")]
+ RuntimeId::Quartz => &quartz_runtime::VERSION,
- #[cfg(feature = "quartz-runtime")]
- if chain_spec.is_quartz() {
- return &quartz_runtime::VERSION;
- }
+ #[cfg(feature = "opal-runtime")]
+ RuntimeId::Opal => &opal_runtime::VERSION,
- #[cfg(feature = "opal-runtime")]
- if chain_spec.is_opal() {
- return &opal_runtime::VERSION;
+ RuntimeId::Unknown(chain) => panic!("{}", no_runtime_err!(chain)),
}
-
- panic!("{}", no_runtime_err!(chain_spec));
}
}
@@ -214,53 +204,51 @@
.ok_or_else(|| "Could not find wasm file in genesis state!".into())
}
+macro_rules! async_run_with_runtime {
+ (
+ $runtime_api:path, $executor:path,
+ $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,
+ $( $code:tt )*
+ ) => {
+ $runner.async_run(|$config| {
+ let $components = new_partial::<
+ $runtime_api, $executor, _
+ >(
+ &$config,
+ crate::service::parachain_build_import_queue,
+ )?;
+ let task_manager = $components.task_manager;
+
+ { $( $code )* }.map(|v| (v, task_manager))
+ })
+ };
+}
+
macro_rules! construct_async_run {
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
let runner = $cli.create_runner($cmd)?;
- #[cfg(feature = "unique-runtime")]
- if runner.config().chain_spec.is_unique() {
- return runner.async_run(|$config| {
- let $components = new_partial::<
- unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _
- >(
- &$config,
- crate::service::parachain_build_import_queue,
- )?;
- let task_manager = $components.task_manager;
- { $( $code )* }.map(|v| (v, task_manager))
- });
- }
+ match runner.config().chain_spec.runtime_id() {
+ #[cfg(feature = "unique-runtime")]
+ RuntimeId::Unique => async_run_with_runtime!(
+ unique_runtime::RuntimeApi, UniqueRuntimeExecutor,
+ runner, $components, $cli, $cmd, $config, $( $code )*
+ ),
+
+ #[cfg(feature = "quartz-runtime")]
+ RuntimeId::Quartz => async_run_with_runtime!(
+ quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,
+ runner, $components, $cli, $cmd, $config, $( $code )*
+ ),
- #[cfg(feature = "quartz-runtime")]
- if runner.config().chain_spec.is_quartz() {
- return runner.async_run(|$config| {
- let $components = new_partial::<
- quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _
- >(
- &$config,
- crate::service::parachain_build_import_queue,
- )?;
- let task_manager = $components.task_manager;
- { $( $code )* }.map(|v| (v, task_manager))
- });
- }
+ #[cfg(feature = "opal-runtime")]
+ RuntimeId::Opal => async_run_with_runtime!(
+ opal_runtime::RuntimeApi, OpalRuntimeExecutor,
+ runner, $components, $cli, $cmd, $config, $( $code )*
+ ),
- #[cfg(feature = "opal-runtime")]
- if runner.config().chain_spec.is_opal() {
- return runner.async_run(|$config| {
- let $components = new_partial::<
- opal_runtime::RuntimeApi, OpalRuntimeExecutor, _
- >(
- &$config,
- crate::service::parachain_build_import_queue,
- )?;
- let task_manager = $components.task_manager;
- { $( $code )* }.map(|v| (v, task_manager))
- });
+ RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into())
}
-
- Err(no_runtime_err!(runner.config().chain_spec).into())
}}
}
@@ -364,23 +352,17 @@
Some(Subcommand::Benchmark(cmd)) => {
if cfg!(feature = "runtime-benchmarks") {
let runner = cli.create_runner(cmd)?;
- runner.sync_run(|config| {
+ runner.sync_run(|config| match config.chain_spec.runtime_id() {
#[cfg(feature = "unique-runtime")]
- if config.chain_spec.is_unique() {
- return cmd.run::<Block, UniqueRuntimeExecutor>(config);
- }
+ RuntimeId::Unique => cmd.run::<Block, UniqueRuntimeExecutor>(config),
#[cfg(feature = "quartz-runtime")]
- if config.chain_spec.is_quartz() {
- return cmd.run::<Block, QuartzRuntimeExecutor>(config);
- }
+ RuntimeId::Quartz => cmd.run::<Block, QuartzRuntimeExecutor>(config),
#[cfg(feature = "opal-runtime")]
- if config.chain_spec.is_opal() {
- return cmd.run::<Block, OpalRuntimeExecutor>(config);
- }
+ RuntimeId::Opal => cmd.run::<Block, OpalRuntimeExecutor>(config),
- Err(no_runtime_err!(config.chain_spec).into())
+ RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),
})
} else {
Err("Benchmarking wasn't enabled when building the node. \
@@ -435,43 +417,39 @@
}
);
- #[cfg(feature = "unique-runtime")]
- if config.chain_spec.is_unique() {
- return crate::service::start_node::<
+ match config.chain_spec.runtime_id() {
+ #[cfg(feature = "unique-runtime")]
+ RuntimeId::Unique => crate::service::start_node::<
unique_runtime::Runtime,
unique_runtime::RuntimeApi,
UniqueRuntimeExecutor,
>(config, polkadot_config, id)
.await
.map(|r| r.0)
- .map_err(Into::into);
- }
+ .map_err(Into::into),
- #[cfg(feature = "quartz-runtime")]
- if config.chain_spec.is_quartz() {
- return crate::service::start_node::<
+ #[cfg(feature = "quartz-runtime")]
+ RuntimeId::Quartz => crate::service::start_node::<
quartz_runtime::Runtime,
quartz_runtime::RuntimeApi,
QuartzRuntimeExecutor,
>(config, polkadot_config, id)
.await
.map(|r| r.0)
- .map_err(Into::into);
- }
+ .map_err(Into::into),
- #[cfg(feature = "opal-runtime")]
- if config.chain_spec.is_opal() {
- return crate::service::start_node::<
+ #[cfg(feature = "opal-runtime")]
+ RuntimeId::Opal => crate::service::start_node::<
opal_runtime::Runtime,
opal_runtime::RuntimeApi,
OpalRuntimeExecutor,
>(config, polkadot_config, id)
.await
.map(|r| r.0)
- .map_err(Into::into);
+ .map_err(Into::into),
+
+ RuntimeId::Unknown(chain) => Err(no_runtime_err!(chain).into()),
}
-
- Err(no_runtime_err!(config.chain_spec).into())
})
}
}