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::{38 ParachainConsensus, ParachainBlockImport as TParachainBlockImport,39};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_minimal_node::build_minimal_relay_chain_node;495051use sp_api::BlockT;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::{NetworkService, NetworkBlock};55use sc_service::{BasePath, Configuration, PartialComponents, 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 up_common::types::opaque::{69 AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,70};717273use up_data_structs::{74 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,75 RmrkPartType, RmrkTheme,76};777879#[cfg(feature = "unique-runtime")]80pub struct UniqueRuntimeExecutor;8182#[cfg(feature = "quartz-runtime")]8384pub struct QuartzRuntimeExecutor;858687pub struct OpalRuntimeExecutor;8889#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]90pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9192#[cfg(all(93 not(feature = "unique-runtime"),94 feature = "quartz-runtime",95 feature = "runtime-benchmarks"96))]97pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9899#[cfg(all(100 not(feature = "unique-runtime"),101 not(feature = "quartz-runtime"),102 feature = "runtime-benchmarks"103))]104pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;105106#[cfg(feature = "unique-runtime")]107impl NativeExecutionDispatch for UniqueRuntimeExecutor {108 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;109110 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {111 unique_runtime::api::dispatch(method, data)112 }113114 fn native_version() -> sc_executor::NativeVersion {115 unique_runtime::native_version()116 }117}118119#[cfg(feature = "quartz-runtime")]120impl NativeExecutionDispatch for QuartzRuntimeExecutor {121 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;122123 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124 quartz_runtime::api::dispatch(method, data)125 }126127 fn native_version() -> sc_executor::NativeVersion {128 quartz_runtime::native_version()129 }130}131132impl NativeExecutionDispatch for OpalRuntimeExecutor {133 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;134135 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {136 opal_runtime::api::dispatch(method, data)137 }138139 fn native_version() -> sc_executor::NativeVersion {140 opal_runtime::native_version()141 }142}143144pub struct AutosealInterval {145 interval: Interval,146}147148impl AutosealInterval {149 pub fn new(config: &Configuration, interval: Duration) -> Self {150 let _tokio_runtime = config.tokio_handle.enter();151 let interval = tokio::time::interval(interval);152153 Self { interval }154 }155}156157impl Stream for AutosealInterval {158 type Item = tokio::time::Instant;159160 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {161 self.interval.poll_tick(cx).map(Some)162 }163}164165pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(166 client: Arc<C>,167 config: &Configuration,168) -> Result<Arc<fc_db::Backend<Block>>, String> {169 let config_dir = config170 .base_path171 .as_ref()172 .map(|base_path| base_path.config_dir(config.chain_spec.id()))173 .unwrap_or_else(|| {174 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())175 });176 let database_dir = config_dir.join("frontier").join("db");177178 Ok(Arc::new(fc_db::Backend::<Block>::new(179 client,180 &fc_db::DatabaseSettings {181 source: fc_db::DatabaseSource::RocksDb {182 path: database_dir,183 cache_size: 0,184 },185 },186 )?))187}188189type FullClient<RuntimeApi, ExecutorDispatch> =190 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;191type FullBackend = sc_service::TFullBackend<Block>;192type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;193type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =194 TParachainBlockImport<Arc<FullClient<RuntimeApi, ExecutorDispatch>>>;195196197198199200#[allow(clippy::type_complexity)]201pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(202 config: &Configuration,203 build_import_queue: BIQ,204) -> Result<205 PartialComponents<206 FullClient<RuntimeApi, ExecutorDispatch>,207 FullBackend,208 FullSelectChain,209 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,210 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,211 (212 Option<Telemetry>,213 Option<FilterPool>,214 Arc<fc_db::Backend<Block>>,215 Option<TelemetryWorkerHandle>,216 FeeHistoryCache,217 ),218 >,219 sc_service::Error,220>221where222 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,223 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>224 + Send225 + Sync226 + 'static,227 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,228 ExecutorDispatch: NativeExecutionDispatch + 'static,229 BIQ: FnOnce(230 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,231 &Configuration,232 Option<TelemetryHandle>,233 &TaskManager,234 ) -> Result<235 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,236 sc_service::Error,237 >,238{239 let _telemetry = config240 .telemetry_endpoints241 .clone()242 .filter(|x| !x.is_empty())243 .map(|endpoints| -> Result<_, sc_telemetry::Error> {244 let worker = TelemetryWorker::new(16)?;245 let telemetry = worker.handle().new_telemetry(endpoints);246 Ok((worker, telemetry))247 })248 .transpose()?;249250 let telemetry = config251 .telemetry_endpoints252 .clone()253 .filter(|x| !x.is_empty())254 .map(|endpoints| -> Result<_, sc_telemetry::Error> {255 let worker = TelemetryWorker::new(16)?;256 let telemetry = worker.handle().new_telemetry(endpoints);257 Ok((worker, telemetry))258 })259 .transpose()?;260261 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(262 config.wasm_method,263 config.default_heap_pages,264 config.max_runtime_instances,265 config.runtime_cache_size,266 );267268 let (client, backend, keystore_container, task_manager) =269 sc_service::new_full_parts::<Block, RuntimeApi, _>(270 config,271 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),272 executor,273 )?;274 let client = Arc::new(client);275276 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());277278 let telemetry = telemetry.map(|(worker, telemetry)| {279 task_manager280 .spawn_handle()281 .spawn("telemetry", None, worker.run());282 telemetry283 });284285 let select_chain = sc_consensus::LongestChain::new(backend.clone());286287 let transaction_pool = sc_transaction_pool::BasicPool::new_full(288 config.transaction_pool.clone(),289 config.role.is_authority().into(),290 config.prometheus_registry(),291 task_manager.spawn_essential_handle(),292 client.clone(),293 );294295 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));296297 let frontier_backend = open_frontier_backend(client.clone(), config)?;298299 let import_queue = build_import_queue(300 client.clone(),301 config,302 telemetry.as_ref().map(|telemetry| telemetry.handle()),303 &task_manager,304 )?;305 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));306307 let params = PartialComponents {308 backend,309 client,310 import_queue,311 keystore_container,312 task_manager,313 transaction_pool,314 select_chain,315 other: (316 telemetry,317 filter_pool,318 frontier_backend,319 telemetry_worker_handle,320 fee_history_cache,321 ),322 };323324 Ok(params)325}326327async fn build_relay_chain_interface(328 polkadot_config: Configuration,329 parachain_config: &Configuration,330 telemetry_worker_handle: Option<TelemetryWorkerHandle>,331 task_manager: &mut TaskManager,332 collator_options: CollatorOptions,333 hwbench: Option<sc_sysinfo::HwBench>,334) -> RelayChainResult<(335 Arc<(dyn RelayChainInterface + 'static)>,336 Option<CollatorPair>,337)> {338 match collator_options.relay_chain_rpc_url {339 Some(relay_chain_url) => {340 build_minimal_relay_chain_node(polkadot_config, task_manager, relay_chain_url).await341 }342 None => build_inprocess_relay_chain(343 polkadot_config,344 parachain_config,345 telemetry_worker_handle,346 task_manager,347 hwbench,348 ),349 }350}351352353354355#[sc_tracing::logging::prefix_logs_with("Parachain")]356async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(357 parachain_config: Configuration,358 polkadot_config: Configuration,359 collator_options: CollatorOptions,360 id: ParaId,361 build_import_queue: BIQ,362 build_consensus: BIC,363 hwbench: Option<sc_sysinfo::HwBench>,364) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>365where366 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,367 Runtime: RuntimeInstance + Send + Sync + 'static,368 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,369 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,370 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>371 + Send372 + Sync373 + 'static,374 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>375 + fp_rpc::EthereumRuntimeRPCApi<Block>376 + fp_rpc::ConvertTransactionRuntimeApi<Block>377 + sp_session::SessionKeys<Block>378 + sp_block_builder::BlockBuilder<Block>379 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>380 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>381 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>382 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>383 + rmrk_rpc::RmrkApi<384 Block,385 AccountId,386 RmrkCollectionInfo<AccountId>,387 RmrkInstanceInfo<AccountId>,388 RmrkResourceInfo,389 RmrkPropertyInfo,390 RmrkBaseInfo<AccountId>,391 RmrkPartType,392 RmrkTheme,393 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>394 + sp_api::Metadata<Block>395 + sp_offchain::OffchainWorkerApi<Block>396 + cumulus_primitives_core::CollectCollationInfo<Block>,397 ExecutorDispatch: NativeExecutionDispatch + 'static,398 BIQ: FnOnce(399 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,400 &Configuration,401 Option<TelemetryHandle>,402 &TaskManager,403 ) -> Result<404 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,405 sc_service::Error,406 >,407 BIC: FnOnce(408 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,409 Option<&Registry>,410 Option<TelemetryHandle>,411 &TaskManager,412 Arc<dyn RelayChainInterface>,413 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,414 Arc<NetworkService<Block, Hash>>,415 SyncCryptoStorePtr,416 bool,417 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,418{419 let parachain_config = prepare_node_config(parachain_config);420421 let params =422 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;423 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =424 params.other;425426 let client = params.client.clone();427 let backend = params.backend.clone();428 let mut task_manager = params.task_manager;429430 let (relay_chain_interface, collator_key) = build_relay_chain_interface(431 polkadot_config,432 ¶chain_config,433 telemetry_worker_handle,434 &mut task_manager,435 collator_options.clone(),436 hwbench.clone(),437 )438 .await439 .map_err(|e| match e {440 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,441 s => s.to_string().into(),442 })?;443444 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);445446 let force_authoring = parachain_config.force_authoring;447 let validator = parachain_config.role.is_authority();448 let prometheus_registry = parachain_config.prometheus_registry().cloned();449 let transaction_pool = params.transaction_pool.clone();450 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);451452 let (network, system_rpc_tx, tx_handler_controller, start_network) =453 sc_service::build_network(sc_service::BuildNetworkParams {454 config: ¶chain_config,455 client: client.clone(),456 transaction_pool: transaction_pool.clone(),457 spawn_handle: task_manager.spawn_handle(),458 import_queue: import_queue.clone(),459 block_announce_validator_builder: Some(Box::new(|_| {460 Box::new(block_announce_validator)461 })),462 warp_sync: None,463 })?;464465 let rpc_client = client.clone();466 let rpc_pool = transaction_pool.clone();467 let select_chain = params.select_chain.clone();468 let rpc_network = network.clone();469470 let rpc_frontier_backend = frontier_backend.clone();471472 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(473 task_manager.spawn_handle(),474 overrides_handle::<_, _, Runtime>(client.clone()),475 50,476 50,477 prometheus_registry.clone(),478 ));479480 task_manager.spawn_essential_handle().spawn(481 "frontier-mapping-sync-worker",482 None,483 MappingSyncWorker::new(484 client.import_notification_stream(),485 Duration::new(6, 0),486 client.clone(),487 backend.clone(),488 frontier_backend.clone(),489 3,490 0,491 SyncStrategy::Normal,492 )493 .for_each(|()| futures::future::ready(())),494 );495496 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {497 let full_deps = unique_rpc::FullDeps {498 backend: rpc_frontier_backend.clone(),499 deny_unsafe,500 client: rpc_client.clone(),501 pool: rpc_pool.clone(),502 graph: rpc_pool.pool().clone(),503 504 enable_dev_signer: false,505 filter_pool: filter_pool.clone(),506 network: rpc_network.clone(),507 select_chain: select_chain.clone(),508 is_authority: validator,509 510 max_past_logs: 10000,511 block_data_cache: block_data_cache.clone(),512 fee_history_cache: fee_history_cache.clone(),513 514 fee_history_limit: 2048,515 };516517 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(518 full_deps,519 subscription_task_executor,520 )521 .map_err(Into::into)522 });523524 sc_service::spawn_tasks(sc_service::SpawnTasksParams {525 rpc_builder,526 client: client.clone(),527 transaction_pool: transaction_pool.clone(),528 task_manager: &mut task_manager,529 config: parachain_config,530 keystore: params.keystore_container.sync_keystore(),531 backend: backend.clone(),532 network: network.clone(),533 system_rpc_tx,534 telemetry: telemetry.as_mut(),535 tx_handler_controller,536 })?;537538 if let Some(hwbench) = hwbench {539 sc_sysinfo::print_hwbench(&hwbench);540541 if let Some(ref mut telemetry) = telemetry {542 let telemetry_handle = telemetry.handle();543 task_manager.spawn_handle().spawn(544 "telemetry_hwbench",545 None,546 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),547 );548 }549 }550551 let announce_block = {552 let network = network.clone();553 Arc::new(Box::new(move |hash, data| {554 network.announce_block(hash, data)555 }))556 };557558 let relay_chain_slot_duration = Duration::from_secs(6);559560 if validator {561 let parachain_consensus = build_consensus(562 client.clone(),563 prometheus_registry.as_ref(),564 telemetry.as_ref().map(|t| t.handle()),565 &task_manager,566 relay_chain_interface.clone(),567 transaction_pool,568 network,569 params.keystore_container.sync_keystore(),570 force_authoring,571 )?;572573 let spawner = task_manager.spawn_handle();574575 let params = StartCollatorParams {576 para_id: id,577 block_status: client.clone(),578 announce_block,579 client: client.clone(),580 task_manager: &mut task_manager,581 spawner,582 parachain_consensus,583 import_queue,584 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),585 relay_chain_interface,586 relay_chain_slot_duration,587 };588589 start_collator(params).await?;590 } else {591 let params = StartFullNodeParams {592 client: client.clone(),593 announce_block,594 task_manager: &mut task_manager,595 para_id: id,596 import_queue,597 relay_chain_interface,598 relay_chain_slot_duration,599 };600601 start_full_node(params)?;602 }603604 start_network.start_network();605606 Ok((task_manager, client))607}608609610pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(611 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,612 config: &Configuration,613 telemetry: Option<TelemetryHandle>,614 task_manager: &TaskManager,615) -> Result<616 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,617 sc_service::Error,618>619where620 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>621 + Send622 + Sync623 + 'static,624 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>625 + sp_block_builder::BlockBuilder<Block>626 + sp_consensus_aura::AuraApi<Block, AuraId>627 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,628 ExecutorDispatch: NativeExecutionDispatch + 'static,629{630 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;631632 let block_import = ParachainBlockImport::new(client.clone());633634 cumulus_client_consensus_aura::import_queue::<635 sp_consensus_aura::sr25519::AuthorityPair,636 _,637 _,638 _,639 _,640 _,641 >(cumulus_client_consensus_aura::ImportQueueParams {642 block_import,643 client: client.clone(),644 create_inherent_data_providers: move |_, _| async move {645 let time = sp_timestamp::InherentDataProvider::from_system_time();646647 let slot =648 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(649 *time,650 slot_duration,651 );652653 Ok((slot, time))654 },655 registry: config.prometheus_registry(),656 spawner: &task_manager.spawn_essential_handle(),657 telemetry,658 })659 .map_err(Into::into)660}661662663pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(664 parachain_config: Configuration,665 polkadot_config: Configuration,666 collator_options: CollatorOptions,667 id: ParaId,668 hwbench: Option<sc_sysinfo::HwBench>,669) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>670where671 Runtime: RuntimeInstance + Send + Sync + 'static,672 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,673 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,674 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>675 + Send676 + Sync677 + 'static,678 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>679 + fp_rpc::EthereumRuntimeRPCApi<Block>680 + fp_rpc::ConvertTransactionRuntimeApi<Block>681 + sp_session::SessionKeys<Block>682 + sp_block_builder::BlockBuilder<Block>683 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>684 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>685 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>686 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>687 + rmrk_rpc::RmrkApi<688 Block,689 AccountId,690 RmrkCollectionInfo<AccountId>,691 RmrkInstanceInfo<AccountId>,692 RmrkResourceInfo,693 RmrkPropertyInfo,694 RmrkBaseInfo<AccountId>,695 RmrkPartType,696 RmrkTheme,697 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>698 + sp_api::Metadata<Block>699 + sp_offchain::OffchainWorkerApi<Block>700 + cumulus_primitives_core::CollectCollationInfo<Block>701 + sp_consensus_aura::AuraApi<Block, AuraId>,702 ExecutorDispatch: NativeExecutionDispatch + 'static,703{704 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(705 parachain_config,706 polkadot_config,707 collator_options,708 id,709 parachain_build_import_queue,710 |client,711 prometheus_registry,712 telemetry,713 task_manager,714 relay_chain_interface,715 transaction_pool,716 sync_oracle,717 keystore,718 force_authoring| {719 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;720721 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(722 task_manager.spawn_handle(),723 client.clone(),724 transaction_pool,725 prometheus_registry,726 telemetry.clone(),727 );728729 let block_import = ParachainBlockImport::new(client.clone());730731 Ok(AuraConsensus::build::<732 sp_consensus_aura::sr25519::AuthorityPair,733 _,734 _,735 _,736 _,737 _,738 _,739 >(BuildAuraConsensusParams {740 proposer_factory,741 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {742 let relay_chain_interface = relay_chain_interface.clone();743 async move {744 let parachain_inherent =745 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(746 relay_parent,747 &relay_chain_interface,748 &validation_data,749 id,750 ).await;751752 let time = sp_timestamp::InherentDataProvider::from_system_time();753754 let slot =755 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(756 *time,757 slot_duration,758 );759760 let parachain_inherent = parachain_inherent.ok_or_else(|| {761 Box::<dyn std::error::Error + Send + Sync>::from(762 "Failed to create parachain inherent",763 )764 })?;765 Ok((slot, time, parachain_inherent))766 }767 },768 block_import,769 para_client: client,770 backoff_authoring_blocks: Option::<()>::None,771 sync_oracle,772 keystore,773 force_authoring,774 slot_duration,775 776 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),777 telemetry,778 max_block_proposal_slot_portion: None,779 }))780 },781 hwbench,782 )783 .await784}785786fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(787 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,788 config: &Configuration,789 _: Option<TelemetryHandle>,790 task_manager: &TaskManager,791) -> Result<792 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,793 sc_service::Error,794>795where796 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>797 + Send798 + Sync799 + 'static,800 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>801 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,802 ExecutorDispatch: NativeExecutionDispatch + 'static,803{804 Ok(sc_consensus_manual_seal::import_queue(805 Box::new(client.clone()),806 &task_manager.spawn_essential_handle(),807 config.prometheus_registry(),808 ))809}810811812813pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(814 config: Configuration,815 autoseal_interval: Duration,816) -> sc_service::error::Result<TaskManager>817where818 Runtime: RuntimeInstance + Send + Sync + 'static,819 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,820 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,821 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>822 + Send823 + Sync824 + 'static,825 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>826 + fp_rpc::EthereumRuntimeRPCApi<Block>827 + fp_rpc::ConvertTransactionRuntimeApi<Block>828 + sp_session::SessionKeys<Block>829 + sp_block_builder::BlockBuilder<Block>830 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>831 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>832 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>833 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>834 + rmrk_rpc::RmrkApi<835 Block,836 AccountId,837 RmrkCollectionInfo<AccountId>,838 RmrkInstanceInfo<AccountId>,839 RmrkResourceInfo,840 RmrkPropertyInfo,841 RmrkBaseInfo<AccountId>,842 RmrkPartType,843 RmrkTheme,844 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>845 + sp_api::Metadata<Block>846 + sp_offchain::OffchainWorkerApi<Block>847 + cumulus_primitives_core::CollectCollationInfo<Block>848 + sp_consensus_aura::AuraApi<Block, AuraId>,849 ExecutorDispatch: NativeExecutionDispatch + 'static,850{851 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};852 use fc_consensus::FrontierBlockImport;853 use sc_client_api::HeaderBackend;854855 let sc_service::PartialComponents {856 client,857 backend,858 mut task_manager,859 import_queue,860 keystore_container,861 select_chain: maybe_select_chain,862 transaction_pool,863 other:864 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),865 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(866 &config,867 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,868 )?;869 let prometheus_registry = config.prometheus_registry().cloned();870871 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(872 task_manager.spawn_handle(),873 overrides_handle::<_, _, Runtime>(client.clone()),874 50,875 50,876 prometheus_registry.clone(),877 ));878879 let (network, system_rpc_tx, tx_handler_controller, network_starter) =880 sc_service::build_network(sc_service::BuildNetworkParams {881 config: &config,882 client: client.clone(),883 transaction_pool: transaction_pool.clone(),884 spawn_handle: task_manager.spawn_handle(),885 import_queue,886 block_announce_validator_builder: None,887 warp_sync: None,888 })?;889890 if config.offchain_worker.enabled {891 sc_service::build_offchain_workers(892 &config,893 task_manager.spawn_handle(),894 client.clone(),895 network.clone(),896 );897 }898899 let collator = config.role.is_authority();900901 let select_chain = maybe_select_chain.clone();902903 if collator {904 let block_import =905 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());906907 let env = sc_basic_authorship::ProposerFactory::new(908 task_manager.spawn_handle(),909 client.clone(),910 transaction_pool.clone(),911 prometheus_registry.as_ref(),912 telemetry.as_ref().map(|x| x.handle()),913 );914915 let transactions_commands_stream: Box<916 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,917 > = Box::new(918 transaction_pool919 .pool()920 .validated_pool()921 .import_notification_stream()922 .map(|_| EngineCommand::SealNewBlock {923 create_empty: true,924 finalize: false, 925 parent_hash: None,926 sender: None,927 }),928 );929930 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));931 let idle_commands_stream: Box<932 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,933 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {934 create_empty: true,935 finalize: false, 936 parent_hash: None,937 sender: None,938 }));939940 let commands_stream = select(transactions_commands_stream, idle_commands_stream);941942 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;943 let client_set_aside_for_cidp = client.clone();944945 task_manager.spawn_essential_handle().spawn_blocking(946 "authorship_task",947 Some("block-authoring"),948 run_manual_seal(ManualSealParams {949 block_import,950 env,951 client: client.clone(),952 pool: transaction_pool.clone(),953 commands_stream,954 select_chain: select_chain.clone(),955 consensus_data_provider: None,956 create_inherent_data_providers: move |block: Hash, ()| {957 let current_para_block = client_set_aside_for_cidp958 .number(block)959 .expect("Header lookup should succeed")960 .expect("Header passed in as parent should be present in backend.");961962 let client_for_xcm = client_set_aside_for_cidp.clone();963 async move {964 let time = sp_timestamp::InherentDataProvider::from_system_time();965966 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {967 current_para_block,968 relay_offset: 1000,969 relay_blocks_per_para_block: 2,970 para_blocks_per_relay_epoch: 0,971 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(972 &*client_for_xcm,973 block,974 Default::default(),975 Default::default(),976 ),977 relay_randomness_config: (),978 raw_downward_messages: vec![],979 raw_horizontal_messages: vec![],980 };981982 let slot =983 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(984 *time,985 slot_duration,986 );987988 Ok((time, slot, mocked_parachain))989 }990 },991 }),992 );993 }994995 task_manager.spawn_essential_handle().spawn(996 "frontier-mapping-sync-worker",997 Some("block-authoring"),998 MappingSyncWorker::new(999 client.import_notification_stream(),1000 Duration::new(6, 0),1001 client.clone(),1002 backend.clone(),1003 frontier_backend.clone(),1004 3,1005 0,1006 SyncStrategy::Normal,1007 )1008 .for_each(|()| futures::future::ready(())),1009 );10101011 let rpc_client = client.clone();1012 let rpc_pool = transaction_pool.clone();1013 let rpc_network = network.clone();1014 let rpc_frontier_backend = frontier_backend.clone();1015 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1016 let full_deps = unique_rpc::FullDeps {1017 backend: rpc_frontier_backend.clone(),1018 deny_unsafe,1019 client: rpc_client.clone(),1020 pool: rpc_pool.clone(),1021 graph: rpc_pool.pool().clone(),1022 1023 enable_dev_signer: false,1024 filter_pool: filter_pool.clone(),1025 network: rpc_network.clone(),1026 select_chain: select_chain.clone(),1027 is_authority: collator,1028 1029 max_past_logs: 10000,1030 block_data_cache: block_data_cache.clone(),1031 fee_history_cache: fee_history_cache.clone(),1032 1033 fee_history_limit: 2048,1034 };10351036 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1037 full_deps,1038 subscription_executor,1039 )1040 .map_err(Into::into)1041 });10421043 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1044 network,1045 client,1046 keystore: keystore_container.sync_keystore(),1047 task_manager: &mut task_manager,1048 transaction_pool,1049 rpc_builder,1050 backend,1051 system_rpc_tx,1052 config,1053 telemetry: None,1054 tx_handler_controller,1055 })?;10561057 network_starter.start_network();1058 Ok(task_manager)1059}