difftreelog
refactor merge with new node template
in: master
6 files changed
node/src/chain_spec.rsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556// use nft_runtime::{7// AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, Signature, SudoConfig,8// SystemConfig, WASM_BINARY,9// };10// use nft_runtime::{ContractsConfig, ContractsSchedule, NftConfig, CollectionType};11use nft_runtime::*;6use nft_runtime::*;12use sc_service::ChainType;7use sp_core::{Pair, Public, sr25519};8use nft_runtime::{9 AccountId, AuraConfig, BalancesConfig, EVMConfig, EthereumConfig, GenesisConfig, GrandpaConfig,10 SudoConfig, SystemConfig, WASM_BINARY, Signature11};13use sp_consensus_aura::sr25519::AuthorityId as AuraId;12use sp_consensus_aura::sr25519::AuthorityId as AuraId;14use sp_core::{sr25519, Pair, Public};15use sp_finality_grandpa::AuthorityId as GrandpaId;13use sp_finality_grandpa::AuthorityId as GrandpaId;16use sp_runtime::traits::{IdentifyAccount, Verify};14use sp_runtime::traits::{Verify, IdentifyAccount};15use sc_service::ChainType;17use serde_json::map::Map;16use serde_json::map::Map;18// use crate::chain_spec::api::chain_extension::*;17use std::collections::BTreeMap;191820// Note this is the URL for the telemetry server19// Note this is the URL for the telemetry server21//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";20//const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";150 ];149 ];151150152 GenesisConfig {151 GenesisConfig {153 system: Some(SystemConfig {152 system: SystemConfig {154 code: wasm_binary.to_vec(),153 code: wasm_binary.to_vec(),155 changes_trie_config: Default::default(),154 changes_trie_config: Default::default(),156 }),155 },157 pallet_balances: Some(BalancesConfig {156 pallet_balances: BalancesConfig {158 balances: endowed_accounts157 balances: endowed_accounts159 .iter()158 .iter()160 .cloned()159 .cloned()161 .map(|k| (k, 1 << 100))160 .map(|k| (k, 1 << 100))162 .collect(),161 .collect(),163 }),162 },164 pallet_aura: Some(AuraConfig {163 pallet_aura: AuraConfig {165 authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),164 authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(),166 }),165 },167 pallet_grandpa: Some(GrandpaConfig {166 pallet_grandpa: GrandpaConfig {168 authorities: initial_authorities167 authorities: initial_authorities169 .iter()168 .iter()170 .map(|x| (x.1.clone(), 1))169 .map(|x| (x.1.clone(), 1))171 .collect(),170 .collect(),172 }),171 },173 pallet_treasury: Some(Default::default()),172 pallet_treasury: Default::default(),174 pallet_sudo: Some(SudoConfig { key: root_key }),173 pallet_sudo: SudoConfig { key: root_key },175 pallet_vesting: Some(VestingConfig {174 pallet_vesting: VestingConfig {176 vesting: vested_accounts175 vesting: vested_accounts177 .iter()176 .iter()178 .cloned()177 .cloned()179 .map(|k| (k, 1000, 100, 1 << 98))178 .map(|k| (k, 1000, 100, 1 << 98))180 .collect(),179 .collect(),181 }),180 },182 pallet_nft: Some(NftConfig {181 pallet_nft: NftConfig {183 collection_id: vec![(182 collection_id: vec![(184 1,183 1,185 Collection {184 Collection {214 variable_on_chain_schema_limit: 1024,213 variable_on_chain_schema_limit: 1024,215 const_on_chain_schema_limit: 1024,214 const_on_chain_schema_limit: 1024,216 },215 },217 }),216 },218 pallet_contracts: Some(ContractsConfig {217 pallet_contracts: ContractsConfig {219 current_schedule: ContractsSchedule {218 current_schedule: ContractsSchedule {220 enable_println,219 enable_println,221 ..Default::default()220 ..Default::default()222 },221 },223 }),222 },223 pallet_evm: EVMConfig {224 accounts: BTreeMap::new(),225 },226 pallet_ethereum: EthereumConfig {},224 }227 }225}228}226229node/src/command.rsdiffbeforeafterboth75 let runner = cli.create_runner(cmd)?;75 let runner = cli.create_runner(cmd)?;76 runner.async_run(|config| {76 runner.async_run(|config| {77 let PartialComponents { client, task_manager, import_queue, ..}77 let PartialComponents { client, task_manager, import_queue, ..}78 = service::new_partial(&config)?;78 = service::new_partial(&config, &cli)?;79 Ok((cmd.run(client, import_queue), task_manager))79 Ok((cmd.run(client, import_queue), task_manager))80 })80 })81 },81 },82 Some(Subcommand::ExportBlocks(cmd)) => {82 Some(Subcommand::ExportBlocks(cmd)) => {83 let runner = cli.create_runner(cmd)?;83 let runner = cli.create_runner(cmd)?;84 runner.async_run(|config| {84 runner.async_run(|config| {85 let PartialComponents { client, task_manager, ..}85 let PartialComponents { client, task_manager, ..}86 = service::new_partial(&config)?;86 = service::new_partial(&config, &cli)?;87 Ok((cmd.run(client, config.database), task_manager))87 Ok((cmd.run(client, config.database), task_manager))88 })88 })89 },89 },90 Some(Subcommand::ExportState(cmd)) => {90 Some(Subcommand::ExportState(cmd)) => {91 let runner = cli.create_runner(cmd)?;91 let runner = cli.create_runner(cmd)?;92 runner.async_run(|config| {92 runner.async_run(|config| {93 let PartialComponents { client, task_manager, ..}93 let PartialComponents { client, task_manager, ..}94 = service::new_partial(&config)?;94 = service::new_partial(&config, &cli)?;95 Ok((cmd.run(client, config.chain_spec), task_manager))95 Ok((cmd.run(client, config.chain_spec), task_manager))96 })96 })97 },97 },98 Some(Subcommand::ImportBlocks(cmd)) => {98 Some(Subcommand::ImportBlocks(cmd)) => {99 let runner = cli.create_runner(cmd)?;99 let runner = cli.create_runner(cmd)?;100 runner.async_run(|config| {100 runner.async_run(|config| {101 let PartialComponents { client, task_manager, import_queue, ..}101 let PartialComponents { client, task_manager, import_queue, ..}102 = service::new_partial(&config)?;102 = service::new_partial(&config, &cli)?;103 Ok((cmd.run(client, import_queue), task_manager))103 Ok((cmd.run(client, import_queue), task_manager))104 })104 })105 },105 },111 let runner = cli.create_runner(cmd)?;111 let runner = cli.create_runner(cmd)?;112 runner.async_run(|config| {112 runner.async_run(|config| {113 let PartialComponents { client, task_manager, backend, ..}113 let PartialComponents { client, task_manager, backend, ..}114 = service::new_partial(&config)?;114 = service::new_partial(&config, &cli)?;115 Ok((cmd.run(client, backend), task_manager))115 Ok((cmd.run(client, backend), task_manager))116 })116 })117 },117 },130 runner.run_node_until_exit(|config| async move {130 runner.run_node_until_exit(|config| async move {131 match config.role {131 match config.role {132 Role::Light => service::new_light(config),132 Role::Light => service::new_light(config),133 _ => service::new_full(config),133 _ => service::new_full(config, &cli),134 }.map_err(sc_cli::Error::Service)134 }.map_err(sc_cli::Error::Service)135 })135 })136 }136 }node/src/lib.rsdiffbeforeafterbothno changes
node/src/main.rsdiffbeforeafterbothno syntactic changes
node/src/rpc.rsdiffbeforeafterboth3//! used by Substrate nodes. This file extends those RPC definitions with3//! used by Substrate nodes. This file extends those RPC definitions with4//! capabilities that are specific to this project's runtime configuration.4//! capabilities that are specific to this project's runtime configuration.56#![warn(missing_docs)]758use std::sync::Arc;6use std::sync::Arc;978use std::collections::BTreeMap;9use fc_rpc_core::types::{PendingTransactions, FilterPool};10use nft_runtime::{opaque::Block, AccountId, Balance, Index, BlockNumber};10use nft_runtime::{Hash, AccountId, Index, opaque::Block, Balance};11use sp_api::ProvideRuntimeApi;11use sp_api::ProvideRuntimeApi;12use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};12use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};13use sc_client_api::{14 backend::{StorageProvider, Backend, StateBackend, AuxStore},15 client::BlockchainEvents16};17use sc_rpc::SubscriptionTaskExecutor;18use sp_runtime::traits::BlakeTwo256;13use sp_block_builder::BlockBuilder;19use sp_block_builder::BlockBuilder;14pub use sc_rpc_api::DenyUnsafe;20use sc_rpc_api::DenyUnsafe;15use sp_transaction_pool::TransactionPool;21use sp_transaction_pool::TransactionPool;22use sc_network::NetworkService;23use jsonrpc_pubsub::manager::SubscriptionManager;24use pallet_ethereum::EthereumStorageSchema;16use pallet_contracts_rpc::{Contracts, ContractsApi};25use fc_rpc::{StorageOverride, SchemaV1Override};2627/// Light client extra dependencies.28pub struct LightDeps<C, F, P> {29 /// The client instance to use.30 pub client: Arc<C>,31 /// Transaction pool instance.32 pub pool: Arc<P>,33 /// Remote access to the blockchain (async).34 pub remote_blockchain: Arc<dyn sc_client_api::light::RemoteBlockchain<Block>>,35 /// Fetcher instance.36 pub fetcher: Arc<F>,37}173818/// Full client dependencies.39/// Full client dependencies.19pub struct FullDeps<C, P> {40pub struct FullDeps<C, P> {23 pub pool: Arc<P>,44 pub pool: Arc<P>,24 /// Whether to deny unsafe calls45 /// Whether to deny unsafe calls25 pub deny_unsafe: DenyUnsafe,46 pub deny_unsafe: DenyUnsafe,47 /// The Node authority flag48 pub is_authority: bool,49 /// Whether to enable dev signer50 pub enable_dev_signer: bool,51 /// Network service52 pub network: Arc<NetworkService<Block, Hash>>,53 /// Ethereum pending transactions.54 pub pending_transactions: PendingTransactions,55 /// EthFilterApi pool.56 pub filter_pool: Option<FilterPool>,57 /// Backend.58 pub backend: Arc<fc_db::Backend<Block>>,26}59}276028/// Instantiate all full RPC extensions.61/// Instantiate all full RPC extensions.29pub fn create_full<C, P>(62pub fn create_full<C, P, BE>(30 deps: FullDeps<C, P>,63 deps: FullDeps<C, P>,64 subscription_task_executor: SubscriptionTaskExecutor31) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where65) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where66 BE: Backend<Block> + 'static,67 BE::State: StateBackend<BlakeTwo256>,32 C: ProvideRuntimeApi<Block>,68 C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,69 C: BlockchainEvents<Block>,33 C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static,70 C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError>,34 C: Send + Sync + 'static,71 C: Send + Sync + 'static,35 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,72 C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,36 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,73 C::Api: BlockBuilder<Block>,37 C::Api: BlockBuilder<Block>,74 C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,38 C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber>,75 C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,39 P: TransactionPool + 'static,76 P: TransactionPool<Block=Block> + 'static,40{77{41 use substrate_frame_rpc_system::{FullSystem, SystemApi};78 use substrate_frame_rpc_system::{FullSystem, SystemApi};42 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};79 use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};80 use fc_rpc::{81 EthApi, EthApiServer, EthFilterApi, EthFilterApiServer, NetApi, NetApiServer,82 EthPubSubApi, EthPubSubApiServer, Web3Api, Web3ApiServer, EthDevSigner, EthSigner,83 HexEncodedIdProvider,84 };438544 let mut io = jsonrpc_core::IoHandler::default();86 let mut io = jsonrpc_core::IoHandler::default();45 let FullDeps {87 let FullDeps {46 client,88 client,47 pool,89 pool,48 deny_unsafe,90 deny_unsafe,91 is_authority,92 network,93 pending_transactions,94 filter_pool,95 backend,96 enable_dev_signer,49 } = deps;97 } = deps;509851 io.extend_with(99 io.extend_with(52 SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))100 SystemApi::to_delegate(FullSystem::new(client.clone(), pool.clone(), deny_unsafe))53 );101 );5410255 io.extend_with(103 io.extend_with(56 TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))104 TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))57 );105 );106107 // io.extend_with(108 // ContractsApi::to_delegate(Contracts::new(client.clone()))109 // );110111 let mut signers = Vec::new();112 if enable_dev_signer {113 signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);114 }115 let mut overrides = BTreeMap::new();116 overrides.insert(117 EthereumStorageSchema::V1,118 Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + Send + Sync>119 );120 io.extend_with(121 EthApiServer::to_delegate(EthApi::new(122 client.clone(),123 pool.clone(),124 nft_runtime::TransactionConverter,125 network.clone(),126 pending_transactions.clone(),127 signers,128 overrides,129 backend,130 is_authority,131 ))132 );133134 if let Some(filter_pool) = filter_pool {135 io.extend_with(136 EthFilterApiServer::to_delegate(EthFilterApi::new(137 client.clone(),138 filter_pool.clone(),139 500 as usize, // max stored filters140 ))141 );142 }143144 io.extend_with(145 NetApiServer::to_delegate(NetApi::new(146 client.clone(),147 network.clone(),148 ))149 );5815059 io.extend_with(151 io.extend_with(60 ContractsApi::to_delegate(Contracts::new(client.clone()))152 Web3ApiServer::to_delegate(Web3Api::new(153 client.clone(),154 ))61 );155 );62 15663 // Extend this RPC with a custom API by using the following syntax.157 io.extend_with(64 // `YourRpcStruct` should have a reference to a client, which is needed158 EthPubSubApiServer::to_delegate(EthPubSubApi::new(65 // to call into the runtime.159 pool.clone(),66 // `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));`160 client.clone(),161 network.clone(),162 SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(163 HexEncodedIdProvider::default(),164 Arc::new(subscription_task_executor)165 ),166 ))167 );6716868 io169 io69}170}171172/// Instantiate all Light RPC extensions.173pub fn create_light<C, P, M, F>(174 deps: LightDeps<C, F, P>,175) -> jsonrpc_core::IoHandler<M> where176 C: sp_blockchain::HeaderBackend<Block>,177 C: Send + Sync + 'static,178 F: sc_client_api::light::Fetcher<Block> + 'static,179 P: TransactionPool + 'static,180 M: jsonrpc_core::Metadata + Default,181{182 use substrate_frame_rpc_system::{LightSystem, SystemApi};183184 let LightDeps {185 client,186 pool,187 remote_blockchain,188 fetcher189 } = deps;190 let mut io = jsonrpc_core::IoHandler::default();191 io.extend_with(192 SystemApi::<Hash, AccountId, Index>::to_delegate(193 LightSystem::new(client, remote_blockchain, fetcher, pool)194 )195 );196197 io198}70199node/src/service.rsdiffbeforeafterboth5// file 'LICENSE', which is part of this source code package.5// file 'LICENSE', which is part of this source code package.6//6//778use std::sync::Arc;8use std::{sync::{Arc, Mutex}, cell::RefCell, time::Duration, collections::{HashMap, BTreeMap}};9use fc_rpc::EthTask;9use std::time::Duration;10use fc_rpc_core::types::{FilterPool, PendingTransactions};10use sc_client_api::{ExecutorProvider, RemoteBackend};11use sc_client_api::{ExecutorProvider, RemoteBackend, BlockchainEvents};12use fc_consensus::FrontierBlockImport;13use fc_mapping_sync::MappingSyncWorker;11use nft_runtime::{self, opaque::Block, RuntimeApi};14use nft_runtime::{self, opaque::Block, RuntimeApi, SLOT_DURATION};12use sc_service::{error::Error as ServiceError, Configuration, TaskManager};15use sc_service::{error::Error as ServiceError, Configuration, TaskManager, BasePath};13use sp_inherents::InherentDataProviders;16use sp_inherents::{InherentDataProviders, ProvideInherentData, InherentIdentifier, InherentData};14use sc_executor::native_executor_instance;17use sc_executor::native_executor_instance;15pub use sc_executor::NativeExecutor;18pub use sc_executor::NativeExecutor;19use sc_consensus_aura::{ImportQueueParams, StartAuraParams, SlotProportion};16use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};20use sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};17use sc_finality_grandpa::SharedVoterState;21use sc_finality_grandpa::SharedVoterState;18use sc_keystore::LocalKeystore;22use sp_timestamp::InherentError;23use sc_telemetry::{Telemetry, TelemetryWorker};24use sc_cli::SubstrateCli;25use futures::StreamExt;2627use crate::cli::Cli;192820// Our native executor instance.29// Our native executor instance.21native_executor_instance!(30native_executor_instance!(29type FullBackend = sc_service::TFullBackend<Block>;38type FullBackend = sc_service::TFullBackend<Block>;30type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;39type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;4041pub type ConsensusResult = (42 sc_consensus_aura::AuraBlockImport<43 Block,44 FullClient,45 FrontierBlockImport<46 Block,47 sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>,48 FullClient49 >,50 AuraPair51 >,52 sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>53);5455/// Provide a mock duration starting at 0 in millisecond for timestamp inherent.56/// Each call will increment timestamp by slot_duration making Aura think time has passed.57pub struct MockTimestampInherentDataProvider;5859pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0";6061thread_local!(static TIMESTAMP: RefCell<u64> = RefCell::new(0));6263impl ProvideInherentData for MockTimestampInherentDataProvider {64 fn inherent_identifier(&self) -> &'static InherentIdentifier {65 &INHERENT_IDENTIFIER66 }6768 fn provide_inherent_data(69 &self,70 inherent_data: &mut InherentData,71 ) -> Result<(), sp_inherents::Error> {72 TIMESTAMP.with(|x| {73 *x.borrow_mut() += SLOT_DURATION;74 inherent_data.put_data(INHERENT_IDENTIFIER, &*x.borrow())75 })76 }7778 fn error_to_string(&self, error: &[u8]) -> Option<String> {79 InherentError::try_from(&INHERENT_IDENTIFIER, error).map(|e| format!("{:?}", e))80 }81}8283pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {84 let config_dir = config.base_path.as_ref()85 .map(|base_path| base_path.config_dir(config.chain_spec.id()))86 .unwrap_or_else(|| {87 BasePath::from_project("", "", &crate::cli::Cli::executable_name())88 .config_dir(config.chain_spec.id())89 });90 let database_dir = config_dir.join("frontier").join("db");9192 Ok(Arc::new(fc_db::Backend::<Block>::new(&fc_db::DatabaseSettings {93 source: fc_db::DatabaseSettingsSrc::RocksDb {94 path: database_dir,95 cache_size: 0,96 }97 })?))98}319932pub fn new_partial(config: &Configuration) -> Result<sc_service::PartialComponents<100pub fn new_partial(config: &Configuration, #[allow(unused_variables)] cli: &Cli) -> Result<101 sc_service::PartialComponents<33 FullClient, FullBackend, FullSelectChain,102 FullClient, FullBackend, FullSelectChain,34 sp_consensus::DefaultImportQueue<Block, FullClient>,103 sp_consensus::import_queue::BasicQueue<Block, sp_api::TransactionFor<FullClient, Block>>,35 sc_transaction_pool::FullPool<Block, FullClient>,104 sc_transaction_pool::FullPool<Block, FullClient>,36 (105 (ConsensusResult, PendingTransactions, Option<FilterPool>, Arc<fc_db::Backend<Block>>, Option<Telemetry>),37 sc_consensus_aura::AuraBlockImport<38 Block,39 FullClient,40 sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>,41 AuraPair42 >,43 sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,44 )45>, ServiceError> {106>, ServiceError> {46 if config.keystore_remote.is_some() {107 let inherent_data_providers = sp_inherents::InherentDataProviders::new();47 return Err(ServiceError::Other(10848 format!("Remote Keystores are not supported.")))49 }50 let inherent_data_providers = sp_inherents::InherentDataProviders::new();109 let telemetry = config.telemetry_endpoints.clone()110 .filter(|x| !x.is_empty())111 .map(|endpoints| -> Result<_, sc_telemetry::Error> {112 let worker = TelemetryWorker::new(16)?;113 let telemetry = worker.handle().new_telemetry(endpoints);114 Ok((worker, telemetry))115 })116 .transpose()?;5111752 let (client, backend, keystore_container, task_manager) =118 let (client, backend, keystore_container, task_manager) =53 sc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;119 sc_service::new_full_parts::<Block, RuntimeApi, Executor>(120 &config,121 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),122 )?;54 let client = Arc::new(client);123 let client = Arc::new(client);124125 let telemetry = telemetry126 .map(|(worker, telemetry)| {127 task_manager.spawn_handle().spawn("telemetry", worker.run());128 telemetry129 });5513056 let select_chain = sc_consensus::LongestChain::new(backend.clone());131 let select_chain = sc_consensus::LongestChain::new(backend.clone());5713263 client.clone(),138 client.clone(),64 );139 );140141 let pending_transactions: PendingTransactions142 = Some(Arc::new(Mutex::new(HashMap::new())));143144 let filter_pool: Option<FilterPool>145 = Some(Arc::new(Mutex::new(BTreeMap::new())));146147 let frontier_backend = open_frontier_backend(config)?;6514866 let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(149 let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(67 client.clone(), &(client.clone() as Arc<_>), select_chain.clone(),150 client.clone(),151 &(client.clone() as Arc<_>),152 select_chain.clone(),153 telemetry.as_ref().map(|x| x.handle()),68 )?;154 )?;155156 let frontier_block_import = FrontierBlockImport::new(157 grandpa_block_import.clone(),158 client.clone(),159 frontier_backend.clone(),160 );6916170 let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(162 let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(71 grandpa_block_import.clone(), client.clone(),163 frontier_block_import, client.clone(),72 );164 );7316574 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(166 let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(167 ImportQueueParams {75 sc_consensus_aura::slot_duration(&*client)?,168 slot_duration: sc_consensus_aura::slot_duration(&*client)?,76 aura_block_import.clone(),169 block_import: aura_block_import.clone(),77 Some(Box::new(grandpa_block_import.clone())),170 justification_import: Some(Box::new(grandpa_block_import.clone())),78 client.clone(),171 client: client.clone(),79 inherent_data_providers.clone(),172 inherent_data_providers: inherent_data_providers.clone(),80 &task_manager.spawn_handle(),173 spawner: &task_manager.spawn_essential_handle(),81 config.prometheus_registry(),174 registry: config.prometheus_registry(),82 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),175 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),176 check_for_equivocation: Default::default(),177 telemetry: telemetry.as_ref().map(|x| x.handle()),178 }83 )?;179 )?;8418085 Ok(sc_service::PartialComponents {181 Ok(sc_service::PartialComponents {86 client, backend, task_manager, import_queue, keystore_container, select_chain, transaction_pool,182 client, backend, task_manager, import_queue, keystore_container,87 inherent_data_providers,183 select_chain, transaction_pool, inherent_data_providers,88 other: (aura_block_import, grandpa_link),184 other: (185 (aura_block_import, grandpa_link),186 pending_transactions,187 filter_pool,188 frontier_backend,189 telemetry,190 )89 })191 })90}192}9192fn remote_keystore(_url: &String) -> Result<Arc<LocalKeystore>, &'static str> {93 // FIXME: here would the concrete keystore be built,94 // must return a concrete type (NOT `LocalKeystore`) that95 // implements `CryptoStore` and `SyncCryptoStore`96 Err("Remote Keystore not supported.")97}9819399/// Builds a new service for a full client.194/// Builds a new service for a full client.100pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError> {195pub fn new_full(196 config: Configuration,197 cli: &Cli,198) -> Result<TaskManager, ServiceError> {199 let enable_dev_signer = cli.run.shared_params.dev;200101 let sc_service::PartialComponents {201 let sc_service::PartialComponents {102 client, backend, mut task_manager, import_queue, mut keystore_container, select_chain, transaction_pool,202 client, backend, mut task_manager, import_queue, keystore_container,103 inherent_data_providers,203 select_chain, transaction_pool, inherent_data_providers,104 other: (block_import, grandpa_link),204 other: (consensus_result, pending_transactions, filter_pool, frontier_backend, mut telemetry),105 } = new_partial(&config)?;205 } = new_partial(&config, cli)?;106107 if let Some(url) = &config.keystore_remote {108 match remote_keystore(url) {109 Ok(k) => keystore_container.set_remote_keystore(k),110 Err(e) => {111 return Err(ServiceError::Other(112 format!("Error hooking up remote keystore for {}: {}", url, e)))113 }114 };115 }116117 config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());118206119 let (network, network_status_sinks, system_rpc_tx, network_starter) =207 let (network, network_status_sinks, system_rpc_tx, network_starter) =120 sc_service::build_network(sc_service::BuildNetworkParams {208 sc_service::build_network(sc_service::BuildNetworkParams {121 config: &config,209 config: &config,122 client: client.clone(),210 client: Arc::clone(&client),123 transaction_pool: transaction_pool.clone(),211 transaction_pool: Arc::clone(&transaction_pool),124 spawn_handle: task_manager.spawn_handle(),212 spawn_handle: task_manager.spawn_handle(),125 import_queue,213 import_queue,126 on_demand: None,214 on_demand: None,129217130 if config.offchain_worker.enabled {218 if config.offchain_worker.enabled {131 sc_service::build_offchain_workers(219 sc_service::build_offchain_workers(132 &config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),220 &config, task_manager.spawn_handle(), Arc::clone(&client), network.clone(),133 );221 );134 }222 }135223139 let name = config.network.node_name.clone();227 let name = config.network.node_name.clone();140 let enable_grandpa = !config.disable_grandpa;228 let enable_grandpa = !config.disable_grandpa;141 let prometheus_registry = config.prometheus_registry().cloned();229 let prometheus_registry = config.prometheus_registry().cloned();230 let is_authority = role.is_authority();231 let subscription_task_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());142232143 let rpc_extensions_builder = {233 let rpc_extensions_builder = {144 let client = client.clone();234 let client = Arc::clone(&client);145 let pool = transaction_pool.clone();235 let pool = Arc::clone(&transaction_pool);236 let network = network.clone();237 let pending = pending_transactions.clone();238 let filter_pool = filter_pool.clone();239 let frontier_backend = frontier_backend.clone();146240147 Box::new(move |deny_unsafe, _| {241 Box::new(move |deny_unsafe, _| {148 let deps = crate::rpc::FullDeps {242 let deps = crate::rpc::FullDeps {149 client: client.clone(),243 client: Arc::clone(&client),150 pool: pool.clone(),244 pool: Arc::clone(&pool),151 deny_unsafe,245 deny_unsafe,246 is_authority,247 enable_dev_signer,248 network: network.clone(),249 pending_transactions: pending.clone(),250 filter_pool: filter_pool.clone(),251 backend: frontier_backend.clone(),152 };252 };153154 crate::rpc::create_full(deps)253 crate::rpc::create_full(254 deps,255 subscription_task_executor.clone()256 )155 })257 })156 };258 };259260 task_manager.spawn_essential_handle().spawn(261 "frontier-mapping-sync-worker",262 MappingSyncWorker::new(263 client.import_notification_stream(),264 Duration::new(6, 0),265 Arc::clone(&client),266 Arc::clone(&backend),267 frontier_backend.clone(),268 ).for_each(|()| futures::future::ready(()))269 );157270158 let (_rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(271 let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {159 sc_service::SpawnTasksParams {160 network: network.clone(),272 network: network.clone(),161 client: client.clone(),273 client: Arc::clone(&client),162 keystore: keystore_container.sync_keystore(),274 keystore: keystore_container.sync_keystore(),163 task_manager: &mut task_manager,275 task_manager: &mut task_manager,164 transaction_pool: transaction_pool.clone(),276 transaction_pool: Arc::clone(&transaction_pool),165 rpc_extensions_builder,277 rpc_extensions_builder: rpc_extensions_builder,166 on_demand: None,278 on_demand: None,167 remote_blockchain: None,279 remote_blockchain: None,168 backend,280 backend, network_status_sinks, system_rpc_tx, config, telemetry: telemetry.as_mut(),169 network_status_sinks,170 system_rpc_tx,171 config,172 },281 })?;173 )?;282174283 // Spawn Frontier EthFilterApi maintenance task.175 if role.is_authority() {284 if let Some(filter_pool) = filter_pool {285 // Each filter is allowed to stay in the pool for 100 blocks.286 const FILTER_RETAIN_THRESHOLD: u64 = 100;287 task_manager.spawn_essential_handle().spawn(288 "frontier-filter-pool",289 EthTask::filter_pool_task(290 Arc::clone(&client),291 filter_pool,292 FILTER_RETAIN_THRESHOLD,293 )294 );295 }296297 // Spawn Frontier pending transactions maintenance task (as essential, otherwise we leak).176 let proposer = sc_basic_authorship::ProposerFactory::new(298 if let Some(pending_transactions) = pending_transactions {177 task_manager.spawn_handle(),178 client.clone(),179 transaction_pool,180 prometheus_registry.as_ref(),181 );182183 let can_author_with =299 const TRANSACTION_RETAIN_THRESHOLD: u64 = 5;184 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());300 task_manager.spawn_essential_handle().spawn(185301 "frontier-pending-transactions",186 let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _, _>(302 EthTask::pending_transaction_task(187 sc_consensus_aura::slot_duration(&*client)?,303 Arc::clone(&client),188 client.clone(),304 pending_transactions,189 select_chain,305 TRANSACTION_RETAIN_THRESHOLD,190 block_import,191 proposer,192 network.clone(),193 inherent_data_providers.clone(),194 force_authoring,195 backoff_authoring_blocks,196 keystore_container.sync_keystore(),197 can_author_with,198 )?;306 )199307 );200 // the AURA authoring task is considered essential, i.e. if it308 }201 // fails we take down the service with it.309310 let (aura_block_import, grandpa_link) = consensus_result;311312 if role.is_authority() {313 let proposer = sc_basic_authorship::ProposerFactory::new(202 task_manager.spawn_essential_handle().spawn_blocking("aura", aura);314 task_manager.spawn_handle(),203 }315 Arc::clone(&client),316 Arc::clone(&transaction_pool),317 prometheus_registry.as_ref(),318 telemetry.as_ref().map(|x| x.handle()),319 );320321 let can_author_with =322 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());323 let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _>(324 StartAuraParams {325 slot_duration: sc_consensus_aura::slot_duration(&*client)?,326 client: Arc::clone(&client),327 select_chain,328 block_import: aura_block_import,329 proposer_factory: proposer,330 sync_oracle: network.clone(),331 inherent_data_providers: inherent_data_providers.clone(),332 force_authoring,333 backoff_authoring_blocks,334 keystore: keystore_container.sync_keystore(),335 can_author_with,336 block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),337 telemetry: telemetry.as_ref().map(|x| x.handle()),338 }339 )?;340341 // the AURA authoring task is considered essential, i.e. if it342 // fails we take down the service with it.343 task_manager.spawn_essential_handle().spawn_blocking("aura", aura);204344205 // if the node isn't actively participating in consensus then it doesn't345 // if the node isn't actively participating in consensus then it doesn't206 // need a keystore, regardless of which protocol we use below.346 // need a keystore, regardless of which protocol we use below.217 name: Some(name),357 name: Some(name),218 observer_enabled: false,358 observer_enabled: false,219 keystore,359 keystore,220 is_authority: role.is_network_authority(),360 is_authority: role.is_authority(),361 telemetry: telemetry.as_ref().map(|x| x.handle()),221 };362 };222363223 if enable_grandpa {364 if enable_grandpa {231 config: grandpa_config,372 config: grandpa_config,232 link: grandpa_link,373 link: grandpa_link,233 network,374 network,234 telemetry_on_connect: telemetry_connection_notifier.map(|x| x.on_connect_stream()),375 telemetry: telemetry.as_ref().map(|x| x.handle()),235 voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),376 voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),236 prometheus_registry,377 prometheus_registry,237 shared_voter_state: SharedVoterState::empty(),378 shared_voter_state: SharedVoterState::empty(),244 sc_finality_grandpa::run_grandpa_voter(grandpa_config)?385 sc_finality_grandpa::run_grandpa_voter(grandpa_config)?245 );386 );246 }387 }388 }247389248 network_starter.start_network();390 network_starter.start_network();249 Ok(task_manager)391 Ok(task_manager)250}392}251/// Builds a new service for a light client.393/// Builds a new service for a light client.252pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> {394pub fn new_light(config: Configuration) -> Result<TaskManager, ServiceError> {395 let telemetry = config.telemetry_endpoints.clone()396 .filter(|x| !x.is_empty())397 .map(|endpoints| -> Result<_, sc_telemetry::Error> {398 let worker = TelemetryWorker::new(16)?;399 let telemetry = worker.handle().new_telemetry(endpoints);400 Ok((worker, telemetry))401 })402 .transpose()?;403253 let (client, backend, keystore_container, mut task_manager, on_demand) =404 let (client, backend, keystore_container, mut task_manager, on_demand) =254 sc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;405 sc_service::new_light_parts::<Block, RuntimeApi, Executor>(255406 &config,407 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),408 )?;409410 let mut telemetry = telemetry256 config.network.extra_sets.push(sc_finality_grandpa::grandpa_peers_set_config());411 .map(|(worker, telemetry)| {412 task_manager.spawn_handle().spawn("telemetry", worker.run());413 telemetry414 });257415258 let select_chain = sc_consensus::LongestChain::new(backend.clone());416 let select_chain = sc_consensus::LongestChain::new(backend.clone());259417269 client.clone(),427 client.clone(),270 &(client.clone() as Arc<_>),428 &(client.clone() as Arc<_>),271 select_chain.clone(),429 select_chain.clone(),430 telemetry.as_ref().map(|x| x.handle()),272 )?;431 )?;273274 let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(275 grandpa_block_import.clone(),276 client.clone(),277 );278432279 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(433 let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _>(434 ImportQueueParams {280 sc_consensus_aura::slot_duration(&*client)?,435 slot_duration: sc_consensus_aura::slot_duration(&*client)?,281 aura_block_import,436 block_import: grandpa_block_import.clone(),282 Some(Box::new(grandpa_block_import)),437 justification_import: Some(Box::new(grandpa_block_import)),283 client.clone(),438 client: client.clone(),284 InherentDataProviders::new(),439 inherent_data_providers: InherentDataProviders::new(),285 &task_manager.spawn_handle(),440 spawner: &task_manager.spawn_essential_handle(),286 config.prometheus_registry(),441 registry: config.prometheus_registry(),287 sp_consensus::NeverCanAuthor,442 can_author_with: sp_consensus::NeverCanAuthor,443 check_for_equivocation: Default::default(),444 telemetry: telemetry.as_ref().map(|x| x.handle()),445 }288 )?;446 )?;447448 let light_deps = crate::rpc::LightDeps {449 remote_blockchain: backend.remote_blockchain(),450 fetcher: on_demand.clone(),451 client: client.clone(),452 pool: transaction_pool.clone(),453 };454455 let rpc_extensions = crate::rpc::create_light(light_deps);289456290 let (network, network_status_sinks, system_rpc_tx, network_starter) =457 let (network, network_status_sinks, system_rpc_tx, network_starter) =291 sc_service::build_network(sc_service::BuildNetworkParams {458 sc_service::build_network(sc_service::BuildNetworkParams {300467301 if config.offchain_worker.enabled {468 if config.offchain_worker.enabled {302 sc_service::build_offchain_workers(469 sc_service::build_offchain_workers(303 &config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),470 &config, task_manager.spawn_handle(), client.clone(), network.clone(),304 );471 );305 }472 }306473309 transaction_pool,476 transaction_pool,310 task_manager: &mut task_manager,477 task_manager: &mut task_manager,311 on_demand: Some(on_demand),478 on_demand: Some(on_demand),312 rpc_extensions_builder: Box::new(|_, _| ()),479 rpc_extensions_builder: Box::new(sc_service::NoopRpcExtensionBuilder(rpc_extensions)),313 config,480 config,314 client,481 client,315 keystore: keystore_container.sync_keystore(),482 keystore: keystore_container.sync_keystore(),316 backend,483 backend,317 network,484 network,318 network_status_sinks,485 network_status_sinks,319 system_rpc_tx,486 system_rpc_tx,487 telemetry: telemetry.as_mut(),320 })?;488 })?;321489322 network_starter.start_network();490 network_starter.start_network();