diff --git a/substrate/core/cli/src/lib.rs b/substrate/core/cli/src/lib.rs index 564065e0a6..be1db4f931 100644 --- a/substrate/core/cli/src/lib.rs +++ b/substrate/core/cli/src/lib.rs @@ -27,6 +27,7 @@ pub mod informant; use client::ExecutionStrategies; use service::{ + config::Configuration, ServiceFactory, FactoryFullConfiguration, RuntimeGenesis, FactoryGenesis, PruningMode, ChainSpec, }; @@ -220,17 +221,17 @@ where fdlimit::raise_fd_limit(); match cli_args { - params::CoreParams::Run(params) => run_node::( + params::CoreParams::Run(params) => run_node( params, spec_factory, exit, run_service, impl_name, version, ).map(|_| None), params::CoreParams::BuildSpec(params) => - build_spec::(params, spec_factory, version).map(|_| None), + build_spec(params, spec_factory, version).map(|_| None), params::CoreParams::ExportBlocks(params) => export_blocks::(params, spec_factory, exit, version).map(|_| None), params::CoreParams::ImportBlocks(params) => import_blocks::(params, spec_factory, exit, version).map(|_| None), params::CoreParams::PurgeChain(params) => - purge_chain::(params, spec_factory, version).map(|_| None), + purge_chain(params, spec_factory, version).map(|_| None), params::CoreParams::Revert(params) => revert_chain::(params, spec_factory, version).map(|_| None), params::CoreParams::Custom(params) => Ok(Some(params)), @@ -292,8 +293,8 @@ fn parse_ed25519_secret(hex: &String) -> error::Result( - options: &mut FactoryFullConfiguration, +fn fill_transaction_pool_configuration( + options: &mut Configuration, params: TransactionPoolParams, ) -> error::Result<()> { // ready queue @@ -384,12 +385,13 @@ fn fill_config_keystore_password( Ok(()) } -fn create_run_node_config( +fn create_run_node_config( cli: RunCmd, spec_factory: S, impl_name: &'static str, version: &VersionInfo -) -> error::Result> +) -> error::Result> where - F: ServiceFactory, - S: FnOnce(&str) -> Result>>, String>, + C: Default, + G: RuntimeGenesis, + S: FnOnce(&str) -> Result>, String>, { let spec = load_spec(&cli.shared_params, spec_factory)?; let mut config = service::Configuration::default_with_spec(spec.clone()); @@ -471,7 +473,7 @@ where is_dev, )?; - fill_transaction_pool_configuration::(&mut config, cli.pool_config)?; + fill_transaction_pool_configuration(&mut config, cli.pool_config)?; config.dev_key_seed = cli.keyring.account .map(|a| format!("//{}", a)).or_else(|| { @@ -516,7 +518,7 @@ where Ok(config) } -fn run_node( +fn run_node( cli: MergeParameters, spec_factory: S, exit: E, @@ -526,12 +528,13 @@ fn run_node( ) -> error::Result<()> where RP: StructOpt + Clone, - F: ServiceFactory, + C: Default, + G: RuntimeGenesis, E: IntoExit, - S: FnOnce(&str) -> Result>>, String>, - RS: FnOnce(E, RunCmd, RP, FactoryFullConfiguration) -> Result<(), String>, + S: FnOnce(&str) -> Result>, String>, + RS: FnOnce(E, RunCmd, RP, Configuration) -> Result<(), String>, { - let config = create_run_node_config::(cli.left.clone(), spec_factory, impl_name, version)?; + let config = create_run_node_config(cli.left.clone(), spec_factory, impl_name, version)?; run_service(exit, cli.left, cli.right, config).map_err(Into::into) } @@ -544,13 +547,13 @@ where // 9803-9874 Unassigned // 9926-9949 Unassigned -fn with_default_boot_node( - spec: &mut ChainSpec>, +fn with_default_boot_node( + spec: &mut ChainSpec, cli: BuildSpecCmd, version: &VersionInfo, ) -> error::Result<()> where - F: ServiceFactory + G: RuntimeGenesis { if spec.boot_nodes().is_empty() { let base_path = base_path(&cli.shared_params, version); @@ -568,20 +571,20 @@ where Ok(()) } -fn build_spec( +fn build_spec( cli: BuildSpecCmd, spec_factory: S, version: &VersionInfo, ) -> error::Result<()> where - F: ServiceFactory, - S: FnOnce(&str) -> Result>>, String>, + G: RuntimeGenesis, + S: FnOnce(&str) -> Result>, String>, { info!("Building chain spec"); let raw_output = cli.raw; let mut spec = load_spec(&cli.shared_params, spec_factory)?; - with_default_boot_node::(&mut spec, cli, version)?; - let json = service::chain_ops::build_spec::>(spec, raw_output)?; + with_default_boot_node(&mut spec, cli, version)?; + let json = service::chain_ops::build_spec(spec, raw_output)?; print!("{}", json); @@ -589,12 +592,13 @@ where } /// Creates a configuration including the database path. -pub fn create_config_with_db_path( +pub fn create_config_with_db_path( spec_factory: S, cli: &SharedParams, version: &VersionInfo, -) -> error::Result> +) -> error::Result> where - F: ServiceFactory, - S: FnOnce(&str) -> Result>>, String>, + C: Default, + G: RuntimeGenesis, + S: FnOnce(&str) -> Result>, String>, { let spec = load_spec(cli, spec_factory)?; let base_path = base_path(cli, version); @@ -616,7 +620,7 @@ where E: IntoExit, S: FnOnce(&str) -> Result>>, String>, { - let config = create_config_with_db_path::(spec_factory, &cli.shared_params, version)?; + let config = create_config_with_db_path(spec_factory, &cli.shared_params, version)?; info!("DB path: {}", config.database_path.display()); let from = cli.from.unwrap_or(1); @@ -649,7 +653,7 @@ where E: IntoExit, S: FnOnce(&str) -> Result>>, String>, { - let mut config = create_config_with_db_path::(spec_factory, &cli.shared_params, version)?; + let mut config = create_config_with_db_path(spec_factory, &cli.shared_params, version)?; config.execution_strategies = ExecutionStrategies { importing: cli.execution.into(), other: cli.execution.into(), @@ -679,21 +683,21 @@ where F: ServiceFactory, S: FnOnce(&str) -> Result>>, String>, { - let config = create_config_with_db_path::(spec_factory, &cli.shared_params, version)?; + let config = create_config_with_db_path(spec_factory, &cli.shared_params, version)?; let blocks = cli.num; Ok(service::chain_ops::revert_chain::(config, blocks.into())?) } -fn purge_chain( +fn purge_chain( cli: PurgeChainCmd, spec_factory: S, version: &VersionInfo, ) -> error::Result<()> where - F: ServiceFactory, - S: FnOnce(&str) -> Result>>, String>, + G: RuntimeGenesis, + S: FnOnce(&str) -> Result>, String>, { - let config = create_config_with_db_path::(spec_factory, &cli.shared_params, version)?; + let config = create_config_with_db_path::<(), _, _>(spec_factory, &cli.shared_params, version)?; let db_path = config.database_path; if cli.yes == false { diff --git a/substrate/core/service/src/chain_spec.rs b/substrate/core/service/src/chain_spec.rs index bae353ceb9..8d84b4880c 100644 --- a/substrate/core/service/src/chain_spec.rs +++ b/substrate/core/service/src/chain_spec.rs @@ -127,7 +127,7 @@ impl Clone for ChainSpec { } } -impl ChainSpec { +impl ChainSpec { /// A list of bootnode addresses. pub fn boot_nodes(&self) -> &[String] { &self.spec.boot_nodes @@ -215,7 +215,9 @@ impl ChainSpec { genesis: GenesisSource::Factory(constructor), } } +} +impl ChainSpec { /// Dump to json string. pub fn to_json(self, raw: bool) -> Result { #[derive(Serialize, Deserialize)] diff --git a/substrate/core/service/src/components.rs b/substrate/core/service/src/components.rs index 2ca99e0b31..fb869df020 100644 --- a/substrate/core/service/src/components.rs +++ b/substrate/core/service/src/components.rs @@ -506,6 +506,16 @@ impl Future for FullComponents { } } +impl Executor + Send>> +for FullComponents { + fn execute( + &self, + future: Box + Send> + ) -> Result<(), futures::future::ExecuteError + Send>>> { + self.service.execute(future) + } +} + impl Components for FullComponents { type Factory = Factory; type Executor = FullExecutor; @@ -606,6 +616,12 @@ impl Deref for LightComponents { } } +impl DerefMut for LightComponents { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.service + } +} + impl Future for LightComponents { type Item = (); type Error = (); @@ -615,6 +631,16 @@ impl Future for LightComponents { } } +impl Executor + Send>> +for LightComponents { + fn execute( + &self, + future: Box + Send> + ) -> Result<(), futures::future::ExecuteError + Send>>> { + self.service.execute(future) + } +} + impl Components for LightComponents { type Factory = Factory; type Executor = LightExecutor; diff --git a/substrate/core/service/src/lib.rs b/substrate/core/service/src/lib.rs index 8b8c0893d3..2940bde7cf 100644 --- a/substrate/core/service/src/lib.rs +++ b/substrate/core/service/src/lib.rs @@ -93,7 +93,7 @@ pub struct Service { /// The elements must then be polled manually. to_poll: Vec + Send>>, /// Configuration of this Service - pub config: FactoryFullConfiguration, + config: FactoryFullConfiguration, rpc_handlers: rpc::RpcHandler, _rpc: Box, _telemetry: Option, @@ -149,13 +149,6 @@ pub struct TelemetryOnConnect { } impl Service { - /// Get event stream for telemetry connection established events. - pub fn telemetry_on_connect_stream(&self) -> TelemetryOnConnectNotifications { - let (sink, stream) = mpsc::unbounded(); - self._telemetry_on_connect_sinks.lock().push(sink); - stream - } - /// Creates a new service. pub fn new( mut config: FactoryFullConfiguration, @@ -200,7 +193,7 @@ impl Service { let transaction_pool = Arc::new( Components::build_transaction_pool(config.transaction_pool.clone(), client.clone())? ); - let transaction_pool_adapter = Arc::new(TransactionPoolAdapter:: { + let transaction_pool_adapter = Arc::new(TransactionPoolAdapter { imports_external_transactions: !config.roles.is_light(), pool: transaction_pool.clone(), client: client.clone(), @@ -383,9 +376,9 @@ impl Service { ) }; let rpc_handlers = gen_handler(); - let rpc = start_rpc_servers::(&config, gen_handler)?; + let rpc = start_rpc_servers(&config, gen_handler)?; - let _ = to_spawn_tx.unbounded_send(Box::new(build_network_future::( + let _ = to_spawn_tx.unbounded_send(Box::new(build_network_future( network_mut, client.clone(), network_status_sinks.clone(), @@ -460,6 +453,27 @@ impl Service { }) } + /// Returns a reference to the config passed at initialization. + pub fn config(&self) -> &FactoryFullConfiguration { + &self.config + } + + /// Returns a reference to the config passed at initialization. + /// + /// > **Note**: This method is currently necessary because we extract some elements from the + /// > configuration at the end of the service initialization. It is intended to be + /// > removed. + pub fn config_mut(&mut self) -> &mut FactoryFullConfiguration { + &mut self.config + } + + /// Get event stream for telemetry connection established events. + pub fn telemetry_on_connect_stream(&self) -> TelemetryOnConnectNotifications { + let (sink, stream) = mpsc::unbounded(); + self._telemetry_on_connect_sinks.lock().push(sink); + stream + } + /// Return a shared instance of Telemetry (if enabled) pub fn telemetry(&self) -> Option { self._telemetry.as_ref().map(|t| t.clone()) @@ -577,14 +591,15 @@ impl Executor + Send>> /// /// The `status_sink` contain a list of senders to send a periodic network status to. fn build_network_future< - Components: components::Components, - S: network::specialization::NetworkSpecialization>, + B: BlockT, + C: client::BlockchainEvents, + S: network::specialization::NetworkSpecialization, H: network::ExHashT > ( - mut network: network::NetworkWorker, S, H>, - client: Arc>, - status_sinks: Arc>, NetworkState)>>>>, - rpc_rx: futures03::channel::mpsc::UnboundedReceiver>>, + mut network: network::NetworkWorker, + client: Arc, + status_sinks: Arc, NetworkState)>>>>, + rpc_rx: futures03::channel::mpsc::UnboundedReceiver>, should_have_peers: bool, ) -> impl Future { // Compatibility shim while we're transitionning to stable Futures. @@ -710,8 +725,8 @@ impl Drop for Service where Components: components::Comp /// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. #[cfg(not(target_os = "unknown"))] -fn start_rpc_servers rpc::RpcHandler>( - config: &FactoryFullConfiguration, +fn start_rpc_servers rpc::RpcHandler>( + config: &Configuration, mut gen_handler: H ) -> Result, error::Error> { fn maybe_start_server(address: Option, mut start: F) -> Result, io::Error> @@ -751,8 +766,8 @@ fn start_rpc_servers rpc::RpcHandler>( /// Starts RPC servers that run in their own thread, and returns an opaque object that keeps them alive. #[cfg(target_os = "unknown")] -fn start_rpc_servers rpc::RpcHandler>( - _: &FactoryFullConfiguration, +fn start_rpc_servers rpc::RpcHandler>( + _: &Configuration, _: H ) -> Result, error::Error> { Ok(Box::new(())) @@ -779,16 +794,10 @@ impl RpcSession { } /// Transaction pool adapter. -pub struct TransactionPoolAdapter { +pub struct TransactionPoolAdapter { imports_external_transactions: bool, - pool: Arc>, - client: Arc>, -} - -impl TransactionPoolAdapter { - fn best_block_id(&self) -> Option>> { - Some(BlockId::hash(self.client.info().chain.best_hash)) - } + pool: Arc

, + client: Arc, } /// Get transactions for propagation. @@ -812,14 +821,20 @@ where .collect() } -impl network::TransactionPool, ComponentBlock> for - TransactionPoolAdapter where ::RuntimeApi: Send + Sync +impl network::TransactionPool for + TransactionPoolAdapter> +where + C: network::ClientHandle + Send + Sync, + PoolApi: ChainApi, + B: BlockT, + H: std::hash::Hash + Eq + sr_primitives::traits::Member + serde::Serialize, + E: txpool::error::IntoPoolError + From, { - fn transactions(&self) -> Vec<(ComponentExHash, ComponentExtrinsic)> { + fn transactions(&self) -> Vec<(H, ::Extrinsic)> { transactions_to_propagate(&self.pool) } - fn import(&self, transaction: &ComponentExtrinsic) -> Option> { + fn import(&self, transaction: &::Extrinsic) -> Option { if !self.imports_external_transactions { debug!("Transaction rejected"); return None; @@ -828,12 +843,12 @@ impl network::TransactionPool, ComponentBlock< let encoded = transaction.encode(); match Decode::decode(&mut &encoded[..]) { Ok(uxt) => { - let best_block_id = self.best_block_id()?; + let best_block_id = BlockId::hash(self.client.info().chain.best_hash); match self.pool.submit_one(&best_block_id, uxt) { Ok(hash) => Some(hash), Err(e) => match e.into_pool_error() { Ok(txpool::error::Error::AlreadyImported(hash)) => { - hash.downcast::>().ok() + hash.downcast::().ok() .map(|x| x.as_ref().clone()) }, Ok(e) => { @@ -854,7 +869,7 @@ impl network::TransactionPool, ComponentBlock< } } - fn on_broadcasted(&self, propagations: HashMap, Vec>) { + fn on_broadcasted(&self, propagations: HashMap>) { self.pool.on_broadcasted(propagations) } } diff --git a/substrate/node-template/src/service.rs b/substrate/node-template/src/service.rs index 31323e11ad..e903f1150b 100644 --- a/substrate/node-template/src/service.rs +++ b/substrate/node-template/src/service.rs @@ -83,8 +83,8 @@ construct_service_factory! { client, proposer, service.network(), - service.config.custom.inherent_data_providers.clone(), - service.config.force_authoring, + service.config().custom.inherent_data_providers.clone(), + service.config().force_authoring, )?; service.spawn_task(Box::new(aura.select(service.on_exit()).then(|_| Ok(())))); } diff --git a/substrate/node/cli/src/factory_impl.rs b/substrate/node/cli/src/factory_impl.rs index 41ac992abb..6e72ff08c1 100644 --- a/substrate/node/cli/src/factory_impl.rs +++ b/substrate/node/cli/src/factory_impl.rs @@ -26,10 +26,8 @@ use keyring::sr25519::Keyring; use node_runtime::{Call, CheckedExtrinsic, UncheckedExtrinsic, SignedExtra, BalancesCall, ExistentialDeposit}; use primitives::{sr25519, crypto::Pair}; use sr_primitives::{generic::Era, traits::{Block as BlockT, Header as HeaderT, SignedExtension}}; -use substrate_service::ServiceFactory; use transaction_factory::RuntimeAdapter; use transaction_factory::modes::Mode; -use crate::service; use inherents::InherentData; use timestamp; use finality_tracker; @@ -140,7 +138,7 @@ impl RuntimeAdapter for FactoryState { let index = self.extract_index(&sender, prior_block_hash); let phase = self.extract_phase(*prior_block_hash); - sign::(CheckedExtrinsic { + sign::(CheckedExtrinsic { signed: Some((sender.clone(), Self::build_extra(index, phase))), function: Call::Balances( BalancesCall::transfer( @@ -233,7 +231,7 @@ fn gen_seed_bytes(seed: u64) -> [u8; 32] { /// Creates an `UncheckedExtrinsic` containing the appropriate signature for /// a `CheckedExtrinsics`. -fn sign( +fn sign( xt: CheckedExtrinsic, key: &sr25519::Pair, additional_signed: ::AdditionalSigned, diff --git a/substrate/node/cli/src/lib.rs b/substrate/node/cli/src/lib.rs index adf9d81fa7..71cb19001d 100644 --- a/substrate/node/cli/src/lib.rs +++ b/substrate/node/cli/src/lib.rs @@ -186,7 +186,7 @@ pub fn run(args: I, exit: E, version: cli::VersionInfo) -> error::Resul match &ret { Ok(Some(CustomSubcommands::Factory(cli_args))) => { - let mut config = cli::create_config_with_db_path::( + let mut config = cli::create_config_with_db_path( load_spec, &cli_args.shared_params, &version, diff --git a/substrate/node/cli/src/service.rs b/substrate/node/cli/src/service.rs index 0fc97e99d5..e69e0ce233 100644 --- a/substrate/node/cli/src/service.rs +++ b/substrate/node/cli/src/service.rs @@ -99,11 +99,11 @@ construct_service_factory! { FullComponents::::new(config) }, AuthoritySetup = { |mut service: Self::FullService| { - let (block_import, link_half, babe_link) = service.config.custom.import_setup.take() + let (block_import, link_half, babe_link) = service.config_mut().custom.import_setup.take() .expect("Link Half and Block Import are present for Full Services or setup failed before. qed"); // spawn any futures that were created in the previous setup steps - if let Some(tasks) = service.config.custom.tasks_to_spawn.take() { + if let Some(tasks) = service.config_mut().custom.tasks_to_spawn.take() { for task in tasks { service.spawn_task( task.select(service.on_exit()) @@ -129,8 +129,8 @@ construct_service_factory! { block_import, env: proposer, sync_oracle: service.network(), - inherent_data_providers: service.config.custom.inherent_data_providers.clone(), - force_authoring: service.config.force_authoring, + inherent_data_providers: service.config().custom.inherent_data_providers.clone(), + force_authoring: service.config().force_authoring, time_source: babe_link, }; @@ -142,12 +142,12 @@ construct_service_factory! { // FIXME #1578 make this available through chainspec gossip_duration: Duration::from_millis(333), justification_period: 4096, - name: Some(service.config.name.clone()), + name: Some(service.config().name.clone()), keystore: Some(service.keystore()), }; - if !service.config.disable_grandpa { - if service.config.roles.is_authority() { + if !service.config().disable_grandpa { + if service.config().roles.is_authority() { let telemetry_on_connect = TelemetryOnConnect { telemetry_connection_sinks: service.telemetry_on_connect_stream(), }; @@ -155,7 +155,7 @@ construct_service_factory! { config: config, link: link_half, network: service.network(), - inherent_data_providers: service.config.custom.inherent_data_providers.clone(), + inherent_data_providers: service.config().custom.inherent_data_providers.clone(), on_exit: service.on_exit(), telemetry_on_connect: Some(telemetry_on_connect), }; @@ -331,7 +331,7 @@ mod tests { let block_factory = |service: &SyncService<::FullService>| { let service = service.get(); let mut inherent_data = service - .config + .config() .custom .inherent_data_providers .create_inherent_data()