,
- /// Transaction pool instance.
- pub pool: Arc,
- /// Graph pool instance.
- pub graph: Arc>,
- /// Network service
- pub network: Arc>,
- /// Whether to deny unsafe calls
- pub deny_unsafe: DenyUnsafe,
- /// The Node authority flag
- pub is_authority: bool,
- /// Frontier Backend.
- pub frontier_backend: Arc>,
- /// EthFilterApi pool.
- pub filter_pool: FilterPool,
- /// Maximum fee history cache size.
- pub fee_history_limit: u64,
- /// Fee history cache.
- pub fee_history_cache: FeeHistoryCache,
- /// Ethereum data access overrides.
- pub overrides: Arc>,
- /// Cache for Ethereum block data.
- pub block_data_cache: Arc>,
-}
-
-/// Instantiate all RPC extensions.
-pub fn create_full(
- deps: FullDeps,
- subscription_task_executor: SubscriptionTaskExecutor,
-) -> Result, Box>
-where
- C: ProvideRuntimeApi
- + HeaderBackend
- + AuxStore
- + StorageProvider
- + HeaderMetadata
- + BlockchainEvents
- + Send
- + Sync
- + 'static,
- C: sc_client_api::BlockBackend,
- C::Api: substrate_frame_rpc_system::AccountNonceApi
- + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi
- + BlockBuilder
- + orml_oracle_rpc::OracleRuntimeApi
- + pallet_loans_rpc::LoansRuntimeApi
- + pallet_router_rpc::RouterRuntimeApi
- + fp_rpc::ConvertTransactionRuntimeApi
- + fp_rpc::EthereumRuntimeRPCApi,
- P: TransactionPool + Sync + Send + 'static,
- BE: Backend + 'static,
- BE::State: StateBackend,
- BE::Blockchain: BlockchainBackend,
- A: ChainApi + 'static,
-{
- let mut io = RpcModule::new(());
- let FullDeps {
- client,
- pool,
- graph,
- network,
- deny_unsafe,
- is_authority,
- frontier_backend,
- filter_pool,
- fee_history_limit,
- fee_history_cache,
- overrides,
- block_data_cache,
- } = deps;
-
- io.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?;
- io.merge(TransactionPayment::new(client.clone()).into_rpc())?;
-
- // let no_tx_converter: Option = None;
- enum Never {}
- impl fp_rpc::ConvertTransaction for Never {
- fn convert_transaction(&self, _transaction: pallet_ethereum::Transaction) -> T {
- // The Never type is not instantiable, but this method requires the type to be
- // instantiated to be called (`&self` parameter), so if the code compiles we have the
- // guarantee that this function will never be called.
- unreachable!()
- }
- }
- let convert_transaction: Option = None;
-
- io.merge(
- Eth::new(
- Arc::clone(&client),
- Arc::clone(&pool),
- graph.clone(),
- convert_transaction,
- Arc::clone(&network),
- Default::default(),
- Arc::clone(&overrides),
- Arc::clone(&frontier_backend),
- is_authority,
- Arc::clone(&block_data_cache),
- fee_history_cache,
- fee_history_limit,
- 1,
- )
- .into_rpc(),
- )?;
-
- let max_past_logs: u32 = 10_000;
- let max_stored_filters: usize = 500;
- io.merge(
- EthFilter::new(
- client.clone(),
- frontier_backend,
- filter_pool,
- max_stored_filters,
- max_past_logs,
- block_data_cache,
- )
- .into_rpc(),
- )?;
-
- io.merge(Net::new(Arc::clone(&client), network.clone(), true).into_rpc())?;
-
- io.merge(Web3::new(Arc::clone(&client)).into_rpc())?;
-
- io.merge(
- EthPubSub::new(
- pool,
- Arc::clone(&client),
- network,
- subscription_task_executor,
- overrides,
- )
- .into_rpc(),
- )?;
-
- io.merge(Oracle::new(client.clone()).into_rpc())?;
- io.merge(Loans::new(client.clone()).into_rpc())?;
- io.merge(Router::new(client.clone()).into_rpc())?;
-
- Ok(io)
-}
diff --git a/node/parallel/src/evm_service.rs b/node/parallel/src/evm_service.rs
deleted file mode 100644
index 19e36ce89..000000000
--- a/node/parallel/src/evm_service.rs
+++ /dev/null
@@ -1,1238 +0,0 @@
-// Copyright 2021 Parallel Finance Developer.
-// This file is part of Parallel Finance.
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#![allow(dead_code, unused)]
-
-use cumulus_client_consensus_common::{ParachainCandidate, ParachainConsensus};
-use cumulus_primitives_core::relay_chain::v2::{Hash as PHash, PersistedValidationData};
-use cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider;
-use futures::lock::Mutex;
-use sc_consensus::{import_queue::Verifier as VerifierT, BlockImportParams};
-use sp_api::ApiExt;
-use sp_consensus::CacheKeyId;
-use sp_consensus_aura::{sr25519::AuthorityId as AuraId, AuraApi};
-use sp_runtime::{generic::BlockId, traits::Header as HeaderT};
-use std::sync::Arc;
-
-use cumulus_client_cli::CollatorOptions;
-use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};
-use cumulus_client_consensus_common::ParachainBlockImport;
-use cumulus_client_consensus_relay_chain::Verifier as RelayChainVerifier;
-use cumulus_client_network::BlockAnnounceValidator;
-use cumulus_client_service::{
- prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,
-};
-use cumulus_primitives_core::ParaId;
-use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;
-use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};
-use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;
-use fc_consensus::FrontierBlockImport;
-use fc_rpc_core::types::{FeeHistoryCache, FilterPool};
-use futures::StreamExt;
-use polkadot_service::CollatorPair;
-use sc_client_api::{BlockchainEvents, ExecutorProvider};
-use sc_consensus::import_queue::BasicQueue;
-use sc_consensus_manual_seal::{self as manual_seal};
-use sc_executor::NativeElseWasmExecutor;
-use sc_network::NetworkService;
-use sc_network_common::service::NetworkBlock;
-use sc_service::error::Error as ServiceError;
-use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
-use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
-use sp_api::ConstructRuntimeApi;
-use sp_blockchain::HeaderBackend;
-use sp_keystore::SyncCryptoStorePtr;
-use sp_runtime::traits::BlakeTwo256;
-use std::{collections::BTreeMap, time::Duration};
-use substrate_prometheus_endpoint::Registry;
-
-use primitives::*;
-
-pub struct VanillaExecutor;
-impl sc_executor::NativeExecutionDispatch for VanillaExecutor {
- type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
-
- fn dispatch(method: &str, data: &[u8]) -> Option> {
- vanilla_runtime::api::dispatch(method, data)
- }
-
- fn native_version() -> sc_executor::NativeVersion {
- vanilla_runtime::native_version()
- }
-}
-
-pub type FullBackend = sc_service::TFullBackend;
-pub type FullClient =
- sc_service::TFullClient>;
-pub type FullSelectChain = sc_consensus::LongestChain;
-
-pub enum BuildOnAccess {
- Uninitialized(Option R + Send + Sync>>),
- Initialized(R),
-}
-
-impl BuildOnAccess {
- fn get_mut(&mut self) -> &mut R {
- loop {
- match self {
- Self::Uninitialized(f) => {
- *self = Self::Initialized((f.take().unwrap())());
- }
- Self::Initialized(ref mut r) => return r,
- }
- }
- }
-}
-
-pub struct WaitForAuraConsensus {
- pub client: Arc,
- pub aura_consensus: Arc>>>>,
- pub relay_chain_consensus: Arc>>>,
-}
-
-impl Clone for WaitForAuraConsensus {
- fn clone(&self) -> Self {
- Self {
- client: self.client.clone(),
- aura_consensus: self.aura_consensus.clone(),
- relay_chain_consensus: self.relay_chain_consensus.clone(),
- }
- }
-}
-
-#[async_trait::async_trait]
-impl ParachainConsensus for WaitForAuraConsensus
-where
- Client: sp_api::ProvideRuntimeApi + Send + Sync,
- Client::Api: AuraApi,
-{
- async fn produce_candidate(
- &mut self,
- parent: &Header,
- relay_parent: PHash,
- validation_data: &PersistedValidationData,
- ) -> Option> {
- let block_id = BlockId::hash(parent.hash());
- if self
- .client
- .runtime_api()
- .has_api::>(&block_id)
- .unwrap_or(false)
- {
- self.aura_consensus
- .lock()
- .await
- .get_mut()
- .produce_candidate(parent, relay_parent, validation_data)
- .await
- } else {
- self.relay_chain_consensus
- .lock()
- .await
- .produce_candidate(parent, relay_parent, validation_data)
- .await
- }
- }
-}
-
-pub struct Verifier {
- pub client: Arc,
- pub aura_verifier: BuildOnAccess>>,
- pub relay_chain_verifier: Box>,
-}
-
-#[async_trait::async_trait]
-impl VerifierT for Verifier
-where
- Client: sp_api::ProvideRuntimeApi + Send + Sync,
- Client::Api: AuraApi,
-{
- async fn verify(
- &mut self,
- block_import: BlockImportParams,
- ) -> Result<
- (
- BlockImportParams,
- Option)>>,
- ),
- String,
- > {
- let block_id = BlockId::hash(*block_import.header.parent_hash());
-
- if self
- .client
- .runtime_api()
- .has_api::>(&block_id)
- .unwrap_or(false)
- {
- self.aura_verifier.get_mut().verify(block_import).await
- } else {
- self.relay_chain_verifier.verify(block_import).await
- }
- }
-}
-
-/// Vanilla network runtime executor.
-pub mod vanilla {
- pub use vanilla_runtime::RuntimeApi;
-
- /// vanilla runtime executor.
- pub struct Executor;
- impl sc_executor::NativeExecutionDispatch for Executor {
- #[cfg(not(feature = "runtime-benchmarks"))]
- type ExtendHostFunctions = ();
-
- #[cfg(feature = "runtime-benchmarks")]
- type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
-
- fn dispatch(method: &str, data: &[u8]) -> Option> {
- vanilla_runtime::api::dispatch(method, data)
- }
-
- fn native_version() -> sc_executor::NativeVersion {
- vanilla_runtime::native_version()
- }
- }
-}
-
-pub struct KerriaExecutor;
-impl sc_executor::NativeExecutionDispatch for KerriaExecutor {
- type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;
-
- fn dispatch(method: &str, data: &[u8]) -> Option> {
- kerria_runtime::api::dispatch(method, data)
- }
-
- fn native_version() -> sc_executor::NativeVersion {
- kerria_runtime::native_version()
- }
-}
-
-/// Starts a `ServiceBuilder` for a full service.
-///
-/// Use this macro if you don't actually need the full service, but just the builder in order to
-/// be able to perform chain operations.
-pub fn new_partial(
- config: &Configuration,
- build_import_queue: BIQ,
-) -> Result<
- PartialComponents<
- TFullClient>,
- TFullBackend,
- (),
- sc_consensus::DefaultImportQueue<
- Block,
- TFullClient>,
- >,
- sc_transaction_pool::FullPool<
- Block,
- TFullClient>,
- >,
- (
- Option,
- Option,
- Arc>,
- ),
- >,
- sc_service::Error,
->
-where
- RuntimeApi: ConstructRuntimeApi>>
- + Send
- + Sync
- + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata
- + sp_session::SessionKeys
- + sp_api::ApiExt<
- Block,
- StateBackend = sc_client_api::StateBackendFor, Block>,
- > + sp_offchain::OffchainWorkerApi
- + sp_block_builder::BlockBuilder
- + sp_consensus_aura::AuraApi
- + frame_system_rpc_runtime_api::AccountNonceApi
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi
- + fp_rpc::EthereumRuntimeRPCApi
- + orml_oracle_rpc::OracleRuntimeApi
- + pallet_loans_rpc::LoansRuntimeApi
- + pallet_router_rpc::RouterRuntimeApi,
- sc_client_api::StateBackendFor, Block>: sp_api::StateBackend,
- Executor: sc_executor::NativeExecutionDispatch + 'static,
- BIQ: FnOnce(
- Arc>>,
- FrontierBlockImport<
- Block,
- Arc>>,
- TFullClient>,
- >,
- &Configuration,
- Option,
- &TaskManager,
- ) -> Result<
- sc_consensus::DefaultImportQueue<
- Block,
- TFullClient>,
- >,
- sc_service::Error,
- >,
-{
- let telemetry = config
- .telemetry_endpoints
- .clone()
- .filter(|x| !x.is_empty())
- .map(|endpoints| -> Result<_, sc_telemetry::Error> {
- let worker = TelemetryWorker::new(16)?;
- let telemetry = worker.handle().new_telemetry(endpoints);
- Ok((worker, telemetry))
- })
- .transpose()?;
-
- let executor = sc_executor::NativeElseWasmExecutor::::new(
- config.wasm_method,
- config.default_heap_pages,
- config.max_runtime_instances,
- config.runtime_cache_size,
- );
-
- let (client, backend, keystore_container, task_manager) =
- sc_service::new_full_parts::(
- config,
- telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
- executor,
- )?;
- let client = Arc::new(client);
-
- let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
-
- let telemetry = telemetry.map(|(worker, telemetry)| {
- task_manager
- .spawn_handle()
- .spawn("telemetry", None, worker.run());
- telemetry
- });
-
- let transaction_pool = sc_transaction_pool::BasicPool::new_full(
- config.transaction_pool.clone(),
- config.role.is_authority().into(),
- config.prometheus_registry(),
- task_manager.spawn_essential_handle(),
- client.clone(),
- );
-
- let frontier_backend = crate::evm_rpc::open_frontier_backend(client.clone(), config)?;
- let frontier_block_import =
- FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());
-
- let import_queue = build_import_queue(
- client.clone(),
- frontier_block_import,
- config,
- telemetry.as_ref().map(|telemetry| telemetry.handle()),
- &task_manager,
- )?;
-
- let params = PartialComponents {
- backend,
- client,
- import_queue,
- keystore_container,
- task_manager,
- transaction_pool,
- select_chain: (),
- other: (telemetry, telemetry_worker_handle, frontier_backend),
- };
-
- Ok(params)
-}
-
-async fn build_relay_chain_interface(
- polkadot_config: Configuration,
- parachain_config: &Configuration,
- telemetry_worker_handle: Option,
- task_manager: &mut TaskManager,
- collator_options: CollatorOptions,
-) -> RelayChainResult<(
- Arc<(dyn RelayChainInterface + 'static)>,
- Option,
-)> {
- match collator_options.relay_chain_rpc_url {
- Some(relay_chain_url) => {
- build_minimal_relay_chain_node(polkadot_config, task_manager, relay_chain_url).await
- }
- None => build_inprocess_relay_chain(
- polkadot_config,
- parachain_config,
- telemetry_worker_handle,
- task_manager,
- None,
- ),
- }
-}
-
-/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
-///
-/// This is the actual implementation that is abstract over the executor and the runtime api.
-#[sc_tracing::logging::prefix_logs_with("Parachain")]
-async fn start_node_impl(
- parachain_config: Configuration,
- polkadot_config: Configuration,
- collator_options: CollatorOptions,
- id: ParaId,
- build_import_queue: BIQ,
- build_consensus: BIC,
-) -> sc_service::error::Result<(
- TaskManager,
- Arc>>,
-)>
-where
- RuntimeApi: ConstructRuntimeApi>>
- + Send
- + Sync
- + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata
- + sp_session::SessionKeys
- + sp_api::ApiExt<
- Block,
- StateBackend = sc_client_api::StateBackendFor, Block>,
- > + sp_offchain::OffchainWorkerApi
- + sp_block_builder::BlockBuilder
- + substrate_frame_rpc_system::AccountNonceApi
- + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi
- + sp_consensus_aura::AuraApi
- + fp_rpc::EthereumRuntimeRPCApi
- + fp_rpc::ConvertTransactionRuntimeApi
- + cumulus_primitives_core::CollectCollationInfo
- + orml_oracle_rpc::OracleRuntimeApi
- + pallet_loans_rpc::LoansRuntimeApi
- + pallet_router_rpc::RouterRuntimeApi,
- sc_client_api::StateBackendFor, Block>: sp_api::StateBackend,
- Executor: sc_executor::NativeExecutionDispatch + 'static,
- BIQ: FnOnce(
- Arc>>,
- FrontierBlockImport<
- Block,
- Arc>>,
- TFullClient>,
- >,
- &Configuration,
- Option,
- &TaskManager,
- ) -> Result<
- sc_consensus::DefaultImportQueue<
- Block,
- TFullClient>,
- >,
- sc_service::Error,
- >,
- BIC: FnOnce(
- Arc>>,
- Option<&Registry>,
- Option,
- &TaskManager,
- Arc,
- Arc<
- sc_transaction_pool::FullPool<
- Block,
- TFullClient>,
- >,
- >,
- Arc>,
- SyncCryptoStorePtr,
- bool,
- ) -> Result>, sc_service::Error>,
-{
- let parachain_config = prepare_node_config(parachain_config);
-
- let params = new_partial::(¶chain_config, build_import_queue)?;
- let (mut telemetry, telemetry_worker_handle, frontier_backend) = params.other;
-
- let client = params.client.clone();
- let backend = params.backend.clone();
-
- let mut task_manager = params.task_manager;
- let (relay_chain_interface, collator_key) = build_relay_chain_interface(
- polkadot_config,
- ¶chain_config,
- telemetry_worker_handle,
- &mut task_manager,
- collator_options.clone(),
- )
- .await
- .map_err(|e| match e {
- RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,
- s => format!("{}", s).into(),
- })?;
- let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);
-
- let force_authoring = parachain_config.force_authoring;
- let is_authority = parachain_config.role.is_authority();
- let prometheus_registry = parachain_config.prometheus_registry().cloned();
- let transaction_pool = params.transaction_pool.clone();
- let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);
- let (network, system_rpc_tx, tx_handler_controller, start_network) =
- sc_service::build_network(sc_service::BuildNetworkParams {
- config: ¶chain_config,
- client: client.clone(),
- transaction_pool: transaction_pool.clone(),
- spawn_handle: task_manager.spawn_handle(),
- import_queue: import_queue.clone(),
- block_announce_validator_builder: Some(Box::new(|_| {
- Box::new(block_announce_validator)
- })),
- warp_sync: None,
- })?;
-
- let filter_pool: FilterPool = Arc::new(std::sync::Mutex::new(BTreeMap::new()));
- let fee_history_cache: FeeHistoryCache = Arc::new(std::sync::Mutex::new(BTreeMap::new()));
- let overrides = crate::evm_rpc::overrides_handle(client.clone());
-
- // Frontier offchain DB task. Essential.
- // Maps emulated ethereum data to substrate native data.
- task_manager.spawn_essential_handle().spawn(
- "frontier-mapping-sync-worker",
- Some("frontier"),
- fc_mapping_sync::MappingSyncWorker::new(
- client.import_notification_stream(),
- Duration::new(6, 0),
- client.clone(),
- backend.clone(),
- frontier_backend.clone(),
- 3,
- 0,
- fc_mapping_sync::SyncStrategy::Parachain,
- )
- .for_each(|()| futures::future::ready(())),
- );
-
- // Frontier `EthFilterApi` maintenance. Manages the pool of user-created Filters.
- // Each filter is allowed to stay in the pool for 100 blocks.
- const FILTER_RETAIN_THRESHOLD: u64 = 100;
- task_manager.spawn_essential_handle().spawn(
- "frontier-filter-pool",
- Some("frontier"),
- fc_rpc::EthTask::filter_pool_task(
- client.clone(),
- filter_pool.clone(),
- FILTER_RETAIN_THRESHOLD,
- ),
- );
-
- const FEE_HISTORY_LIMIT: u64 = 2048;
- task_manager.spawn_essential_handle().spawn(
- "frontier-fee-history",
- Some("frontier"),
- fc_rpc::EthTask::fee_history_task(
- client.clone(),
- overrides.clone(),
- fee_history_cache.clone(),
- FEE_HISTORY_LIMIT,
- ),
- );
-
- let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
- task_manager.spawn_handle(),
- overrides.clone(),
- 50,
- 50,
- prometheus_registry.clone(),
- ));
-
- let rpc_extensions_builder = {
- let client = client.clone();
- let network = network.clone();
- let transaction_pool = transaction_pool.clone();
- let frontier_backend = frontier_backend.clone();
- let overrides = overrides.clone();
- let fee_history_cache = fee_history_cache.clone();
- let block_data_cache = block_data_cache.clone();
-
- Box::new(move |deny_unsafe, subscription| {
- let deps = crate::evm_rpc::FullDeps {
- client: client.clone(),
- pool: transaction_pool.clone(),
- graph: transaction_pool.pool().clone(),
- network: network.clone(),
- is_authority,
- deny_unsafe,
- frontier_backend: frontier_backend.clone(),
- filter_pool: filter_pool.clone(),
- fee_history_limit: FEE_HISTORY_LIMIT,
- fee_history_cache: fee_history_cache.clone(),
- block_data_cache: block_data_cache.clone(),
- overrides: overrides.clone(),
- };
-
- crate::evm_rpc::create_full(deps, subscription).map_err(Into::into)
- })
- };
-
- // Spawn basic services.
- sc_service::spawn_tasks(sc_service::SpawnTasksParams {
- rpc_builder: Box::new(rpc_extensions_builder),
- client: client.clone(),
- transaction_pool: transaction_pool.clone(),
- task_manager: &mut task_manager,
- config: parachain_config,
- keystore: params.keystore_container.sync_keystore(),
- backend: backend.clone(),
- network: network.clone(),
- system_rpc_tx,
- tx_handler_controller,
- telemetry: telemetry.as_mut(),
- })?;
-
- let announce_block = {
- let network = network.clone();
- Arc::new(move |hash, data| network.announce_block(hash, data))
- };
-
- let relay_chain_slot_duration = Duration::from_secs(6);
-
- if is_authority {
- let parachain_consensus = build_consensus(
- client.clone(),
- prometheus_registry.as_ref(),
- telemetry.as_ref().map(|t| t.handle()),
- &task_manager,
- relay_chain_interface.clone(),
- transaction_pool,
- network,
- params.keystore_container.sync_keystore(),
- force_authoring,
- )?;
-
- let spawner = task_manager.spawn_handle();
-
- let params = StartCollatorParams {
- para_id: id,
- block_status: client.clone(),
- announce_block,
- client: client.clone(),
- task_manager: &mut task_manager,
- relay_chain_interface: relay_chain_interface.clone(),
- spawner,
- parachain_consensus,
- import_queue,
- collator_key: collator_key.expect("Command line arguments do not allow this. qed"),
- relay_chain_slot_duration,
- };
-
- start_collator(params).await?;
- } else {
- let params = StartFullNodeParams {
- client: client.clone(),
- announce_block,
- task_manager: &mut task_manager,
- para_id: id,
- relay_chain_interface,
- relay_chain_slot_duration,
- import_queue,
- };
-
- start_full_node(params)?;
- }
-
- start_network.start_network();
-
- Ok((task_manager, client))
-}
-
-/// Build the import queue.
-#[allow(dead_code, unused)]
-pub fn build_import_queue(
- client: Arc>>,
- block_import: FrontierBlockImport<
- Block,
- Arc>>,
- TFullClient>,
- >,
- config: &Configuration,
- telemetry_handle: Option,
- task_manager: &TaskManager,
-) -> Result<
- sc_consensus::DefaultImportQueue<
- Block,
- TFullClient>,
- >,
- sc_service::Error,
->
-where
- RuntimeApi: ConstructRuntimeApi>>
- + Send
- + Sync
- + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata
- + sp_session::SessionKeys
- + sp_api::ApiExt<
- Block,
- StateBackend = sc_client_api::StateBackendFor, Block>,
- > + sp_offchain::OffchainWorkerApi
- + sp_block_builder::BlockBuilder
- + frame_system_rpc_runtime_api::AccountNonceApi
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi
- + fp_rpc::EthereumRuntimeRPCApi
- + sp_consensus_aura::AuraApi,
- sc_client_api::StateBackendFor, Block>: sp_api::StateBackend,
- Executor: sc_executor::NativeExecutionDispatch + 'static,
-{
- let client2 = client.clone();
-
- let aura_verifier = move || {
- let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client2).unwrap();
-
- Box::new(cumulus_client_consensus_aura::build_verifier::<
- sp_consensus_aura::sr25519::AuthorityPair,
- _,
- _,
- >(
- cumulus_client_consensus_aura::BuildVerifierParams {
- client: client2.clone(),
- create_inherent_data_providers: move |_, _| async move {
- let time = sp_timestamp::InherentDataProvider::from_system_time();
-
- let slot =
- sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
- *time,
- slot_duration,
- );
-
- Ok((slot, time))
- },
- telemetry: telemetry_handle,
- },
- )) as Box<_>
- };
-
- let relay_chain_verifier = Box::new(RelayChainVerifier::new(client.clone(), |_, _| async {
- Ok(())
- })) as Box<_>;
-
- let verifier = Verifier {
- client,
- relay_chain_verifier,
- aura_verifier: BuildOnAccess::Uninitialized(Some(Box::new(aura_verifier))),
- };
-
- let registry = config.prometheus_registry();
- let spawner = task_manager.spawn_essential_handle();
-
- Ok(BasicQueue::new(
- verifier,
- Box::new(ParachainBlockImport::new(block_import)),
- None,
- &spawner,
- registry,
- ))
-}
-
-/// Start a parachain node for evm node(only for vanilla now)
-pub async fn start_node(
- parachain_config: Configuration,
- polkadot_config: Configuration,
- collator_options: CollatorOptions,
- id: ParaId,
-) -> sc_service::error::Result<(
- TaskManager,
- Arc>>,
-)>
-where
- RuntimeApi: ConstructRuntimeApi>>
- + Send
- + Sync
- + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata
- + sp_session::SessionKeys
- + sp_api::ApiExt<
- Block,
- StateBackend = sc_client_api::StateBackendFor, Block>,
- > + sp_offchain::OffchainWorkerApi
- + sp_block_builder::BlockBuilder
- + substrate_frame_rpc_system::AccountNonceApi
- + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi
- + sp_consensus_aura::AuraApi
- + fp_rpc::EthereumRuntimeRPCApi
- + fp_rpc::ConvertTransactionRuntimeApi
- + cumulus_primitives_core::CollectCollationInfo
- + orml_oracle_rpc::OracleRuntimeApi
- + pallet_loans_rpc::LoansRuntimeApi
- + pallet_router_rpc::RouterRuntimeApi,
- sc_client_api::StateBackendFor, Block>: sp_api::StateBackend,
- Executor: sc_executor::NativeExecutionDispatch + 'static,
-{
- start_node_impl::(
- parachain_config,
- polkadot_config,
- collator_options,
- id,
- |client,
- block_import,
- config,
- telemetry,
- task_manager| {
- let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
-
- cumulus_client_consensus_aura::import_queue::<
- sp_consensus_aura::sr25519::AuthorityPair,
- _,
- _,
- _,
- _,
- _,
- >(cumulus_client_consensus_aura::ImportQueueParams {
- block_import,
- client,
- create_inherent_data_providers: move |_, _| async move {
- let time = sp_timestamp::InherentDataProvider::from_system_time();
-
- let slot =
- sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
- *time,
- slot_duration,
- );
-
- Ok((slot, time))
- },
- registry: config.prometheus_registry(),
- spawner: &task_manager.spawn_essential_handle(),
- telemetry,
- })
- .map_err(Into::into)
- },
- |client,
- prometheus_registry,
- telemetry,
- task_manager,
- relay_chain_interface,
- transaction_pool,
- sync_oracle,
- keystore,
- force_authoring| {
- let spawn_handle = task_manager.spawn_handle();
-
- let slot_duration =
- cumulus_client_consensus_aura::slot_duration(&*client).unwrap();
-
- let proposer_factory =
- sc_basic_authorship::ProposerFactory::with_proof_recording(
- spawn_handle,
- client.clone(),
- transaction_pool,
- prometheus_registry,
- telemetry.clone(),
- );
-
- let relay_chain_for_aura = relay_chain_interface.clone();
-
- Ok(AuraConsensus::build::<
- sp_consensus_aura::sr25519::AuthorityPair,
- _,
- _,
- _,
- _,
- _,
- _,
- >(BuildAuraConsensusParams {
- proposer_factory,
- create_inherent_data_providers:
- move |_, (relay_parent, validation_data)| {
- let relay_chain_for_aura = relay_chain_for_aura.clone();
- async move {
- let parachain_inherent =
- cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(
- relay_parent,
- &relay_chain_for_aura,
- &validation_data,
- id,
- ).await;
- let time = sp_timestamp::InherentDataProvider::from_system_time();
- let slot =
- sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(
- *time,
- slot_duration,
- );
-
- let parachain_inherent = parachain_inherent.ok_or_else(|| {
- Box::::from(
- "Failed to create parachain inherent",
- )
- })?;
- Ok((slot, time, parachain_inherent))
- }
- },
- block_import: client.clone(),
- para_client: client,
- backoff_authoring_blocks: Option::<()>::None,
- sync_oracle,
- keystore,
- force_authoring,
- slot_duration,
- // We got around 500ms for proposing
- block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),
- // And a maximum of 750ms if slots are skipped
- max_block_proposal_slot_portion: Some(SlotProportion::new(1f32 / 16f32)),
- telemetry,
- })
- )
- }).await
-}
-
-/// Build a partial chain component config
-pub fn new_dev_partial(
- config: &Configuration,
-) -> Result<
- sc_service::PartialComponents<
- FullClient,
- FullBackend,
- FullSelectChain,
- sc_consensus::DefaultImportQueue>,
- sc_transaction_pool::FullPool>,
- (
- FrontierBlockImport<
- Block,
- Arc>,
- FullClient,
- >,
- Option,
- Arc>,
- ),
- >,
- ServiceError,
->
-where
- RuntimeApi:
- ConstructRuntimeApi> + Send + Sync + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata
- + sp_session::SessionKeys
- + sp_api::ApiExt<
- Block,
- StateBackend = sc_client_api::StateBackendFor, Block>,
- > + sp_offchain::OffchainWorkerApi
- + sp_block_builder::BlockBuilder
- + sp_consensus_aura::AuraApi
- + frame_system_rpc_runtime_api::AccountNonceApi
- + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi
- + fp_rpc::EthereumRuntimeRPCApi
- + fp_rpc::ConvertTransactionRuntimeApi
- + orml_oracle_rpc::OracleRuntimeApi
- + pallet_loans_rpc::LoansRuntimeApi
- + pallet_router_rpc::RouterRuntimeApi,
- sc_client_api::StateBackendFor, Block>: sp_api::StateBackend,
- Executor: sc_executor::NativeExecutionDispatch + 'static,
-{
- if config.keystore_remote.is_some() {
- return Err(ServiceError::Other(
- "Remote Keystores are not supported.".to_string(),
- ));
- }
-
- let telemetry = config
- .telemetry_endpoints
- .clone()
- .filter(|x| !x.is_empty())
- .map(|endpoints| -> Result<_, sc_telemetry::Error> {
- let worker = TelemetryWorker::new(16)?;
- let telemetry = worker.handle().new_telemetry(endpoints);
- Ok((worker, telemetry))
- })
- .transpose()?;
- let executor = sc_executor::NativeElseWasmExecutor::::new(
- config.wasm_method,
- config.default_heap_pages,
- config.max_runtime_instances,
- config.runtime_cache_size,
- );
-
- let (client, backend, keystore_container, task_manager) =
- sc_service::new_full_parts::(
- config,
- telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
- executor,
- )?;
- let client = Arc::new(client);
- let telemetry = telemetry.map(|(worker, telemetry)| {
- task_manager
- .spawn_handle()
- .spawn("telemetry", None, worker.run());
- telemetry
- });
- let select_chain = sc_consensus::LongestChain::new(backend.clone());
- let transaction_pool = sc_transaction_pool::BasicPool::new_full(
- config.transaction_pool.clone(),
- config.role.is_authority().into(),
- config.prometheus_registry(),
- task_manager.spawn_essential_handle(),
- client.clone(),
- );
- let frontier_backend = crate::evm_rpc::open_frontier_backend(client.clone(), config)?;
-
- let frontier_block_import =
- FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());
-
- let import_queue = sc_consensus_manual_seal::import_queue(
- Box::new(frontier_block_import.clone()),
- &task_manager.spawn_essential_handle(),
- config.prometheus_registry(),
- );
-
- Ok(sc_service::PartialComponents {
- client,
- backend,
- task_manager,
- import_queue,
- keystore_container,
- select_chain,
- transaction_pool,
- other: (frontier_block_import, telemetry, frontier_backend),
- })
-}
-
-/// Builds a new service.
-pub fn start_dev_node(
- config: Configuration,
-) -> Result
-where
- RuntimeApi: ConstructRuntimeApi>>
- + Send
- + Sync
- + 'static,
- RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue
- + sp_api::Metadata