ChainSpec trait (#5185)

* ChainSpec trait

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Added docs

* Fixed build

* Fixed build

Co-authored-by: Bastian Köcher <bkchr@users.noreply.github.com>
This commit is contained in:
Arkadiy Paronyan
2020-03-12 00:00:10 +01:00
committed by GitHub
parent d2345e8d5c
commit dc0bf210fb
38 changed files with 354 additions and 335 deletions
@@ -12,7 +12,7 @@ use sp_runtime::traits::{Verify, IdentifyAccount};
//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; //const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. /// 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 /// 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 /// is little more than one of a number of alternatives which can easily be converted
@@ -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) { Ok(match Alternative::from(id) {
Some(spec) => Some(spec.load()?), Some(spec) => Box::new(spec.load()?),
None => None, None => Box::new(ChainSpec::from_json_file(std::path::PathBuf::from(id))?),
}) })
} }
@@ -4,7 +4,7 @@ use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use sc_client::LongestChain; use sc_client::LongestChain;
use sc_client_api::ExecutorProvider; 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 sc_service::{error::{Error as ServiceError}, AbstractService, Configuration, ServiceBuilder};
use sp_inherents::InherentDataProviders; use sp_inherents::InherentDataProviders;
use sc_executor::native_executor_instance; use sc_executor::native_executor_instance;
@@ -69,7 +69,7 @@ macro_rules! new_full_start {
} }
/// Builds a new service for a full client. /// 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> -> Result<impl AbstractService, ServiceError>
{ {
let is_authority = config.roles.is_authority(); let is_authority = config.roles.is_authority();
@@ -181,7 +181,7 @@ pub fn new_full(config: Configuration<GenesisConfig>)
} }
/// Builds a new service for a light client. /// 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> -> Result<impl AbstractService, ServiceError>
{ {
let inherent_data_providers = InherentDataProviders::new(); let inherent_data_providers = InherentDataProviders::new();
+1 -1
View File
@@ -56,7 +56,7 @@ pub struct Extensions {
} }
/// Specialized `ChainSpec`. /// Specialized `ChainSpec`.
pub type ChainSpec = sc_service::ChainSpec< pub type ChainSpec = sc_service::GenericChainSpec<
GenesisConfig, GenesisConfig,
Extensions, Extensions,
>; >;
+3 -3
View File
@@ -46,7 +46,7 @@ where
cmd.update_config(&mut config, load_spec, &version)?; cmd.update_config(&mut config, load_spec, &version)?;
let client = sc_service::new_full_client::< 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)?; >(&config)?;
let inspect = node_inspect::Inspector::<node_runtime::Block>::new(client); let inspect = node_inspect::Inspector::<node_runtime::Block>::new(client);
@@ -56,7 +56,7 @@ where
cmd.init(&version)?; cmd.init(&version)?;
cmd.update_config(&mut config, load_spec, &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)) => { Some(Subcommand::Factory(cli_args)) => {
cli_args.shared_params.init(&version)?; cli_args.shared_params.init(&version)?;
@@ -108,7 +108,7 @@ where
subcommand.update_config(&mut config, load_spec, &version)?; subcommand.update_config(&mut config, load_spec, &version)?;
subcommand.run( subcommand.run(
config, config,
|config: service::NodeConfiguration| Ok(new_full_start!(config).0), |config: sc_service::Configuration| Ok(new_full_start!(config).0),
) )
}, },
} }
+3 -3
View File
@@ -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) { Ok(match ChainSpec::from(id) {
Some(spec) => Some(spec.load()?), Some(spec) => Box::new(spec.load()?),
None => None, None => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(id))?),
}) })
} }
+3 -6
View File
@@ -25,7 +25,7 @@ use sc_client::{self, LongestChain};
use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider, StorageAndProofProvider}; use grandpa::{self, FinalityProofProvider as GrandpaFinalityProofProvider, StorageAndProofProvider};
use node_executor; use node_executor;
use node_primitives::Block; use node_primitives::Block;
use node_runtime::{GenesisConfig, RuntimeApi}; use node_runtime::RuntimeApi;
use sc_service::{ use sc_service::{
AbstractService, ServiceBuilder, config::Configuration, error::{Error as ServiceError}, AbstractService, ServiceBuilder, config::Configuration, error::{Error as ServiceError},
}; };
@@ -270,11 +270,8 @@ type ConcreteTransactionPool = sc_transaction_pool::BasicPool<
ConcreteBlock 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. /// Builds a new service for a full client.
pub fn new_full(config: NodeConfiguration) pub fn new_full(config: Configuration)
-> Result< -> Result<
Service< Service<
ConcreteBlock, ConcreteBlock,
@@ -296,7 +293,7 @@ pub fn new_full(config: NodeConfiguration)
} }
/// Builds a new service for a light client. /// Builds a new service for a light client.
pub fn new_light(config: NodeConfiguration) pub fn new_light(config: Configuration)
-> Result<impl AbstractService, ServiceError> { -> Result<impl AbstractService, ServiceError> {
type RpcExtension = jsonrpc_core::IoHandler<sc_rpc::Metadata>; type RpcExtension = jsonrpc_core::IoHandler<sc_rpc::Metadata>;
let inherent_data_providers = InherentDataProviders::new(); let inherent_data_providers = InherentDataProviders::new();
+4 -7
View File
@@ -31,15 +31,12 @@ impl InspectCmd {
} }
/// Parse CLI arguments and initialize given config. /// Parse CLI arguments and initialize given config.
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
mut config: &mut sc_service::config::Configuration<G, E>, mut config: &mut sc_service::config::Configuration,
spec_factory: impl FnOnce(&str) -> Result<Option<sc_service::ChainSpec<G, E>>, String>, spec_factory: impl FnOnce(&str) -> Result<Box<dyn sc_service::ChainSpec>, String>,
version: &sc_cli::VersionInfo, version: &sc_cli::VersionInfo,
) -> sc_cli::Result<()> where ) -> sc_cli::Result<()> {
G: sc_service::RuntimeGenesis,
E: sc_service::ChainSpecExtension,
{
self.shared_params.update_config(config, spec_factory, version)?; self.shared_params.update_config(config, spec_factory, version)?;
// make sure to configure keystore // make sure to configure keystore
@@ -128,7 +128,7 @@ fn generate_chain_spec(
Default::default(), 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( fn generate_authority_keys_and_store(
@@ -50,6 +50,15 @@ pub fn extension_derive(ast: &DeriveInput) -> proc_macro::TokenStream {
_ => None, _ => 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,
}
}
} }
} }
}) })
+51 -4
View File
@@ -26,6 +26,7 @@ use sp_core::storage::{StorageKey, StorageData, ChildInfo, Storage, StorageChild
use sp_runtime::BuildStorage; use sp_runtime::BuildStorage;
use serde_json as json; use serde_json as json;
use crate::RuntimeGenesis; use crate::RuntimeGenesis;
use crate::extension::GetExtension;
use sc_network::Multiaddr; use sc_network::Multiaddr;
use sc_telemetry::TelemetryEndpoints; use sc_telemetry::TelemetryEndpoints;
@@ -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. /// 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)] #[derive(Serialize, Deserialize)]
struct Container<G, E> { struct Container<G, E> {
#[serde(flatten)] #[serde(flatten)]
@@ -306,7 +307,7 @@ impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, E> {
(_, genesis) => genesis, (_, genesis) => genesis,
}; };
let container = Container { let container = Container {
client_spec: self.client_spec, client_spec: self.client_spec.clone(),
genesis, genesis,
}; };
json::to_string_pretty(&container) json::to_string_pretty(&container)
@@ -314,6 +315,52 @@ impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -344,7 +391,7 @@ mod tests {
PathBuf::from("./res/chain_spec.json") PathBuf::from("./res/chain_spec.json")
).unwrap(); ).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)] #[derive(Debug, Serialize, Deserialize)]
+30 -4
View File
@@ -17,6 +17,8 @@
//! Chain Spec extensions helpers. //! Chain Spec extensions helpers.
use std::fmt::Debug; use std::fmt::Debug;
use std::any::{TypeId, Any};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use serde::{Serialize, Deserialize, de::DeserializeOwned}; use serde::{Serialize, Deserialize, de::DeserializeOwned};
@@ -120,6 +122,8 @@ pub trait Extension: Serialize + DeserializeOwned + Clone {
/// Get an extension of specific type. /// Get an extension of specific type.
fn get<T: 'static>(&self) -> Option<&T>; 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. /// Get forkable extensions of specific type.
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
@@ -137,6 +141,7 @@ impl Extension for crate::NoExtension {
type Forks = Self; type Forks = Self;
fn get<T: 'static>(&self) -> Option<&T> { None } fn get<T: 'static>(&self) -> Option<&T> { None }
fn get_any(&self, _t: TypeId) -> &dyn Any { self }
} }
pub trait IsForks { pub trait IsForks {
@@ -225,22 +230,25 @@ impl<B, E> Extension for Forks<B, E> where
type Forks = Self; type Forks = Self;
fn get<T: 'static>(&self) -> Option<&T> { fn get<T: 'static>(&self) -> Option<&T> {
use std::any::{TypeId, Any};
match TypeId::of::<T>() { match TypeId::of::<T>() {
x if x == TypeId::of::<E>() => Any::downcast_ref(&self.base), x if x == TypeId::of::<E>() => Any::downcast_ref(&self.base),
_ => self.base.get(), _ => 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 fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
BlockNumber: Ord + Clone + 'static, BlockNumber: Ord + Clone + 'static,
T: Group + 'static, T: Group + 'static,
<Self::Forks as IsForks>::Extension: Extension, <Self::Forks as IsForks>::Extension: Extension,
<<Self::Forks as IsForks>::Extension as Group>::Fork: Extension, <<Self::Forks as IsForks>::Extension as Group>::Fork: Extension,
{ {
use std::any::{TypeId, Any};
if TypeId::of::<BlockNumber>() == TypeId::of::<B>() { if TypeId::of::<BlockNumber>() == TypeId::of::<B>() {
Any::downcast_ref(&self.for_type::<T>()?).cloned() Any::downcast_ref(&self.for_type::<T>()?).cloned()
} else { } else {
@@ -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> {
Any::downcast_ref(GetExtension::get_any(e, TypeId::of::<T>()))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+37 -9
View File
@@ -30,14 +30,14 @@
//! ```rust //! ```rust
//! use std::collections::HashMap; //! use std::collections::HashMap;
//! use serde::{Serialize, Deserialize}; //! use serde::{Serialize, Deserialize};
//! use sc_chain_spec::{ChainSpec, ChainSpecExtension}; //! use sc_chain_spec::{GenericChainSpec, ChainSpecExtension};
//! //!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecExtension)] //! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecExtension)]
//! pub struct MyExtension { //! pub struct MyExtension {
//! pub known_blocks: HashMap<u64, String>, //! pub known_blocks: HashMap<u64, String>,
//! } //! }
//! //!
//! pub type MyChainSpec<G> = ChainSpec<G, MyExtension>; //! pub type MyChainSpec<G> = GenericChainSpec<G, MyExtension>;
//! ``` //! ```
//! //!
//! Some parameters may require different values depending on the //! Some parameters may require different values depending on the
@@ -49,7 +49,7 @@
//! //!
//! ```rust //! ```rust
//! use serde::{Serialize, Deserialize}; //! use serde::{Serialize, Deserialize};
//! use sc_chain_spec::{Forks, ChainSpec, ChainSpecGroup, ChainSpecExtension}; //! use sc_chain_spec::{Forks, ChainSpecGroup, ChainSpecExtension, GenericChainSpec};
//! //!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)] //! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
//! pub struct ClientParams { //! pub struct ClientParams {
@@ -71,10 +71,10 @@
//! pub type BlockNumber = u64; //! pub type BlockNumber = u64;
//! //!
//! /// A chain spec supporting forkable `ClientParams`. //! /// A chain spec supporting forkable `ClientParams`.
//! pub type MyChainSpec1<G> = ChainSpec<G, Forks<BlockNumber, ClientParams>>; //! pub type MyChainSpec1<G> = GenericChainSpec<G, Forks<BlockNumber, ClientParams>>;
//! //!
//! /// A chain spec supporting forkable `Extension`. //! /// A chain spec supporting forkable `Extension`.
//! pub type MyChainSpec2<G> = ChainSpec<G, Forks<BlockNumber, Extension>>; //! pub type MyChainSpec2<G> = GenericChainSpec<G, Forks<BlockNumber, Extension>>;
//! ``` //! ```
//! //!
//! It's also possible to have a set of parameters that is allowed to change //! It's also possible to have a set of parameters that is allowed to change
@@ -84,7 +84,7 @@
//! //!
//! ```rust //! ```rust
//! use serde::{Serialize, Deserialize}; //! use serde::{Serialize, Deserialize};
//! use sc_chain_spec::{Forks, ChainSpec, ChainSpecGroup, ChainSpecExtension}; //! use sc_chain_spec::{Forks, GenericChainSpec, ChainSpecGroup, ChainSpecExtension};
//! //!
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)] //! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
//! pub struct ClientParams { //! pub struct ClientParams {
@@ -104,20 +104,48 @@
//! pub pool: Forks<u64, PoolParams>, //! pub pool: Forks<u64, PoolParams>,
//! } //! }
//! //!
//! pub type MyChainSpec<G> = ChainSpec<G, Extension>; //! pub type MyChainSpec<G> = GenericChainSpec<G, Extension>;
//! ``` //! ```
mod chain_spec; mod chain_spec;
mod extension; mod extension;
pub use chain_spec::{ChainSpec, Properties, NoExtension}; pub use chain_spec::{ChainSpec as GenericChainSpec, Properties, NoExtension};
pub use extension::{Group, Fork, Forks, Extension}; pub use extension::{Group, Fork, Forks, Extension, GetExtension, get_extension};
pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup}; pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
use serde::{Serialize, de::DeserializeOwned}; use serde::{Serialize, de::DeserializeOwned};
use sp_runtime::BuildStorage; use sp_runtime::BuildStorage;
use sc_network::Multiaddr;
use sc_telemetry::TelemetryEndpoints;
/// A set of traits for the runtime genesis config. /// A set of traits for the runtime genesis config.
pub trait RuntimeGenesis: Serialize + DeserializeOwned + BuildStorage {} pub trait RuntimeGenesis: Serialize + DeserializeOwned + BuildStorage {}
impl<T: Serialize + DeserializeOwned + BuildStorage> RuntimeGenesis for T {} impl<T: Serialize + DeserializeOwned + BuildStorage> RuntimeGenesis for T {}
/// Common interface to `GenericChainSpec`
pub trait ChainSpec: BuildStorage {
/// Spec name.
fn name(&self) -> &str;
/// Spec id.
fn id(&self) -> &str;
/// A list of bootnode addresses.
fn boot_nodes(&self) -> &[String];
/// Telemetry endpoints (if any)
fn telemetry_endpoints(&self) -> &Option<TelemetryEndpoints>;
/// Network protocol id.
fn protocol_id(&self) -> Option<&str>;
/// Additional loosly-typed properties of the chain.
///
/// Returns an empty JSON object if 'properties' not defined in config
fn properties(&self) -> Properties;
/// Returns a reference to defined chain spec extensions.
fn extensions(&self) -> &dyn GetExtension;
/// Add a bootnode to the list.
fn add_boot_node(&mut self, addr: Multiaddr);
/// Return spec as JSON.
fn as_json(&self, raw: bool) -> Result<String, String>;
/// Return StorageBuilder for this spec.
fn as_storage_builder(&self) -> &dyn BuildStorage;
}
@@ -17,7 +17,7 @@
use structopt::StructOpt; use structopt::StructOpt;
use log::info; use log::info;
use sc_network::config::build_multiaddr; use sc_network::config::build_multiaddr;
use sc_service::{Configuration, ChainSpecExtension, RuntimeGenesis, ChainSpec}; use sc_service::{Configuration, ChainSpec};
use crate::error; use crate::error;
use crate::VersionInfo; use crate::VersionInfo;
@@ -49,16 +49,12 @@ pub struct BuildSpecCmd {
impl BuildSpecCmd { impl BuildSpecCmd {
/// Run the build-spec command /// Run the build-spec command
pub fn run<G, E>( pub fn run(
self, self,
config: Configuration<G, E>, config: Configuration,
) -> error::Result<()> ) -> error::Result<()> {
where
G: RuntimeGenesis,
E: ChainSpecExtension,
{
info!("Building chain spec"); info!("Building chain spec");
let mut spec = config.expect_chain_spec().clone(); let mut spec = config.chain_spec.expect("`chain_spec` is set to `Some` in `update_config`");
let raw_output = self.raw; let raw_output = self.raw;
if spec.boot_nodes().is_empty() && !self.disable_default_bootnode { if spec.boot_nodes().is_empty() && !self.disable_default_bootnode {
@@ -72,7 +68,7 @@ impl BuildSpecCmd {
spec.add_boot_node(addr) spec.add_boot_node(addr)
} }
let json = sc_service::chain_ops::build_spec(spec, raw_output)?; let json = sc_service::chain_ops::build_spec(&*spec, raw_output)?;
print!("{}", json); print!("{}", json);
@@ -80,15 +76,13 @@ impl BuildSpecCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
@@ -18,7 +18,7 @@ use std::fmt::Debug;
use std::str::FromStr; use std::str::FromStr;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{
Configuration, ChainSpecExtension, RuntimeGenesis, ServiceBuilderCommand, Roles, ChainSpec, Configuration, ServiceBuilderCommand, Roles, ChainSpec,
}; };
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use sp_runtime::generic::BlockId; use sp_runtime::generic::BlockId;
@@ -53,15 +53,13 @@ pub struct CheckBlockCmd {
impl CheckBlockCmd { impl CheckBlockCmd {
/// Run the check-block command /// Run the check-block command
pub fn run<G, E, B, BC, BB>( pub fn run<B, BC, BB>(
self, self,
config: Configuration<G, E>, config: Configuration,
builder: B, builder: B,
) -> error::Result<()> ) -> error::Result<()>
where where
B: FnOnce(Configuration<G, E>) -> Result<BC, sc_service::error::Error>, B: FnOnce(Configuration) -> Result<BC, sc_service::error::Error>,
G: RuntimeGenesis,
E: ChainSpecExtension,
BC: ServiceBuilderCommand<Block = BB> + Unpin, BC: ServiceBuilderCommand<Block = BB> + Unpin,
BB: sp_runtime::traits::Block + Debug, BB: sp_runtime::traits::Block + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
@@ -86,15 +84,13 @@ impl CheckBlockCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
self.import_params.update_config(&mut config, Roles::FULL, self.shared_params.dev)?; self.import_params.update_config(&mut config, Roles::FULL, self.shared_params.dev)?;
@@ -21,7 +21,7 @@ use std::fmt::Debug;
use log::info; use log::info;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{
Configuration, ChainSpecExtension, RuntimeGenesis, ServiceBuilderCommand, ChainSpec, Configuration, ServiceBuilderCommand, ChainSpec,
config::DatabaseConfig, Roles, config::DatabaseConfig, Roles,
}; };
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
@@ -65,15 +65,13 @@ pub struct ExportBlocksCmd {
impl ExportBlocksCmd { impl ExportBlocksCmd {
/// Run the export-blocks command /// Run the export-blocks command
pub fn run<G, E, B, BC, BB>( pub fn run<B, BC, BB>(
self, self,
config: Configuration<G, E>, config: Configuration,
builder: B, builder: B,
) -> error::Result<()> ) -> error::Result<()>
where where
B: FnOnce(Configuration<G, E>) -> Result<BC, sc_service::error::Error>, B: FnOnce(Configuration) -> Result<BC, sc_service::error::Error>,
G: RuntimeGenesis,
E: ChainSpecExtension,
BC: ServiceBuilderCommand<Block = BB> + Unpin, BC: ServiceBuilderCommand<Block = BB> + Unpin,
BB: sp_runtime::traits::Block + Debug, BB: sp_runtime::traits::Block + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
@@ -98,15 +96,13 @@ impl ExportBlocksCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
self.pruning_params.update_config(&mut config, Roles::FULL, true)?; self.pruning_params.update_config(&mut config, Roles::FULL, true)?;
@@ -20,7 +20,7 @@ use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{
Configuration, ChainSpecExtension, RuntimeGenesis, ServiceBuilderCommand, ChainSpec, Roles, Configuration, ServiceBuilderCommand, ChainSpec, Roles,
}; };
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
@@ -59,15 +59,13 @@ impl<T: Read + Seek> ReadPlusSeek for T {}
impl ImportBlocksCmd { impl ImportBlocksCmd {
/// Run the import-blocks command /// Run the import-blocks command
pub fn run<G, E, B, BC, BB>( pub fn run<B, BC, BB>(
self, self,
config: Configuration<G, E>, config: Configuration,
builder: B, builder: B,
) -> error::Result<()> ) -> error::Result<()>
where where
B: FnOnce(Configuration<G, E>) -> Result<BC, sc_service::error::Error>, B: FnOnce(Configuration) -> Result<BC, sc_service::error::Error>,
G: RuntimeGenesis,
E: ChainSpecExtension,
BC: ServiceBuilderCommand<Block = BB> + Unpin, BC: ServiceBuilderCommand<Block = BB> + Unpin,
BB: sp_runtime::traits::Block + Debug, BB: sp_runtime::traits::Block + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
@@ -88,15 +86,13 @@ impl ImportBlocksCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
self.import_params.update_config(&mut config, Roles::FULL, self.shared_params.dev)?; self.import_params.update_config(&mut config, Roles::FULL, self.shared_params.dev)?;
+7 -13
View File
@@ -25,9 +25,7 @@ mod purge_chain_cmd;
use std::fmt::Debug; use std::fmt::Debug;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{ Configuration, ServiceBuilderCommand, ChainSpec };
Configuration, ChainSpecExtension, RuntimeGenesis, ServiceBuilderCommand, ChainSpec,
};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use crate::error; use crate::error;
@@ -87,15 +85,13 @@ impl Subcommand {
} }
/// Run any `CoreParams` command /// Run any `CoreParams` command
pub fn run<G, E, B, BC, BB>( pub fn run<B, BC, BB>(
self, self,
config: Configuration<G, E>, config: Configuration,
builder: B, builder: B,
) -> error::Result<()> ) -> error::Result<()>
where where
B: FnOnce(Configuration<G, E>) -> Result<BC, sc_service::error::Error>, B: FnOnce(Configuration) -> Result<BC, sc_service::error::Error>,
G: RuntimeGenesis,
E: ChainSpecExtension,
BC: ServiceBuilderCommand<Block = BB> + Unpin, BC: ServiceBuilderCommand<Block = BB> + Unpin,
BB: sp_runtime::traits::Block + Debug, BB: sp_runtime::traits::Block + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
@@ -112,15 +108,13 @@ impl Subcommand {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
match self { match self {
Subcommand::BuildSpec(cmd) => cmd.update_config(&mut config, spec_factory, version), Subcommand::BuildSpec(cmd) => cmd.update_config(&mut config, spec_factory, version),
@@ -18,10 +18,7 @@ use std::fmt::Debug;
use std::io::{Write, self}; use std::io::{Write, self};
use std::fs; use std::fs;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{ Configuration, ChainSpec, config::{DatabaseConfig} };
Configuration, ChainSpecExtension, RuntimeGenesis, ChainSpec,
config::{DatabaseConfig},
};
use crate::error; use crate::error;
use crate::VersionInfo; use crate::VersionInfo;
@@ -41,14 +38,10 @@ pub struct PurgeChainCmd {
impl PurgeChainCmd { impl PurgeChainCmd {
/// Run the purge command /// Run the purge command
pub fn run<G, E>( pub fn run(
self, self,
config: Configuration<G, E>, config: Configuration,
) -> error::Result<()> ) -> error::Result<()> {
where
G: RuntimeGenesis,
E: ChainSpecExtension,
{
let db_path = match config.expect_database() { let db_path = match config.expect_database() {
DatabaseConfig::Path { path, .. } => path, DatabaseConfig::Path { path, .. } => path,
_ => { _ => {
@@ -88,15 +81,13 @@ impl PurgeChainCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
config.use_in_memory_keystore()?; config.use_in_memory_keystore()?;
@@ -17,7 +17,7 @@
use std::fmt::Debug; use std::fmt::Debug;
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{ use sc_service::{
Configuration, ChainSpecExtension, RuntimeGenesis, ServiceBuilderCommand, ChainSpec, Roles, Configuration, ServiceBuilderCommand, ChainSpec, Roles,
}; };
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
@@ -43,15 +43,13 @@ pub struct RevertCmd {
impl RevertCmd { impl RevertCmd {
/// Run the revert command /// Run the revert command
pub fn run<G, E, B, BC, BB>( pub fn run<B, BC, BB>(
self, self,
config: Configuration<G, E>, config: Configuration,
builder: B, builder: B,
) -> error::Result<()> ) -> error::Result<()>
where where
B: FnOnce(Configuration<G, E>) -> Result<BC, sc_service::error::Error>, B: FnOnce(Configuration) -> Result<BC, sc_service::error::Error>,
G: RuntimeGenesis,
E: ChainSpecExtension,
BC: ServiceBuilderCommand<Block = BB> + Unpin, BC: ServiceBuilderCommand<Block = BB> + Unpin,
BB: sp_runtime::traits::Block + Debug, BB: sp_runtime::traits::Block + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
@@ -64,15 +62,13 @@ impl RevertCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> where ) -> error::Result<()> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
self.pruning_params.update_config(&mut config, Roles::FULL, true)?; self.pruning_params.update_config(&mut config, Roles::FULL, true)?;
+16 -20
View File
@@ -23,7 +23,7 @@ use names::{Generator, Name};
use regex::Regex; use regex::Regex;
use chrono::prelude::*; use chrono::prelude::*;
use sc_service::{ use sc_service::{
AbstractService, Configuration, ChainSpecExtension, RuntimeGenesis, ChainSpec, Roles, AbstractService, Configuration, ChainSpec, Roles,
config::{KeystoreConfig, PrometheusConfig}, config::{KeystoreConfig, PrometheusConfig},
}; };
use sc_telemetry::TelemetryEndpoints; use sc_telemetry::TelemetryEndpoints;
@@ -291,16 +291,14 @@ impl RunCmd {
} }
/// Update and prepare a `Configuration` with command line parameters of `RunCmd` and `VersionInfo` /// Update and prepare a `Configuration` with command line parameters of `RunCmd` and `VersionInfo`
pub fn update_config<G, E, F>( pub fn update_config<F>(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> ) -> error::Result<()>
where where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
self.shared_params.update_config(&mut config, spec_factory, version)?; self.shared_params.update_config(&mut config, spec_factory, version)?;
@@ -447,18 +445,16 @@ impl RunCmd {
} }
/// Run the command that runs the node /// Run the command that runs the node
pub fn run<G, E, FNL, FNF, SL, SF>( pub fn run<FNL, FNF, SL, SF>(
self, self,
config: Configuration<G, E>, config: Configuration,
new_light: FNL, new_light: FNL,
new_full: FNF, new_full: FNF,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<()> ) -> error::Result<()>
where where
G: RuntimeGenesis, FNL: FnOnce(Configuration) -> Result<SL, sc_service::error::Error>,
E: ChainSpecExtension, FNF: FnOnce(Configuration) -> Result<SF, sc_service::error::Error>,
FNL: FnOnce(Configuration<G, E>) -> Result<SL, sc_service::error::Error>,
FNF: FnOnce(Configuration<G, E>) -> Result<SF, sc_service::error::Error>,
SL: AbstractService + Unpin, SL: AbstractService + Unpin,
SF: AbstractService + Unpin, SF: AbstractService + Unpin,
{ {
@@ -625,7 +621,7 @@ fn parse_cors(s: &str) -> Result<Cors, Box<dyn std::error::Error>> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use sc_service::config::DatabaseConfig; use sc_service::{GenericChainSpec, config::DatabaseConfig};
const TEST_VERSION_INFO: &'static VersionInfo = &VersionInfo { const TEST_VERSION_INFO: &'static VersionInfo = &VersionInfo {
name: "node-test", name: "node-test",
@@ -655,7 +651,7 @@ mod tests {
#[test] #[test]
fn keystore_path_is_generated_correctly() { fn keystore_path_is_generated_correctly() {
let chain_spec = ChainSpec::from_genesis( let chain_spec = GenericChainSpec::from_genesis(
"test", "test",
"test-id", "test-id",
|| (), || (),
@@ -673,9 +669,9 @@ mod tests {
let mut config = Configuration::default(); let mut config = Configuration::default();
config.config_dir = Some(PathBuf::from("/test/path")); config.config_dir = Some(PathBuf::from("/test/path"));
config.chain_spec = Some(chain_spec.clone()); config.chain_spec = Some(Box::new(chain_spec.clone()));
let chain_spec = chain_spec.clone(); let chain_spec = chain_spec.clone();
cli.update_config(&mut config, move |_| Ok(Some(chain_spec)), TEST_VERSION_INFO).unwrap(); cli.update_config(&mut config, move |_| Ok(Box::new(chain_spec)), TEST_VERSION_INFO).unwrap();
let expected_path = match keystore_path { let expected_path = match keystore_path {
Some(path) => PathBuf::from(path), Some(path) => PathBuf::from(path),
@@ -688,7 +684,7 @@ mod tests {
#[test] #[test]
fn ensure_load_spec_provide_defaults() { fn ensure_load_spec_provide_defaults() {
let chain_spec = ChainSpec::from_genesis( let chain_spec = GenericChainSpec::from_genesis(
"test", "test",
"test-id", "test-id",
|| (), || (),
@@ -703,7 +699,7 @@ mod tests {
let cli = RunCmd::from_iter(args); let cli = RunCmd::from_iter(args);
let mut config = Configuration::from_version(TEST_VERSION_INFO); let mut config = Configuration::from_version(TEST_VERSION_INFO);
cli.update_config(&mut config, |_| Ok(Some(chain_spec)), TEST_VERSION_INFO).unwrap(); cli.update_config(&mut config, |_| Ok(Box::new(chain_spec)), TEST_VERSION_INFO).unwrap();
assert!(config.chain_spec.is_some()); assert!(config.chain_spec.is_some());
assert!(!config.network.boot_nodes.is_empty()); assert!(!config.network.boot_nodes.is_empty());
@@ -712,7 +708,7 @@ mod tests {
#[test] #[test]
fn ensure_update_config_for_running_node_provides_defaults() { fn ensure_update_config_for_running_node_provides_defaults() {
let chain_spec = ChainSpec::from_genesis( let chain_spec = GenericChainSpec::from_genesis(
"test", "test",
"test-id", "test-id",
|| (), || (),
@@ -728,7 +724,7 @@ mod tests {
let mut config = Configuration::from_version(TEST_VERSION_INFO); let mut config = Configuration::from_version(TEST_VERSION_INFO);
cli.init(&TEST_VERSION_INFO).unwrap(); cli.init(&TEST_VERSION_INFO).unwrap();
cli.update_config(&mut config, |_| Ok(Some(chain_spec)), TEST_VERSION_INFO).unwrap(); cli.update_config(&mut config, |_| Ok(Box::new(chain_spec)), TEST_VERSION_INFO).unwrap();
assert!(config.config_dir.is_some()); assert!(config.config_dir.is_some());
assert!(config.database.is_some()); assert!(config.database.is_some());
@@ -15,7 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>. // along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{Configuration, RuntimeGenesis, config::DatabaseConfig}; use sc_service::{Configuration, config::DatabaseConfig};
use crate::error; use crate::error;
use crate::arg_enums::{ use crate::arg_enums::{
@@ -79,15 +79,12 @@ pub struct ImportParams {
impl ImportParams { impl ImportParams {
/// Put block import CLI params into `config` object. /// Put block import CLI params into `config` object.
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
role: sc_service::Roles, role: sc_service::Roles,
is_dev: bool, is_dev: bool,
) -> error::Result<()> ) -> error::Result<()> {
where
G: RuntimeGenesis,
{
use sc_client_api::execution_extensions::ExecutionStrategies; use sc_client_api::execution_extensions::ExecutionStrategies;
if let Some(DatabaseConfig::Path { ref mut cache_size, .. }) = config.database { if let Some(DatabaseConfig::Path { ref mut cache_size, .. }) = config.database {
@@ -21,7 +21,7 @@ use structopt::StructOpt;
use sc_network::{ use sc_network::{
config::{NonReservedPeerMode, TransportConfig}, multiaddr::Protocol, config::{NonReservedPeerMode, TransportConfig}, multiaddr::Protocol,
}; };
use sc_service::{Configuration, RuntimeGenesis}; use sc_service::Configuration;
use crate::error; use crate::error;
use crate::params::node_key_params::NodeKeyParams; use crate::params::node_key_params::NodeKeyParams;
@@ -101,16 +101,13 @@ pub struct NetworkConfigurationParams {
impl NetworkConfigurationParams { impl NetworkConfigurationParams {
/// Fill the given `NetworkConfiguration` by looking at the cli parameters. /// Fill the given `NetworkConfiguration` by looking at the cli parameters.
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
config_path: PathBuf, config_path: PathBuf,
client_id: String, client_id: String,
is_dev: bool, is_dev: bool,
) -> error::Result<()> ) -> error::Result<()> {
where
G: RuntimeGenesis,
{
config.network.boot_nodes.extend(self.bootnodes.clone()); config.network.boot_nodes.extend(self.bootnodes.clone());
config.network.config_path = Some(config_path.clone()); config.network.config_path = Some(config_path.clone());
config.network.net_config_path = Some(config_path.clone()); config.network.net_config_path = Some(config_path.clone());
@@ -16,7 +16,7 @@
use std::{path::PathBuf, str::FromStr}; use std::{path::PathBuf, str::FromStr};
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{Configuration, RuntimeGenesis}; use sc_service::Configuration;
use sc_network::config::NodeKeyConfig; use sc_network::config::NodeKeyConfig;
use sp_core::H256; use sp_core::H256;
@@ -93,14 +93,11 @@ pub struct NodeKeyParams {
impl NodeKeyParams { impl NodeKeyParams {
/// Create a `NodeKeyConfig` from the given `NodeKeyParams` in the context /// Create a `NodeKeyConfig` from the given `NodeKeyParams` in the context
/// of an optional network config storage directory. /// of an optional network config storage directory.
pub fn update_config<'a, G, E>( pub fn update_config<'a>(
&self, &self,
mut config: &'a mut Configuration<G, E>, mut config: &'a mut Configuration,
net_config_path: Option<&PathBuf>, net_config_path: Option<&PathBuf>,
) -> error::Result<&'a NodeKeyConfig> ) -> error::Result<&'a NodeKeyConfig> {
where
G: RuntimeGenesis,
{
config.network.node_key = match self.node_key_type { config.network.node_key = match self.node_key_type {
NodeKeyType::Ed25519 => { NodeKeyType::Ed25519 => {
let secret = if let Some(node_key) = self.node_key.as_ref() { let secret = if let Some(node_key) = self.node_key.as_ref() {
@@ -146,7 +143,7 @@ mod tests {
fn test_node_key_config_input() { fn test_node_key_config_input() {
fn secret_input(net_config_dir: Option<&PathBuf>) -> error::Result<()> { fn secret_input(net_config_dir: Option<&PathBuf>) -> error::Result<()> {
NodeKeyType::variants().iter().try_for_each(|t| { NodeKeyType::variants().iter().try_for_each(|t| {
let mut config = Configuration::<(), ()>::default(); let mut config = Configuration::default();
let node_key_type = NodeKeyType::from_str(t).unwrap(); let node_key_type = NodeKeyType::from_str(t).unwrap();
let sk = match node_key_type { let sk = match node_key_type {
NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec() NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec()
@@ -173,7 +170,7 @@ mod tests {
fn test_node_key_config_file() { fn test_node_key_config_file() {
fn secret_file(net_config_dir: Option<&PathBuf>) -> error::Result<()> { fn secret_file(net_config_dir: Option<&PathBuf>) -> error::Result<()> {
NodeKeyType::variants().iter().try_for_each(|t| { NodeKeyType::variants().iter().try_for_each(|t| {
let mut config = Configuration::<(), ()>::default(); let mut config = Configuration::default();
let node_key_type = NodeKeyType::from_str(t).unwrap(); let node_key_type = NodeKeyType::from_str(t).unwrap();
let tmp = tempfile::Builder::new().prefix("alice").tempdir()?; let tmp = tempfile::Builder::new().prefix("alice").tempdir()?;
let file = tmp.path().join(format!("{}_mysecret", t)).to_path_buf(); let file = tmp.path().join(format!("{}_mysecret", t)).to_path_buf();
@@ -212,7 +209,7 @@ mod tests {
fn no_config_dir() -> error::Result<()> { fn no_config_dir() -> error::Result<()> {
with_def_params(|params| { with_def_params(|params| {
let mut config = Configuration::<(), ()>::default(); let mut config = Configuration::default();
let typ = params.node_key_type; let typ = params.node_key_type;
params.update_config(&mut config, None) params.update_config(&mut config, None)
.and_then(|c| match c { .and_then(|c| match c {
@@ -225,7 +222,7 @@ mod tests {
fn some_config_dir(net_config_dir: &PathBuf) -> error::Result<()> { fn some_config_dir(net_config_dir: &PathBuf) -> error::Result<()> {
with_def_params(|params| { with_def_params(|params| {
let mut config = Configuration::<(), ()>::default(); let mut config = Configuration::default();
let dir = PathBuf::from(net_config_dir.clone()); let dir = PathBuf::from(net_config_dir.clone());
let typ = params.node_key_type; let typ = params.node_key_type;
params.update_config(&mut config, Some(net_config_dir)) params.update_config(&mut config, Some(net_config_dir))
@@ -15,7 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>. // along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use structopt::StructOpt; use structopt::StructOpt;
use sc_service::{Configuration, RuntimeGenesis, PruningMode}; use sc_service::{Configuration, PruningMode};
use crate::error; use crate::error;
@@ -33,15 +33,12 @@ pub struct PruningParams {
impl PruningParams { impl PruningParams {
/// Put block pruning CLI params into `config` object. /// Put block pruning CLI params into `config` object.
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
role: sc_service::Roles, role: sc_service::Roles,
unsafe_pruning: bool, unsafe_pruning: bool,
) -> error::Result<()> ) -> error::Result<()> {
where
G: RuntimeGenesis,
{
// by default we disable pruning if the node is an authority (i.e. // by default we disable pruning if the node is an authority (i.e.
// `ArchiveAll`), otherwise we keep state for the last 256 blocks. if the // `ArchiveAll`), otherwise we keep state for the last 256 blocks. if the
// node is an authority and pruning is enabled explicitly, then we error // node is an authority and pruning is enabled explicitly, then we error
@@ -18,8 +18,7 @@ use std::path::PathBuf;
use structopt::StructOpt; use structopt::StructOpt;
use app_dirs::{AppInfo, AppDataType}; use app_dirs::{AppInfo, AppDataType};
use sc_service::{ use sc_service::{
Configuration, ChainSpecExtension, RuntimeGenesis, Configuration, config::DatabaseConfig, ChainSpec,
config::DatabaseConfig, ChainSpec,
}; };
use crate::VersionInfo; use crate::VersionInfo;
@@ -50,25 +49,19 @@ pub struct SharedParams {
impl SharedParams { impl SharedParams {
/// Load spec to `Configuration` from `SharedParams` and spec factory. /// Load spec to `Configuration` from `SharedParams` and spec factory.
pub fn update_config<'a, G, E, F>( pub fn update_config<'a, F>(
&self, &self,
mut config: &'a mut Configuration<G, E>, mut config: &'a mut Configuration,
spec_factory: F, spec_factory: F,
version: &VersionInfo, version: &VersionInfo,
) -> error::Result<&'a ChainSpec<G, E>> where ) -> error::Result<&'a dyn ChainSpec> where
G: RuntimeGenesis, F: FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
E: ChainSpecExtension,
F: FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>,
{ {
let chain_key = match self.chain { let chain_key = match self.chain {
Some(ref chain) => chain.clone(), Some(ref chain) => chain.clone(),
None => if self.dev { "dev".into() } else { "".into() } None => if self.dev { "dev".into() } else { "".into() }
}; };
let spec = match spec_factory(&chain_key)? { let spec = spec_factory(&chain_key)?;
Some(spec) => spec,
None => ChainSpec::from_json_file(PathBuf::from(chain_key))?
};
config.network.boot_nodes = spec.boot_nodes().to_vec(); config.network.boot_nodes = spec.boot_nodes().to_vec();
config.telemetry_endpoints = spec.telemetry_endpoints().clone(); config.telemetry_endpoints = spec.telemetry_endpoints().clone();
@@ -87,7 +80,7 @@ impl SharedParams {
}); });
} }
Ok(config.chain_spec.as_ref().unwrap()) Ok(config.expect_chain_spec())
} }
/// Initialize substrate. This must be done only once. /// Initialize substrate. This must be done only once.
@@ -31,9 +31,9 @@ pub struct TransactionPoolParams {
impl TransactionPoolParams { impl TransactionPoolParams {
/// Fill the given `PoolConfiguration` by looking at the cli parameters. /// Fill the given `PoolConfiguration` by looking at the cli parameters.
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
config: &mut Configuration<G, E>, config: &mut Configuration,
) -> error::Result<()> { ) -> error::Result<()> {
// ready queue // ready queue
config.transaction_pool.ready.count = self.pool_limit; config.transaction_pool.ready.count = self.pool_limit;
+6 -6
View File
@@ -79,12 +79,12 @@ fn build_runtime() -> Result<tokio::runtime::Runtime, std::io::Error> {
/// A helper function that runs a future with tokio and stops if the process receives the signal /// A helper function that runs a future with tokio and stops if the process receives the signal
/// SIGTERM or SIGINT /// SIGTERM or SIGINT
pub fn run_until_exit<FUT, ERR, G, E, F>( pub fn run_until_exit<FUT, ERR, F>(
mut config: Configuration<G, E>, mut config: Configuration,
future_builder: F, future_builder: F,
) -> error::Result<()> ) -> error::Result<()>
where where
F: FnOnce(Configuration<G, E>) -> error::Result<FUT>, F: FnOnce(Configuration) -> error::Result<FUT>,
FUT: Future<Output = Result<(), ERR>> + future::Future, FUT: Future<Output = Result<(), ERR>> + future::Future,
ERR: 'static + std::error::Error, ERR: 'static + std::error::Error,
{ {
@@ -106,12 +106,12 @@ where
/// A helper function that runs an `AbstractService` with tokio and stops if the process receives /// A helper function that runs an `AbstractService` with tokio and stops if the process receives
/// the signal SIGTERM or SIGINT /// the signal SIGTERM or SIGINT
pub fn run_service_until_exit<T, G, E, F>( pub fn run_service_until_exit<T, F>(
mut config: Configuration<G, E>, mut config: Configuration,
service_builder: F, service_builder: F,
) -> error::Result<()> ) -> error::Result<()>
where where
F: FnOnce(Configuration<G, E>) -> Result<T, sc_service::error::Error>, F: FnOnce(Configuration) -> Result<T, sc_service::error::Error>,
T: AbstractService + Unpin, T: AbstractService + Unpin,
{ {
let mut runtime = build_runtime()?; let mut runtime = build_runtime()?;
+2 -3
View File
@@ -285,10 +285,10 @@ pub enum DatabaseSettingsSrc {
} }
/// Create an instance of db-backed client. /// Create an instance of db-backed client.
pub fn new_client<E, S, Block, RA>( pub fn new_client<E, Block, RA>(
settings: DatabaseSettings, settings: DatabaseSettings,
executor: E, executor: E,
genesis_storage: &S, genesis_storage: &dyn BuildStorage,
fork_blocks: ForkBlocks<Block>, fork_blocks: ForkBlocks<Block>,
bad_blocks: BadBlocks<Block>, bad_blocks: BadBlocks<Block>,
execution_extensions: ExecutionExtensions<Block>, execution_extensions: ExecutionExtensions<Block>,
@@ -307,7 +307,6 @@ pub fn new_client<E, S, Block, RA>(
where where
Block: BlockT, Block: BlockT,
E: CodeExecutor + RuntimeInfo, E: CodeExecutor + RuntimeInfo,
S: BuildStorage,
{ {
let backend = Arc::new(Backend::new(settings, CANONICALIZATION_DELAY)?); let backend = Arc::new(Backend::new(settings, CANONICALIZATION_DELAY)?);
let executor = sc_client::LocalCallExecutor::new(backend.clone(), executor); let executor = sc_client::LocalCallExecutor::new(backend.clone(), executor);
+29 -50
View File
@@ -26,7 +26,7 @@ use sc_client_api::{
ExecutorProvider, CallExecutor ExecutorProvider, CallExecutor
}; };
use sc_client::Client; use sc_client::Client;
use sc_chain_spec::{RuntimeGenesis, Extension}; use sc_chain_spec::get_extension;
use sp_consensus::import_queue::ImportQueue; use sp_consensus::import_queue::ImportQueue;
use futures::{ use futures::{
Future, FutureExt, StreamExt, Future, FutureExt, StreamExt,
@@ -119,10 +119,10 @@ pub type BackgroundTask = Pin<Box<dyn Future<Output=()> + Send>>;
/// The order in which the `with_*` methods are called doesn't matter, as the correct binding of /// The order in which the `with_*` methods are called doesn't matter, as the correct binding of
/// generics is done when you call `build`. /// generics is done when you call `build`.
/// ///
pub struct ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, pub struct ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend> TExPool, TRpc, Backend>
{ {
config: Configuration<TGen, TCSExt>, config: Configuration,
pub (crate) client: Arc<TCl>, pub (crate) client: Arc<TCl>,
backend: Arc<Backend>, backend: Arc<Backend>,
tasks_builder: TaskManagerBuilder, tasks_builder: TaskManagerBuilder,
@@ -193,24 +193,20 @@ type TFullParts<TBl, TRtApi, TExecDisp> = (
); );
/// Creates a new full client for the given config. /// Creates a new full client for the given config.
pub fn new_full_client<TBl, TRtApi, TExecDisp, TGen, TCSExt>( pub fn new_full_client<TBl, TRtApi, TExecDisp>(
config: &Configuration<TGen, TCSExt>, config: &Configuration,
) -> Result<TFullClient<TBl, TRtApi, TExecDisp>, Error> where ) -> Result<TFullClient<TBl, TRtApi, TExecDisp>, Error> where
TBl: BlockT, TBl: BlockT,
TExecDisp: NativeExecutionDispatch + 'static, TExecDisp: NativeExecutionDispatch + 'static,
TGen: sp_runtime::BuildStorage + serde::Serialize + for<'de> serde::Deserialize<'de>,
TCSExt: Extension,
{ {
new_full_parts(config).map(|parts| parts.0) new_full_parts(config).map(|parts| parts.0)
} }
fn new_full_parts<TBl, TRtApi, TExecDisp, TGen, TCSExt>( fn new_full_parts<TBl, TRtApi, TExecDisp>(
config: &Configuration<TGen, TCSExt>, config: &Configuration,
) -> Result<TFullParts<TBl, TRtApi, TExecDisp>, Error> where ) -> Result<TFullParts<TBl, TRtApi, TExecDisp>, Error> where
TBl: BlockT, TBl: BlockT,
TExecDisp: NativeExecutionDispatch + 'static, TExecDisp: NativeExecutionDispatch + 'static,
TGen: sp_runtime::BuildStorage + serde::Serialize + for<'de> serde::Deserialize<'de>,
TCSExt: Extension,
{ {
let keystore = match &config.keystore { let keystore = match &config.keystore {
KeystoreConfig::Path { path, password } => Keystore::open( KeystoreConfig::Path { path, password } => Keystore::open(
@@ -230,15 +226,11 @@ fn new_full_parts<TBl, TRtApi, TExecDisp, TGen, TCSExt>(
); );
let chain_spec = config.expect_chain_spec(); let chain_spec = config.expect_chain_spec();
let fork_blocks = chain_spec let fork_blocks = get_extension::<sc_client::ForkBlocks<TBl>>(chain_spec.extensions())
.extensions()
.get::<sc_client::ForkBlocks<TBl>>()
.cloned() .cloned()
.unwrap_or_default(); .unwrap_or_default();
let bad_blocks = chain_spec let bad_blocks = get_extension::<sc_client::BadBlocks<TBl>>(chain_spec.extensions())
.extensions()
.get::<sc_client::BadBlocks<TBl>>()
.cloned() .cloned()
.unwrap_or_default(); .unwrap_or_default();
@@ -267,7 +259,7 @@ fn new_full_parts<TBl, TRtApi, TExecDisp, TGen, TCSExt>(
sc_client_db::new_client( sc_client_db::new_client(
db_config, db_config,
executor, executor,
config.expect_chain_spec(), config.expect_chain_spec().as_storage_builder(),
fork_blocks, fork_blocks,
bad_blocks, bad_blocks,
extensions, extensions,
@@ -278,16 +270,13 @@ fn new_full_parts<TBl, TRtApi, TExecDisp, TGen, TCSExt>(
Ok((client, backend, keystore, tasks_builder)) Ok((client, backend, keystore, tasks_builder))
} }
impl<TGen, TCSExt> ServiceBuilder<(), (), TGen, TCSExt, (), (), (), (), (), (), (), (), ()> impl ServiceBuilder<(), (), (), (), (), (), (), (), (), (), ()> {
where TGen: RuntimeGenesis, TCSExt: Extension {
/// Start the service builder with a configuration. /// Start the service builder with a configuration.
pub fn new_full<TBl: BlockT, TRtApi, TExecDisp: NativeExecutionDispatch + 'static>( pub fn new_full<TBl: BlockT, TRtApi, TExecDisp: NativeExecutionDispatch + 'static>(
config: Configuration<TGen, TCSExt> config: Configuration,
) -> Result<ServiceBuilder< ) -> Result<ServiceBuilder<
TBl, TBl,
TRtApi, TRtApi,
TGen,
TCSExt,
TFullClient<TBl, TRtApi, TExecDisp>, TFullClient<TBl, TRtApi, TExecDisp>,
Arc<OnDemand<TBl>>, Arc<OnDemand<TBl>>,
(), (),
@@ -323,12 +312,10 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
/// Start the service builder with a configuration. /// Start the service builder with a configuration.
pub fn new_light<TBl: BlockT, TRtApi, TExecDisp: NativeExecutionDispatch + 'static>( pub fn new_light<TBl: BlockT, TRtApi, TExecDisp: NativeExecutionDispatch + 'static>(
config: Configuration<TGen, TCSExt> config: Configuration,
) -> Result<ServiceBuilder< ) -> Result<ServiceBuilder<
TBl, TBl,
TRtApi, TRtApi,
TGen,
TCSExt,
TLightClient<TBl, TRtApi, TExecDisp>, TLightClient<TBl, TRtApi, TExecDisp>,
Arc<OnDemand<TBl>>, Arc<OnDemand<TBl>>,
(), (),
@@ -386,7 +373,7 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
let remote_blockchain = backend.remote_blockchain(); let remote_blockchain = backend.remote_blockchain();
let client = Arc::new(sc_client::light::new_light( let client = Arc::new(sc_client::light::new_light(
backend.clone(), backend.clone(),
config.expect_chain_spec(), config.expect_chain_spec().as_storage_builder(),
executor, executor,
config.prometheus_config.as_ref().map(|config| config.registry.clone()), config.prometheus_config.as_ref().map(|config| config.registry.clone()),
)?); )?);
@@ -411,8 +398,8 @@ where TGen: RuntimeGenesis, TCSExt: Extension {
} }
} }
impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend> impl<TBl, TRtApi, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend>
ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend> { TExPool, TRpc, Backend> {
/// Returns a reference to the client that was stored in this builder. /// Returns a reference to the client that was stored in this builder.
@@ -458,9 +445,9 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
pub fn with_opt_select_chain<USc>( pub fn with_opt_select_chain<USc>(
self, self,
select_chain_builder: impl FnOnce( select_chain_builder: impl FnOnce(
&Configuration<TGen, TCSExt>, &Arc<Backend> &Configuration, &Arc<Backend>,
) -> Result<Option<USc>, Error> ) -> Result<Option<USc>, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, USc, TImpQu, TFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, USc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend>, Error> { TExPool, TRpc, Backend>, Error> {
let select_chain = select_chain_builder(&self.config, &self.backend)?; let select_chain = select_chain_builder(&self.config, &self.backend)?;
@@ -486,8 +473,8 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
/// Defines which head-of-chain strategy to use. /// Defines which head-of-chain strategy to use.
pub fn with_select_chain<USc>( pub fn with_select_chain<USc>(
self, self,
builder: impl FnOnce(&Configuration<TGen, TCSExt>, &Arc<Backend>) -> Result<USc, Error> builder: impl FnOnce(&Configuration, &Arc<Backend>) -> Result<USc, Error>,
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, USc, TImpQu, TFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, USc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend>, Error> { TExPool, TRpc, Backend>, Error> {
self.with_opt_select_chain(|cfg, b| builder(cfg, b).map(Option::Some)) self.with_opt_select_chain(|cfg, b| builder(cfg, b).map(Option::Some))
} }
@@ -495,9 +482,9 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
/// Defines which import queue to use. /// Defines which import queue to use.
pub fn with_import_queue<UImpQu>( pub fn with_import_queue<UImpQu>(
self, self,
builder: impl FnOnce(&Configuration<TGen, TCSExt>, Arc<TCl>, Option<TSc>, Arc<TExPool>) builder: impl FnOnce(&Configuration, Arc<TCl>, Option<TSc>, Arc<TExPool>)
-> Result<UImpQu, Error> -> Result<UImpQu, Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, TFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, UImpQu, TFprb, TFpp,
TExPool, TRpc, Backend>, Error> TExPool, TRpc, Backend>, Error>
where TSc: Clone { where TSc: Clone {
let import_queue = builder( let import_queue = builder(
@@ -533,8 +520,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
) -> Result<ServiceBuilder< ) -> Result<ServiceBuilder<
TBl, TBl,
TRtApi, TRtApi,
TGen,
TCSExt,
TCl, TCl,
TFchr, TFchr,
TSc, TSc,
@@ -573,8 +558,6 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
) -> Result<ServiceBuilder< ) -> Result<ServiceBuilder<
TBl, TBl,
TRtApi, TRtApi,
TGen,
TCSExt,
TCl, TCl,
TFchr, TFchr,
TSc, TSc,
@@ -592,14 +575,14 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
pub fn with_import_queue_and_opt_fprb<UImpQu, UFprb>( pub fn with_import_queue_and_opt_fprb<UImpQu, UFprb>(
self, self,
builder: impl FnOnce( builder: impl FnOnce(
&Configuration<TGen, TCSExt>, &Configuration,
Arc<TCl>, Arc<TCl>,
Arc<Backend>, Arc<Backend>,
Option<TFchr>, Option<TFchr>,
Option<TSc>, Option<TSc>,
Arc<TExPool>, Arc<TExPool>,
) -> Result<(UImpQu, Option<UFprb>), Error> ) -> Result<(UImpQu, Option<UFprb>), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, UFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, UImpQu, UFprb, TFpp,
TExPool, TRpc, Backend>, Error> TExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone { where TSc: Clone, TFchr: Clone {
let (import_queue, fprb) = builder( let (import_queue, fprb) = builder(
@@ -634,14 +617,14 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
pub fn with_import_queue_and_fprb<UImpQu, UFprb>( pub fn with_import_queue_and_fprb<UImpQu, UFprb>(
self, self,
builder: impl FnOnce( builder: impl FnOnce(
&Configuration<TGen, TCSExt>, &Configuration,
Arc<TCl>, Arc<TCl>,
Arc<Backend>, Arc<Backend>,
Option<TFchr>, Option<TFchr>,
Option<TSc>, Option<TSc>,
Arc<TExPool>, Arc<TExPool>,
) -> Result<(UImpQu, UFprb), Error> ) -> Result<(UImpQu, UFprb), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, UImpQu, UFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, UImpQu, UFprb, TFpp,
TExPool, TRpc, Backend>, Error> TExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone { where TSc: Clone, TFchr: Clone {
self.with_import_queue_and_opt_fprb(|cfg, cl, b, f, sc, tx| self.with_import_queue_and_opt_fprb(|cfg, cl, b, f, sc, tx|
@@ -658,7 +641,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
Arc<TCl>, Arc<TCl>,
Option<TFchr>, Option<TFchr>,
) -> Result<(UExPool, Option<BackgroundTask>), Error> ) -> Result<(UExPool, Option<BackgroundTask>), Error>
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
UExPool, TRpc, Backend>, Error> UExPool, TRpc, Backend>, Error>
where TSc: Clone, TFchr: Clone { where TSc: Clone, TFchr: Clone {
let (transaction_pool, background_task) = transaction_pool_builder( let (transaction_pool, background_task) = transaction_pool_builder(
@@ -694,7 +677,7 @@ impl<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, T
pub fn with_rpc_extensions<URpc>( pub fn with_rpc_extensions<URpc>(
self, self,
rpc_ext_builder: impl FnOnce(&Self) -> Result<URpc, Error>, rpc_ext_builder: impl FnOnce(&Self) -> Result<URpc, Error>,
) -> Result<ServiceBuilder<TBl, TRtApi, TGen, TCSExt, TCl, TFchr, TSc, TImpQu, TFprb, TFpp, ) -> Result<ServiceBuilder<TBl, TRtApi, TCl, TFchr, TSc, TImpQu, TFprb, TFpp,
TExPool, URpc, Backend>, Error> TExPool, URpc, Backend>, Error>
where TSc: Clone, TFchr: Clone { where TSc: Clone, TFchr: Clone {
let rpc_extensions = rpc_ext_builder(&self)?; let rpc_extensions = rpc_ext_builder(&self)?;
@@ -755,12 +738,10 @@ pub trait ServiceBuilderCommand {
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>; ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;
} }
impl<TBl, TRtApi, TGen, TCSExt, TBackend, TExec, TSc, TImpQu, TExPool, TRpc> impl<TBl, TRtApi, TBackend, TExec, TSc, TImpQu, TExPool, TRpc>
ServiceBuilder< ServiceBuilder<
TBl, TBl,
TRtApi, TRtApi,
TGen,
TCSExt,
Client<TBackend, TExec, TBl, TRtApi>, Client<TBackend, TExec, TBl, TRtApi>,
Arc<OnDemand<TBl>>, Arc<OnDemand<TBl>>,
TSc, TSc,
@@ -781,8 +762,6 @@ ServiceBuilder<
sp_api::ApiExt<TBl, StateBackend = TBackend::State>, sp_api::ApiExt<TBl, StateBackend = TBackend::State>,
TBl: BlockT, TBl: BlockT,
TRtApi: 'static + Send + Sync, TRtApi: 'static + Send + Sync,
TGen: RuntimeGenesis,
TCSExt: Extension,
TBackend: 'static + sc_client_api::backend::Backend<TBl> + Send, TBackend: 'static + sc_client_api::backend::Backend<TBl> + Send,
TExec: 'static + sc_client::CallExecutor<TBl> + Send + Sync + Clone, TExec: 'static + sc_client::CallExecutor<TBl> + Send + Sync + Clone,
TSc: Clone, TSc: Clone,
+5 -8
View File
@@ -19,7 +19,7 @@
use crate::error; use crate::error;
use crate::builder::{ServiceBuilderCommand, ServiceBuilder}; use crate::builder::{ServiceBuilderCommand, ServiceBuilder};
use crate::error::Error; use crate::error::Error;
use sc_chain_spec::{ChainSpec, RuntimeGenesis, Extension}; use sc_chain_spec::ChainSpec;
use log::{warn, info}; use log::{warn, info};
use futures::{future, prelude::*}; use futures::{future, prelude::*};
use sp_runtime::traits::{ use sp_runtime::traits::{
@@ -38,19 +38,16 @@ use std::{io::{Read, Write, Seek}, pin::Pin};
use sc_client_api::BlockBody; use sc_client_api::BlockBody;
/// Build a chain spec json /// Build a chain spec json
pub fn build_spec<G, E>(spec: ChainSpec<G, E>, raw: bool) -> error::Result<String> where pub fn build_spec(spec: &dyn ChainSpec, raw: bool) -> error::Result<String> {
G: RuntimeGenesis, Ok(spec.as_json(raw)?)
E: Extension,
{
Ok(spec.to_json(raw)?)
} }
impl< impl<
TBl, TRtApi, TGen, TCSExt, TBackend, TBl, TRtApi, TBackend,
TExecDisp, TFchr, TSc, TImpQu, TFprb, TFpp, TExecDisp, TFchr, TSc, TImpQu, TFprb, TFpp,
TExPool, TRpc, Backend TExPool, TRpc, Backend
> ServiceBuilderCommand for ServiceBuilder< > ServiceBuilderCommand for ServiceBuilder<
TBl, TRtApi, TGen, TCSExt, TBl, TRtApi,
Client<TBackend, LocalCallExecutor<TBackend, NativeExecutor<TExecDisp>>, TBl, TRtApi>, Client<TBackend, LocalCallExecutor<TBackend, NativeExecutor<TExecDisp>>, TBl, TRtApi>,
TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend TFchr, TSc, TImpQu, TFprb, TFpp, TExPool, TRpc, Backend
> where > where
+7 -7
View File
@@ -23,7 +23,7 @@ pub use sc_executor::WasmExecutionMethod;
use std::{future::Future, path::{PathBuf, Path}, pin::Pin, net::SocketAddr, sync::Arc}; use std::{future::Future, path::{PathBuf, Path}, pin::Pin, net::SocketAddr, sync::Arc};
pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions; pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions;
use sc_chain_spec::{ChainSpec, NoExtension}; use sc_chain_spec::ChainSpec;
use sp_core::crypto::Protected; use sp_core::crypto::Protected;
use target_info::Target; use target_info::Target;
use sc_telemetry::TelemetryEndpoints; use sc_telemetry::TelemetryEndpoints;
@@ -51,7 +51,7 @@ pub struct VersionInfo {
} }
/// Service configuration. /// Service configuration.
pub struct Configuration<G, E = NoExtension> { pub struct Configuration {
/// Implementation name /// Implementation name
pub impl_name: &'static str, pub impl_name: &'static str,
/// Implementation version /// Implementation version
@@ -79,7 +79,7 @@ pub struct Configuration<G, E = NoExtension> {
/// Pruning settings. /// Pruning settings.
pub pruning: PruningMode, pub pruning: PruningMode,
/// Chain configuration. /// Chain configuration.
pub chain_spec: Option<ChainSpec<G, E>>, pub chain_spec: Option<Box<dyn ChainSpec>>,
/// Node name. /// Node name.
pub name: String, pub name: String,
/// Wasm execution method. /// Wasm execution method.
@@ -192,7 +192,7 @@ impl PrometheusConfig {
} }
} }
impl<G, E> Default for Configuration<G, E> { impl Default for Configuration {
/// Create a default config /// Create a default config
fn default() -> Self { fn default() -> Self {
Configuration { Configuration {
@@ -233,7 +233,7 @@ impl<G, E> Default for Configuration<G, E> {
} }
} }
impl<G, E> Configuration<G, E> { impl Configuration {
/// Create a default config using `VersionInfo` /// Create a default config using `VersionInfo`
pub fn from_version(version: &VersionInfo) -> Self { pub fn from_version(version: &VersionInfo) -> Self {
let mut config = Configuration::default(); let mut config = Configuration::default();
@@ -270,8 +270,8 @@ impl<G, E> Configuration<G, E> {
/// ### Panics /// ### Panics
/// ///
/// This method panic if the `chain_spec` is `None` /// This method panic if the `chain_spec` is `None`
pub fn expect_chain_spec(&self) -> &ChainSpec<G, E> { pub fn expect_chain_spec(&self) -> &dyn ChainSpec {
self.chain_spec.as_ref().expect("chain_spec must be specified") &**self.chain_spec.as_ref().expect("chain_spec must be specified")
} }
/// Return a reference to the `DatabaseConfig` of this `Configuration`. /// Return a reference to the `DatabaseConfig` of this `Configuration`.
+7 -5
View File
@@ -59,7 +59,9 @@ pub use self::builder::{
TFullCallExecutor, TLightCallExecutor, TFullCallExecutor, TLightCallExecutor,
}; };
pub use config::{Configuration, Roles, PruningMode}; pub use config::{Configuration, Roles, PruningMode};
pub use sc_chain_spec::{ChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension}; pub use sc_chain_spec::{
ChainSpec, GenericChainSpec, Properties, RuntimeGenesis, Extension as ChainSpecExtension
};
pub use sp_transaction_pool::{TransactionPool, InPoolTransaction, error::IntoPoolError}; pub use sp_transaction_pool::{TransactionPool, InPoolTransaction, error::IntoPoolError};
pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions; pub use sc_transaction_pool::txpool::Options as TransactionPoolOptions;
pub use sc_client::FinalityNotifications; pub use sc_client::FinalityNotifications;
@@ -487,8 +489,8 @@ mod waiting {
/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. /// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive.
#[cfg(not(target_os = "unknown"))] #[cfg(not(target_os = "unknown"))]
fn start_rpc_servers<G, E, H: FnMut() -> sc_rpc_server::RpcHandler<sc_rpc::Metadata>>( fn start_rpc_servers<H: FnMut() -> sc_rpc_server::RpcHandler<sc_rpc::Metadata>>(
config: &Configuration<G, E>, config: &Configuration,
mut gen_handler: H mut gen_handler: H
) -> Result<Box<dyn std::any::Any + Send + Sync>, error::Error> { ) -> Result<Box<dyn std::any::Any + Send + Sync>, error::Error> {
fn maybe_start_server<T, F>(address: Option<SocketAddr>, mut start: F) -> Result<Option<T>, io::Error> fn maybe_start_server<T, F>(address: Option<SocketAddr>, mut start: F) -> Result<Option<T>, io::Error>
@@ -528,8 +530,8 @@ fn start_rpc_servers<G, E, H: FnMut() -> sc_rpc_server::RpcHandler<sc_rpc::Metad
/// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. /// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive.
#[cfg(target_os = "unknown")] #[cfg(target_os = "unknown")]
fn start_rpc_servers<G, E, H: FnMut() -> sc_rpc_server::RpcHandler<sc_rpc::Metadata>>( fn start_rpc_servers<H: FnMut() -> sc_rpc_server::RpcHandler<sc_rpc::Metadata>>(
_: &Configuration<G, E>, _: &Configuration,
_: H _: H
) -> Result<Box<dyn std::any::Any + Send + Sync>, error::Error> { ) -> Result<Box<dyn std::any::Any + Send + Sync>, error::Error> {
Ok(Box::new(())) Ok(Box::new(()))
+32 -26
View File
@@ -29,9 +29,11 @@ use tokio::{runtime::Runtime, prelude::FutureExt};
use tokio::timer::Interval; use tokio::timer::Interval;
use sc_service::{ use sc_service::{
AbstractService, AbstractService,
ChainSpec, GenericChainSpec,
ChainSpecExtension,
Configuration, Configuration,
config::{DatabaseConfig, KeystoreConfig}, config::{DatabaseConfig, KeystoreConfig},
RuntimeGenesis,
Roles, Roles,
Error, Error,
}; };
@@ -48,7 +50,7 @@ struct TestNet<G, E, F, L, U> {
authority_nodes: Vec<(usize, SyncService<F>, U, Multiaddr)>, authority_nodes: Vec<(usize, SyncService<F>, U, Multiaddr)>,
full_nodes: Vec<(usize, SyncService<F>, U, Multiaddr)>, full_nodes: Vec<(usize, SyncService<F>, U, Multiaddr)>,
light_nodes: Vec<(usize, SyncService<L>, Multiaddr)>, light_nodes: Vec<(usize, SyncService<L>, Multiaddr)>,
chain_spec: ChainSpec<G, E>, chain_spec: GenericChainSpec<G, E>,
base_port: u16, base_port: u16,
nodes: usize, nodes: usize,
} }
@@ -129,15 +131,15 @@ where F: Send + 'static, L: Send +'static, U: Clone + Send + 'static
} }
} }
fn node_config<G, E: Clone> ( fn node_config<G: RuntimeGenesis + 'static, E: ChainSpecExtension + Clone + 'static> (
index: usize, index: usize,
spec: &ChainSpec<G, E>, spec: &GenericChainSpec<G, E>,
role: Roles, role: Roles,
task_executor: Arc<dyn Fn(Pin<Box<dyn futures::Future<Output = ()> + Send>>) + Send + Sync>, task_executor: Arc<dyn Fn(Pin<Box<dyn futures::Future<Output = ()> + Send>>) + Send + Sync>,
key_seed: Option<String>, key_seed: Option<String>,
base_port: u16, base_port: u16,
root: &TempDir, root: &TempDir,
) -> Configuration<G, E> ) -> Configuration
{ {
let root = root.path().join(format!("node-{}", index)); let root = root.path().join(format!("node-{}", index));
@@ -191,7 +193,7 @@ fn node_config<G, E: Clone> (
state_cache_size: 16777216, state_cache_size: 16777216,
state_cache_child_ratio: None, state_cache_child_ratio: None,
pruning: Default::default(), pruning: Default::default(),
chain_spec: Some((*spec).clone()), chain_spec: Some(Box::new((*spec).clone())),
name: format!("Node {}", index), name: format!("Node {}", index),
wasm_method: sc_service::config::WasmExecutionMethod::Interpreted, wasm_method: sc_service::config::WasmExecutionMethod::Interpreted,
execution_strategies: Default::default(), execution_strategies: Default::default(),
@@ -217,16 +219,17 @@ fn node_config<G, E: Clone> (
impl<G, E, F, L, U> TestNet<G, E, F, L, U> where impl<G, E, F, L, U> TestNet<G, E, F, L, U> where
F: AbstractService, F: AbstractService,
L: AbstractService, L: AbstractService,
E: Clone, E: ChainSpecExtension + Clone + 'static,
G: RuntimeGenesis + 'static,
{ {
fn new( fn new(
temp: &TempDir, temp: &TempDir,
spec: ChainSpec<G, E>, spec: GenericChainSpec<G, E>,
full: impl Iterator<Item = impl FnOnce(Configuration<G, E>) -> Result<(F, U), Error>>, full: impl Iterator<Item = impl FnOnce(Configuration) -> Result<(F, U), Error>>,
light: impl Iterator<Item = impl FnOnce(Configuration<G, E>) -> Result<L, Error>>, light: impl Iterator<Item = impl FnOnce(Configuration) -> Result<L, Error>>,
authorities: impl Iterator<Item = ( authorities: impl Iterator<Item = (
String, String,
impl FnOnce(Configuration<G, E>) -> Result<(F, U), Error> impl FnOnce(Configuration) -> Result<(F, U), Error>
)>, )>,
base_port: u16 base_port: u16
) -> TestNet<G, E, F, L, U> { ) -> TestNet<G, E, F, L, U> {
@@ -249,9 +252,9 @@ impl<G, E, F, L, U> TestNet<G, E, F, L, U> where
fn insert_nodes( fn insert_nodes(
&mut self, &mut self,
temp: &TempDir, temp: &TempDir,
full: impl Iterator<Item = impl FnOnce(Configuration<G, E>) -> Result<(F, U), Error>>, full: impl Iterator<Item = impl FnOnce(Configuration) -> Result<(F, U), Error>>,
light: impl Iterator<Item = impl FnOnce(Configuration<G, E>) -> Result<L, Error>>, light: impl Iterator<Item = impl FnOnce(Configuration) -> Result<L, Error>>,
authorities: impl Iterator<Item = (String, impl FnOnce(Configuration<G, E>) -> Result<(F, U), Error>)> authorities: impl Iterator<Item = (String, impl FnOnce(Configuration) -> Result<(F, U), Error>)>
) { ) {
let executor = self.runtime.executor(); let executor = self.runtime.executor();
@@ -317,14 +320,15 @@ fn tempdir_with_prefix(prefix: &str) -> TempDir {
} }
pub fn connectivity<G, E, Fb, F, Lb, L>( pub fn connectivity<G, E, Fb, F, Lb, L>(
spec: ChainSpec<G, E>, spec: GenericChainSpec<G, E>,
full_builder: Fb, full_builder: Fb,
light_builder: Lb, light_builder: Lb,
) where ) where
E: Clone, E: ChainSpecExtension + Clone + 'static,
Fb: Fn(Configuration<G, E>) -> Result<F, Error>, G: RuntimeGenesis + 'static,
Fb: Fn(Configuration) -> Result<F, Error>,
F: AbstractService, F: AbstractService,
Lb: Fn(Configuration<G, E>) -> Result<L, Error>, Lb: Fn(Configuration) -> Result<L, Error>,
L: AbstractService, L: AbstractService,
{ {
const NUM_FULL_NODES: usize = 5; const NUM_FULL_NODES: usize = 5;
@@ -415,20 +419,21 @@ pub fn connectivity<G, E, Fb, F, Lb, L>(
} }
pub fn sync<G, E, Fb, F, Lb, L, B, ExF, U>( pub fn sync<G, E, Fb, F, Lb, L, B, ExF, U>(
spec: ChainSpec<G, E>, spec: GenericChainSpec<G, E>,
full_builder: Fb, full_builder: Fb,
light_builder: Lb, light_builder: Lb,
mut make_block_and_import: B, mut make_block_and_import: B,
mut extrinsic_factory: ExF mut extrinsic_factory: ExF
) where ) where
Fb: Fn(Configuration<G, E>) -> Result<(F, U), Error>, Fb: Fn(Configuration) -> Result<(F, U), Error>,
F: AbstractService, F: AbstractService,
Lb: Fn(Configuration<G, E>) -> Result<L, Error>, Lb: Fn(Configuration) -> Result<L, Error>,
L: AbstractService, L: AbstractService,
B: FnMut(&F, &mut U), B: FnMut(&F, &mut U),
ExF: FnMut(&F, &U) -> <F::Block as BlockT>::Extrinsic, ExF: FnMut(&F, &U) -> <F::Block as BlockT>::Extrinsic,
U: Clone + Send + 'static, U: Clone + Send + 'static,
E: Clone, E: ChainSpecExtension + Clone + 'static,
G: RuntimeGenesis + 'static,
{ {
const NUM_FULL_NODES: usize = 10; const NUM_FULL_NODES: usize = 10;
// FIXME: BABE light client support is currently not working. // FIXME: BABE light client support is currently not working.
@@ -485,16 +490,17 @@ pub fn sync<G, E, Fb, F, Lb, L, B, ExF, U>(
} }
pub fn consensus<G, E, Fb, F, Lb, L>( pub fn consensus<G, E, Fb, F, Lb, L>(
spec: ChainSpec<G, E>, spec: GenericChainSpec<G, E>,
full_builder: Fb, full_builder: Fb,
light_builder: Lb, light_builder: Lb,
authorities: impl IntoIterator<Item = String> authorities: impl IntoIterator<Item = String>
) where ) where
Fb: Fn(Configuration<G, E>) -> Result<F, Error>, Fb: Fn(Configuration) -> Result<F, Error>,
F: AbstractService, F: AbstractService,
Lb: Fn(Configuration<G, E>) -> Result<L, Error>, Lb: Fn(Configuration) -> Result<L, Error>,
L: AbstractService, L: AbstractService,
E: Clone, E: ChainSpecExtension + Clone + 'static,
G: RuntimeGenesis + 'static,
{ {
const NUM_FULL_NODES: usize = 10; const NUM_FULL_NODES: usize = 10;
const NUM_LIGHT_NODES: usize = 10; const NUM_LIGHT_NODES: usize = 10;
+2 -2
View File
@@ -243,10 +243,10 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
Block: BlockT, Block: BlockT,
{ {
/// Creates new Substrate Client with given blockchain and code executor. /// Creates new Substrate Client with given blockchain and code executor.
pub fn new<S: BuildStorage>( pub fn new(
backend: Arc<B>, backend: Arc<B>,
executor: E, executor: E,
build_genesis_storage: &S, build_genesis_storage: &dyn BuildStorage,
fork_blocks: ForkBlocks<Block>, fork_blocks: ForkBlocks<Block>,
bad_blocks: BadBlocks<Block>, bad_blocks: BadBlocks<Block>,
execution_extensions: ExecutionExtensions<Block>, execution_extensions: ExecutionExtensions<Block>,
+2 -3
View File
@@ -55,9 +55,9 @@ pub fn new_light_backend<B, S>(blockchain: Arc<Blockchain<S>>) -> Arc<Backend<S,
} }
/// Create an instance of light client. /// Create an instance of light client.
pub fn new_light<B, S, GS, RA, E>( pub fn new_light<B, S, RA, E>(
backend: Arc<Backend<S, HashFor<B>>>, backend: Arc<Backend<S, HashFor<B>>>,
genesis_storage: &GS, genesis_storage: &dyn BuildStorage,
code_executor: E, code_executor: E,
prometheus_registry: Option<Registry>, prometheus_registry: Option<Registry>,
) -> ClientResult< ) -> ClientResult<
@@ -74,7 +74,6 @@ pub fn new_light<B, S, GS, RA, E>(
where where
B: BlockT, B: BlockT,
S: BlockchainStorage<B> + 'static, S: BlockchainStorage<B> + 'static,
GS: BuildStorage,
E: CodeExecutor + RuntimeInfo + Clone + 'static, E: CodeExecutor + RuntimeInfo + Clone + 'static,
{ {
let local_executor = LocalCallExecutor::new(backend.clone(), code_executor); let local_executor = LocalCallExecutor::new(backend.clone(), code_executor);
+1 -1
View File
@@ -101,7 +101,7 @@ use crate::traits::IdentifyAccount;
/// Complex storage builder stuff. /// Complex storage builder stuff.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub trait BuildStorage: Sized { pub trait BuildStorage {
/// Build the storage out of this builder. /// Build the storage out of this builder.
fn build_storage(&self) -> Result<sp_core::storage::Storage, String> { fn build_storage(&self) -> Result<sp_core::storage::Storage, String> {
let mut storage = Default::default(); let mut storage = Default::default();
+6 -6
View File
@@ -19,7 +19,7 @@ use log::{debug, info};
use std::sync::Arc; use std::sync::Arc;
use sc_service::{ use sc_service::{
AbstractService, RpcSession, Roles, Configuration, config::{DatabaseConfig, KeystoreConfig}, AbstractService, RpcSession, Roles, Configuration, config::{DatabaseConfig, KeystoreConfig},
ChainSpec, RuntimeGenesis GenericChainSpec, RuntimeGenesis
}; };
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use futures::{prelude::*, channel::{oneshot, mpsc}, future::{poll_fn, ok}, compat::*}; use futures::{prelude::*, channel::{oneshot, mpsc}, future::{poll_fn, ok}, compat::*};
@@ -34,11 +34,11 @@ pub use console_log::init_with_level as init_console_log;
/// Create a service configuration from a chain spec. /// Create a service configuration from a chain spec.
/// ///
/// This configuration contains good defaults for a browser light client. /// This configuration contains good defaults for a browser light client.
pub async fn browser_configuration<G, E>(chain_spec: ChainSpec<G, E>) pub async fn browser_configuration<G, E>(chain_spec: GenericChainSpec<G, E>)
-> Result<Configuration<G, E>, Box<dyn std::error::Error>> -> Result<Configuration, Box<dyn std::error::Error>>
where where
G: RuntimeGenesis, G: RuntimeGenesis + 'static,
E: Extension, E: Extension + 'static,
{ {
let name = chain_spec.name().to_string(); let name = chain_spec.name().to_string();
@@ -46,7 +46,7 @@ where
let mut config = Configuration::default(); let mut config = Configuration::default();
config.network.boot_nodes = chain_spec.boot_nodes().to_vec(); config.network.boot_nodes = chain_spec.boot_nodes().to_vec();
config.telemetry_endpoints = chain_spec.telemetry_endpoints().clone(); config.telemetry_endpoints = chain_spec.telemetry_endpoints().clone();
config.chain_spec = Some(chain_spec); config.chain_spec = Some(Box::new(chain_spec));
config.network.transport = sc_network::config::TransportConfig::Normal { config.network.transport = sc_network::config::TransportConfig::Normal {
wasm_external_transport: Some(transport.clone()), wasm_external_transport: Some(transport.clone()),
allow_private_ipv4: true, allow_private_ipv4: true,
@@ -14,12 +14,12 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>. // along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use std::{fmt::Debug, path::PathBuf}; use std::fmt::Debug;
use sp_runtime::{BuildStorage, traits::{Block as BlockT, Header as HeaderT, NumberFor}}; use sp_runtime::{traits::{Block as BlockT, Header as HeaderT, NumberFor}};
use sc_client::StateMachine; use sc_client::StateMachine;
use sc_cli::{ExecutionStrategy, WasmExecutionMethod, VersionInfo}; use sc_cli::{ExecutionStrategy, WasmExecutionMethod, VersionInfo};
use sc_client_db::BenchmarkingState; use sc_client_db::BenchmarkingState;
use sc_service::{RuntimeGenesis, ChainSpecExtension, Configuration, ChainSpec}; use sc_service::{Configuration, ChainSpec};
use sc_executor::{NativeExecutor, NativeExecutionDispatch}; use sc_executor::{NativeExecutor, NativeExecutionDispatch};
use codec::{Encode, Decode}; use codec::{Encode, Decode};
use frame_benchmarking::BenchmarkResults; use frame_benchmarking::BenchmarkResults;
@@ -82,13 +82,11 @@ impl BenchmarkCmd {
} }
/// Runs the command and benchmarks the chain. /// Runs the command and benchmarks the chain.
pub fn run<G, E, BB, ExecDispatch>( pub fn run<BB, ExecDispatch>(
self, self,
config: Configuration<G, E>, config: Configuration,
) -> sc_cli::Result<()> ) -> sc_cli::Result<()>
where where
G: RuntimeGenesis,
E: ChainSpecExtension,
BB: BlockT + Debug, BB: BlockT + Debug,
<<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug, <<<BB as BlockT>::Header as HeaderT>::Number as std::str::FromStr>::Err: std::fmt::Debug,
<BB as BlockT>::Hash: std::str::FromStr, <BB as BlockT>::Hash: std::str::FromStr,
@@ -164,21 +162,16 @@ impl BenchmarkCmd {
} }
/// Update and prepare a `Configuration` with command line parameters /// Update and prepare a `Configuration` with command line parameters
pub fn update_config<G, E>( pub fn update_config(
&self, &self,
mut config: &mut Configuration<G, E>, mut config: &mut Configuration,
spec_factory: impl FnOnce(&str) -> Result<Option<ChainSpec<G, E>>, String>, spec_factory: impl FnOnce(&str) -> Result<Box<dyn ChainSpec>, String>,
_version: &VersionInfo, _version: &VersionInfo,
) -> sc_cli::Result<()> where ) -> sc_cli::Result<()>
G: RuntimeGenesis,
E: ChainSpecExtension,
{ {
// Configure chain spec. // Configure chain spec.
let chain_key = self.shared_params.chain.clone().unwrap_or("dev".into()); let chain_key = self.shared_params.chain.clone().unwrap_or("dev".into());
let spec = match spec_factory(&chain_key)? { let spec = spec_factory(&chain_key)?;
Some(spec) => spec,
None => ChainSpec::from_json_file(PathBuf::from(chain_key))?
};
config.chain_spec = Some(spec); config.chain_spec = Some(spec);
// Make sure to configure keystore. // Make sure to configure keystore.