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::{67 AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,68};697071use up_data_structs::{72 RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,73 RmrkPartType, RmrkTheme,74};757677#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]8182pub struct QuartzRuntimeExecutor;838485pub struct OpalRuntimeExecutor;8687#[cfg(feature = "unique-runtime")]88pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8990#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]91pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9293#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]94pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;9596#[cfg(feature = "unique-runtime")]97impl NativeExecutionDispatch for UniqueRuntimeExecutor {98 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;99100 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {101 unique_runtime::api::dispatch(method, data)102 }103104 fn native_version() -> sc_executor::NativeVersion {105 unique_runtime::native_version()106 }107}108109#[cfg(feature = "quartz-runtime")]110impl NativeExecutionDispatch for QuartzRuntimeExecutor {111 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112113 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {114 quartz_runtime::api::dispatch(method, data)115 }116117 fn native_version() -> sc_executor::NativeVersion {118 quartz_runtime::native_version()119 }120}121122impl NativeExecutionDispatch for OpalRuntimeExecutor {123 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;124125 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {126 opal_runtime::api::dispatch(method, data)127 }128129 fn native_version() -> sc_executor::NativeVersion {130 opal_runtime::native_version()131 }132}133134pub struct AutosealInterval {135 interval: Interval,136}137138impl AutosealInterval {139 pub fn new(config: &Configuration, interval: Duration) -> Self {140 let _tokio_runtime = config.tokio_handle.enter();141 let interval = tokio::time::interval(interval);142143 Self { interval }144 }145}146147impl Stream for AutosealInterval {148 type Item = tokio::time::Instant;149150 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {151 self.interval.poll_tick(cx).map(Some)152 }153}154155pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {156 let config_dir = config157 .base_path158 .as_ref()159 .map(|base_path| base_path.config_dir(config.chain_spec.id()))160 .unwrap_or_else(|| {161 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())162 });163 let database_dir = config_dir.join("frontier").join("db");164165 Ok(Arc::new(fc_db::Backend::<Block>::new(166 &fc_db::DatabaseSettings {167 source: fc_db::DatabaseSource::RocksDb {168 path: database_dir,169 cache_size: 0,170 },171 },172 )?))173}174175type FullClient<RuntimeApi, ExecutorDispatch> =176 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;177type FullBackend = sc_service::TFullBackend<Block>;178type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;179180181182183184#[allow(clippy::type_complexity)]185pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(186 config: &Configuration,187 build_import_queue: BIQ,188) -> Result<189 PartialComponents<190 FullClient<RuntimeApi, ExecutorDispatch>,191 FullBackend,192 FullSelectChain,193 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,194 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,195 (196 Option<Telemetry>,197 Option<FilterPool>,198 Arc<fc_db::Backend<Block>>,199 Option<TelemetryWorkerHandle>,200 FeeHistoryCache,201 ),202 >,203 sc_service::Error,204>205where206 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,207 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>208 + Send209 + Sync210 + 'static,211 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,212 ExecutorDispatch: NativeExecutionDispatch + 'static,213 BIQ: FnOnce(214 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,215 &Configuration,216 Option<TelemetryHandle>,217 &TaskManager,218 ) -> Result<219 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,220 sc_service::Error,221 >,222{223 let _telemetry = config224 .telemetry_endpoints225 .clone()226 .filter(|x| !x.is_empty())227 .map(|endpoints| -> Result<_, sc_telemetry::Error> {228 let worker = TelemetryWorker::new(16)?;229 let telemetry = worker.handle().new_telemetry(endpoints);230 Ok((worker, telemetry))231 })232 .transpose()?;233234 let telemetry = config235 .telemetry_endpoints236 .clone()237 .filter(|x| !x.is_empty())238 .map(|endpoints| -> Result<_, sc_telemetry::Error> {239 let worker = TelemetryWorker::new(16)?;240 let telemetry = worker.handle().new_telemetry(endpoints);241 Ok((worker, telemetry))242 })243 .transpose()?;244245 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(246 config.wasm_method,247 config.default_heap_pages,248 config.max_runtime_instances,249 config.runtime_cache_size,250 );251252 let (client, backend, keystore_container, task_manager) =253 sc_service::new_full_parts::<Block, RuntimeApi, _>(254 config,255 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),256 executor,257 )?;258 let client = Arc::new(client);259260 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());261262 let telemetry = telemetry.map(|(worker, telemetry)| {263 task_manager264 .spawn_handle()265 .spawn("telemetry", None, worker.run());266 telemetry267 });268269 let select_chain = sc_consensus::LongestChain::new(backend.clone());270271 let transaction_pool = sc_transaction_pool::BasicPool::new_full(272 config.transaction_pool.clone(),273 config.role.is_authority().into(),274 config.prometheus_registry(),275 task_manager.spawn_essential_handle(),276 client.clone(),277 );278279 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));280281 let frontier_backend = open_frontier_backend(config)?;282283 let import_queue = build_import_queue(284 client.clone(),285 config,286 telemetry.as_ref().map(|telemetry| telemetry.handle()),287 &task_manager,288 )?;289 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));290291 let params = PartialComponents {292 backend,293 client,294 import_queue,295 keystore_container,296 task_manager,297 transaction_pool,298 select_chain,299 other: (300 telemetry,301 filter_pool,302 frontier_backend,303 telemetry_worker_handle,304 fee_history_cache,305 ),306 };307308 Ok(params)309}310311async fn build_relay_chain_interface(312 polkadot_config: Configuration,313 parachain_config: &Configuration,314 telemetry_worker_handle: Option<TelemetryWorkerHandle>,315 task_manager: &mut TaskManager,316 collator_options: CollatorOptions,317 hwbench: Option<sc_sysinfo::HwBench>,318) -> RelayChainResult<(319 Arc<(dyn RelayChainInterface + 'static)>,320 Option<CollatorPair>,321)> {322 match collator_options.relay_chain_rpc_url {323 Some(relay_chain_url) => Ok((324 Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,325 None,326 )),327 None => build_inprocess_relay_chain(328 polkadot_config,329 parachain_config,330 telemetry_worker_handle,331 task_manager,332 hwbench,333 ),334 }335}336337338339340#[sc_tracing::logging::prefix_logs_with("Parachain")]341async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(342 parachain_config: Configuration,343 polkadot_config: Configuration,344 collator_options: CollatorOptions,345 id: ParaId,346 build_import_queue: BIQ,347 build_consensus: BIC,348 hwbench: Option<sc_sysinfo::HwBench>,349) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>350where351 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,352 Runtime: RuntimeInstance + Send + Sync + 'static,353 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,354 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,355 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>356 + Send357 + Sync358 + 'static,359 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>360 + fp_rpc::EthereumRuntimeRPCApi<Block>361 + fp_rpc::ConvertTransactionRuntimeApi<Block>362 + sp_session::SessionKeys<Block>363 + sp_block_builder::BlockBuilder<Block>364 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>365 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>366 + up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>367 + rmrk_rpc::RmrkApi<368 Block,369 AccountId,370 RmrkCollectionInfo<AccountId>,371 RmrkInstanceInfo<AccountId>,372 RmrkResourceInfo,373 RmrkPropertyInfo,374 RmrkBaseInfo<AccountId>,375 RmrkPartType,376 RmrkTheme,377 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>378 + sp_api::Metadata<Block>379 + sp_offchain::OffchainWorkerApi<Block>380 + cumulus_primitives_core::CollectCollationInfo<Block>,381 ExecutorDispatch: NativeExecutionDispatch + 'static,382 BIQ: FnOnce(383 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,384 &Configuration,385 Option<TelemetryHandle>,386 &TaskManager,387 ) -> Result<388 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,389 sc_service::Error,390 >,391 BIC: FnOnce(392 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,393 Option<&Registry>,394 Option<TelemetryHandle>,395 &TaskManager,396 Arc<dyn RelayChainInterface>,397 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,398 Arc<NetworkService<Block, Hash>>,399 SyncCryptoStorePtr,400 bool,401 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,402{403 let parachain_config = prepare_node_config(parachain_config);404405 let params =406 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;407 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =408 params.other;409410 let client = params.client.clone();411 let backend = params.backend.clone();412 let mut task_manager = params.task_manager;413414 let (relay_chain_interface, collator_key) = build_relay_chain_interface(415 polkadot_config,416 ¶chain_config,417 telemetry_worker_handle,418 &mut task_manager,419 collator_options.clone(),420 hwbench.clone(),421 )422 .await423 .map_err(|e| match e {424 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,425 s => s.to_string().into(),426 })?;427428 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);429430 let force_authoring = parachain_config.force_authoring;431 let validator = parachain_config.role.is_authority();432 let prometheus_registry = parachain_config.prometheus_registry().cloned();433 let transaction_pool = params.transaction_pool.clone();434 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);435436 let (network, system_rpc_tx, start_network) =437 sc_service::build_network(sc_service::BuildNetworkParams {438 config: ¶chain_config,439 client: client.clone(),440 transaction_pool: transaction_pool.clone(),441 spawn_handle: task_manager.spawn_handle(),442 import_queue: import_queue.clone(),443 block_announce_validator_builder: Some(Box::new(|_| {444 Box::new(block_announce_validator)445 })),446 warp_sync: None,447 })?;448449 let rpc_client = client.clone();450 let rpc_pool = transaction_pool.clone();451 let select_chain = params.select_chain.clone();452 let rpc_network = network.clone();453454 let rpc_frontier_backend = frontier_backend.clone();455456 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(457 task_manager.spawn_handle(),458 overrides_handle::<_, _, Runtime>(client.clone()),459 50,460 50,461 prometheus_registry.clone(),462 ));463464 task_manager.spawn_essential_handle().spawn(465 "frontier-mapping-sync-worker",466 None,467 MappingSyncWorker::new(468 client.import_notification_stream(),469 Duration::new(6, 0),470 client.clone(),471 backend.clone(),472 frontier_backend.clone(),473 3,474 0,475 SyncStrategy::Normal,476 )477 .for_each(|()| futures::future::ready(())),478 );479480 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {481 let full_deps = unique_rpc::FullDeps {482 backend: rpc_frontier_backend.clone(),483 deny_unsafe,484 client: rpc_client.clone(),485 pool: rpc_pool.clone(),486 graph: rpc_pool.pool().clone(),487 488 enable_dev_signer: false,489 filter_pool: filter_pool.clone(),490 network: rpc_network.clone(),491 select_chain: select_chain.clone(),492 is_authority: validator,493 494 max_past_logs: 10000,495 block_data_cache: block_data_cache.clone(),496 fee_history_cache: fee_history_cache.clone(),497 498 fee_history_limit: 2048,499 };500501 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(502 full_deps,503 subscription_task_executor,504 )505 .map_err(Into::into)506 });507508 sc_service::spawn_tasks(sc_service::SpawnTasksParams {509 rpc_builder,510 client: client.clone(),511 transaction_pool: transaction_pool.clone(),512 task_manager: &mut task_manager,513 config: parachain_config,514 keystore: params.keystore_container.sync_keystore(),515 backend: backend.clone(),516 network: network.clone(),517 system_rpc_tx,518 telemetry: telemetry.as_mut(),519 })?;520521 if let Some(hwbench) = hwbench {522 sc_sysinfo::print_hwbench(&hwbench);523524 if let Some(ref mut telemetry) = telemetry {525 let telemetry_handle = telemetry.handle();526 task_manager.spawn_handle().spawn(527 "telemetry_hwbench",528 None,529 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),530 );531 }532 }533534 let announce_block = {535 let network = network.clone();536 Arc::new(move |hash, data| network.announce_block(hash, data))537 };538539 let relay_chain_slot_duration = Duration::from_secs(6);540541 if validator {542 let parachain_consensus = build_consensus(543 client.clone(),544 prometheus_registry.as_ref(),545 telemetry.as_ref().map(|t| t.handle()),546 &task_manager,547 relay_chain_interface.clone(),548 transaction_pool,549 network,550 params.keystore_container.sync_keystore(),551 force_authoring,552 )?;553554 let spawner = task_manager.spawn_handle();555556 let params = StartCollatorParams {557 para_id: id,558 block_status: client.clone(),559 announce_block,560 client: client.clone(),561 task_manager: &mut task_manager,562 spawner,563 parachain_consensus,564 import_queue,565 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),566 relay_chain_interface,567 relay_chain_slot_duration,568 };569570 start_collator(params).await?;571 } else {572 let params = StartFullNodeParams {573 client: client.clone(),574 announce_block,575 task_manager: &mut task_manager,576 para_id: id,577 import_queue,578 relay_chain_interface,579 relay_chain_slot_duration,580 collator_options,581 };582583 start_full_node(params)?;584 }585586 start_network.start_network();587588 Ok((task_manager, client))589}590591592pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(593 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,594 config: &Configuration,595 telemetry: Option<TelemetryHandle>,596 task_manager: &TaskManager,597) -> Result<598 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,599 sc_service::Error,600>601where602 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>603 + Send604 + Sync605 + 'static,606 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>607 + sp_block_builder::BlockBuilder<Block>608 + sp_consensus_aura::AuraApi<Block, AuraId>609 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,610 ExecutorDispatch: NativeExecutionDispatch + 'static,611{612 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;613614 cumulus_client_consensus_aura::import_queue::<615 sp_consensus_aura::sr25519::AuthorityPair,616 _,617 _,618 _,619 _,620 _,621 _,622 >(cumulus_client_consensus_aura::ImportQueueParams {623 block_import: client.clone(),624 client: client.clone(),625 create_inherent_data_providers: move |_, _| async move {626 let time = sp_timestamp::InherentDataProvider::from_system_time();627628 let slot =629 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(630 *time,631 slot_duration,632 );633634 Ok((time, slot))635 },636 registry: config.prometheus_registry(),637 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),638 spawner: &task_manager.spawn_essential_handle(),639 telemetry,640 })641 .map_err(Into::into)642}643644645pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(646 parachain_config: Configuration,647 polkadot_config: Configuration,648 collator_options: CollatorOptions,649 id: ParaId,650 hwbench: Option<sc_sysinfo::HwBench>,651) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>652where653 Runtime: RuntimeInstance + Send + Sync + 'static,654 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,655 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,656 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>657 + Send658 + Sync659 + 'static,660 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>661 + fp_rpc::EthereumRuntimeRPCApi<Block>662 + fp_rpc::ConvertTransactionRuntimeApi<Block>663 + sp_session::SessionKeys<Block>664 + sp_block_builder::BlockBuilder<Block>665 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>666 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>667 + up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>668 + rmrk_rpc::RmrkApi<669 Block,670 AccountId,671 RmrkCollectionInfo<AccountId>,672 RmrkInstanceInfo<AccountId>,673 RmrkResourceInfo,674 RmrkPropertyInfo,675 RmrkBaseInfo<AccountId>,676 RmrkPartType,677 RmrkTheme,678 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>679 + sp_api::Metadata<Block>680 + sp_offchain::OffchainWorkerApi<Block>681 + cumulus_primitives_core::CollectCollationInfo<Block>682 + sp_consensus_aura::AuraApi<Block, AuraId>,683 ExecutorDispatch: NativeExecutionDispatch + 'static,684{685 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(686 parachain_config,687 polkadot_config,688 collator_options,689 id,690 parachain_build_import_queue,691 |client,692 prometheus_registry,693 telemetry,694 task_manager,695 relay_chain_interface,696 transaction_pool,697 sync_oracle,698 keystore,699 force_authoring| {700 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;701702 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(703 task_manager.spawn_handle(),704 client.clone(),705 transaction_pool,706 prometheus_registry,707 telemetry.clone(),708 );709710 Ok(AuraConsensus::build::<711 sp_consensus_aura::sr25519::AuthorityPair,712 _,713 _,714 _,715 _,716 _,717 _,718 >(BuildAuraConsensusParams {719 proposer_factory,720 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {721 let relay_chain_interface = relay_chain_interface.clone();722 async move {723 let parachain_inherent =724 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(725 relay_parent,726 &relay_chain_interface,727 &validation_data,728 id,729 ).await;730731 let time = sp_timestamp::InherentDataProvider::from_system_time();732733 let slot =734 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(735 *time,736 slot_duration,737 );738739 let parachain_inherent = parachain_inherent.ok_or_else(|| {740 Box::<dyn std::error::Error + Send + Sync>::from(741 "Failed to create parachain inherent",742 )743 })?;744 Ok((time, slot, parachain_inherent))745 }746 },747 block_import: client.clone(),748 para_client: client,749 backoff_authoring_blocks: Option::<()>::None,750 sync_oracle,751 keystore,752 force_authoring,753 slot_duration,754 755 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),756 telemetry,757 max_block_proposal_slot_portion: None,758 }))759 },760 hwbench,761 )762 .await763}764765fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(766 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,767 config: &Configuration,768 _: Option<TelemetryHandle>,769 task_manager: &TaskManager,770) -> Result<771 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,772 sc_service::Error,773>774where775 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>776 + Send777 + Sync778 + 'static,779 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>780 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,781 ExecutorDispatch: NativeExecutionDispatch + 'static,782{783 Ok(sc_consensus_manual_seal::import_queue(784 Box::new(client.clone()),785 &task_manager.spawn_essential_handle(),786 config.prometheus_registry(),787 ))788}789790791792pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(793 config: Configuration,794 autoseal_interval: Duration,795) -> sc_service::error::Result<TaskManager>796where797 Runtime: RuntimeInstance + Send + Sync + 'static,798 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,799 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,800 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>801 + Send802 + Sync803 + 'static,804 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>805 + fp_rpc::EthereumRuntimeRPCApi<Block>806 + fp_rpc::ConvertTransactionRuntimeApi<Block>807 + sp_session::SessionKeys<Block>808 + sp_block_builder::BlockBuilder<Block>809 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>810 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>811 + up_rpc::UniqueApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>812 + rmrk_rpc::RmrkApi<813 Block,814 AccountId,815 RmrkCollectionInfo<AccountId>,816 RmrkInstanceInfo<AccountId>,817 RmrkResourceInfo,818 RmrkPropertyInfo,819 RmrkBaseInfo<AccountId>,820 RmrkPartType,821 RmrkTheme,822 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>823 + sp_api::Metadata<Block>824 + sp_offchain::OffchainWorkerApi<Block>825 + cumulus_primitives_core::CollectCollationInfo<Block>826 + sp_consensus_aura::AuraApi<Block, AuraId>,827 ExecutorDispatch: NativeExecutionDispatch + 'static,828{829 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};830 use fc_consensus::FrontierBlockImport;831 use sc_client_api::HeaderBackend;832833 let sc_service::PartialComponents {834 client,835 backend,836 mut task_manager,837 import_queue,838 keystore_container,839 select_chain: maybe_select_chain,840 transaction_pool,841 other:842 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),843 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(844 &config,845 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,846 )?;847 let prometheus_registry = config.prometheus_registry().cloned();848849 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(850 task_manager.spawn_handle(),851 overrides_handle::<_, _, Runtime>(client.clone()),852 50,853 50,854 prometheus_registry.clone(),855 ));856857 let (network, system_rpc_tx, network_starter) =858 sc_service::build_network(sc_service::BuildNetworkParams {859 config: &config,860 client: client.clone(),861 transaction_pool: transaction_pool.clone(),862 spawn_handle: task_manager.spawn_handle(),863 import_queue,864 block_announce_validator_builder: None,865 warp_sync: None,866 })?;867868 if config.offchain_worker.enabled {869 sc_service::build_offchain_workers(870 &config,871 task_manager.spawn_handle(),872 client.clone(),873 network.clone(),874 );875 }876877 let collator = config.role.is_authority();878879 let select_chain = maybe_select_chain.clone();880881 if collator {882 let block_import =883 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());884885 let env = sc_basic_authorship::ProposerFactory::new(886 task_manager.spawn_handle(),887 client.clone(),888 transaction_pool.clone(),889 prometheus_registry.as_ref(),890 telemetry.as_ref().map(|x| x.handle()),891 );892893 let transactions_commands_stream: Box<894 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,895 > = Box::new(896 transaction_pool897 .pool()898 .validated_pool()899 .import_notification_stream()900 .map(|_| EngineCommand::SealNewBlock {901 create_empty: true,902 finalize: false,903 parent_hash: None,904 sender: None,905 }),906 );907908 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));909 let idle_commands_stream: Box<910 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,911 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {912 create_empty: true,913 finalize: false,914 parent_hash: None,915 sender: None,916 }));917918 let commands_stream = select(transactions_commands_stream, idle_commands_stream);919920 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;921 let client_set_aside_for_cidp = client.clone();922923 task_manager.spawn_essential_handle().spawn_blocking(924 "authorship_task",925 Some("block-authoring"),926 run_manual_seal(ManualSealParams {927 block_import,928 env,929 client: client.clone(),930 pool: transaction_pool.clone(),931 commands_stream,932 select_chain: select_chain.clone(),933 consensus_data_provider: None,934 create_inherent_data_providers: move |block: Hash, ()| {935 let current_para_block = client_set_aside_for_cidp936 .number(block)937 .expect("Header lookup should succeed")938 .expect("Header passed in as parent should be present in backend.");939940 let client_for_xcm = client_set_aside_for_cidp.clone();941 async move {942 let time = sp_timestamp::InherentDataProvider::from_system_time();943944 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {945 current_para_block,946 relay_offset: 1000,947 relay_blocks_per_para_block: 2,948 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(949 &*client_for_xcm,950 block,951 Default::default(),952 Default::default(),953 ),954 raw_downward_messages: vec![],955 raw_horizontal_messages: vec![],956 };957958 let slot =959 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(960 *time,961 slot_duration,962 );963964 Ok((time, slot, mocked_parachain))965 }966 },967 }),968 );969 }970971 task_manager.spawn_essential_handle().spawn(972 "frontier-mapping-sync-worker",973 Some("block-authoring"),974 MappingSyncWorker::new(975 client.import_notification_stream(),976 Duration::new(6, 0),977 client.clone(),978 backend.clone(),979 frontier_backend.clone(),980 3,981 0,982 SyncStrategy::Normal,983 )984 .for_each(|()| futures::future::ready(())),985 );986987 let rpc_client = client.clone();988 let rpc_pool = transaction_pool.clone();989 let rpc_network = network.clone();990 let rpc_frontier_backend = frontier_backend.clone();991 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {992 let full_deps = unique_rpc::FullDeps {993 backend: rpc_frontier_backend.clone(),994 deny_unsafe,995 client: rpc_client.clone(),996 pool: rpc_pool.clone(),997 graph: rpc_pool.pool().clone(),998 999 enable_dev_signer: false,1000 filter_pool: filter_pool.clone(),1001 network: rpc_network.clone(),1002 select_chain: select_chain.clone(),1003 is_authority: collator,1004 1005 max_past_logs: 10000,1006 block_data_cache: block_data_cache.clone(),1007 fee_history_cache: fee_history_cache.clone(),1008 1009 fee_history_limit: 2048,1010 };10111012 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1013 full_deps,1014 subscription_executor,1015 )1016 .map_err(Into::into)1017 });10181019 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1020 network,1021 client,1022 keystore: keystore_container.sync_keystore(),1023 task_manager: &mut task_manager,1024 transaction_pool,1025 rpc_builder,1026 backend,1027 system_rpc_tx,1028 config,1029 telemetry: None,1030 })?;10311032 network_starter.start_network();1033 Ok(task_manager)1034}