123456789101112131415161718use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_rpc_core::types::FeeHistoryCache;24use futures::{25 Stream, StreamExt,26 stream::select,27 task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};343536use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::ParachainConsensus;38use cumulus_client_service::{39 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,40};41use cumulus_client_cli::CollatorOptions;42use cumulus_client_network::BlockAnnounceValidator;43use cumulus_primitives_core::ParaId;44use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;45use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};46use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;474849use sc_client_api::ExecutorProvider;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::NetworkService;53use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};54use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};55use sp_keystore::SyncCryptoStorePtr;56use sp_runtime::traits::BlakeTwo256;57use substrate_prometheus_endpoint::Registry;58use sc_client_api::BlockchainEvents;5960use polkadot_service::CollatorPair;616263use fc_rpc_core::types::FilterPool;64use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6566use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};676869707172737475#[cfg(feature = "unique-runtime")]76pub struct UniqueRuntimeExecutor;7778#[cfg(feature = "quartz-runtime")]798081pub struct QuartzRuntimeExecutor;828384pub struct OpalRuntimeExecutor;8586#[cfg(feature = "unique-runtime")]87impl NativeExecutionDispatch for UniqueRuntimeExecutor {88 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8990 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {91 unique_runtime::api::dispatch(method, data)92 }9394 fn native_version() -> sc_executor::NativeVersion {95 unique_runtime::native_version()96 }97}9899#[cfg(feature = "quartz-runtime")]100impl NativeExecutionDispatch for QuartzRuntimeExecutor {101 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;102103 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {104 quartz_runtime::api::dispatch(method, data)105 }106107 fn native_version() -> sc_executor::NativeVersion {108 quartz_runtime::native_version()109 }110}111112impl NativeExecutionDispatch for OpalRuntimeExecutor {113 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;114115 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {116 opal_runtime::api::dispatch(method, data)117 }118119 fn native_version() -> sc_executor::NativeVersion {120 opal_runtime::native_version()121 }122}123124pub struct AutosealInterval {125 interval: Interval,126}127128impl AutosealInterval {129 pub fn new(config: &Configuration, interval: Duration) -> Self {130 let _tokio_runtime = config.tokio_handle.enter();131 let interval = tokio::time::interval(interval);132133 Self { interval }134 }135}136137impl Stream for AutosealInterval {138 type Item = tokio::time::Instant;139140 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {141 self.interval.poll_tick(cx).map(Some)142 }143}144145pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {146 let config_dir = config147 .base_path148 .as_ref()149 .map(|base_path| base_path.config_dir(config.chain_spec.id()))150 .unwrap_or_else(|| {151 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())152 });153 let database_dir = config_dir.join("frontier").join("db");154155 Ok(Arc::new(fc_db::Backend::<Block>::new(156 &fc_db::DatabaseSettings {157 source: fc_db::DatabaseSource::RocksDb {158 path: database_dir,159 cache_size: 0,160 },161 },162 )?))163}164165type FullClient<RuntimeApi, ExecutorDispatch> =166 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;167type FullBackend = sc_service::TFullBackend<Block>;168type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;169170171172173174#[allow(clippy::type_complexity)]175pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(176 config: &Configuration,177 build_import_queue: BIQ,178) -> Result<179 PartialComponents<180 FullClient<RuntimeApi, ExecutorDispatch>,181 FullBackend,182 FullSelectChain,183 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,184 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,185 (186 Option<Telemetry>,187 Option<FilterPool>,188 Arc<fc_db::Backend<Block>>,189 Option<TelemetryWorkerHandle>,190 FeeHistoryCache,191 ),192 >,193 sc_service::Error,194>195where196 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,197 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>198 + Send199 + Sync200 + 'static,201 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,202 ExecutorDispatch: NativeExecutionDispatch + 'static,203 BIQ: FnOnce(204 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,205 &Configuration,206 Option<TelemetryHandle>,207 &TaskManager,208 ) -> Result<209 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,210 sc_service::Error,211 >,212{213 let _telemetry = config214 .telemetry_endpoints215 .clone()216 .filter(|x| !x.is_empty())217 .map(|endpoints| -> Result<_, sc_telemetry::Error> {218 let worker = TelemetryWorker::new(16)?;219 let telemetry = worker.handle().new_telemetry(endpoints);220 Ok((worker, telemetry))221 })222 .transpose()?;223224 let telemetry = config225 .telemetry_endpoints226 .clone()227 .filter(|x| !x.is_empty())228 .map(|endpoints| -> Result<_, sc_telemetry::Error> {229 let worker = TelemetryWorker::new(16)?;230 let telemetry = worker.handle().new_telemetry(endpoints);231 Ok((worker, telemetry))232 })233 .transpose()?;234235 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(236 config.wasm_method,237 config.default_heap_pages,238 config.max_runtime_instances,239 config.runtime_cache_size,240 );241242 let (client, backend, keystore_container, task_manager) =243 sc_service::new_full_parts::<Block, RuntimeApi, _>(244 config,245 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),246 executor,247 )?;248 let client = Arc::new(client);249250 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());251252 let telemetry = telemetry.map(|(worker, telemetry)| {253 task_manager254 .spawn_handle()255 .spawn("telemetry", None, worker.run());256 telemetry257 });258259 let select_chain = sc_consensus::LongestChain::new(backend.clone());260261 let transaction_pool = sc_transaction_pool::BasicPool::new_full(262 config.transaction_pool.clone(),263 config.role.is_authority().into(),264 config.prometheus_registry(),265 task_manager.spawn_essential_handle(),266 client.clone(),267 );268269 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));270271 let frontier_backend = open_frontier_backend(config)?;272273 let import_queue = build_import_queue(274 client.clone(),275 config,276 telemetry.as_ref().map(|telemetry| telemetry.handle()),277 &task_manager,278 )?;279 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));280281 let params = PartialComponents {282 backend,283 client,284 import_queue,285 keystore_container,286 task_manager,287 transaction_pool,288 select_chain,289 other: (290 telemetry,291 filter_pool,292 frontier_backend,293 telemetry_worker_handle,294 fee_history_cache,295 ),296 };297298 Ok(params)299}300301async fn build_relay_chain_interface(302 polkadot_config: Configuration,303 parachain_config: &Configuration,304 telemetry_worker_handle: Option<TelemetryWorkerHandle>,305 task_manager: &mut TaskManager,306 collator_options: CollatorOptions,307 hwbench: Option<sc_sysinfo::HwBench>,308) -> RelayChainResult<(309 Arc<(dyn RelayChainInterface + 'static)>,310 Option<CollatorPair>,311)> {312 match collator_options.relay_chain_rpc_url {313 Some(relay_chain_url) => Ok((314 Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,315 None,316 )),317 None => build_inprocess_relay_chain(318 polkadot_config,319 parachain_config,320 telemetry_worker_handle,321 task_manager,322 hwbench,323 ),324 }325}326327328329330#[sc_tracing::logging::prefix_logs_with("Parachain")]331async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(332 parachain_config: Configuration,333 polkadot_config: Configuration,334 collator_options: CollatorOptions,335 id: ParaId,336 build_import_queue: BIQ,337 build_consensus: BIC,338 hwbench: Option<sc_sysinfo::HwBench>,339) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>340where341 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,342 Runtime: RuntimeInstance + Send + Sync + 'static,343 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,344 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,345 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>346 + Send347 + Sync348 + 'static,349 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>350 + fp_rpc::EthereumRuntimeRPCApi<Block>351 + fp_rpc::ConvertTransactionRuntimeApi<Block>352 + sp_session::SessionKeys<Block>353 + sp_block_builder::BlockBuilder<Block>354 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>355 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>356 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>357 358359360361362363364365366367368369 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>370 + sp_api::Metadata<Block>371 + sp_offchain::OffchainWorkerApi<Block>372 + cumulus_primitives_core::CollectCollationInfo<Block>,373 ExecutorDispatch: NativeExecutionDispatch + 'static,374 BIQ: FnOnce(375 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,376 &Configuration,377 Option<TelemetryHandle>,378 &TaskManager,379 ) -> Result<380 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,381 sc_service::Error,382 >,383 BIC: FnOnce(384 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,385 Option<&Registry>,386 Option<TelemetryHandle>,387 &TaskManager,388 Arc<dyn RelayChainInterface>,389 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,390 Arc<NetworkService<Block, Hash>>,391 SyncCryptoStorePtr,392 bool,393 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,394{395 if matches!(parachain_config.role, Role::Light) {396 return Err("Light client not supported!".into());397 }398399 let parachain_config = prepare_node_config(parachain_config);400401 let params =402 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;403 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =404 params.other;405406 let client = params.client.clone();407 let backend = params.backend.clone();408 let mut task_manager = params.task_manager;409410 let (relay_chain_interface, collator_key) = build_relay_chain_interface(411 polkadot_config,412 ¶chain_config,413 telemetry_worker_handle,414 &mut task_manager,415 collator_options.clone(),416 hwbench.clone(),417 )418 .await419 .map_err(|e| match e {420 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,421 s => s.to_string().into(),422 })?;423424 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);425426 let force_authoring = parachain_config.force_authoring;427 let validator = parachain_config.role.is_authority();428 let prometheus_registry = parachain_config.prometheus_registry().cloned();429 let transaction_pool = params.transaction_pool.clone();430 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);431432 let (network, system_rpc_tx, start_network) =433 sc_service::build_network(sc_service::BuildNetworkParams {434 config: ¶chain_config,435 client: client.clone(),436 transaction_pool: transaction_pool.clone(),437 spawn_handle: task_manager.spawn_handle(),438 import_queue: import_queue.clone(),439 block_announce_validator_builder: Some(Box::new(|_| {440 Box::new(block_announce_validator)441 })),442 warp_sync: None,443 })?;444445 let rpc_client = client.clone();446 let rpc_pool = transaction_pool.clone();447 let select_chain = params.select_chain.clone();448 let rpc_network = network.clone();449450 let rpc_frontier_backend = frontier_backend.clone();451452 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(453 task_manager.spawn_handle(),454 overrides_handle::<_, _, Runtime>(client.clone()),455 50,456 50,457 prometheus_registry.clone(),458 ));459460 task_manager.spawn_essential_handle().spawn(461 "frontier-mapping-sync-worker",462 None,463 MappingSyncWorker::new(464 client.import_notification_stream(),465 Duration::new(6, 0),466 client.clone(),467 backend.clone(),468 frontier_backend.clone(),469 3,470 0,471 SyncStrategy::Normal,472 )473 .for_each(|()| futures::future::ready(())),474 );475476 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {477 let full_deps = unique_rpc::FullDeps {478 backend: rpc_frontier_backend.clone(),479 deny_unsafe,480 client: rpc_client.clone(),481 pool: rpc_pool.clone(),482 graph: rpc_pool.pool().clone(),483 484 enable_dev_signer: false,485 filter_pool: filter_pool.clone(),486 network: rpc_network.clone(),487 select_chain: select_chain.clone(),488 is_authority: validator,489 490 max_past_logs: 10000,491 block_data_cache: block_data_cache.clone(),492 fee_history_cache: fee_history_cache.clone(),493 494 fee_history_limit: 2048,495 };496497 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(498 full_deps,499 subscription_task_executor,500 )501 .map_err(Into::into)502 });503504 sc_service::spawn_tasks(sc_service::SpawnTasksParams {505 rpc_builder,506 client: client.clone(),507 transaction_pool: transaction_pool.clone(),508 task_manager: &mut task_manager,509 config: parachain_config,510 keystore: params.keystore_container.sync_keystore(),511 backend: backend.clone(),512 network: network.clone(),513 system_rpc_tx,514 telemetry: telemetry.as_mut(),515 })?;516517 if let Some(hwbench) = hwbench {518 sc_sysinfo::print_hwbench(&hwbench);519520 if let Some(ref mut telemetry) = telemetry {521 let telemetry_handle = telemetry.handle();522 task_manager.spawn_handle().spawn(523 "telemetry_hwbench",524 None,525 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),526 );527 }528 }529530 let announce_block = {531 let network = network.clone();532 Arc::new(move |hash, data| network.announce_block(hash, data))533 };534535 let relay_chain_slot_duration = Duration::from_secs(6);536537 if validator {538 let parachain_consensus = build_consensus(539 client.clone(),540 prometheus_registry.as_ref(),541 telemetry.as_ref().map(|t| t.handle()),542 &task_manager,543 relay_chain_interface.clone(),544 transaction_pool,545 network,546 params.keystore_container.sync_keystore(),547 force_authoring,548 )?;549550 let spawner = task_manager.spawn_handle();551552 let params = StartCollatorParams {553 para_id: id,554 block_status: client.clone(),555 announce_block,556 client: client.clone(),557 task_manager: &mut task_manager,558 spawner,559 parachain_consensus,560 import_queue,561 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),562 relay_chain_interface,563 relay_chain_slot_duration,564 };565566 start_collator(params).await?;567 } else {568 let params = StartFullNodeParams {569 client: client.clone(),570 announce_block,571 task_manager: &mut task_manager,572 para_id: id,573 import_queue,574 relay_chain_interface,575 relay_chain_slot_duration,576 collator_options,577 };578579 start_full_node(params)?;580 }581582 start_network.start_network();583584 Ok((task_manager, client))585}586587588pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(589 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,590 config: &Configuration,591 telemetry: Option<TelemetryHandle>,592 task_manager: &TaskManager,593) -> Result<594 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,595 sc_service::Error,596>597where598 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>599 + Send600 + Sync601 + 'static,602 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>603 + sp_block_builder::BlockBuilder<Block>604 + sp_consensus_aura::AuraApi<Block, AuraId>605 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,606 ExecutorDispatch: NativeExecutionDispatch + 'static,607{608 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;609610 cumulus_client_consensus_aura::import_queue::<611 sp_consensus_aura::sr25519::AuthorityPair,612 _,613 _,614 _,615 _,616 _,617 _,618 >(cumulus_client_consensus_aura::ImportQueueParams {619 block_import: client.clone(),620 client: client.clone(),621 create_inherent_data_providers: move |_, _| async move {622 let time = sp_timestamp::InherentDataProvider::from_system_time();623624 let slot =625 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(626 *time,627 slot_duration,628 );629630 Ok((time, slot))631 },632 registry: config.prometheus_registry(),633 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),634 spawner: &task_manager.spawn_essential_handle(),635 telemetry,636 })637 .map_err(Into::into)638}639640641pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(642 parachain_config: Configuration,643 polkadot_config: Configuration,644 collator_options: CollatorOptions,645 id: ParaId,646 hwbench: Option<sc_sysinfo::HwBench>,647) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>648where649 Runtime: RuntimeInstance + Send + Sync + 'static,650 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,651 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,652 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>653 + Send654 + Sync655 + 'static,656 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>657 + fp_rpc::EthereumRuntimeRPCApi<Block>658 + fp_rpc::ConvertTransactionRuntimeApi<Block>659 + sp_session::SessionKeys<Block>660 + sp_block_builder::BlockBuilder<Block>661 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>662 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>663 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>664 665666667668669670671672673674675676 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>677 + sp_api::Metadata<Block>678 + sp_offchain::OffchainWorkerApi<Block>679 + cumulus_primitives_core::CollectCollationInfo<Block>680 + sp_consensus_aura::AuraApi<Block, AuraId>,681 ExecutorDispatch: NativeExecutionDispatch + 'static,682{683 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(684 parachain_config,685 polkadot_config,686 collator_options,687 id,688 parachain_build_import_queue,689 |client,690 prometheus_registry,691 telemetry,692 task_manager,693 relay_chain_interface,694 transaction_pool,695 sync_oracle,696 keystore,697 force_authoring| {698 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;699700 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(701 task_manager.spawn_handle(),702 client.clone(),703 transaction_pool,704 prometheus_registry,705 telemetry.clone(),706 );707708 Ok(AuraConsensus::build::<709 sp_consensus_aura::sr25519::AuthorityPair,710 _,711 _,712 _,713 _,714 _,715 _,716 >(BuildAuraConsensusParams {717 proposer_factory,718 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {719 let relay_chain_interface = relay_chain_interface.clone();720 async move {721 let parachain_inherent =722 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(723 relay_parent,724 &relay_chain_interface,725 &validation_data,726 id,727 ).await;728729 let time = sp_timestamp::InherentDataProvider::from_system_time();730731 let slot =732 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(733 *time,734 slot_duration,735 );736737 let parachain_inherent = parachain_inherent.ok_or_else(|| {738 Box::<dyn std::error::Error + Send + Sync>::from(739 "Failed to create parachain inherent",740 )741 })?;742 Ok((time, slot, parachain_inherent))743 }744 },745 block_import: client.clone(),746 para_client: client,747 backoff_authoring_blocks: Option::<()>::None,748 sync_oracle,749 keystore,750 force_authoring,751 slot_duration,752 753 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),754 telemetry,755 max_block_proposal_slot_portion: None,756 }))757 },758 hwbench,759 )760 .await761}762763fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(764 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,765 config: &Configuration,766 _: Option<TelemetryHandle>,767 task_manager: &TaskManager,768) -> Result<769 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,770 sc_service::Error,771>772where773 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>774 + Send775 + Sync776 + 'static,777 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>778 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,779 ExecutorDispatch: NativeExecutionDispatch + 'static,780{781 Ok(sc_consensus_manual_seal::import_queue(782 Box::new(client.clone()),783 &task_manager.spawn_essential_handle(),784 config.prometheus_registry(),785 ))786}787788789790pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(791 config: Configuration,792 autoseal_interval: Duration,793) -> sc_service::error::Result<TaskManager>794where795 Runtime: RuntimeInstance + Send + Sync + 'static,796 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,797 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,798 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>799 + Send800 + Sync801 + 'static,802 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>803 + fp_rpc::EthereumRuntimeRPCApi<Block>804 + fp_rpc::ConvertTransactionRuntimeApi<Block>805 + sp_session::SessionKeys<Block>806 + sp_block_builder::BlockBuilder<Block>807 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>808 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>809 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>810 811812813814815816817818819820821822 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>823 + sp_api::Metadata<Block>824 + sp_offchain::OffchainWorkerApi<Block>825 + cumulus_primitives_core::CollectCollationInfo<Block>826 + sp_consensus_aura::AuraApi<Block, AuraId>,827 ExecutorDispatch: NativeExecutionDispatch + 'static,828{829 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};830 use fc_consensus::FrontierBlockImport;831 use sc_client_api::HeaderBackend;832833 let sc_service::PartialComponents {834 client,835 backend,836 mut task_manager,837 import_queue,838 keystore_container,839 select_chain: maybe_select_chain,840 transaction_pool,841 other:842 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),843 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(844 &config,845 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,846 )?;847 let prometheus_registry = config.prometheus_registry().cloned();848849 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(850 task_manager.spawn_handle(),851 overrides_handle::<_, _, Runtime>(client.clone()),852 50,853 50,854 prometheus_registry.clone(),855 ));856857 let (network, system_rpc_tx, network_starter) =858 sc_service::build_network(sc_service::BuildNetworkParams {859 config: &config,860 client: client.clone(),861 transaction_pool: transaction_pool.clone(),862 spawn_handle: task_manager.spawn_handle(),863 import_queue,864 block_announce_validator_builder: None,865 warp_sync: None,866 })?;867868 if config.offchain_worker.enabled {869 sc_service::build_offchain_workers(870 &config,871 task_manager.spawn_handle(),872 client.clone(),873 network.clone(),874 );875 }876877 let collator = config.role.is_authority();878879 let select_chain = maybe_select_chain.clone();880881 if collator {882 let block_import =883 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());884885 let env = sc_basic_authorship::ProposerFactory::new(886 task_manager.spawn_handle(),887 client.clone(),888 transaction_pool.clone(),889 prometheus_registry.as_ref(),890 telemetry.as_ref().map(|x| x.handle()),891 );892893 let transactions_commands_stream: Box<894 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,895 > = Box::new(896 transaction_pool897 .pool()898 .validated_pool()899 .import_notification_stream()900 .map(|_| EngineCommand::SealNewBlock {901 create_empty: true,902 finalize: false,903 parent_hash: None,904 sender: None,905 }),906 );907908 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));909 let idle_commands_stream: Box<910 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,911 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {912 create_empty: true,913 finalize: false,914 parent_hash: None,915 sender: None,916 }));917918 let commands_stream = select(transactions_commands_stream, idle_commands_stream);919920 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;921 let client_set_aside_for_cidp = client.clone();922923 task_manager.spawn_essential_handle().spawn_blocking(924 "authorship_task",925 Some("block-authoring"),926 run_manual_seal(ManualSealParams {927 block_import,928 env,929 client: client.clone(),930 pool: transaction_pool.clone(),931 commands_stream,932 select_chain: select_chain.clone(),933 consensus_data_provider: None,934 create_inherent_data_providers: move |block: Hash, ()| {935 let current_para_block = client_set_aside_for_cidp936 .number(block)937 .expect("Header lookup should succeed")938 .expect("Header passed in as parent should be present in backend.");939940 let client_for_xcm = client_set_aside_for_cidp.clone();941 async move {942 let time = sp_timestamp::InherentDataProvider::from_system_time();943944 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {945 current_para_block,946 relay_offset: 1000,947 relay_blocks_per_para_block: 2,948 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(949 &*client_for_xcm,950 block,951 Default::default(),952 Default::default(),953 ),954 raw_downward_messages: vec![],955 raw_horizontal_messages: vec![],956 };957958 let slot =959 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(960 *time,961 slot_duration,962 );963964 Ok((time, slot, mocked_parachain))965 }966 },967 }),968 );969 }970971 task_manager.spawn_essential_handle().spawn(972 "frontier-mapping-sync-worker",973 Some("block-authoring"),974 MappingSyncWorker::new(975 client.import_notification_stream(),976 Duration::new(6, 0),977 client.clone(),978 backend.clone(),979 frontier_backend.clone(),980 3,981 0,982 SyncStrategy::Normal,983 )984 .for_each(|()| futures::future::ready(())),985 );986987 let rpc_client = client.clone();988 let rpc_pool = transaction_pool.clone();989 let rpc_network = network.clone();990 let rpc_frontier_backend = frontier_backend.clone();991 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {992 let full_deps = unique_rpc::FullDeps {993 backend: rpc_frontier_backend.clone(),994 deny_unsafe,995 client: rpc_client.clone(),996 pool: rpc_pool.clone(),997 graph: rpc_pool.pool().clone(),998 999 enable_dev_signer: false,1000 filter_pool: filter_pool.clone(),1001 network: rpc_network.clone(),1002 select_chain: select_chain.clone(),1003 is_authority: collator,1004 1005 max_past_logs: 10000,1006 block_data_cache: block_data_cache.clone(),1007 fee_history_cache: fee_history_cache.clone(),1008 1009 fee_history_limit: 2048,1010 };10111012 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1013 full_deps,1014 subscription_executor,1015 )1016 .map_err(Into::into)1017 });10181019 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1020 network,1021 client,1022 keystore: keystore_container.sync_keystore(),1023 task_manager: &mut task_manager,1024 transaction_pool,1025 rpc_builder,1026 backend,1027 system_rpc_tx,1028 config,1029 telemetry: None,1030 })?;10311032 network_starter.start_network();1033 Ok(task_manager)1034}