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;61use sc_consensus::ImportQueue;6263use polkadot_service::CollatorPair;646566use fc_rpc_core::types::FilterPool;67use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6869use up_common::types::opaque::{70 AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,71};727374use up_data_structs::{75 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,76 RmrkPartType, RmrkTheme,77};787980#[cfg(feature = "unique-runtime")]81pub struct UniqueRuntimeExecutor;8283#[cfg(feature = "quartz-runtime")]8485pub struct QuartzRuntimeExecutor;868788pub struct OpalRuntimeExecutor;8990#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]91pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9293#[cfg(all(94 not(feature = "unique-runtime"),95 feature = "quartz-runtime",96 feature = "runtime-benchmarks"97))]98pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;99100#[cfg(all(101 not(feature = "unique-runtime"),102 not(feature = "quartz-runtime"),103 feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;106107#[cfg(feature = "unique-runtime")]108impl NativeExecutionDispatch for UniqueRuntimeExecutor {109 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;110111 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112 unique_runtime::api::dispatch(method, data)113 }114115 fn native_version() -> sc_executor::NativeVersion {116 unique_runtime::native_version()117 }118}119120#[cfg(feature = "quartz-runtime")]121impl NativeExecutionDispatch for QuartzRuntimeExecutor {122 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;123124 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {125 quartz_runtime::api::dispatch(method, data)126 }127128 fn native_version() -> sc_executor::NativeVersion {129 quartz_runtime::native_version()130 }131}132133impl NativeExecutionDispatch for OpalRuntimeExecutor {134 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;135136 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {137 opal_runtime::api::dispatch(method, data)138 }139140 fn native_version() -> sc_executor::NativeVersion {141 opal_runtime::native_version()142 }143}144145pub struct AutosealInterval {146 interval: Interval,147}148149impl AutosealInterval {150 pub fn new(config: &Configuration, interval: Duration) -> Self {151 let _tokio_runtime = config.tokio_handle.enter();152 let interval = tokio::time::interval(interval);153154 Self { interval }155 }156}157158impl Stream for AutosealInterval {159 type Item = tokio::time::Instant;160161 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {162 self.interval.poll_tick(cx).map(Some)163 }164}165166pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(167 client: Arc<C>,168 config: &Configuration,169) -> Result<Arc<fc_db::Backend<Block>>, String> {170 let config_dir = config171 .base_path172 .as_ref()173 .map(|base_path| base_path.config_dir(config.chain_spec.id()))174 .unwrap_or_else(|| {175 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())176 });177 let database_dir = config_dir.join("frontier").join("db");178179 Ok(Arc::new(fc_db::Backend::<Block>::new(180 client,181 &fc_db::DatabaseSettings {182 source: fc_db::DatabaseSource::RocksDb {183 path: database_dir,184 cache_size: 0,185 },186 },187 )?))188}189190type FullClient<RuntimeApi, ExecutorDispatch> =191 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;192type FullBackend = sc_service::TFullBackend<Block>;193type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;194type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =195 TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;196197198199200201#[allow(clippy::type_complexity)]202pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(203 config: &Configuration,204 build_import_queue: BIQ,205) -> Result<206 PartialComponents<207 FullClient<RuntimeApi, ExecutorDispatch>,208 FullBackend,209 FullSelectChain,210 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,211 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,212 (213 Option<Telemetry>,214 Option<FilterPool>,215 Arc<fc_db::Backend<Block>>,216 Option<TelemetryWorkerHandle>,217 FeeHistoryCache,218 ),219 >,220 sc_service::Error,221>222where223 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,224 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>225 + Send226 + Sync227 + 'static,228 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,229 ExecutorDispatch: NativeExecutionDispatch + 'static,230 BIQ: FnOnce(231 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,232 Arc<FullBackend>,233 &Configuration,234 Option<TelemetryHandle>,235 &TaskManager,236 ) -> Result<237 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,238 sc_service::Error,239 >,240{241 let _telemetry = config242 .telemetry_endpoints243 .clone()244 .filter(|x| !x.is_empty())245 .map(|endpoints| -> Result<_, sc_telemetry::Error> {246 let worker = TelemetryWorker::new(16)?;247 let telemetry = worker.handle().new_telemetry(endpoints);248 Ok((worker, telemetry))249 })250 .transpose()?;251252 let telemetry = config253 .telemetry_endpoints254 .clone()255 .filter(|x| !x.is_empty())256 .map(|endpoints| -> Result<_, sc_telemetry::Error> {257 let worker = TelemetryWorker::new(16)?;258 let telemetry = worker.handle().new_telemetry(endpoints);259 Ok((worker, telemetry))260 })261 .transpose()?;262263 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(264 config.wasm_method,265 config.default_heap_pages,266 config.max_runtime_instances,267 config.runtime_cache_size,268 );269270 let (client, backend, keystore_container, task_manager) =271 sc_service::new_full_parts::<Block, RuntimeApi, _>(272 config,273 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),274 executor,275 )?;276 let client = Arc::new(client);277278 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());279280 let telemetry = telemetry.map(|(worker, telemetry)| {281 task_manager282 .spawn_handle()283 .spawn("telemetry", None, worker.run());284 telemetry285 });286287 let select_chain = sc_consensus::LongestChain::new(backend.clone());288289 let transaction_pool = sc_transaction_pool::BasicPool::new_full(290 config.transaction_pool.clone(),291 config.role.is_authority().into(),292 config.prometheus_registry(),293 task_manager.spawn_essential_handle(),294 client.clone(),295 );296297 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));298299 let frontier_backend = open_frontier_backend(client.clone(), config)?;300301 let import_queue = build_import_queue(302 client.clone(),303 backend.clone(),304 config,305 telemetry.as_ref().map(|telemetry| telemetry.handle()),306 &task_manager,307 )?;308 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));309310 let params = PartialComponents {311 backend,312 client,313 import_queue,314 keystore_container,315 task_manager,316 transaction_pool,317 select_chain,318 other: (319 telemetry,320 filter_pool,321 frontier_backend,322 telemetry_worker_handle,323 fee_history_cache,324 ),325 };326327 Ok(params)328}329330async fn build_relay_chain_interface(331 polkadot_config: Configuration,332 parachain_config: &Configuration,333 telemetry_worker_handle: Option<TelemetryWorkerHandle>,334 task_manager: &mut TaskManager,335 collator_options: CollatorOptions,336 hwbench: Option<sc_sysinfo::HwBench>,337) -> RelayChainResult<(338 Arc<(dyn RelayChainInterface + 'static)>,339 Option<CollatorPair>,340)> {341 if collator_options.relay_chain_rpc_urls.is_empty() {342 build_inprocess_relay_chain(343 polkadot_config,344 parachain_config,345 telemetry_worker_handle,346 task_manager,347 hwbench,348 )349 } else {350 build_minimal_relay_chain_node(351 polkadot_config,352 task_manager,353 collator_options.relay_chain_rpc_urls,354 )355 .await356 }357}358359360361362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364 parachain_config: Configuration,365 polkadot_config: Configuration,366 collator_options: CollatorOptions,367 id: ParaId,368 build_import_queue: BIQ,369 build_consensus: BIC,370 hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374 Runtime: RuntimeInstance + Send + Sync + 'static,375 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,376 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378 + Send379 + Sync380 + 'static,381 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382 + fp_rpc::EthereumRuntimeRPCApi<Block>383 + fp_rpc::ConvertTransactionRuntimeApi<Block>384 + sp_session::SessionKeys<Block>385 + sp_block_builder::BlockBuilder<Block>386 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390 + rmrk_rpc::RmrkApi<391 Block,392 AccountId,393 RmrkCollectionInfo<AccountId>,394 RmrkInstanceInfo<AccountId>,395 RmrkResourceInfo,396 RmrkPropertyInfo,397 RmrkBaseInfo<AccountId>,398 RmrkPartType,399 RmrkTheme,400 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>401 + sp_api::Metadata<Block>402 + sp_offchain::OffchainWorkerApi<Block>403 + cumulus_primitives_core::CollectCollationInfo<Block>,404 ExecutorDispatch: NativeExecutionDispatch + 'static,405 BIQ: FnOnce(406 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,407 Arc<FullBackend>,408 &Configuration,409 Option<TelemetryHandle>,410 &TaskManager,411 ) -> Result<412 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,413 sc_service::Error,414 >,415 BIC: FnOnce(416 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,417 Arc<FullBackend>,418 Option<&Registry>,419 Option<TelemetryHandle>,420 &TaskManager,421 Arc<dyn RelayChainInterface>,422 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,423 Arc<NetworkService<Block, Hash>>,424 SyncCryptoStorePtr,425 bool,426 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,427{428 let parachain_config = prepare_node_config(parachain_config);429430 let params =431 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;432 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =433 params.other;434435 let client = params.client.clone();436 let backend = params.backend.clone();437 let mut task_manager = params.task_manager;438439 let (relay_chain_interface, collator_key) = build_relay_chain_interface(440 polkadot_config,441 ¶chain_config,442 telemetry_worker_handle,443 &mut task_manager,444 collator_options.clone(),445 hwbench.clone(),446 )447 .await448 .map_err(|e| match e {449 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,450 s => s.to_string().into(),451 })?;452453 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);454455 let force_authoring = parachain_config.force_authoring;456 let validator = parachain_config.role.is_authority();457 let prometheus_registry = parachain_config.prometheus_registry().cloned();458 let transaction_pool = params.transaction_pool.clone();459 let import_queue_service = params.import_queue.service();460461 let (network, system_rpc_tx, tx_handler_controller, start_network) =462 sc_service::build_network(sc_service::BuildNetworkParams {463 config: ¶chain_config,464 client: client.clone(),465 transaction_pool: transaction_pool.clone(),466 spawn_handle: task_manager.spawn_handle(),467 import_queue: params.import_queue,468 block_announce_validator_builder: Some(Box::new(|_| {469 Box::new(block_announce_validator)470 })),471 warp_sync: None,472 })?;473474 let rpc_client = client.clone();475 let rpc_pool = transaction_pool.clone();476 let select_chain = params.select_chain.clone();477 let rpc_network = network.clone();478479 let rpc_frontier_backend = frontier_backend.clone();480481 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(482 task_manager.spawn_handle(),483 overrides_handle::<_, _, Runtime>(client.clone()),484 50,485 50,486 prometheus_registry.clone(),487 ));488489 task_manager.spawn_essential_handle().spawn(490 "frontier-mapping-sync-worker",491 None,492 MappingSyncWorker::new(493 client.import_notification_stream(),494 Duration::new(6, 0),495 client.clone(),496 backend.clone(),497 frontier_backend.clone(),498 3,499 0,500 SyncStrategy::Normal,501 )502 .for_each(|()| futures::future::ready(())),503 );504505 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {506 let full_deps = unique_rpc::FullDeps {507 backend: rpc_frontier_backend.clone(),508 deny_unsafe,509 client: rpc_client.clone(),510 pool: rpc_pool.clone(),511 graph: rpc_pool.pool().clone(),512 513 enable_dev_signer: false,514 filter_pool: filter_pool.clone(),515 network: rpc_network.clone(),516 select_chain: select_chain.clone(),517 is_authority: validator,518 519 max_past_logs: 10000,520 block_data_cache: block_data_cache.clone(),521 fee_history_cache: fee_history_cache.clone(),522 523 fee_history_limit: 2048,524 };525526 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(527 full_deps,528 subscription_task_executor,529 )530 .map_err(Into::into)531 });532533 sc_service::spawn_tasks(sc_service::SpawnTasksParams {534 rpc_builder,535 client: client.clone(),536 transaction_pool: transaction_pool.clone(),537 task_manager: &mut task_manager,538 config: parachain_config,539 keystore: params.keystore_container.sync_keystore(),540 backend: backend.clone(),541 network: network.clone(),542 system_rpc_tx,543 telemetry: telemetry.as_mut(),544 tx_handler_controller,545 })?;546547 if let Some(hwbench) = hwbench {548 sc_sysinfo::print_hwbench(&hwbench);549550 if let Some(ref mut telemetry) = telemetry {551 let telemetry_handle = telemetry.handle();552 task_manager.spawn_handle().spawn(553 "telemetry_hwbench",554 None,555 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),556 );557 }558 }559560 let announce_block = {561 let network = network.clone();562 Arc::new(Box::new(move |hash, data| {563 network.announce_block(hash, data)564 }))565 };566567 let relay_chain_slot_duration = Duration::from_secs(6);568569 if validator {570 let parachain_consensus = build_consensus(571 client.clone(),572 backend.clone(),573 prometheus_registry.as_ref(),574 telemetry.as_ref().map(|t| t.handle()),575 &task_manager,576 relay_chain_interface.clone(),577 transaction_pool,578 network,579 params.keystore_container.sync_keystore(),580 force_authoring,581 )?;582583 let spawner = task_manager.spawn_handle();584585 let params = StartCollatorParams {586 para_id: id,587 block_status: client.clone(),588 announce_block,589 client: client.clone(),590 task_manager: &mut task_manager,591 spawner,592 parachain_consensus,593 import_queue: import_queue_service,594 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),595 relay_chain_interface,596 relay_chain_slot_duration,597 };598599 start_collator(params).await?;600 } else {601 let params = StartFullNodeParams {602 client: client.clone(),603 announce_block,604 task_manager: &mut task_manager,605 para_id: id,606 import_queue: import_queue_service,607 relay_chain_interface,608 relay_chain_slot_duration,609 };610611 start_full_node(params)?;612 }613614 start_network.start_network();615616 Ok((task_manager, client))617}618619620pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(621 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,622 backend: Arc<FullBackend>,623 config: &Configuration,624 telemetry: Option<TelemetryHandle>,625 task_manager: &TaskManager,626) -> Result<627 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,628 sc_service::Error,629>630where631 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>632 + Send633 + Sync634 + 'static,635 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>636 + sp_block_builder::BlockBuilder<Block>637 + sp_consensus_aura::AuraApi<Block, AuraId>638 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,639 ExecutorDispatch: NativeExecutionDispatch + 'static,640{641 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;642643 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());644645 cumulus_client_consensus_aura::import_queue::<646 sp_consensus_aura::sr25519::AuthorityPair,647 _,648 _,649 _,650 _,651 _,652 >(cumulus_client_consensus_aura::ImportQueueParams {653 block_import,654 client: client.clone(),655 create_inherent_data_providers: move |_, _| async move {656 let time = sp_timestamp::InherentDataProvider::from_system_time();657658 let slot =659 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(660 *time,661 slot_duration,662 );663664 Ok((slot, time))665 },666 registry: config.prometheus_registry(),667 spawner: &task_manager.spawn_essential_handle(),668 telemetry,669 })670 .map_err(Into::into)671}672673674pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(675 parachain_config: Configuration,676 polkadot_config: Configuration,677 collator_options: CollatorOptions,678 id: ParaId,679 hwbench: Option<sc_sysinfo::HwBench>,680) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>681where682 Runtime: RuntimeInstance + Send + Sync + 'static,683 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,684 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,685 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>686 + Send687 + Sync688 + 'static,689 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>690 + fp_rpc::EthereumRuntimeRPCApi<Block>691 + fp_rpc::ConvertTransactionRuntimeApi<Block>692 + sp_session::SessionKeys<Block>693 + sp_block_builder::BlockBuilder<Block>694 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>695 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>696 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>697 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>698 + rmrk_rpc::RmrkApi<699 Block,700 AccountId,701 RmrkCollectionInfo<AccountId>,702 RmrkInstanceInfo<AccountId>,703 RmrkResourceInfo,704 RmrkPropertyInfo,705 RmrkBaseInfo<AccountId>,706 RmrkPartType,707 RmrkTheme,708 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>709 + sp_api::Metadata<Block>710 + sp_offchain::OffchainWorkerApi<Block>711 + cumulus_primitives_core::CollectCollationInfo<Block>712 + sp_consensus_aura::AuraApi<Block, AuraId>,713 ExecutorDispatch: NativeExecutionDispatch + 'static,714{715 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(716 parachain_config,717 polkadot_config,718 collator_options,719 id,720 parachain_build_import_queue,721 |client,722 backend,723 prometheus_registry,724 telemetry,725 task_manager,726 relay_chain_interface,727 transaction_pool,728 sync_oracle,729 keystore,730 force_authoring| {731 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;732733 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(734 task_manager.spawn_handle(),735 client.clone(),736 transaction_pool,737 prometheus_registry,738 telemetry.clone(),739 );740741 let block_import = ParachainBlockImport::new(client.clone(), backend.clone());742743 Ok(AuraConsensus::build::<744 sp_consensus_aura::sr25519::AuthorityPair,745 _,746 _,747 _,748 _,749 _,750 _,751 >(BuildAuraConsensusParams {752 proposer_factory,753 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {754 let relay_chain_interface = relay_chain_interface.clone();755 async move {756 let parachain_inherent =757 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(758 relay_parent,759 &relay_chain_interface,760 &validation_data,761 id,762 ).await;763764 let time = sp_timestamp::InherentDataProvider::from_system_time();765766 let slot =767 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(768 *time,769 slot_duration,770 );771772 let parachain_inherent = parachain_inherent.ok_or_else(|| {773 Box::<dyn std::error::Error + Send + Sync>::from(774 "Failed to create parachain inherent",775 )776 })?;777 Ok((slot, time, parachain_inherent))778 }779 },780 block_import,781 para_client: client,782 backoff_authoring_blocks: Option::<()>::None,783 sync_oracle,784 keystore,785 force_authoring,786 slot_duration,787 788 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),789 telemetry,790 max_block_proposal_slot_portion: None,791 }))792 },793 hwbench,794 )795 .await796}797798fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(799 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,800 _: Arc<FullBackend>,801 config: &Configuration,802 _: Option<TelemetryHandle>,803 task_manager: &TaskManager,804) -> Result<805 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,806 sc_service::Error,807>808where809 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>810 + Send811 + Sync812 + 'static,813 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>814 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,815 ExecutorDispatch: NativeExecutionDispatch + 'static,816{817 Ok(sc_consensus_manual_seal::import_queue(818 Box::new(client.clone()),819 &task_manager.spawn_essential_handle(),820 config.prometheus_registry(),821 ))822}823824825826pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(827 config: Configuration,828 autoseal_interval: Duration,829) -> sc_service::error::Result<TaskManager>830where831 Runtime: RuntimeInstance + Send + Sync + 'static,832 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,833 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,834 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>835 + Send836 + Sync837 + 'static,838 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>839 + fp_rpc::EthereumRuntimeRPCApi<Block>840 + fp_rpc::ConvertTransactionRuntimeApi<Block>841 + sp_session::SessionKeys<Block>842 + sp_block_builder::BlockBuilder<Block>843 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>844 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>845 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>846 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>847 + rmrk_rpc::RmrkApi<848 Block,849 AccountId,850 RmrkCollectionInfo<AccountId>,851 RmrkInstanceInfo<AccountId>,852 RmrkResourceInfo,853 RmrkPropertyInfo,854 RmrkBaseInfo<AccountId>,855 RmrkPartType,856 RmrkTheme,857 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>858 + sp_api::Metadata<Block>859 + sp_offchain::OffchainWorkerApi<Block>860 + cumulus_primitives_core::CollectCollationInfo<Block>861 + sp_consensus_aura::AuraApi<Block, AuraId>,862 ExecutorDispatch: NativeExecutionDispatch + 'static,863{864 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};865 use fc_consensus::FrontierBlockImport;866 use sc_client_api::HeaderBackend;867868 let sc_service::PartialComponents {869 client,870 backend,871 mut task_manager,872 import_queue,873 keystore_container,874 select_chain: maybe_select_chain,875 transaction_pool,876 other:877 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),878 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(879 &config,880 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,881 )?;882 let prometheus_registry = config.prometheus_registry().cloned();883884 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(885 task_manager.spawn_handle(),886 overrides_handle::<_, _, Runtime>(client.clone()),887 50,888 50,889 prometheus_registry.clone(),890 ));891892 let (network, system_rpc_tx, tx_handler_controller, network_starter) =893 sc_service::build_network(sc_service::BuildNetworkParams {894 config: &config,895 client: client.clone(),896 transaction_pool: transaction_pool.clone(),897 spawn_handle: task_manager.spawn_handle(),898 import_queue,899 block_announce_validator_builder: None,900 warp_sync: None,901 })?;902903 if config.offchain_worker.enabled {904 sc_service::build_offchain_workers(905 &config,906 task_manager.spawn_handle(),907 client.clone(),908 network.clone(),909 );910 }911912 let collator = config.role.is_authority();913914 let select_chain = maybe_select_chain.clone();915916 if collator {917 let block_import =918 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());919920 let env = sc_basic_authorship::ProposerFactory::new(921 task_manager.spawn_handle(),922 client.clone(),923 transaction_pool.clone(),924 prometheus_registry.as_ref(),925 telemetry.as_ref().map(|x| x.handle()),926 );927928 let transactions_commands_stream: Box<929 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,930 > = Box::new(931 transaction_pool932 .pool()933 .validated_pool()934 .import_notification_stream()935 .map(|_| EngineCommand::SealNewBlock {936 create_empty: true,937 finalize: false,938 parent_hash: None,939 sender: None,940 }),941 );942943 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));944 let idle_commands_stream: Box<945 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,946 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {947 create_empty: true,948 finalize: false,949 parent_hash: None,950 sender: None,951 }));952953 let commands_stream = select(transactions_commands_stream, idle_commands_stream);954955 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;956 let client_set_aside_for_cidp = client.clone();957958 task_manager.spawn_essential_handle().spawn_blocking(959 "authorship_task",960 Some("block-authoring"),961 run_manual_seal(ManualSealParams {962 block_import,963 env,964 client: client.clone(),965 pool: transaction_pool.clone(),966 commands_stream,967 select_chain: select_chain.clone(),968 consensus_data_provider: None,969 create_inherent_data_providers: move |block: Hash, ()| {970 let current_para_block = client_set_aside_for_cidp971 .number(block)972 .expect("Header lookup should succeed")973 .expect("Header passed in as parent should be present in backend.");974975 let client_for_xcm = client_set_aside_for_cidp.clone();976 async move {977 let time = sp_timestamp::InherentDataProvider::from_system_time();978979 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {980 current_para_block,981 relay_offset: 1000,982 relay_blocks_per_para_block: 2,983 para_blocks_per_relay_epoch: 0,984 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(985 &*client_for_xcm,986 block,987 Default::default(),988 Default::default(),989 ),990 relay_randomness_config: (),991 raw_downward_messages: vec![],992 raw_horizontal_messages: vec![],993 };994995 let slot =996 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(997 *time,998 slot_duration,999 );10001001 Ok((time, slot, mocked_parachain))1002 }1003 },1004 }),1005 );1006 }10071008 task_manager.spawn_essential_handle().spawn(1009 "frontier-mapping-sync-worker",1010 Some("block-authoring"),1011 MappingSyncWorker::new(1012 client.import_notification_stream(),1013 Duration::new(6, 0),1014 client.clone(),1015 backend.clone(),1016 frontier_backend.clone(),1017 3,1018 0,1019 SyncStrategy::Normal,1020 )1021 .for_each(|()| futures::future::ready(())),1022 );10231024 let rpc_client = client.clone();1025 let rpc_pool = transaction_pool.clone();1026 let rpc_network = network.clone();1027 let rpc_frontier_backend = frontier_backend.clone();1028 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1029 let full_deps = unique_rpc::FullDeps {1030 backend: rpc_frontier_backend.clone(),1031 deny_unsafe,1032 client: rpc_client.clone(),1033 pool: rpc_pool.clone(),1034 graph: rpc_pool.pool().clone(),1035 1036 enable_dev_signer: false,1037 filter_pool: filter_pool.clone(),1038 network: rpc_network.clone(),1039 select_chain: select_chain.clone(),1040 is_authority: collator,1041 1042 max_past_logs: 10000,1043 block_data_cache: block_data_cache.clone(),1044 fee_history_cache: fee_history_cache.clone(),1045 1046 fee_history_limit: 2048,1047 };10481049 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1050 full_deps,1051 subscription_executor,1052 )1053 .map_err(Into::into)1054 });10551056 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1057 network,1058 client,1059 keystore: keystore_container.sync_keystore(),1060 task_manager: &mut task_manager,1061 transaction_pool,1062 rpc_builder,1063 backend,1064 system_rpc_tx,1065 config,1066 telemetry: None,1067 tx_handler_controller,1068 })?;10691070 network_starter.start_network();1071 Ok(task_manager)1072}