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, 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 up_common::types::opaque::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};676869use up_data_structs::{70 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,71 RmrkPartType, RmrkTheme,72};737475#[cfg(feature = "unique-runtime")]76pub struct UniqueRuntimeExecutor;7778#[cfg(feature = "quartz-runtime")]7980pub struct QuartzRuntimeExecutor;818283pub struct OpalRuntimeExecutor;8485#[cfg(feature = "unique-runtime")]86pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8788#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]89pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9091#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]92pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;9394#[cfg(feature = "unique-runtime")]95impl NativeExecutionDispatch for UniqueRuntimeExecutor {96 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9798 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {99 unique_runtime::api::dispatch(method, data)100 }101102 fn native_version() -> sc_executor::NativeVersion {103 unique_runtime::native_version()104 }105}106107#[cfg(feature = "quartz-runtime")]108impl NativeExecutionDispatch for QuartzRuntimeExecutor {109 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;110111 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112 quartz_runtime::api::dispatch(method, data)113 }114115 fn native_version() -> sc_executor::NativeVersion {116 quartz_runtime::native_version()117 }118}119120impl NativeExecutionDispatch for OpalRuntimeExecutor {121 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;122123 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124 opal_runtime::api::dispatch(method, data)125 }126127 fn native_version() -> sc_executor::NativeVersion {128 opal_runtime::native_version()129 }130}131132pub struct AutosealInterval {133 interval: Interval,134}135136impl AutosealInterval {137 pub fn new(config: &Configuration, interval: Duration) -> Self {138 let _tokio_runtime = config.tokio_handle.enter();139 let interval = tokio::time::interval(interval);140141 Self { interval }142 }143}144145impl Stream for AutosealInterval {146 type Item = tokio::time::Instant;147148 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {149 self.interval.poll_tick(cx).map(Some)150 }151}152153pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {154 let config_dir = config155 .base_path156 .as_ref()157 .map(|base_path| base_path.config_dir(config.chain_spec.id()))158 .unwrap_or_else(|| {159 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())160 });161 let database_dir = config_dir.join("frontier").join("db");162163 Ok(Arc::new(fc_db::Backend::<Block>::new(164 &fc_db::DatabaseSettings {165 source: fc_db::DatabaseSource::RocksDb {166 path: database_dir,167 cache_size: 0,168 },169 },170 )?))171}172173type FullClient<RuntimeApi, ExecutorDispatch> =174 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;175type FullBackend = sc_service::TFullBackend<Block>;176type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;177178179180181182#[allow(clippy::type_complexity)]183pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(184 config: &Configuration,185 build_import_queue: BIQ,186) -> Result<187 PartialComponents<188 FullClient<RuntimeApi, ExecutorDispatch>,189 FullBackend,190 FullSelectChain,191 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,192 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,193 (194 Option<Telemetry>,195 Option<FilterPool>,196 Arc<fc_db::Backend<Block>>,197 Option<TelemetryWorkerHandle>,198 FeeHistoryCache,199 ),200 >,201 sc_service::Error,202>203where204 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,205 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>206 + Send207 + Sync208 + 'static,209 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,210 ExecutorDispatch: NativeExecutionDispatch + 'static,211 BIQ: FnOnce(212 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,213 &Configuration,214 Option<TelemetryHandle>,215 &TaskManager,216 ) -> Result<217 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,218 sc_service::Error,219 >,220{221 let _telemetry = config222 .telemetry_endpoints223 .clone()224 .filter(|x| !x.is_empty())225 .map(|endpoints| -> Result<_, sc_telemetry::Error> {226 let worker = TelemetryWorker::new(16)?;227 let telemetry = worker.handle().new_telemetry(endpoints);228 Ok((worker, telemetry))229 })230 .transpose()?;231232 let telemetry = config233 .telemetry_endpoints234 .clone()235 .filter(|x| !x.is_empty())236 .map(|endpoints| -> Result<_, sc_telemetry::Error> {237 let worker = TelemetryWorker::new(16)?;238 let telemetry = worker.handle().new_telemetry(endpoints);239 Ok((worker, telemetry))240 })241 .transpose()?;242243 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(244 config.wasm_method,245 config.default_heap_pages,246 config.max_runtime_instances,247 config.runtime_cache_size,248 );249250 let (client, backend, keystore_container, task_manager) =251 sc_service::new_full_parts::<Block, RuntimeApi, _>(252 config,253 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),254 executor,255 )?;256 let client = Arc::new(client);257258 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());259260 let telemetry = telemetry.map(|(worker, telemetry)| {261 task_manager262 .spawn_handle()263 .spawn("telemetry", None, worker.run());264 telemetry265 });266267 let select_chain = sc_consensus::LongestChain::new(backend.clone());268269 let transaction_pool = sc_transaction_pool::BasicPool::new_full(270 config.transaction_pool.clone(),271 config.role.is_authority().into(),272 config.prometheus_registry(),273 task_manager.spawn_essential_handle(),274 client.clone(),275 );276277 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));278279 let frontier_backend = open_frontier_backend(config)?;280281 let import_queue = build_import_queue(282 client.clone(),283 config,284 telemetry.as_ref().map(|telemetry| telemetry.handle()),285 &task_manager,286 )?;287 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));288289 let params = PartialComponents {290 backend,291 client,292 import_queue,293 keystore_container,294 task_manager,295 transaction_pool,296 select_chain,297 other: (298 telemetry,299 filter_pool,300 frontier_backend,301 telemetry_worker_handle,302 fee_history_cache,303 ),304 };305306 Ok(params)307}308309async fn build_relay_chain_interface(310 polkadot_config: Configuration,311 parachain_config: &Configuration,312 telemetry_worker_handle: Option<TelemetryWorkerHandle>,313 task_manager: &mut TaskManager,314 collator_options: CollatorOptions,315 hwbench: Option<sc_sysinfo::HwBench>,316) -> RelayChainResult<(317 Arc<(dyn RelayChainInterface + 'static)>,318 Option<CollatorPair>,319)> {320 match collator_options.relay_chain_rpc_url {321 Some(relay_chain_url) => Ok((322 Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,323 None,324 )),325 None => build_inprocess_relay_chain(326 polkadot_config,327 parachain_config,328 telemetry_worker_handle,329 task_manager,330 hwbench,331 ),332 }333}334335336337338#[sc_tracing::logging::prefix_logs_with("Parachain")]339async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(340 parachain_config: Configuration,341 polkadot_config: Configuration,342 collator_options: CollatorOptions,343 id: ParaId,344 build_import_queue: BIQ,345 build_consensus: BIC,346 hwbench: Option<sc_sysinfo::HwBench>,347) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>348where349 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,350 Runtime: RuntimeInstance + Send + Sync + 'static,351 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,352 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,353 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>354 + Send355 + Sync356 + 'static,357 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>358 + fp_rpc::EthereumRuntimeRPCApi<Block>359 + fp_rpc::ConvertTransactionRuntimeApi<Block>360 + sp_session::SessionKeys<Block>361 + sp_block_builder::BlockBuilder<Block>362 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>363 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>364 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>365 + rmrk_rpc::RmrkApi<366 Block,367 AccountId,368 RmrkCollectionInfo<AccountId>,369 RmrkInstanceInfo<AccountId>,370 RmrkResourceInfo,371 RmrkPropertyInfo,372 RmrkBaseInfo<AccountId>,373 RmrkPartType,374 RmrkTheme,375 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>376 + sp_api::Metadata<Block>377 + sp_offchain::OffchainWorkerApi<Block>378 + cumulus_primitives_core::CollectCollationInfo<Block>,379 ExecutorDispatch: NativeExecutionDispatch + 'static,380 BIQ: FnOnce(381 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,382 &Configuration,383 Option<TelemetryHandle>,384 &TaskManager,385 ) -> Result<386 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,387 sc_service::Error,388 >,389 BIC: FnOnce(390 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,391 Option<&Registry>,392 Option<TelemetryHandle>,393 &TaskManager,394 Arc<dyn RelayChainInterface>,395 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,396 Arc<NetworkService<Block, Hash>>,397 SyncCryptoStorePtr,398 bool,399 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,400{401 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 + rmrk_rpc::RmrkApi<667 Block,668 AccountId,669 RmrkCollectionInfo<AccountId>,670 RmrkInstanceInfo<AccountId>,671 RmrkResourceInfo,672 RmrkPropertyInfo,673 RmrkBaseInfo<AccountId>,674 RmrkPartType,675 RmrkTheme,676 > + 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 + rmrk_rpc::RmrkApi<811 Block,812 AccountId,813 RmrkCollectionInfo<AccountId>,814 RmrkInstanceInfo<AccountId>,815 RmrkResourceInfo,816 RmrkPropertyInfo,817 RmrkBaseInfo<AccountId>,818 RmrkPartType,819 RmrkTheme,820 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>821 + sp_api::Metadata<Block>822 + sp_offchain::OffchainWorkerApi<Block>823 + cumulus_primitives_core::CollectCollationInfo<Block>824 + sp_consensus_aura::AuraApi<Block, AuraId>,825 ExecutorDispatch: NativeExecutionDispatch + 'static,826{827 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};828 use fc_consensus::FrontierBlockImport;829 use sc_client_api::HeaderBackend;830831 let sc_service::PartialComponents {832 client,833 backend,834 mut task_manager,835 import_queue,836 keystore_container,837 select_chain: maybe_select_chain,838 transaction_pool,839 other:840 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),841 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(842 &config,843 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,844 )?;845 let prometheus_registry = config.prometheus_registry().cloned();846847 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(848 task_manager.spawn_handle(),849 overrides_handle::<_, _, Runtime>(client.clone()),850 50,851 50,852 prometheus_registry.clone(),853 ));854855 let (network, system_rpc_tx, network_starter) =856 sc_service::build_network(sc_service::BuildNetworkParams {857 config: &config,858 client: client.clone(),859 transaction_pool: transaction_pool.clone(),860 spawn_handle: task_manager.spawn_handle(),861 import_queue,862 block_announce_validator_builder: None,863 warp_sync: None,864 })?;865866 if config.offchain_worker.enabled {867 sc_service::build_offchain_workers(868 &config,869 task_manager.spawn_handle(),870 client.clone(),871 network.clone(),872 );873 }874875 let collator = config.role.is_authority();876877 let select_chain = maybe_select_chain.clone();878879 if collator {880 let block_import =881 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());882883 let env = sc_basic_authorship::ProposerFactory::new(884 task_manager.spawn_handle(),885 client.clone(),886 transaction_pool.clone(),887 prometheus_registry.as_ref(),888 telemetry.as_ref().map(|x| x.handle()),889 );890891 let transactions_commands_stream: Box<892 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,893 > = Box::new(894 transaction_pool895 .pool()896 .validated_pool()897 .import_notification_stream()898 .map(|_| EngineCommand::SealNewBlock {899 create_empty: true,900 finalize: false,901 parent_hash: None,902 sender: None,903 }),904 );905906 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));907 let idle_commands_stream: Box<908 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,909 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {910 create_empty: true,911 finalize: false,912 parent_hash: None,913 sender: None,914 }));915916 let commands_stream = select(transactions_commands_stream, idle_commands_stream);917918 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;919 let client_set_aside_for_cidp = client.clone();920921 task_manager.spawn_essential_handle().spawn_blocking(922 "authorship_task",923 Some("block-authoring"),924 run_manual_seal(ManualSealParams {925 block_import,926 env,927 client: client.clone(),928 pool: transaction_pool.clone(),929 commands_stream,930 select_chain: select_chain.clone(),931 consensus_data_provider: None,932 create_inherent_data_providers: move |block: Hash, ()| {933 let current_para_block = client_set_aside_for_cidp934 .number(block)935 .expect("Header lookup should succeed")936 .expect("Header passed in as parent should be present in backend.");937938 let client_for_xcm = client_set_aside_for_cidp.clone();939 async move {940 let time = sp_timestamp::InherentDataProvider::from_system_time();941942 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {943 current_para_block,944 relay_offset: 1000,945 relay_blocks_per_para_block: 2,946 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(947 &*client_for_xcm,948 block,949 Default::default(),950 Default::default(),951 ),952 raw_downward_messages: vec![],953 raw_horizontal_messages: vec![],954 };955956 let slot =957 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(958 *time,959 slot_duration,960 );961962 Ok((time, slot, mocked_parachain))963 }964 },965 }),966 );967 }968969 task_manager.spawn_essential_handle().spawn(970 "frontier-mapping-sync-worker",971 Some("block-authoring"),972 MappingSyncWorker::new(973 client.import_notification_stream(),974 Duration::new(6, 0),975 client.clone(),976 backend.clone(),977 frontier_backend.clone(),978 3,979 0,980 SyncStrategy::Normal,981 )982 .for_each(|()| futures::future::ready(())),983 );984985 let rpc_client = client.clone();986 let rpc_pool = transaction_pool.clone();987 let rpc_network = network.clone();988 let rpc_frontier_backend = frontier_backend.clone();989 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {990 let full_deps = unique_rpc::FullDeps {991 backend: rpc_frontier_backend.clone(),992 deny_unsafe,993 client: rpc_client.clone(),994 pool: rpc_pool.clone(),995 graph: rpc_pool.pool().clone(),996 997 enable_dev_signer: false,998 filter_pool: filter_pool.clone(),999 network: rpc_network.clone(),1000 select_chain: select_chain.clone(),1001 is_authority: collator,1002 1003 max_past_logs: 10000,1004 block_data_cache: block_data_cache.clone(),1005 fee_history_cache: fee_history_cache.clone(),1006 1007 fee_history_limit: 2048,1008 };10091010 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1011 full_deps,1012 subscription_executor,1013 )1014 .map_err(Into::into)1015 });10161017 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1018 network,1019 client,1020 keystore: keystore_container.sync_keystore(),1021 task_manager: &mut task_manager,1022 transaction_pool,1023 rpc_builder,1024 backend,1025 system_rpc_tx,1026 config,1027 telemetry: None,1028 })?;10291030 network_starter.start_network();1031 Ok(task_manager)1032}