Add new RPC method to get the chain type (#5576)

* Add new RPC method to get the chain type

This adds a new RPC method to get the chain type of the running chain.
The chain type needs to be specified in the chain spec. This should make
it easier for tools/UI to display extra information without needing to
rely on parsing the chain name.

* Update client/rpc-api/src/system/mod.rs

Co-Authored-By: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* Primitive crate

* Feedback

Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>
This commit is contained in:
Bastian Köcher
2020-04-08 20:41:51 +02:00
committed by GitHub
parent 1d2cbfbdf9
commit 7cdfaff12b
19 changed files with 135 additions and 26 deletions
+12
View File
@@ -594,6 +594,7 @@ dependencies = [
"ansi_term 0.12.1",
"node-cli",
"rand 0.7.3",
"sc-chain-spec",
"sc-keystore",
"sp-core",
"structopt",
@@ -5841,6 +5842,7 @@ dependencies = [
"sc-telemetry",
"serde",
"serde_json",
"sp-chain-spec",
"sp-core",
"sp-runtime",
]
@@ -6539,6 +6541,7 @@ dependencies = [
"serde_json",
"sp-api",
"sp-blockchain",
"sp-chain-spec",
"sp-core",
"sp-io",
"sp-offchain",
@@ -6568,6 +6571,7 @@ dependencies = [
"parking_lot 0.10.0",
"serde",
"serde_json",
"sp-chain-spec",
"sp-core",
"sp-rpc",
"sp-runtime",
@@ -7267,6 +7271,14 @@ dependencies = [
"sp-state-machine",
]
[[package]]
name = "sp-chain-spec"
version = "2.0.0-alpha.5"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "sp-consensus"
version = "0.8.0-alpha.5"
+1
View File
@@ -122,6 +122,7 @@ members = [
"primitives/consensus/pow",
"primitives/consensus/vrf",
"primitives/core",
"primitives/chain-spec",
"primitives/debug-derive",
"primitives/storage",
"primitives/externalities",
@@ -3,10 +3,10 @@ use node_template_runtime::{
AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig,
SudoConfig, SystemConfig, WASM_BINARY, Signature
};
use sp_consensus_aura::sr25519::{AuthorityId as AuraId};
use sp_finality_grandpa::{AuthorityId as GrandpaId};
use sc_service;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{Verify, IdentifyAccount};
use sc_service::ChainType;
// Note this is the URL for the telemetry server
//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
@@ -42,6 +42,7 @@ pub fn development_config() -> ChainSpec {
ChainSpec::from_genesis(
"Development",
"dev",
ChainType::Development,
|| testnet_genesis(
vec![
authority_keys_from_seed("Alice"),
@@ -67,6 +68,7 @@ pub fn local_testnet_config() -> ChainSpec {
ChainSpec::from_genesis(
"Local Testnet",
"local_testnet",
ChainType::Local,
|| testnet_genesis(
vec![
authority_keys_from_seed("Alice"),
+6 -1
View File
@@ -27,7 +27,7 @@ use node_runtime::{
};
use node_runtime::Block;
use node_runtime::constants::currency::*;
use sc_service;
use sc_service::ChainType;
use hex_literal::hex;
use sc_telemetry::TelemetryEndpoints;
use grandpa_primitives::{AuthorityId as GrandpaId};
@@ -158,6 +158,7 @@ pub fn staging_testnet_config() -> ChainSpec {
ChainSpec::from_genesis(
"Staging Testnet",
"staging_testnet",
ChainType::Live,
staging_testnet_config_genesis,
boot_nodes,
Some(TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)])
@@ -338,6 +339,7 @@ pub fn development_config() -> ChainSpec {
ChainSpec::from_genesis(
"Development",
"dev",
ChainType::Development,
development_config_genesis,
vec![],
None,
@@ -364,6 +366,7 @@ pub fn local_testnet_config() -> ChainSpec {
ChainSpec::from_genesis(
"Local Testnet",
"local_testnet",
ChainType::Local,
local_testnet_genesis,
vec![],
None,
@@ -396,6 +399,7 @@ pub(crate) mod tests {
ChainSpec::from_genesis(
"Integration Test",
"test",
ChainType::Development,
local_testnet_genesis_instant_single,
vec![],
None,
@@ -410,6 +414,7 @@ pub(crate) mod tests {
ChainSpec::from_genesis(
"Integration Test",
"test",
ChainType::Development,
local_testnet_genesis,
vec![],
None,
@@ -11,6 +11,7 @@ repository = "https://github.com/paritytech/substrate/"
[dependencies]
ansi_term = "0.12.1"
sc-keystore = { version = "2.0.0-alpha.5", path = "../../../client/keystore" }
sc-chain-spec = { version = "2.0.0-alpha.5", path = "../../../client/chain-spec" }
node-cli = { version = "2.0.0-alpha.5", path = "../../node/cli" }
sp-core = { version = "2.0.0-alpha.5", path = "../../../primitives/core" }
rand = "0.7.2"
@@ -120,6 +120,7 @@ fn generate_chain_spec(
let chain_spec = chain_spec::ChainSpec::from_genesis(
"Custom",
"custom",
sc_chain_spec::ChainType::Live,
move || genesis_constructor(&authority_seeds, &endowed_accounts, &sudo_account),
vec![],
None,
+1
View File
@@ -16,6 +16,7 @@ sp-core = { version = "2.0.0-alpha.5", path = "../../primitives/core" }
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
sp-runtime = { version = "2.0.0-alpha.5", path = "../../primitives/runtime" }
sp-chain-spec = { version = "2.0.0-alpha.5", path = "../../primitives/chain-spec" }
sc-telemetry = { version = "2.0.0-alpha.5", path = "../telemetry" }
[package.metadata.docs.rs]
+15 -5
View File
@@ -25,8 +25,7 @@ use serde::{Serialize, Deserialize};
use sp_core::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild};
use sp_runtime::BuildStorage;
use serde_json as json;
use crate::RuntimeGenesis;
use crate::extension::GetExtension;
use crate::{RuntimeGenesis, ChainType, extension::GetExtension, Properties};
use sc_network::config::MultiaddrWithPeerId;
use sc_telemetry::TelemetryEndpoints;
@@ -137,6 +136,8 @@ enum Genesis<G> {
struct ClientSpec<E> {
name: String,
id: String,
#[serde(default)]
chain_type: ChainType,
boot_nodes: Vec<MultiaddrWithPeerId>,
telemetry_endpoints: Option<TelemetryEndpoints>,
protocol_id: Option<String>,
@@ -149,9 +150,6 @@ struct ClientSpec<E> {
genesis: serde::de::IgnoredAny,
}
/// Arbitrary properties defined in chain spec as a JSON object
pub type Properties = json::map::Map<String, json::Value>;
/// A type denoting empty extensions.
///
/// We use `Option` here since `()` is not flattenable by serde.
@@ -219,6 +217,7 @@ impl<G, E> ChainSpec<G, E> {
pub fn from_genesis<F: Fn() -> G + 'static + Send + Sync>(
name: &str,
id: &str,
chain_type: ChainType,
constructor: F,
boot_nodes: Vec<MultiaddrWithPeerId>,
telemetry_endpoints: Option<TelemetryEndpoints>,
@@ -229,6 +228,7 @@ impl<G, E> ChainSpec<G, E> {
let client_spec = ClientSpec {
name: name.to_owned(),
id: id.to_owned(),
chain_type,
boot_nodes,
telemetry_endpoints,
protocol_id: protocol_id.map(str::to_owned),
@@ -243,6 +243,11 @@ impl<G, E> ChainSpec<G, E> {
genesis: GenesisSource::Factory(Arc::new(constructor)),
}
}
/// Type of the chain.
fn chain_type(&self) -> ChainType {
self.client_spec.chain_type.clone()
}
}
impl<G, E: serde::de::DeserializeOwned> ChainSpec<G, E> {
@@ -332,6 +337,10 @@ where
ChainSpec::id(self)
}
fn chain_type(&self) -> ChainType {
ChainSpec::chain_type(self)
}
fn telemetry_endpoints(&self) -> &Option<TelemetryEndpoints> {
ChainSpec::telemetry_endpoints(self)
}
@@ -392,6 +401,7 @@ mod tests {
).unwrap();
assert_eq!(spec1.as_json(false), spec2.as_json(false));
assert_eq!(spec2.chain_type(), ChainType::Live)
}
#[derive(Debug, Serialize, Deserialize)]
+5 -3
View File
@@ -107,13 +107,13 @@
//! pub type MyChainSpec<G> = GenericChainSpec<G, Extension>;
//! ```
mod chain_spec;
mod extension;
pub use chain_spec::{ChainSpec as GenericChainSpec, Properties, NoExtension};
pub use chain_spec::{ChainSpec as GenericChainSpec, NoExtension};
pub use extension::{Group, Fork, Forks, Extension, GetExtension, get_extension};
pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
pub use sp_chain_spec::{Properties, ChainType};
use serde::{Serialize, de::DeserializeOwned};
use sp_runtime::BuildStorage;
@@ -124,12 +124,14 @@ use sc_telemetry::TelemetryEndpoints;
pub trait RuntimeGenesis: Serialize + DeserializeOwned + BuildStorage {}
impl<T: Serialize + DeserializeOwned + BuildStorage> RuntimeGenesis for T {}
/// Common interface to `GenericChainSpec`
/// Common interface of a chain specification.
pub trait ChainSpec: BuildStorage + Send {
/// Spec name.
fn name(&self) -> &str;
/// Spec id.
fn id(&self) -> &str;
/// Type of the chain.
fn chain_type(&self) -> ChainType;
/// A list of bootnode addresses.
fn boot_nodes(&self) -> &[MultiaddrWithPeerId];
/// Telemetry endpoints (if any)
+1
View File
@@ -21,6 +21,7 @@ parking_lot = "0.10.0"
sp-core = { version = "2.0.0-alpha.5", path = "../../primitives/core" }
sp-version = { version = "2.0.0-alpha.5", path = "../../primitives/version" }
sp-runtime = { path = "../../primitives/runtime" , version = "2.0.0-alpha.5"}
sp-chain-spec = { path = "../../primitives/chain-spec" , version = "2.0.0-alpha.5"}
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
sp-transaction-pool = { version = "2.0.0-alpha.5", path = "../../primitives/transaction-pool" }
@@ -18,10 +18,7 @@
use std::fmt;
use serde::{Serialize, Deserialize};
use serde_json::{Value, map::Map};
/// Node properties
pub type Properties = Map<String, Value>;
use sp_chain_spec::{Properties, ChainType};
/// Running node's static details.
#[derive(Clone, Debug)]
@@ -34,6 +31,8 @@ pub struct SystemInfo {
pub chain_name: String,
/// A custom set of properties defined in the chain spec.
pub properties: Properties,
/// The type of this chain.
pub chain_type: ChainType,
}
/// Health struct returned by the RPC
+7 -3
View File
@@ -25,7 +25,7 @@ use futures::{future::BoxFuture, compat::Compat};
use self::error::Result as SystemResult;
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo, NodeRole};
pub use self::helpers::{SystemInfo, Health, PeerInfo, NodeRole};
pub use self::gen_client::Client as SystemClient;
/// Substrate system RPC API
@@ -39,13 +39,17 @@ pub trait SystemApi<Hash, Number> {
#[rpc(name = "system_version")]
fn system_version(&self) -> SystemResult<String>;
/// Get the chain's type. Given as a string identifier.
/// Get the chain's name. Given as a string identifier.
#[rpc(name = "system_chain")]
fn system_chain(&self) -> SystemResult<String>;
/// Get the chain's type.
#[rpc(name = "system_chainType")]
fn system_type(&self) -> SystemResult<sp_chain_spec::ChainType>;
/// Get a custom set of properties as a JSON object, defined in the chain spec.
#[rpc(name = "system_properties")]
fn system_properties(&self) -> SystemResult<Properties>;
fn system_properties(&self) -> SystemResult<sp_chain_spec::Properties>;
/// Return health status of the node.
///
+1
View File
@@ -27,6 +27,7 @@ sp-runtime = { version = "2.0.0-alpha.5", path = "../../primitives/runtime" }
sp-utils = { version = "2.0.0-alpha.5", path = "../../primitives/utils" }
sp-rpc = { version = "2.0.0-alpha.5", path = "../../primitives/rpc" }
sp-state-machine = { version = "0.8.0-alpha.5", path = "../../primitives/state-machine" }
sp-chain-spec = { version = "2.0.0-alpha.5", path = "../../primitives/chain-spec" }
sc-executor = { version = "0.8.0-alpha.5", path = "../executor" }
sc-block-builder = { version = "0.8.0-alpha.5", path = "../../client/block-builder" }
sc-keystore = { version = "2.0.0-alpha.5", path = "../keystore" }
+6 -2
View File
@@ -28,7 +28,7 @@ use sp_runtime::traits::{self, Header as HeaderT};
use self::error::Result;
pub use sc_rpc_api::system::*;
pub use self::helpers::{Properties, SystemInfo, Health, PeerInfo, NodeRole};
pub use self::helpers::{SystemInfo, Health, PeerInfo, NodeRole};
pub use self::gen_client::Client as SystemClient;
/// System API implementation
@@ -82,7 +82,11 @@ impl<B: traits::Block> SystemApi<B::Hash, <B::Header as HeaderT>::Number> for Sy
Ok(self.info.chain_name.clone())
}
fn system_properties(&self) -> Result<Properties> {
fn system_type(&self) -> Result<sp_chain_spec::ChainType> {
Ok(self.info.chain_type.clone())
}
fn system_properties(&self) -> Result<sp_chain_spec::Properties> {
Ok(self.info.properties.clone())
}
+13 -4
View File
@@ -105,6 +105,7 @@ fn api<T: Into<Option<Status>>>(sync: T) -> System<Block> {
impl_version: "0.2.0".into(),
chain_name: "testchain".into(),
properties: Default::default(),
chain_type: Default::default(),
}, tx)
}
@@ -117,7 +118,7 @@ fn wait_receiver<T>(rx: Receiver<T>) -> T {
fn system_name_works() {
assert_eq!(
api(None).system_name().unwrap(),
"testclient".to_owned()
"testclient".to_owned(),
);
}
@@ -125,7 +126,7 @@ fn system_name_works() {
fn system_version_works() {
assert_eq!(
api(None).system_version().unwrap(),
"0.2.0".to_owned()
"0.2.0".to_owned(),
);
}
@@ -133,7 +134,7 @@ fn system_version_works() {
fn system_chain_works() {
assert_eq!(
api(None).system_chain().unwrap(),
"testchain".to_owned()
"testchain".to_owned(),
);
}
@@ -141,7 +142,15 @@ fn system_chain_works() {
fn system_properties_works() {
assert_eq!(
api(None).system_properties().unwrap(),
serde_json::map::Map::new()
serde_json::map::Map::new(),
);
}
#[test]
fn system_type_works() {
assert_eq!(
api(None).system_type().unwrap(),
Default::default(),
);
}
+1
View File
@@ -1016,6 +1016,7 @@ ServiceBuilder<
impl_name: config.impl_name.into(),
impl_version: config.impl_version.into(),
properties: chain_spec.properties().clone(),
chain_type: chain_spec.chain_type().clone(),
};
let subscriptions = sc_rpc::Subscriptions::new(Arc::new(tasks_builder.spawn_handle()));
+1 -1
View File
@@ -62,7 +62,7 @@ pub use self::builder::{
pub use config::{Configuration, Role, PruningMode, DatabaseConfig};
pub use sc_chain_spec::{
ChainSpec, GenericChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension,
NoExtension,
NoExtension, ChainType,
};
pub use sp_transaction_pool::{TransactionPool, InPoolTransaction, error::IntoPoolError};
pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions;
@@ -0,0 +1,13 @@
[package]
name = "sp-chain-spec"
version = "2.0.0-alpha.5"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "GPL-3.0"
homepage = "https://substrate.dev"
repository = "https://github.com/paritytech/substrate/"
description = "Substrate chain configurations types."
[dependencies]
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
@@ -0,0 +1,42 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Types and traits related to chain specifications.
/// The type of a chain.
///
/// This can be used by tools to determine the type of a chain for displaying
/// additional information or enabling additional features.
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub enum ChainType {
/// A development chain that runs mainly on one node.
Development,
/// A local chain that runs locally on multiple nodes for testing purposes.
Local,
/// A live chain.
Live,
/// Some custom chain type.
Custom(String),
}
impl Default for ChainType {
fn default() -> Self {
Self::Live
}
}
/// Arbitrary properties defined in chain spec as a JSON object
pub type Properties = serde_json::map::Map<String, serde_json::Value>;