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, create_client_and_start_worker};474849use sc_client_api::ExecutorProvider;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::{NetworkService, NetworkBlock};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) => {324 let rpc_client = create_client_and_start_worker(relay_chain_url, task_manager).await?;325326 Ok((327 Arc::new(RelayChainRpcInterface::new(rpc_client)) as Arc<_>,328 None,329 ))330 }331 None => build_inprocess_relay_chain(332 polkadot_config,333 parachain_config,334 telemetry_worker_handle,335 task_manager,336 hwbench,337 ),338 }339}340341342343344#[sc_tracing::logging::prefix_logs_with("Parachain")]345async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(346 parachain_config: Configuration,347 polkadot_config: Configuration,348 collator_options: CollatorOptions,349 id: ParaId,350 build_import_queue: BIQ,351 build_consensus: BIC,352 hwbench: Option<sc_sysinfo::HwBench>,353) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>354where355 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,356 Runtime: RuntimeInstance + Send + Sync + 'static,357 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,358 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,359 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>360 + Send361 + Sync362 + 'static,363 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>364 + fp_rpc::EthereumRuntimeRPCApi<Block>365 + fp_rpc::ConvertTransactionRuntimeApi<Block>366 + sp_session::SessionKeys<Block>367 + sp_block_builder::BlockBuilder<Block>368 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>369 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>370 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>371 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>372 + rmrk_rpc::RmrkApi<373 Block,374 AccountId,375 RmrkCollectionInfo<AccountId>,376 RmrkInstanceInfo<AccountId>,377 RmrkResourceInfo,378 RmrkPropertyInfo,379 RmrkBaseInfo<AccountId>,380 RmrkPartType,381 RmrkTheme,382 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>383 + sp_api::Metadata<Block>384 + sp_offchain::OffchainWorkerApi<Block>385 + cumulus_primitives_core::CollectCollationInfo<Block>,386 ExecutorDispatch: NativeExecutionDispatch + 'static,387 BIQ: FnOnce(388 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,389 &Configuration,390 Option<TelemetryHandle>,391 &TaskManager,392 ) -> Result<393 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,394 sc_service::Error,395 >,396 BIC: FnOnce(397 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,398 Option<&Registry>,399 Option<TelemetryHandle>,400 &TaskManager,401 Arc<dyn RelayChainInterface>,402 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,403 Arc<NetworkService<Block, Hash>>,404 SyncCryptoStorePtr,405 bool,406 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,407{408 let parachain_config = prepare_node_config(parachain_config);409410 let params =411 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;412 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =413 params.other;414415 let client = params.client.clone();416 let backend = params.backend.clone();417 let mut task_manager = params.task_manager;418419 let (relay_chain_interface, collator_key) = build_relay_chain_interface(420 polkadot_config,421 ¶chain_config,422 telemetry_worker_handle,423 &mut task_manager,424 collator_options.clone(),425 hwbench.clone(),426 )427 .await428 .map_err(|e| match e {429 RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,430 s => s.to_string().into(),431 })?;432433 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);434435 let force_authoring = parachain_config.force_authoring;436 let validator = parachain_config.role.is_authority();437 let prometheus_registry = parachain_config.prometheus_registry().cloned();438 let transaction_pool = params.transaction_pool.clone();439 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);440441 let (network, system_rpc_tx, start_network) =442 sc_service::build_network(sc_service::BuildNetworkParams {443 config: ¶chain_config,444 client: client.clone(),445 transaction_pool: transaction_pool.clone(),446 spawn_handle: task_manager.spawn_handle(),447 import_queue: import_queue.clone(),448 block_announce_validator_builder: Some(Box::new(|_| {449 Box::new(block_announce_validator)450 })),451 warp_sync: None,452 })?;453454 let rpc_client = client.clone();455 let rpc_pool = transaction_pool.clone();456 let select_chain = params.select_chain.clone();457 let rpc_network = network.clone();458459 let rpc_frontier_backend = frontier_backend.clone();460461 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(462 task_manager.spawn_handle(),463 overrides_handle::<_, _, Runtime>(client.clone()),464 50,465 50,466 prometheus_registry.clone(),467 ));468469 task_manager.spawn_essential_handle().spawn(470 "frontier-mapping-sync-worker",471 None,472 MappingSyncWorker::new(473 client.import_notification_stream(),474 Duration::new(6, 0),475 client.clone(),476 backend.clone(),477 frontier_backend.clone(),478 3,479 0,480 SyncStrategy::Normal,481 )482 .for_each(|()| futures::future::ready(())),483 );484485 let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {486 let full_deps = unique_rpc::FullDeps {487 backend: rpc_frontier_backend.clone(),488 deny_unsafe,489 client: rpc_client.clone(),490 pool: rpc_pool.clone(),491 graph: rpc_pool.pool().clone(),492 493 enable_dev_signer: false,494 filter_pool: filter_pool.clone(),495 network: rpc_network.clone(),496 select_chain: select_chain.clone(),497 is_authority: validator,498 499 max_past_logs: 10000,500 block_data_cache: block_data_cache.clone(),501 fee_history_cache: fee_history_cache.clone(),502 503 fee_history_limit: 2048,504 };505506 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(507 full_deps,508 subscription_task_executor,509 )510 .map_err(Into::into)511 });512513 sc_service::spawn_tasks(sc_service::SpawnTasksParams {514 rpc_builder,515 client: client.clone(),516 transaction_pool: transaction_pool.clone(),517 task_manager: &mut task_manager,518 config: parachain_config,519 keystore: params.keystore_container.sync_keystore(),520 backend: backend.clone(),521 network: network.clone(),522 system_rpc_tx,523 telemetry: telemetry.as_mut(),524 })?;525526 if let Some(hwbench) = hwbench {527 sc_sysinfo::print_hwbench(&hwbench);528529 if let Some(ref mut telemetry) = telemetry {530 let telemetry_handle = telemetry.handle();531 task_manager.spawn_handle().spawn(532 "telemetry_hwbench",533 None,534 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),535 );536 }537 }538539 let announce_block = {540 let network = network.clone();541 Arc::new(move |hash, data| network.announce_block(hash, data))542 };543544 let relay_chain_slot_duration = Duration::from_secs(6);545546 if validator {547 let parachain_consensus = build_consensus(548 client.clone(),549 prometheus_registry.as_ref(),550 telemetry.as_ref().map(|t| t.handle()),551 &task_manager,552 relay_chain_interface.clone(),553 transaction_pool,554 network,555 params.keystore_container.sync_keystore(),556 force_authoring,557 )?;558559 let spawner = task_manager.spawn_handle();560561 let params = StartCollatorParams {562 para_id: id,563 block_status: client.clone(),564 announce_block,565 client: client.clone(),566 task_manager: &mut task_manager,567 spawner,568 parachain_consensus,569 import_queue,570 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),571 relay_chain_interface,572 relay_chain_slot_duration,573 };574575 start_collator(params).await?;576 } else {577 let params = StartFullNodeParams {578 client: client.clone(),579 announce_block,580 task_manager: &mut task_manager,581 para_id: id,582 import_queue,583 relay_chain_interface,584 relay_chain_slot_duration,585 collator_options,586 };587588 start_full_node(params)?;589 }590591 start_network.start_network();592593 Ok((task_manager, client))594}595596597pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(598 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,599 config: &Configuration,600 telemetry: Option<TelemetryHandle>,601 task_manager: &TaskManager,602) -> Result<603 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,604 sc_service::Error,605>606where607 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>608 + Send609 + Sync610 + 'static,611 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>612 + sp_block_builder::BlockBuilder<Block>613 + sp_consensus_aura::AuraApi<Block, AuraId>614 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,615 ExecutorDispatch: NativeExecutionDispatch + 'static,616{617 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;618619 cumulus_client_consensus_aura::import_queue::<620 sp_consensus_aura::sr25519::AuthorityPair,621 _,622 _,623 _,624 _,625 _,626 _,627 >(cumulus_client_consensus_aura::ImportQueueParams {628 block_import: client.clone(),629 client: client.clone(),630 create_inherent_data_providers: move |_, _| async move {631 let time = sp_timestamp::InherentDataProvider::from_system_time();632633 let slot =634 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(635 *time,636 slot_duration,637 );638639 Ok((time, slot))640 },641 registry: config.prometheus_registry(),642 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),643 spawner: &task_manager.spawn_essential_handle(),644 telemetry,645 })646 .map_err(Into::into)647}648649650pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(651 parachain_config: Configuration,652 polkadot_config: Configuration,653 collator_options: CollatorOptions,654 id: ParaId,655 hwbench: Option<sc_sysinfo::HwBench>,656) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>657where658 Runtime: RuntimeInstance + Send + Sync + 'static,659 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,660 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,661 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>662 + Send663 + Sync664 + 'static,665 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>666 + fp_rpc::EthereumRuntimeRPCApi<Block>667 + fp_rpc::ConvertTransactionRuntimeApi<Block>668 + sp_session::SessionKeys<Block>669 + sp_block_builder::BlockBuilder<Block>670 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>671 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>672 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>673 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>674 + rmrk_rpc::RmrkApi<675 Block,676 AccountId,677 RmrkCollectionInfo<AccountId>,678 RmrkInstanceInfo<AccountId>,679 RmrkResourceInfo,680 RmrkPropertyInfo,681 RmrkBaseInfo<AccountId>,682 RmrkPartType,683 RmrkTheme,684 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>685 + sp_api::Metadata<Block>686 + sp_offchain::OffchainWorkerApi<Block>687 + cumulus_primitives_core::CollectCollationInfo<Block>688 + sp_consensus_aura::AuraApi<Block, AuraId>,689 ExecutorDispatch: NativeExecutionDispatch + 'static,690{691 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(692 parachain_config,693 polkadot_config,694 collator_options,695 id,696 parachain_build_import_queue,697 |client,698 prometheus_registry,699 telemetry,700 task_manager,701 relay_chain_interface,702 transaction_pool,703 sync_oracle,704 keystore,705 force_authoring| {706 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;707708 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(709 task_manager.spawn_handle(),710 client.clone(),711 transaction_pool,712 prometheus_registry,713 telemetry.clone(),714 );715716 Ok(AuraConsensus::build::<717 sp_consensus_aura::sr25519::AuthorityPair,718 _,719 _,720 _,721 _,722 _,723 _,724 >(BuildAuraConsensusParams {725 proposer_factory,726 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {727 let relay_chain_interface = relay_chain_interface.clone();728 async move {729 let parachain_inherent =730 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(731 relay_parent,732 &relay_chain_interface,733 &validation_data,734 id,735 ).await;736737 let time = sp_timestamp::InherentDataProvider::from_system_time();738739 let slot =740 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(741 *time,742 slot_duration,743 );744745 let parachain_inherent = parachain_inherent.ok_or_else(|| {746 Box::<dyn std::error::Error + Send + Sync>::from(747 "Failed to create parachain inherent",748 )749 })?;750 Ok((time, slot, parachain_inherent))751 }752 },753 block_import: client.clone(),754 para_client: client,755 backoff_authoring_blocks: Option::<()>::None,756 sync_oracle,757 keystore,758 force_authoring,759 slot_duration,760 761 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),762 telemetry,763 max_block_proposal_slot_portion: None,764 }))765 },766 hwbench,767 )768 .await769}770771fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(772 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,773 config: &Configuration,774 _: Option<TelemetryHandle>,775 task_manager: &TaskManager,776) -> Result<777 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,778 sc_service::Error,779>780where781 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>782 + Send783 + Sync784 + 'static,785 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>786 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,787 ExecutorDispatch: NativeExecutionDispatch + 'static,788{789 Ok(sc_consensus_manual_seal::import_queue(790 Box::new(client.clone()),791 &task_manager.spawn_essential_handle(),792 config.prometheus_registry(),793 ))794}795796797798pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(799 config: Configuration,800 autoseal_interval: Duration,801) -> sc_service::error::Result<TaskManager>802where803 Runtime: RuntimeInstance + Send + Sync + 'static,804 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,805 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,806 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>807 + Send808 + Sync809 + 'static,810 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>811 + fp_rpc::EthereumRuntimeRPCApi<Block>812 + fp_rpc::ConvertTransactionRuntimeApi<Block>813 + sp_session::SessionKeys<Block>814 + sp_block_builder::BlockBuilder<Block>815 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>816 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>817 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>818 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>819 + rmrk_rpc::RmrkApi<820 Block,821 AccountId,822 RmrkCollectionInfo<AccountId>,823 RmrkInstanceInfo<AccountId>,824 RmrkResourceInfo,825 RmrkPropertyInfo,826 RmrkBaseInfo<AccountId>,827 RmrkPartType,828 RmrkTheme,829 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>830 + sp_api::Metadata<Block>831 + sp_offchain::OffchainWorkerApi<Block>832 + cumulus_primitives_core::CollectCollationInfo<Block>833 + sp_consensus_aura::AuraApi<Block, AuraId>,834 ExecutorDispatch: NativeExecutionDispatch + 'static,835{836 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};837 use fc_consensus::FrontierBlockImport;838 use sc_client_api::HeaderBackend;839840 let sc_service::PartialComponents {841 client,842 backend,843 mut task_manager,844 import_queue,845 keystore_container,846 select_chain: maybe_select_chain,847 transaction_pool,848 other:849 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),850 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(851 &config,852 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,853 )?;854 let prometheus_registry = config.prometheus_registry().cloned();855856 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(857 task_manager.spawn_handle(),858 overrides_handle::<_, _, Runtime>(client.clone()),859 50,860 50,861 prometheus_registry.clone(),862 ));863864 let (network, system_rpc_tx, network_starter) =865 sc_service::build_network(sc_service::BuildNetworkParams {866 config: &config,867 client: client.clone(),868 transaction_pool: transaction_pool.clone(),869 spawn_handle: task_manager.spawn_handle(),870 import_queue,871 block_announce_validator_builder: None,872 warp_sync: None,873 })?;874875 if config.offchain_worker.enabled {876 sc_service::build_offchain_workers(877 &config,878 task_manager.spawn_handle(),879 client.clone(),880 network.clone(),881 );882 }883884 let collator = config.role.is_authority();885886 let select_chain = maybe_select_chain.clone();887888 if collator {889 let block_import =890 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());891892 let env = sc_basic_authorship::ProposerFactory::new(893 task_manager.spawn_handle(),894 client.clone(),895 transaction_pool.clone(),896 prometheus_registry.as_ref(),897 telemetry.as_ref().map(|x| x.handle()),898 );899900 let transactions_commands_stream: Box<901 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,902 > = Box::new(903 transaction_pool904 .pool()905 .validated_pool()906 .import_notification_stream()907 .map(|_| EngineCommand::SealNewBlock {908 create_empty: true,909 finalize: false,910 parent_hash: None,911 sender: None,912 }),913 );914915 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));916 let idle_commands_stream: Box<917 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,918 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {919 create_empty: true,920 finalize: false,921 parent_hash: None,922 sender: None,923 }));924925 let commands_stream = select(transactions_commands_stream, idle_commands_stream);926927 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;928 let client_set_aside_for_cidp = client.clone();929930 task_manager.spawn_essential_handle().spawn_blocking(931 "authorship_task",932 Some("block-authoring"),933 run_manual_seal(ManualSealParams {934 block_import,935 env,936 client: client.clone(),937 pool: transaction_pool.clone(),938 commands_stream,939 select_chain: select_chain.clone(),940 consensus_data_provider: None,941 create_inherent_data_providers: move |block: Hash, ()| {942 let current_para_block = client_set_aside_for_cidp943 .number(block)944 .expect("Header lookup should succeed")945 .expect("Header passed in as parent should be present in backend.");946947 let client_for_xcm = client_set_aside_for_cidp.clone();948 async move {949 let time = sp_timestamp::InherentDataProvider::from_system_time();950951 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {952 current_para_block,953 relay_offset: 1000,954 relay_blocks_per_para_block: 2,955 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(956 &*client_for_xcm,957 block,958 Default::default(),959 Default::default(),960 ),961 raw_downward_messages: vec![],962 raw_horizontal_messages: vec![],963 };964965 let slot =966 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(967 *time,968 slot_duration,969 );970971 Ok((time, slot, mocked_parachain))972 }973 },974 }),975 );976 }977978 task_manager.spawn_essential_handle().spawn(979 "frontier-mapping-sync-worker",980 Some("block-authoring"),981 MappingSyncWorker::new(982 client.import_notification_stream(),983 Duration::new(6, 0),984 client.clone(),985 backend.clone(),986 frontier_backend.clone(),987 3,988 0,989 SyncStrategy::Normal,990 )991 .for_each(|()| futures::future::ready(())),992 );993994 let rpc_client = client.clone();995 let rpc_pool = transaction_pool.clone();996 let rpc_network = network.clone();997 let rpc_frontier_backend = frontier_backend.clone();998 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {999 let full_deps = unique_rpc::FullDeps {1000 backend: rpc_frontier_backend.clone(),1001 deny_unsafe,1002 client: rpc_client.clone(),1003 pool: rpc_pool.clone(),1004 graph: rpc_pool.pool().clone(),1005 1006 enable_dev_signer: false,1007 filter_pool: filter_pool.clone(),1008 network: rpc_network.clone(),1009 select_chain: select_chain.clone(),1010 is_authority: collator,1011 1012 max_past_logs: 10000,1013 block_data_cache: block_data_cache.clone(),1014 fee_history_cache: fee_history_cache.clone(),1015 1016 fee_history_limit: 2048,1017 };10181019 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1020 full_deps,1021 subscription_executor,1022 )1023 .map_err(Into::into)1024 });10251026 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1027 network,1028 client,1029 keystore: keystore_container.sync_keystore(),1030 task_manager: &mut task_manager,1031 transaction_pool,1032 rpc_builder,1033 backend,1034 system_rpc_tx,1035 config,1036 telemetry: None,1037 })?;10381039 network_starter.start_network();1040 Ok(task_manager)1041}