1234567891011121314151617181920use std::sync::Arc;21use std::sync::Mutex;22use std::collections::BTreeMap;23use std::time::Duration;24use std::pin::Pin;25use fc_rpc_core::types::FeeHistoryCache;26use futures::{27 Stream, StreamExt,28 stream::select,29 task::{Context, Poll},30};31use tokio::time::Interval;3233use unique_rpc::overrides_handle;3435use serde::{Serialize, Deserialize};363738use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};39use cumulus_client_consensus_common::ParachainConsensus;40use cumulus_client_service::{41 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;495051use sc_client_api::ExecutorProvider;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::NetworkService;55use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;6162use polkadot_service::CollatorPair;636465use fc_rpc_core::types::FilterPool;66use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6768use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};697071727374757677#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]818283pub struct QuartzRuntimeExecutor;848586pub struct OpalRuntimeExecutor;8788#[cfg(feature = "unique-runtime")]89impl NativeExecutionDispatch for UniqueRuntimeExecutor {90 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9192 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {93 unique_runtime::api::dispatch(method, data)94 }9596 fn native_version() -> sc_executor::NativeVersion {97 unique_runtime::native_version()98 }99}100101#[cfg(feature = "quartz-runtime")]102impl NativeExecutionDispatch for QuartzRuntimeExecutor {103 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;104105 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {106 quartz_runtime::api::dispatch(method, data)107 }108109 fn native_version() -> sc_executor::NativeVersion {110 quartz_runtime::native_version()111 }112}113114impl NativeExecutionDispatch for OpalRuntimeExecutor {115 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;116117 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {118 opal_runtime::api::dispatch(method, data)119 }120121 fn native_version() -> sc_executor::NativeVersion {122 opal_runtime::native_version()123 }124}125126pub struct AutosealInterval {127 interval: Interval,128}129130impl AutosealInterval {131 pub fn new(config: &Configuration, interval: Duration) -> Self {132 let _tokio_runtime = config.tokio_handle.enter();133 let interval = tokio::time::interval(interval);134135 Self { interval }136 }137}138139impl Stream for AutosealInterval {140 type Item = tokio::time::Instant;141142 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {143 self.interval.poll_tick(cx).map(Some)144 }145}146147pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {148 let config_dir = config149 .base_path150 .as_ref()151 .map(|base_path| base_path.config_dir(config.chain_spec.id()))152 .unwrap_or_else(|| {153 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())154 });155 let database_dir = config_dir.join("frontier").join("db");156157 Ok(Arc::new(fc_db::Backend::<Block>::new(158 &fc_db::DatabaseSettings {159 source: fc_db::DatabaseSource::RocksDb {160 path: database_dir,161 cache_size: 0,162 },163 },164 )?))165}166167type FullClient<RuntimeApi, ExecutorDispatch> =168 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;169type FullBackend = sc_service::TFullBackend<Block>;170type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;171172173174175176#[allow(clippy::type_complexity)]177pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(178 config: &Configuration,179 build_import_queue: BIQ,180) -> Result<181 PartialComponents<182 FullClient<RuntimeApi, ExecutorDispatch>,183 FullBackend,184 FullSelectChain,185 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,186 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,187 (188 Option<Telemetry>,189 Option<FilterPool>,190 Arc<fc_db::Backend<Block>>,191 Option<TelemetryWorkerHandle>,192 FeeHistoryCache,193 ),194 >,195 sc_service::Error,196>197where198 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,199 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>200 + Send201 + Sync202 + 'static,203 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,204 ExecutorDispatch: NativeExecutionDispatch + 'static,205 BIQ: FnOnce(206 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,207 &Configuration,208 Option<TelemetryHandle>,209 &TaskManager,210 ) -> Result<211 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,212 sc_service::Error,213 >,214{215 let _telemetry = config216 .telemetry_endpoints217 .clone()218 .filter(|x| !x.is_empty())219 .map(|endpoints| -> Result<_, sc_telemetry::Error> {220 let worker = TelemetryWorker::new(16)?;221 let telemetry = worker.handle().new_telemetry(endpoints);222 Ok((worker, telemetry))223 })224 .transpose()?;225226 let telemetry = config227 .telemetry_endpoints228 .clone()229 .filter(|x| !x.is_empty())230 .map(|endpoints| -> Result<_, sc_telemetry::Error> {231 let worker = TelemetryWorker::new(16)?;232 let telemetry = worker.handle().new_telemetry(endpoints);233 Ok((worker, telemetry))234 })235 .transpose()?;236237 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(238 config.wasm_method,239 config.default_heap_pages,240 config.max_runtime_instances,241 config.runtime_cache_size,242 );243244 let (client, backend, keystore_container, task_manager) =245 sc_service::new_full_parts::<Block, RuntimeApi, _>(246 config,247 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),248 executor,249 )?;250 let client = Arc::new(client);251252 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());253254 let telemetry = telemetry.map(|(worker, telemetry)| {255 task_manager256 .spawn_handle()257 .spawn("telemetry", None, worker.run());258 telemetry259 });260261 let select_chain = sc_consensus::LongestChain::new(backend.clone());262263 let transaction_pool = sc_transaction_pool::BasicPool::new_full(264 config.transaction_pool.clone(),265 config.role.is_authority().into(),266 config.prometheus_registry(),267 task_manager.spawn_essential_handle(),268 client.clone(),269 );270271 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));272273 let frontier_backend = open_frontier_backend(config)?;274275 let import_queue = build_import_queue(276 client.clone(),277 config,278 telemetry.as_ref().map(|telemetry| telemetry.handle()),279 &task_manager,280 )?;281 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));282283 let params = PartialComponents {284 backend,285 client,286 import_queue,287 keystore_container,288 task_manager,289 transaction_pool,290 select_chain,291 other: (292 telemetry,293 filter_pool,294 frontier_backend,295 telemetry_worker_handle,296 fee_history_cache,297 ),298 };299300 Ok(params)301}302303async fn build_relay_chain_interface(304 polkadot_config: Configuration,305 parachain_config: &Configuration,306 telemetry_worker_handle: Option<TelemetryWorkerHandle>,307 task_manager: &mut TaskManager,308 collator_options: CollatorOptions,309 hwbench: Option<sc_sysinfo::HwBench>,310) -> RelayChainResult<(311 Arc<(dyn RelayChainInterface + 'static)>,312 Option<CollatorPair>,313)> {314 match collator_options.relay_chain_rpc_url {315 Some(relay_chain_url) => Ok((316 Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,317 None,318 )),319 None => build_inprocess_relay_chain(320 polkadot_config,321 parachain_config,322 telemetry_worker_handle,323 task_manager,324 hwbench,325 ),326 }327}328329330331332#[sc_tracing::logging::prefix_logs_with("Parachain")]333async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(334 parachain_config: Configuration,335 polkadot_config: Configuration,336 collator_options: CollatorOptions,337 id: ParaId,338 build_import_queue: BIQ,339 build_consensus: BIC,340 hwbench: Option<sc_sysinfo::HwBench>,341) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>342where343 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,344 Runtime: RuntimeInstance + Send + Sync + 'static,345 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,346 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,347 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>348 + Send349 + Sync350 + 'static,351 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>352 + fp_rpc::EthereumRuntimeRPCApi<Block>353 + fp_rpc::ConvertTransactionRuntimeApi<Block>354 + sp_session::SessionKeys<Block>355 + sp_block_builder::BlockBuilder<Block>356 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>357 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>358 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>359 360361362363364365366367368369370371 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>372 + sp_api::Metadata<Block>373 + sp_offchain::OffchainWorkerApi<Block>374 + cumulus_primitives_core::CollectCollationInfo<Block>,375 ExecutorDispatch: NativeExecutionDispatch + 'static,376 BIQ: FnOnce(377 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,378 &Configuration,379 Option<TelemetryHandle>,380 &TaskManager,381 ) -> Result<382 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,383 sc_service::Error,384 >,385 BIC: FnOnce(386 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,387 Option<&Registry>,388 Option<TelemetryHandle>,389 &TaskManager,390 Arc<dyn RelayChainInterface>,391 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,392 Arc<NetworkService<Block, Hash>>,393 SyncCryptoStorePtr,394 bool,395 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,396{397 if matches!(parachain_config.role, Role::Light) {398 return Err("Light client not supported!".into());399 }400401 let parachain_config = prepare_node_config(parachain_config);402403 let params =404 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;405 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =406 params.other;407408 let client = params.client.clone();409 let backend = params.backend.clone();410 let mut task_manager = params.task_manager;411412 let (relay_chain_interface, collator_key) = build_relay_chain_interface(413 polkadot_config,414 ¶chain_config,415 telemetry_worker_handle,416 &mut task_manager,417 collator_options.clone(),418 hwbench.clone(),419 )420 .await421 .map_err(|e| match e {422 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,423 s => s.to_string().into(),424 })?;425426 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);427428 let force_authoring = parachain_config.force_authoring;429 let validator = parachain_config.role.is_authority();430 let prometheus_registry = parachain_config.prometheus_registry().cloned();431 let transaction_pool = params.transaction_pool.clone();432 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);433434 let (network, system_rpc_tx, start_network) =435 sc_service::build_network(sc_service::BuildNetworkParams {436 config: ¶chain_config,437 client: client.clone(),438 transaction_pool: transaction_pool.clone(),439 spawn_handle: task_manager.spawn_handle(),440 import_queue: import_queue.clone(),441 block_announce_validator_builder: Some(Box::new(|_| {442 Box::new(block_announce_validator)443 })),444 warp_sync: None,445 })?;446447 let rpc_client = client.clone();448 let rpc_pool = transaction_pool.clone();449 let select_chain = params.select_chain.clone();450 let rpc_network = network.clone();451452 let rpc_frontier_backend = frontier_backend.clone();453454 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(455 task_manager.spawn_handle(),456 overrides_handle::<_, _, Runtime>(client.clone()),457 50,458 50,459 prometheus_registry.clone(),460 ));461462 task_manager.spawn_essential_handle().spawn(463 "frontier-mapping-sync-worker",464 None,465 MappingSyncWorker::new(466 client.import_notification_stream(),467 Duration::new(6, 0),468 client.clone(),469 backend.clone(),470 frontier_backend.clone(),471 3,472 0,473 SyncStrategy::Normal,474 )475 .for_each(|()| futures::future::ready(())),476 );477478 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {479 let full_deps = unique_rpc::FullDeps {480 backend: rpc_frontier_backend.clone(),481 deny_unsafe,482 client: rpc_client.clone(),483 pool: rpc_pool.clone(),484 graph: rpc_pool.pool().clone(),485 486 enable_dev_signer: false,487 filter_pool: filter_pool.clone(),488 network: rpc_network.clone(),489 select_chain: select_chain.clone(),490 is_authority: validator,491 492 max_past_logs: 10000,493 block_data_cache: block_data_cache.clone(),494 fee_history_cache: fee_history_cache.clone(),495 496 fee_history_limit: 2048,497 };498499 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(500 full_deps,501 subscription_task_executor,502 )503 .map_err(Into::into)504 });505506 sc_service::spawn_tasks(sc_service::SpawnTasksParams {507 rpc_builder,508 client: client.clone(),509 transaction_pool: transaction_pool.clone(),510 task_manager: &mut task_manager,511 config: parachain_config,512 keystore: params.keystore_container.sync_keystore(),513 backend: backend.clone(),514 network: network.clone(),515 system_rpc_tx,516 telemetry: telemetry.as_mut(),517 })?;518519 if let Some(hwbench) = hwbench {520 sc_sysinfo::print_hwbench(&hwbench);521522 if let Some(ref mut telemetry) = telemetry {523 let telemetry_handle = telemetry.handle();524 task_manager.spawn_handle().spawn(525 "telemetry_hwbench",526 None,527 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),528 );529 }530 }531532 let announce_block = {533 let network = network.clone();534 Arc::new(move |hash, data| network.announce_block(hash, data))535 };536537 let relay_chain_slot_duration = Duration::from_secs(6);538539 if validator {540 let parachain_consensus = build_consensus(541 client.clone(),542 prometheus_registry.as_ref(),543 telemetry.as_ref().map(|t| t.handle()),544 &task_manager,545 relay_chain_interface.clone(),546 transaction_pool,547 network,548 params.keystore_container.sync_keystore(),549 force_authoring,550 )?;551552 let spawner = task_manager.spawn_handle();553554 let params = StartCollatorParams {555 para_id: id,556 block_status: client.clone(),557 announce_block,558 client: client.clone(),559 task_manager: &mut task_manager,560 spawner,561 parachain_consensus,562 import_queue,563 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),564 relay_chain_interface,565 relay_chain_slot_duration,566 };567568 start_collator(params).await?;569 } else {570 let params = StartFullNodeParams {571 client: client.clone(),572 announce_block,573 task_manager: &mut task_manager,574 para_id: id,575 import_queue,576 relay_chain_interface,577 relay_chain_slot_duration,578 collator_options,579 };580581 start_full_node(params)?;582 }583584 start_network.start_network();585586 Ok((task_manager, client))587}588589590pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(591 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,592 config: &Configuration,593 telemetry: Option<TelemetryHandle>,594 task_manager: &TaskManager,595) -> Result<596 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,597 sc_service::Error,598>599where600 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>601 + Send602 + Sync603 + 'static,604 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>605 + sp_block_builder::BlockBuilder<Block>606 + sp_consensus_aura::AuraApi<Block, AuraId>607 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,608 ExecutorDispatch: NativeExecutionDispatch + 'static,609{610 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;611612 cumulus_client_consensus_aura::import_queue::<613 sp_consensus_aura::sr25519::AuthorityPair,614 _,615 _,616 _,617 _,618 _,619 _,620 >(cumulus_client_consensus_aura::ImportQueueParams {621 block_import: client.clone(),622 client: client.clone(),623 create_inherent_data_providers: move |_, _| async move {624 let time = sp_timestamp::InherentDataProvider::from_system_time();625626 let slot =627 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(628 *time,629 slot_duration,630 );631632 Ok((time, slot))633 },634 registry: config.prometheus_registry(),635 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),636 spawner: &task_manager.spawn_essential_handle(),637 telemetry,638 })639 .map_err(Into::into)640}641642643pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(644 parachain_config: Configuration,645 polkadot_config: Configuration,646 collator_options: CollatorOptions,647 id: ParaId,648 hwbench: Option<sc_sysinfo::HwBench>,649) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>650where651 Runtime: RuntimeInstance + Send + Sync + 'static,652 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,653 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,654 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>655 + Send656 + Sync657 + 'static,658 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>659 + fp_rpc::EthereumRuntimeRPCApi<Block>660 + fp_rpc::ConvertTransactionRuntimeApi<Block>661 + sp_session::SessionKeys<Block>662 + sp_block_builder::BlockBuilder<Block>663 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>664 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>665 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>666 667668669670671672673674675676677678 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>679 + sp_api::Metadata<Block>680 + sp_offchain::OffchainWorkerApi<Block>681 + cumulus_primitives_core::CollectCollationInfo<Block>682 + sp_consensus_aura::AuraApi<Block, AuraId>,683 ExecutorDispatch: NativeExecutionDispatch + 'static,684{685 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(686 parachain_config,687 polkadot_config,688 collator_options,689 id,690 parachain_build_import_queue,691 |client,692 prometheus_registry,693 telemetry,694 task_manager,695 relay_chain_interface,696 transaction_pool,697 sync_oracle,698 keystore,699 force_authoring| {700 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;701702 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(703 task_manager.spawn_handle(),704 client.clone(),705 transaction_pool,706 prometheus_registry,707 telemetry.clone(),708 );709710 Ok(AuraConsensus::build::<711 sp_consensus_aura::sr25519::AuthorityPair,712 _,713 _,714 _,715 _,716 _,717 _,718 >(BuildAuraConsensusParams {719 proposer_factory,720 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {721 let relay_chain_interface = relay_chain_interface.clone();722 async move {723 let parachain_inherent =724 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(725 relay_parent,726 &relay_chain_interface,727 &validation_data,728 id,729 ).await;730731 let time = sp_timestamp::InherentDataProvider::from_system_time();732733 let slot =734 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(735 *time,736 slot_duration,737 );738739 let parachain_inherent = parachain_inherent.ok_or_else(|| {740 Box::<dyn std::error::Error + Send + Sync>::from(741 "Failed to create parachain inherent",742 )743 })?;744 Ok((time, slot, parachain_inherent))745 }746 },747 block_import: client.clone(),748 para_client: client,749 backoff_authoring_blocks: Option::<()>::None,750 sync_oracle,751 keystore,752 force_authoring,753 slot_duration,754 755 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),756 telemetry,757 max_block_proposal_slot_portion: None,758 }))759 },760 hwbench,761 )762 .await763}764765fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(766 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,767 config: &Configuration,768 _: Option<TelemetryHandle>,769 task_manager: &TaskManager,770) -> Result<771 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,772 sc_service::Error,773>774where775 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>776 + Send777 + Sync778 + 'static,779 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>780 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,781 ExecutorDispatch: NativeExecutionDispatch + 'static,782{783 Ok(sc_consensus_manual_seal::import_queue(784 Box::new(client.clone()),785 &task_manager.spawn_essential_handle(),786 config.prometheus_registry(),787 ))788}789790791792pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(793 config: Configuration,794 autoseal_interval: Duration,795) -> sc_service::error::Result<TaskManager>796where797 Runtime: RuntimeInstance + Send + Sync + 'static,798 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,799 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,800 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>801 + Send802 + Sync803 + 'static,804 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>805 + fp_rpc::EthereumRuntimeRPCApi<Block>806 + fp_rpc::ConvertTransactionRuntimeApi<Block>807 + sp_session::SessionKeys<Block>808 + sp_block_builder::BlockBuilder<Block>809 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>810 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>811 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>812 813814815816817818819820821822823824 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>825 + sp_api::Metadata<Block>826 + sp_offchain::OffchainWorkerApi<Block>827 + cumulus_primitives_core::CollectCollationInfo<Block>828 + sp_consensus_aura::AuraApi<Block, AuraId>,829 ExecutorDispatch: NativeExecutionDispatch + 'static,830{831 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};832 use fc_consensus::FrontierBlockImport;833 use sc_client_api::HeaderBackend;834835 let sc_service::PartialComponents {836 client,837 backend,838 mut task_manager,839 import_queue,840 keystore_container,841 select_chain: maybe_select_chain,842 transaction_pool,843 other:844 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),845 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(846 &config,847 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,848 )?;849 let prometheus_registry = config.prometheus_registry().cloned();850851 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(852 task_manager.spawn_handle(),853 overrides_handle::<_, _, Runtime>(client.clone()),854 50,855 50,856 prometheus_registry.clone(),857 ));858859 let (network, system_rpc_tx, network_starter) =860 sc_service::build_network(sc_service::BuildNetworkParams {861 config: &config,862 client: client.clone(),863 transaction_pool: transaction_pool.clone(),864 spawn_handle: task_manager.spawn_handle(),865 import_queue,866 block_announce_validator_builder: None,867 warp_sync: None,868 })?;869870 if config.offchain_worker.enabled {871 sc_service::build_offchain_workers(872 &config,873 task_manager.spawn_handle(),874 client.clone(),875 network.clone(),876 );877 }878879 let collator = config.role.is_authority();880881 let select_chain = maybe_select_chain.clone();882883 if collator {884 let block_import =885 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());886887 let env = sc_basic_authorship::ProposerFactory::new(888 task_manager.spawn_handle(),889 client.clone(),890 transaction_pool.clone(),891 prometheus_registry.as_ref(),892 telemetry.as_ref().map(|x| x.handle()),893 );894895 let transactions_commands_stream: Box<896 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,897 > = Box::new(898 transaction_pool899 .pool()900 .validated_pool()901 .import_notification_stream()902 .map(|_| EngineCommand::SealNewBlock {903 create_empty: true,904 finalize: false,905 parent_hash: None,906 sender: None,907 }),908 );909910 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));911 let idle_commands_stream: Box<912 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,913 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {914 create_empty: true,915 finalize: false,916 parent_hash: None,917 sender: None,918 }));919920 let commands_stream = select(transactions_commands_stream, idle_commands_stream);921922 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;923 let client_set_aside_for_cidp = client.clone();924925 task_manager.spawn_essential_handle().spawn_blocking(926 "authorship_task",927 Some("block-authoring"),928 run_manual_seal(ManualSealParams {929 block_import,930 env,931 client: client.clone(),932 pool: transaction_pool.clone(),933 commands_stream,934 select_chain: select_chain.clone(),935 consensus_data_provider: None,936 create_inherent_data_providers: move |block: Hash, ()| {937 let current_para_block = client_set_aside_for_cidp938 .number(block)939 .expect("Header lookup should succeed")940 .expect("Header passed in as parent should be present in backend.");941942 let client_for_xcm = client_set_aside_for_cidp.clone();943 async move {944 let time = sp_timestamp::InherentDataProvider::from_system_time();945946 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {947 current_para_block,948 relay_offset: 1000,949 relay_blocks_per_para_block: 2,950 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(951 &*client_for_xcm,952 block,953 Default::default(),954 Default::default(),955 ),956 raw_downward_messages: vec![],957 raw_horizontal_messages: vec![],958 };959960 let slot =961 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(962 *time,963 slot_duration,964 );965966 Ok((time, slot, mocked_parachain))967 }968 },969 }),970 );971 }972973 task_manager.spawn_essential_handle().spawn(974 "frontier-mapping-sync-worker",975 Some("block-authoring"),976 MappingSyncWorker::new(977 client.import_notification_stream(),978 Duration::new(6, 0),979 client.clone(),980 backend.clone(),981 frontier_backend.clone(),982 3,983 0,984 SyncStrategy::Normal,985 )986 .for_each(|()| futures::future::ready(())),987 );988989 let rpc_client = client.clone();990 let rpc_pool = transaction_pool.clone();991 let rpc_network = network.clone();992 let rpc_frontier_backend = frontier_backend.clone();993 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {994 let full_deps = unique_rpc::FullDeps {995 backend: rpc_frontier_backend.clone(),996 deny_unsafe,997 client: rpc_client.clone(),998 pool: rpc_pool.clone(),999 graph: rpc_pool.pool().clone(),1000 1001 enable_dev_signer: false,1002 filter_pool: filter_pool.clone(),1003 network: rpc_network.clone(),1004 select_chain: select_chain.clone(),1005 is_authority: collator,1006 1007 max_past_logs: 10000,1008 block_data_cache: block_data_cache.clone(),1009 fee_history_cache: fee_history_cache.clone(),1010 1011 fee_history_limit: 2048,1012 };10131014 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1015 full_deps,1016 subscription_executor,1017 )1018 .map_err(Into::into)1019 });10201021 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1022 network,1023 client,1024 keystore: keystore_container.sync_keystore(),1025 task_manager: &mut task_manager,1026 transaction_pool,1027 rpc_builder,1028 backend,1029 system_rpc_tx,1030 config,1031 telemetry: None,1032 })?;10331034 network_starter.start_network();1035 Ok(task_manager)1036}