Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions bin/node-template/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use sp_runtime::traits::{Verify, IdentifyAccount};
//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";

/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
pub type ChainSpec = sc_service::ChainSpec<GenesisConfig>;
pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;

/// The chain specification option. This is expected to come in from the CLI and
/// is little more than one of a number of alternatives which can easily be converted
Expand Down Expand Up @@ -142,9 +142,9 @@ fn testnet_genesis(initial_authorities: Vec<(AuraId, GrandpaId)>,
}
}

pub fn load_spec(id: &str) -> Result<Option<ChainSpec>, String> {
pub fn load_spec(id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match Alternative::from(id) {
Some(spec) => Some(spec.load()?),
None => None,
Some(spec) => Box::new(spec.load()?),
None => Box::new(ChainSpec::from_json_file(std::path::PathBuf::from(id))?),
})
}
6 changes: 3 additions & 3 deletions bin/node-template/node/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::sync::Arc;
use std::time::Duration;
use sc_client::LongestChain;
use sc_client_api::ExecutorProvider;
use node_template_runtime::{self, GenesisConfig, opaque::Block, RuntimeApi};
use node_template_runtime::{self, opaque::Block, RuntimeApi};
use sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};
use sp_inherents::InherentDataProviders;
use sc_executor::native_executor_instance;
Expand Down Expand Up @@ -69,7 +69,7 @@ macro_rules! new_full_start {
}

/// Builds a new service for a full client.
pub fn new_full(config: Configuration<GenesisConfig>)
pub fn new_full(config: Configuration)
-> Result<impl AbstractService, ServiceError>
{
let is_authority = config.roles.is_authority();
Expand Down Expand Up @@ -181,7 +181,7 @@ pub fn new_full(config: Configuration<GenesisConfig>)
}

/// Builds a new service for a light client.
pub fn new_light(config: Configuration<GenesisConfig>)
pub fn new_light(config: Configuration)
-> Result<impl AbstractService, ServiceError>
{
let inherent_data_providers = InherentDataProviders::new();
Expand Down
2 changes: 1 addition & 1 deletion bin/node/cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub struct Extensions {
}

/// Specialized `ChainSpec`.
pub type ChainSpec = sc_service::ChainSpec<
pub type ChainSpec = sc_service::GenericChainSpec<
GenesisConfig,
Extensions,
>;
Expand Down
6 changes: 3 additions & 3 deletions bin/node/cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ where
cmd.update_config(&mut config, load_spec, &version)?;

let client = sc_service::new_full_client::<
node_runtime::Block, node_runtime::RuntimeApi, node_executor::Executor, _, _,
node_runtime::Block, node_runtime::RuntimeApi, node_executor::Executor,
>(&config)?;
let inspect = node_inspect::Inspector::<node_runtime::Block>::new(client);

Expand All @@ -56,7 +56,7 @@ where
cmd.init(&version)?;
cmd.update_config(&mut config, load_spec, &version)?;

cmd.run::<_, _, node_runtime::Block, node_executor::Executor>(config)
cmd.run::<node_runtime::Block, node_executor::Executor>(config)
},
Some(Subcommand::Factory(cli_args)) => {
cli_args.shared_params.init(&version)?;
Expand Down Expand Up @@ -108,7 +108,7 @@ where
subcommand.update_config(&mut config, load_spec, &version)?;
subcommand.run(
config,
|config: service::NodeConfiguration| Ok(new_full_start!(config).0),
|config: sc_service::Configuration| Ok(new_full_start!(config).0),
)
},
}
Expand Down
6 changes: 3 additions & 3 deletions bin/node/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ impl ChainSpec {
}
}

fn load_spec(id: &str) -> Result<Option<chain_spec::ChainSpec>, String> {
fn load_spec(id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match ChainSpec::from(id) {
Some(spec) => Some(spec.load()?),
None => None,
Some(spec) => Box::new(spec.load()?),
None => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(id))?),
})
}
9 changes: 3 additions & 6 deletions bin/node/cli/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use sc_client::{self, LongestChain};
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider, StorageAndProofProvider};
use node_executor;
use node_primitives::Block;
use node_runtime::{GenesisConfig, RuntimeApi};
use node_runtime::RuntimeApi;
use sc_service::{
AbstractService, ServiceBuilder, config::Configuration, error::{Error as ServiceError},
};
Expand Down Expand Up @@ -269,11 +269,8 @@ type ConcreteTransactionPool = sc_transaction_pool::BasicPool<
ConcreteBlock
>;

/// A specialized configuration object for setting up the node..
pub type NodeConfiguration = Configuration<GenesisConfig, crate::chain_spec::Extensions>;

/// Builds a new service for a full client.
pub fn new_full(config: NodeConfiguration)
pub fn new_full(config: Configuration)
-> Result<
Service<
ConcreteBlock,
Expand All @@ -295,7 +292,7 @@ pub fn new_full(config: NodeConfiguration)
}

/// Builds a new service for a light client.
pub fn new_light(config: NodeConfiguration)
pub fn new_light(config: Configuration)
-> Result<impl AbstractService, ServiceError> {
type RpcExtension = jsonrpc_core::IoHandler<sc_rpc::Metadata>;
let inherent_data_providers = InherentDataProviders::new();
Expand Down
11 changes: 4 additions & 7 deletions bin/node/inspect/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,12 @@ impl InspectCmd {
}

/// Parse CLI arguments and initialize given config.
pub fn update_config<G, E>(
pub fn update_config(
&self,
mut config: &mut sc_service::config::Configuration<G, E>,
spec_factory: impl FnOnce(&str) -> Result<Option<sc_service::ChainSpec<G, E>>, String>,
mut config: &mut sc_service::config::Configuration,
spec_factory: impl FnOnce(&str) -> Result<Box<dyn sc_service::ChainSpec>, String>,
version: &sc_cli::VersionInfo,
) -> sc_cli::Result<()> where
G: sc_service::RuntimeGenesis,
E: sc_service::ChainSpecExtension,
{
) -> sc_cli::Result<()> {
self.shared_params.update_config(config, spec_factory, version)?;

// make sure to configure keystore
Expand Down
2 changes: 1 addition & 1 deletion bin/utils/chain-spec-builder/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ fn generate_chain_spec(
Default::default(),
);

chain_spec.to_json(false).map_err(|err| err.to_string())
chain_spec.as_json(false).map_err(|err| err.to_string())
}

fn generate_authority_keys_and_store(
Expand Down
9 changes: 9 additions & 0 deletions client/chain-spec/derive/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ pub fn extension_derive(ast: &DeriveInput) -> proc_macro::TokenStream {
_ => None,
}
}

fn get_any(&self, t: std::any::TypeId) -> &dyn std::any::Any {
use std::any::{Any, TypeId};

match t {
#( x if x == TypeId::of::<#field_types>() => &self.#field_names ),*,
_ => self,
}
}
}
}
})
Expand Down
55 changes: 51 additions & 4 deletions client/chain-spec/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ 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 sc_network::Multiaddr;
use sc_telemetry::TelemetryEndpoints;

Expand Down Expand Up @@ -269,9 +270,9 @@ impl<G, E: serde::de::DeserializeOwned> ChainSpec<G, E> {
}
}

impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, E> {
impl<G: RuntimeGenesis, E: serde::Serialize + Clone> ChainSpec<G, E> {
/// Dump to json string.
pub fn to_json(self, raw: bool) -> Result<String, String> {
pub fn as_json(&self, raw: bool) -> Result<String, String> {
#[derive(Serialize, Deserialize)]
struct Container<G, E> {
#[serde(flatten)]
Expand Down Expand Up @@ -306,14 +307,60 @@ impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, E> {
(_, genesis) => genesis,
};
let container = Container {
client_spec: self.client_spec,
client_spec: self.client_spec.clone(),
genesis,
};
json::to_string_pretty(&container)
.map_err(|e| format!("Error generating spec json: {}", e))
}
}

impl<G, E> crate::ChainSpec for ChainSpec<G, E>
where
G: RuntimeGenesis,
E: GetExtension + serde::Serialize + Clone,
{
fn boot_nodes(&self) -> &[String] {
ChainSpec::boot_nodes(self)
}

fn name(&self) -> &str {
ChainSpec::name(self)
}

fn id(&self) -> &str {
ChainSpec::id(self)
}

fn telemetry_endpoints(&self) -> &Option<TelemetryEndpoints> {
ChainSpec::telemetry_endpoints(self)
}

fn protocol_id(&self) -> Option<&str> {
ChainSpec::protocol_id(self)
}

fn properties(&self) -> Properties {
ChainSpec::properties(self)
}

fn add_boot_node(&mut self, addr: Multiaddr) {
ChainSpec::add_boot_node(self, addr)
}

fn extensions(&self) -> &dyn GetExtension {
ChainSpec::extensions(self) as &dyn GetExtension
}

fn as_json(&self, raw: bool) -> Result<String, String> {
ChainSpec::as_json(self, raw)
}

fn as_storage_builder(&self) -> &dyn BuildStorage {
self
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -344,7 +391,7 @@ mod tests {
PathBuf::from("./res/chain_spec.json")
).unwrap();

assert_eq!(spec1.to_json(false), spec2.to_json(false));
assert_eq!(spec1.as_json(false), spec2.as_json(false));
}

#[derive(Debug, Serialize, Deserialize)]
Expand Down
34 changes: 30 additions & 4 deletions client/chain-spec/src/extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
//! Chain Spec extensions helpers.

use std::fmt::Debug;
use std::any::{TypeId, Any};

use std::collections::BTreeMap;

use serde::{Serialize, Deserialize, de::DeserializeOwned};
Expand Down Expand Up @@ -120,6 +122,8 @@ pub trait Extension: Serialize + DeserializeOwned + Clone {

/// Get an extension of specific type.
fn get<T: 'static>(&self) -> Option<&T>;
/// Get an extension of specific type as refernce to `Any`
fn get_any(&self, t: TypeId) -> &dyn Any;

/// Get forkable extensions of specific type.
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
Expand All @@ -137,6 +141,7 @@ impl Extension for crate::NoExtension {
type Forks = Self;

fn get<T: 'static>(&self) -> Option<&T> { None }
fn get_any(&self, _t: TypeId) -> &dyn Any { self }
}

pub trait IsForks {
Expand Down Expand Up @@ -225,22 +230,25 @@ impl<B, E> Extension for Forks<B, E> where
type Forks = Self;

fn get<T: 'static>(&self) -> Option<&T> {
use std::any::{TypeId, Any};

match TypeId::of::<T>() {
x if x == TypeId::of::<E>() => Any::downcast_ref(&self.base),
_ => self.base.get(),
}
}

fn get_any(&self, t: TypeId) -> &dyn Any {
match t {
x if x == TypeId::of::<E>() => &self.base,
_ => self.base.get_any(t),
}
}

fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
BlockNumber: Ord + Clone + 'static,
T: Group + 'static,
<Self::Forks as IsForks>::Extension: Extension,
<<Self::Forks as IsForks>::Extension as Group>::Fork: Extension,
{
use std::any::{TypeId, Any};

if TypeId::of::<BlockNumber>() == TypeId::of::<B>() {
Any::downcast_ref(&self.for_type::<T>()?).cloned()
} else {
Expand All @@ -250,6 +258,24 @@ impl<B, E> Extension for Forks<B, E> where
}
}

/// A subset if the `Extension` trait that only allows for quering extensions.
pub trait GetExtension {
/// Get an extension of specific type.
fn get_any(&self, t: TypeId) -> &dyn Any;
}

impl <E: Extension> GetExtension for E {
fn get_any(&self, t: TypeId) -> &dyn Any {
Extension::get_any(self, t)
}
}

/// Helper function that queries an extension by type from `GetExtension`
/// trait object.
pub fn get_extension<T: 'static>(e: &dyn GetExtension) -> Option<&T> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docs missing.

Any::downcast_ref(GetExtension::get_any(e, TypeId::of::<T>()))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this function needed and why can't we just use Extension::get instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trait objects can't have generic methods.

}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading