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<Arc<FullClient<RuntimeApi, ExecutorDispatch>>>;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 &Configuration,233 Option<TelemetryHandle>,234 &TaskManager,235 ) -> Result<236 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,237 sc_service::Error,238 >,239{240 let _telemetry = config241 .telemetry_endpoints242 .clone()243 .filter(|x| !x.is_empty())244 .map(|endpoints| -> Result<_, sc_telemetry::Error> {245 let worker = TelemetryWorker::new(16)?;246 let telemetry = worker.handle().new_telemetry(endpoints);247 Ok((worker, telemetry))248 })249 .transpose()?;250251 let telemetry = config252 .telemetry_endpoints253 .clone()254 .filter(|x| !x.is_empty())255 .map(|endpoints| -> Result<_, sc_telemetry::Error> {256 let worker = TelemetryWorker::new(16)?;257 let telemetry = worker.handle().new_telemetry(endpoints);258 Ok((worker, telemetry))259 })260 .transpose()?;261262 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(263 config.wasm_method,264 config.default_heap_pages,265 config.max_runtime_instances,266 config.runtime_cache_size,267 );268269 let (client, backend, keystore_container, task_manager) =270 sc_service::new_full_parts::<Block, RuntimeApi, _>(271 config,272 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),273 executor,274 )?;275 let client = Arc::new(client);276277 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());278279 let telemetry = telemetry.map(|(worker, telemetry)| {280 task_manager281 .spawn_handle()282 .spawn("telemetry", None, worker.run());283 telemetry284 });285286 let select_chain = sc_consensus::LongestChain::new(backend.clone());287288 let transaction_pool = sc_transaction_pool::BasicPool::new_full(289 config.transaction_pool.clone(),290 config.role.is_authority().into(),291 config.prometheus_registry(),292 task_manager.spawn_essential_handle(),293 client.clone(),294 );295296 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));297298 let frontier_backend = open_frontier_backend(client.clone(), config)?;299300 let import_queue = build_import_queue(301 client.clone(),302 config,303 telemetry.as_ref().map(|telemetry| telemetry.handle()),304 &task_manager,305 )?;306 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));307308 let params = PartialComponents {309 backend,310 client,311 import_queue,312 keystore_container,313 task_manager,314 transaction_pool,315 select_chain,316 other: (317 telemetry,318 filter_pool,319 frontier_backend,320 telemetry_worker_handle,321 fee_history_cache,322 ),323 };324325 Ok(params)326}327328async fn build_relay_chain_interface(329 polkadot_config: Configuration,330 parachain_config: &Configuration,331 telemetry_worker_handle: Option<TelemetryWorkerHandle>,332 task_manager: &mut TaskManager,333 collator_options: CollatorOptions,334 hwbench: Option<sc_sysinfo::HwBench>,335) -> RelayChainResult<(336 Arc<(dyn RelayChainInterface + 'static)>,337 Option<CollatorPair>,338)> {339 if collator_options.relay_chain_rpc_urls.is_empty() {340 build_inprocess_relay_chain(341 polkadot_config,342 parachain_config,343 telemetry_worker_handle,344 task_manager,345 hwbench,346 )347 } else {348 build_minimal_relay_chain_node(349 polkadot_config,350 task_manager,351 collator_options.relay_chain_rpc_urls,352 )353 .await354 }355}356357358359360#[sc_tracing::logging::prefix_logs_with("Parachain")]361async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(362 parachain_config: Configuration,363 polkadot_config: Configuration,364 collator_options: CollatorOptions,365 id: ParaId,366 build_import_queue: BIQ,367 build_consensus: BIC,368 hwbench: Option<sc_sysinfo::HwBench>,369) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>370where371 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,372 Runtime: RuntimeInstance + Send + Sync + 'static,373 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,374 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,375 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>376 + Send377 + Sync378 + 'static,379 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>380 + fp_rpc::EthereumRuntimeRPCApi<Block>381 + fp_rpc::ConvertTransactionRuntimeApi<Block>382 + sp_session::SessionKeys<Block>383 + sp_block_builder::BlockBuilder<Block>384 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>385 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>386 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>387 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>388 + rmrk_rpc::RmrkApi<389 Block,390 AccountId,391 RmrkCollectionInfo<AccountId>,392 RmrkInstanceInfo<AccountId>,393 RmrkResourceInfo,394 RmrkPropertyInfo,395 RmrkBaseInfo<AccountId>,396 RmrkPartType,397 RmrkTheme,398 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>399 + sp_api::Metadata<Block>400 + sp_offchain::OffchainWorkerApi<Block>401 + cumulus_primitives_core::CollectCollationInfo<Block>,402 ExecutorDispatch: NativeExecutionDispatch + 'static,403 BIQ: FnOnce(404 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,405 &Configuration,406 Option<TelemetryHandle>,407 &TaskManager,408 ) -> Result<409 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,410 sc_service::Error,411 >,412 BIC: FnOnce(413 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,414 Option<&Registry>,415 Option<TelemetryHandle>,416 &TaskManager,417 Arc<dyn RelayChainInterface>,418 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,419 Arc<NetworkService<Block, Hash>>,420 SyncCryptoStorePtr,421 bool,422 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,423{424 let parachain_config = prepare_node_config(parachain_config);425426 let params =427 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;428 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =429 params.other;430431 let client = params.client.clone();432 let backend = params.backend.clone();433 let mut task_manager = params.task_manager;434435 let (relay_chain_interface, collator_key) = build_relay_chain_interface(436 polkadot_config,437 ¶chain_config,438 telemetry_worker_handle,439 &mut task_manager,440 collator_options.clone(),441 hwbench.clone(),442 )443 .await444 .map_err(|e| match e {445 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,446 s => s.to_string().into(),447 })?;448449 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);450451 let force_authoring = parachain_config.force_authoring;452 let validator = parachain_config.role.is_authority();453 let prometheus_registry = parachain_config.prometheus_registry().cloned();454 let transaction_pool = params.transaction_pool.clone();455 let import_queue_service = params.import_queue.service();456457 let (network, system_rpc_tx, tx_handler_controller, start_network) =458 sc_service::build_network(sc_service::BuildNetworkParams {459 config: ¶chain_config,460 client: client.clone(),461 transaction_pool: transaction_pool.clone(),462 spawn_handle: task_manager.spawn_handle(),463 import_queue: params.import_queue,464 block_announce_validator_builder: Some(Box::new(|_| {465 Box::new(block_announce_validator)466 })),467 warp_sync: None,468 })?;469470 let rpc_client = client.clone();471 let rpc_pool = transaction_pool.clone();472 let select_chain = params.select_chain.clone();473 let rpc_network = network.clone();474475 let rpc_frontier_backend = frontier_backend.clone();476477 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(478 task_manager.spawn_handle(),479 overrides_handle::<_, _, Runtime>(client.clone()),480 50,481 50,482 prometheus_registry.clone(),483 ));484485 task_manager.spawn_essential_handle().spawn(486 "frontier-mapping-sync-worker",487 None,488 MappingSyncWorker::new(489 client.import_notification_stream(),490 Duration::new(6, 0),491 client.clone(),492 backend.clone(),493 frontier_backend.clone(),494 3,495 0,496 SyncStrategy::Normal,497 )498 .for_each(|()| futures::future::ready(())),499 );500501 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {502 let full_deps = unique_rpc::FullDeps {503 backend: rpc_frontier_backend.clone(),504 deny_unsafe,505 client: rpc_client.clone(),506 pool: rpc_pool.clone(),507 graph: rpc_pool.pool().clone(),508 509 enable_dev_signer: false,510 filter_pool: filter_pool.clone(),511 network: rpc_network.clone(),512 select_chain: select_chain.clone(),513 is_authority: validator,514 515 max_past_logs: 10000,516 block_data_cache: block_data_cache.clone(),517 fee_history_cache: fee_history_cache.clone(),518 519 fee_history_limit: 2048,520 };521522 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(523 full_deps,524 subscription_task_executor,525 )526 .map_err(Into::into)527 });528529 sc_service::spawn_tasks(sc_service::SpawnTasksParams {530 rpc_builder,531 client: client.clone(),532 transaction_pool: transaction_pool.clone(),533 task_manager: &mut task_manager,534 config: parachain_config,535 keystore: params.keystore_container.sync_keystore(),536 backend: backend.clone(),537 network: network.clone(),538 system_rpc_tx,539 telemetry: telemetry.as_mut(),540 tx_handler_controller,541 })?;542543 if let Some(hwbench) = hwbench {544 sc_sysinfo::print_hwbench(&hwbench);545546 if let Some(ref mut telemetry) = telemetry {547 let telemetry_handle = telemetry.handle();548 task_manager.spawn_handle().spawn(549 "telemetry_hwbench",550 None,551 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),552 );553 }554 }555556 let announce_block = {557 let network = network.clone();558 Arc::new(Box::new(move |hash, data| {559 network.announce_block(hash, data)560 }))561 };562563 let relay_chain_slot_duration = Duration::from_secs(6);564565 if validator {566 let parachain_consensus = build_consensus(567 client.clone(),568 prometheus_registry.as_ref(),569 telemetry.as_ref().map(|t| t.handle()),570 &task_manager,571 relay_chain_interface.clone(),572 transaction_pool,573 network,574 params.keystore_container.sync_keystore(),575 force_authoring,576 )?;577578 let spawner = task_manager.spawn_handle();579580 let params = StartCollatorParams {581 para_id: id,582 block_status: client.clone(),583 announce_block,584 client: client.clone(),585 task_manager: &mut task_manager,586 spawner,587 parachain_consensus,588 import_queue: import_queue_service,589 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),590 relay_chain_interface,591 relay_chain_slot_duration,592 };593594 start_collator(params).await?;595 } else {596 let params = StartFullNodeParams {597 client: client.clone(),598 announce_block,599 task_manager: &mut task_manager,600 para_id: id,601 import_queue: import_queue_service,602 relay_chain_interface,603 relay_chain_slot_duration,604 };605606 start_full_node(params)?;607 }608609 start_network.start_network();610611 Ok((task_manager, client))612}613614615pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(616 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,617 config: &Configuration,618 telemetry: Option<TelemetryHandle>,619 task_manager: &TaskManager,620) -> Result<621 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,622 sc_service::Error,623>624where625 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>626 + Send627 + Sync628 + 'static,629 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>630 + sp_block_builder::BlockBuilder<Block>631 + sp_consensus_aura::AuraApi<Block, AuraId>632 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,633 ExecutorDispatch: NativeExecutionDispatch + 'static,634{635 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;636637 let block_import = ParachainBlockImport::new(client.clone());638639 cumulus_client_consensus_aura::import_queue::<640 sp_consensus_aura::sr25519::AuthorityPair,641 _,642 _,643 _,644 _,645 _,646 >(cumulus_client_consensus_aura::ImportQueueParams {647 block_import,648 client: client.clone(),649 create_inherent_data_providers: move |_, _| async move {650 let time = sp_timestamp::InherentDataProvider::from_system_time();651652 let slot =653 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(654 *time,655 slot_duration,656 );657658 Ok((slot, time))659 },660 registry: config.prometheus_registry(),661 spawner: &task_manager.spawn_essential_handle(),662 telemetry,663 })664 .map_err(Into::into)665}666667668pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(669 parachain_config: Configuration,670 polkadot_config: Configuration,671 collator_options: CollatorOptions,672 id: ParaId,673 hwbench: Option<sc_sysinfo::HwBench>,674) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>675where676 Runtime: RuntimeInstance + Send + Sync + 'static,677 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,678 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,679 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>680 + Send681 + Sync682 + 'static,683 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>684 + fp_rpc::EthereumRuntimeRPCApi<Block>685 + fp_rpc::ConvertTransactionRuntimeApi<Block>686 + sp_session::SessionKeys<Block>687 + sp_block_builder::BlockBuilder<Block>688 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>689 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>690 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>691 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>692 + rmrk_rpc::RmrkApi<693 Block,694 AccountId,695 RmrkCollectionInfo<AccountId>,696 RmrkInstanceInfo<AccountId>,697 RmrkResourceInfo,698 RmrkPropertyInfo,699 RmrkBaseInfo<AccountId>,700 RmrkPartType,701 RmrkTheme,702 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>703 + sp_api::Metadata<Block>704 + sp_offchain::OffchainWorkerApi<Block>705 + cumulus_primitives_core::CollectCollationInfo<Block>706 + sp_consensus_aura::AuraApi<Block, AuraId>,707 ExecutorDispatch: NativeExecutionDispatch + 'static,708{709 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(710 parachain_config,711 polkadot_config,712 collator_options,713 id,714 parachain_build_import_queue,715 |client,716 prometheus_registry,717 telemetry,718 task_manager,719 relay_chain_interface,720 transaction_pool,721 sync_oracle,722 keystore,723 force_authoring| {724 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;725726 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(727 task_manager.spawn_handle(),728 client.clone(),729 transaction_pool,730 prometheus_registry,731 telemetry.clone(),732 );733734 let block_import = ParachainBlockImport::new(client.clone());735736 Ok(AuraConsensus::build::<737 sp_consensus_aura::sr25519::AuthorityPair,738 _,739 _,740 _,741 _,742 _,743 _,744 >(BuildAuraConsensusParams {745 proposer_factory,746 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {747 let relay_chain_interface = relay_chain_interface.clone();748 async move {749 let parachain_inherent =750 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(751 relay_parent,752 &relay_chain_interface,753 &validation_data,754 id,755 ).await;756757 let time = sp_timestamp::InherentDataProvider::from_system_time();758759 let slot =760 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(761 *time,762 slot_duration,763 );764765 let parachain_inherent = parachain_inherent.ok_or_else(|| {766 Box::<dyn std::error::Error + Send + Sync>::from(767 "Failed to create parachain inherent",768 )769 })?;770 Ok((slot, time, parachain_inherent))771 }772 },773 block_import,774 para_client: client,775 backoff_authoring_blocks: Option::<()>::None,776 sync_oracle,777 keystore,778 force_authoring,779 slot_duration,780 781 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),782 telemetry,783 max_block_proposal_slot_portion: None,784 }))785 },786 hwbench,787 )788 .await789}790791fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(792 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,793 config: &Configuration,794 _: Option<TelemetryHandle>,795 task_manager: &TaskManager,796) -> Result<797 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,798 sc_service::Error,799>800where801 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>802 + Send803 + Sync804 + 'static,805 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>806 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,807 ExecutorDispatch: NativeExecutionDispatch + 'static,808{809 Ok(sc_consensus_manual_seal::import_queue(810 Box::new(client.clone()),811 &task_manager.spawn_essential_handle(),812 config.prometheus_registry(),813 ))814}815816817818pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(819 config: Configuration,820 autoseal_interval: Duration,821) -> sc_service::error::Result<TaskManager>822where823 Runtime: RuntimeInstance + Send + Sync + 'static,824 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,825 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,826 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>827 + Send828 + Sync829 + 'static,830 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>831 + fp_rpc::EthereumRuntimeRPCApi<Block>832 + fp_rpc::ConvertTransactionRuntimeApi<Block>833 + sp_session::SessionKeys<Block>834 + sp_block_builder::BlockBuilder<Block>835 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>836 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>837 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>838 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>839 + rmrk_rpc::RmrkApi<840 Block,841 AccountId,842 RmrkCollectionInfo<AccountId>,843 RmrkInstanceInfo<AccountId>,844 RmrkResourceInfo,845 RmrkPropertyInfo,846 RmrkBaseInfo<AccountId>,847 RmrkPartType,848 RmrkTheme,849 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>850 + sp_api::Metadata<Block>851 + sp_offchain::OffchainWorkerApi<Block>852 + cumulus_primitives_core::CollectCollationInfo<Block>853 + sp_consensus_aura::AuraApi<Block, AuraId>,854 ExecutorDispatch: NativeExecutionDispatch + 'static,855{856 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};857 use fc_consensus::FrontierBlockImport;858 use sc_client_api::HeaderBackend;859860 let sc_service::PartialComponents {861 client,862 backend,863 mut task_manager,864 import_queue,865 keystore_container,866 select_chain: maybe_select_chain,867 transaction_pool,868 other:869 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),870 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(871 &config,872 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,873 )?;874 let prometheus_registry = config.prometheus_registry().cloned();875876 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(877 task_manager.spawn_handle(),878 overrides_handle::<_, _, Runtime>(client.clone()),879 50,880 50,881 prometheus_registry.clone(),882 ));883884 let (network, system_rpc_tx, tx_handler_controller, network_starter) =885 sc_service::build_network(sc_service::BuildNetworkParams {886 config: &config,887 client: client.clone(),888 transaction_pool: transaction_pool.clone(),889 spawn_handle: task_manager.spawn_handle(),890 import_queue,891 block_announce_validator_builder: None,892 warp_sync: None,893 })?;894895 if config.offchain_worker.enabled {896 sc_service::build_offchain_workers(897 &config,898 task_manager.spawn_handle(),899 client.clone(),900 network.clone(),901 );902 }903904 let collator = config.role.is_authority();905906 let select_chain = maybe_select_chain.clone();907908 if collator {909 let block_import =910 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());911912 let env = sc_basic_authorship::ProposerFactory::new(913 task_manager.spawn_handle(),914 client.clone(),915 transaction_pool.clone(),916 prometheus_registry.as_ref(),917 telemetry.as_ref().map(|x| x.handle()),918 );919920 let transactions_commands_stream: Box<921 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,922 > = Box::new(923 transaction_pool924 .pool()925 .validated_pool()926 .import_notification_stream()927 .map(|_| EngineCommand::SealNewBlock {928 create_empty: true,929 finalize: false,930 parent_hash: None,931 sender: None,932 }),933 );934935 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));936 let idle_commands_stream: Box<937 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,938 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {939 create_empty: true,940 finalize: false,941 parent_hash: None,942 sender: None,943 }));944945 let commands_stream = select(transactions_commands_stream, idle_commands_stream);946947 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;948 let client_set_aside_for_cidp = client.clone();949950 task_manager.spawn_essential_handle().spawn_blocking(951 "authorship_task",952 Some("block-authoring"),953 run_manual_seal(ManualSealParams {954 block_import,955 env,956 client: client.clone(),957 pool: transaction_pool.clone(),958 commands_stream,959 select_chain: select_chain.clone(),960 consensus_data_provider: None,961 create_inherent_data_providers: move |block: Hash, ()| {962 let current_para_block = client_set_aside_for_cidp963 .number(block)964 .expect("Header lookup should succeed")965 .expect("Header passed in as parent should be present in backend.");966967 let client_for_xcm = client_set_aside_for_cidp.clone();968 async move {969 let time = sp_timestamp::InherentDataProvider::from_system_time();970971 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {972 current_para_block,973 relay_offset: 1000,974 relay_blocks_per_para_block: 2,975 para_blocks_per_relay_epoch: 0,976 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(977 &*client_for_xcm,978 block,979 Default::default(),980 Default::default(),981 ),982 relay_randomness_config: (),983 raw_downward_messages: vec![],984 raw_horizontal_messages: vec![],985 };986987 let slot =988 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(989 *time,990 slot_duration,991 );992993 Ok((time, slot, mocked_parachain))994 }995 },996 }),997 );998 }9991000 task_manager.spawn_essential_handle().spawn(1001 "frontier-mapping-sync-worker",1002 Some("block-authoring"),1003 MappingSyncWorker::new(1004 client.import_notification_stream(),1005 Duration::new(6, 0),1006 client.clone(),1007 backend.clone(),1008 frontier_backend.clone(),1009 3,1010 0,1011 SyncStrategy::Normal,1012 )1013 .for_each(|()| futures::future::ready(())),1014 );10151016 let rpc_client = client.clone();1017 let rpc_pool = transaction_pool.clone();1018 let rpc_network = network.clone();1019 let rpc_frontier_backend = frontier_backend.clone();1020 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1021 let full_deps = unique_rpc::FullDeps {1022 backend: rpc_frontier_backend.clone(),1023 deny_unsafe,1024 client: rpc_client.clone(),1025 pool: rpc_pool.clone(),1026 graph: rpc_pool.pool().clone(),1027 1028 enable_dev_signer: false,1029 filter_pool: filter_pool.clone(),1030 network: rpc_network.clone(),1031 select_chain: select_chain.clone(),1032 is_authority: collator,1033 1034 max_past_logs: 10000,1035 block_data_cache: block_data_cache.clone(),1036 fee_history_cache: fee_history_cache.clone(),1037 1038 fee_history_limit: 2048,1039 };10401041 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1042 full_deps,1043 subscription_executor,1044 )1045 .map_err(Into::into)1046 });10471048 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1049 network,1050 client,1051 keystore: keystore_container.sync_keystore(),1052 task_manager: &mut task_manager,1053 transaction_pool,1054 rpc_builder,1055 backend,1056 system_rpc_tx,1057 config,1058 telemetry: None,1059 tx_handler_controller,1060 })?;10611062 network_starter.start_network();1063 Ok(task_manager)1064}