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, tx_handler_controller, 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 tx_handler_controller,525 })?;526527 if let Some(hwbench) = hwbench {528 sc_sysinfo::print_hwbench(&hwbench);529530 if let Some(ref mut telemetry) = telemetry {531 let telemetry_handle = telemetry.handle();532 task_manager.spawn_handle().spawn(533 "telemetry_hwbench",534 None,535 sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),536 );537 }538 }539540 let announce_block = {541 let network = network.clone();542 Arc::new(Box::new(move |hash, data| {543 network.announce_block(hash, data)544 }))545 };546547 let relay_chain_slot_duration = Duration::from_secs(6);548549 if validator {550 let parachain_consensus = build_consensus(551 client.clone(),552 prometheus_registry.as_ref(),553 telemetry.as_ref().map(|t| t.handle()),554 &task_manager,555 relay_chain_interface.clone(),556 transaction_pool,557 network,558 params.keystore_container.sync_keystore(),559 force_authoring,560 )?;561562 let spawner = task_manager.spawn_handle();563564 let params = StartCollatorParams {565 para_id: id,566 block_status: client.clone(),567 announce_block,568 client: client.clone(),569 task_manager: &mut task_manager,570 spawner,571 parachain_consensus,572 import_queue,573 collator_key: collator_key.expect("Command line arguments do not allow this. qed"),574 relay_chain_interface,575 relay_chain_slot_duration,576 };577578 start_collator(params).await?;579 } else {580 let params = StartFullNodeParams {581 client: client.clone(),582 announce_block,583 task_manager: &mut task_manager,584 para_id: id,585 import_queue,586 relay_chain_interface,587 relay_chain_slot_duration,588 collator_options,589 };590591 start_full_node(params)?;592 }593594 start_network.start_network();595596 Ok((task_manager, client))597}598599600pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(601 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,602 config: &Configuration,603 telemetry: Option<TelemetryHandle>,604 task_manager: &TaskManager,605) -> Result<606 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,607 sc_service::Error,608>609where610 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>611 + Send612 + Sync613 + 'static,614 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>615 + sp_block_builder::BlockBuilder<Block>616 + sp_consensus_aura::AuraApi<Block, AuraId>617 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,618 ExecutorDispatch: NativeExecutionDispatch + 'static,619{620 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;621622 cumulus_client_consensus_aura::import_queue::<623 sp_consensus_aura::sr25519::AuthorityPair,624 _,625 _,626 _,627 _,628 _,629 >(cumulus_client_consensus_aura::ImportQueueParams {630 block_import: client.clone(),631 client: client.clone(),632 create_inherent_data_providers: move |_, _| async move {633 let time = sp_timestamp::InherentDataProvider::from_system_time();634635 let slot =636 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(637 *time,638 slot_duration,639 );640641 Ok((slot, time))642 },643 registry: config.prometheus_registry(),644 spawner: &task_manager.spawn_essential_handle(),645 telemetry,646 })647 .map_err(Into::into)648}649650651pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(652 parachain_config: Configuration,653 polkadot_config: Configuration,654 collator_options: CollatorOptions,655 id: ParaId,656 hwbench: Option<sc_sysinfo::HwBench>,657) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>658where659 Runtime: RuntimeInstance + Send + Sync + 'static,660 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,661 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,662 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>663 + Send664 + Sync665 + 'static,666 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>667 + fp_rpc::EthereumRuntimeRPCApi<Block>668 + fp_rpc::ConvertTransactionRuntimeApi<Block>669 + sp_session::SessionKeys<Block>670 + sp_block_builder::BlockBuilder<Block>671 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>672 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>673 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>674 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>675 + rmrk_rpc::RmrkApi<676 Block,677 AccountId,678 RmrkCollectionInfo<AccountId>,679 RmrkInstanceInfo<AccountId>,680 RmrkResourceInfo,681 RmrkPropertyInfo,682 RmrkBaseInfo<AccountId>,683 RmrkPartType,684 RmrkTheme,685 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>686 + sp_api::Metadata<Block>687 + sp_offchain::OffchainWorkerApi<Block>688 + cumulus_primitives_core::CollectCollationInfo<Block>689 + sp_consensus_aura::AuraApi<Block, AuraId>,690 ExecutorDispatch: NativeExecutionDispatch + 'static,691{692 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(693 parachain_config,694 polkadot_config,695 collator_options,696 id,697 parachain_build_import_queue,698 |client,699 prometheus_registry,700 telemetry,701 task_manager,702 relay_chain_interface,703 transaction_pool,704 sync_oracle,705 keystore,706 force_authoring| {707 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;708709 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(710 task_manager.spawn_handle(),711 client.clone(),712 transaction_pool,713 prometheus_registry,714 telemetry.clone(),715 );716717 Ok(AuraConsensus::build::<718 sp_consensus_aura::sr25519::AuthorityPair,719 _,720 _,721 _,722 _,723 _,724 _,725 >(BuildAuraConsensusParams {726 proposer_factory,727 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {728 let relay_chain_interface = relay_chain_interface.clone();729 async move {730 let parachain_inherent =731 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(732 relay_parent,733 &relay_chain_interface,734 &validation_data,735 id,736 ).await;737738 let time = sp_timestamp::InherentDataProvider::from_system_time();739740 let slot =741 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(742 *time,743 slot_duration,744 );745746 let parachain_inherent = parachain_inherent.ok_or_else(|| {747 Box::<dyn std::error::Error + Send + Sync>::from(748 "Failed to create parachain inherent",749 )750 })?;751 Ok((slot, time, parachain_inherent))752 }753 },754 block_import: client.clone(),755 para_client: client,756 backoff_authoring_blocks: Option::<()>::None,757 sync_oracle,758 keystore,759 force_authoring,760 slot_duration,761 762 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),763 telemetry,764 max_block_proposal_slot_portion: None,765 }))766 },767 hwbench,768 )769 .await770}771772fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(773 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,774 config: &Configuration,775 _: Option<TelemetryHandle>,776 task_manager: &TaskManager,777) -> Result<778 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,779 sc_service::Error,780>781where782 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>783 + Send784 + Sync785 + 'static,786 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>787 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,788 ExecutorDispatch: NativeExecutionDispatch + 'static,789{790 Ok(sc_consensus_manual_seal::import_queue(791 Box::new(client.clone()),792 &task_manager.spawn_essential_handle(),793 config.prometheus_registry(),794 ))795}796797798799pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(800 config: Configuration,801 autoseal_interval: Duration,802) -> sc_service::error::Result<TaskManager>803where804 Runtime: RuntimeInstance + Send + Sync + 'static,805 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,806 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,807 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>808 + Send809 + Sync810 + 'static,811 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>812 + fp_rpc::EthereumRuntimeRPCApi<Block>813 + fp_rpc::ConvertTransactionRuntimeApi<Block>814 + sp_session::SessionKeys<Block>815 + sp_block_builder::BlockBuilder<Block>816 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>817 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>818 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>819 + app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>820 + rmrk_rpc::RmrkApi<821 Block,822 AccountId,823 RmrkCollectionInfo<AccountId>,824 RmrkInstanceInfo<AccountId>,825 RmrkResourceInfo,826 RmrkPropertyInfo,827 RmrkBaseInfo<AccountId>,828 RmrkPartType,829 RmrkTheme,830 > + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>831 + sp_api::Metadata<Block>832 + sp_offchain::OffchainWorkerApi<Block>833 + cumulus_primitives_core::CollectCollationInfo<Block>834 + sp_consensus_aura::AuraApi<Block, AuraId>,835 ExecutorDispatch: NativeExecutionDispatch + 'static,836{837 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};838 use fc_consensus::FrontierBlockImport;839 use sc_client_api::HeaderBackend;840841 let sc_service::PartialComponents {842 client,843 backend,844 mut task_manager,845 import_queue,846 keystore_container,847 select_chain: maybe_select_chain,848 transaction_pool,849 other:850 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),851 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(852 &config,853 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,854 )?;855 let prometheus_registry = config.prometheus_registry().cloned();856857 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(858 task_manager.spawn_handle(),859 overrides_handle::<_, _, Runtime>(client.clone()),860 50,861 50,862 prometheus_registry.clone(),863 ));864865 let (network, system_rpc_tx, tx_handler_controller, network_starter) =866 sc_service::build_network(sc_service::BuildNetworkParams {867 config: &config,868 client: client.clone(),869 transaction_pool: transaction_pool.clone(),870 spawn_handle: task_manager.spawn_handle(),871 import_queue,872 block_announce_validator_builder: None,873 warp_sync: None,874 })?;875876 if config.offchain_worker.enabled {877 sc_service::build_offchain_workers(878 &config,879 task_manager.spawn_handle(),880 client.clone(),881 network.clone(),882 );883 }884885 let collator = config.role.is_authority();886887 let select_chain = maybe_select_chain.clone();888889 if collator {890 let block_import =891 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());892893 let env = sc_basic_authorship::ProposerFactory::new(894 task_manager.spawn_handle(),895 client.clone(),896 transaction_pool.clone(),897 prometheus_registry.as_ref(),898 telemetry.as_ref().map(|x| x.handle()),899 );900901 let transactions_commands_stream: Box<902 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,903 > = Box::new(904 transaction_pool905 .pool()906 .validated_pool()907 .import_notification_stream()908 .map(|_| EngineCommand::SealNewBlock {909 create_empty: true,910 finalize: false,911 parent_hash: None,912 sender: None,913 }),914 );915916 let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));917 let idle_commands_stream: Box<918 dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,919 > = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {920 create_empty: true,921 finalize: false,922 parent_hash: None,923 sender: None,924 }));925926 let commands_stream = select(transactions_commands_stream, idle_commands_stream);927928 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;929 let client_set_aside_for_cidp = client.clone();930931 task_manager.spawn_essential_handle().spawn_blocking(932 "authorship_task",933 Some("block-authoring"),934 run_manual_seal(ManualSealParams {935 block_import,936 env,937 client: client.clone(),938 pool: transaction_pool.clone(),939 commands_stream,940 select_chain: select_chain.clone(),941 consensus_data_provider: None,942 create_inherent_data_providers: move |block: Hash, ()| {943 let current_para_block = client_set_aside_for_cidp944 .number(block)945 .expect("Header lookup should succeed")946 .expect("Header passed in as parent should be present in backend.");947948 let client_for_xcm = client_set_aside_for_cidp.clone();949 async move {950 let time = sp_timestamp::InherentDataProvider::from_system_time();951952 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {953 current_para_block,954 relay_offset: 1000,955 relay_blocks_per_para_block: 2,956 para_blocks_per_relay_epoch: 0,957 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(958 &*client_for_xcm,959 block,960 Default::default(),961 Default::default(),962 ),963 relay_randomness_config: (),964 raw_downward_messages: vec![],965 raw_horizontal_messages: vec![],966 };967968 let slot =969 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(970 *time,971 slot_duration,972 );973974 Ok((time, slot, mocked_parachain))975 }976 },977 }),978 );979 }980981 task_manager.spawn_essential_handle().spawn(982 "frontier-mapping-sync-worker",983 Some("block-authoring"),984 MappingSyncWorker::new(985 client.import_notification_stream(),986 Duration::new(6, 0),987 client.clone(),988 backend.clone(),989 frontier_backend.clone(),990 3,991 0,992 SyncStrategy::Normal,993 )994 .for_each(|()| futures::future::ready(())),995 );996997 let rpc_client = client.clone();998 let rpc_pool = transaction_pool.clone();999 let rpc_network = network.clone();1000 let rpc_frontier_backend = frontier_backend.clone();1001 let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1002 let full_deps = unique_rpc::FullDeps {1003 backend: rpc_frontier_backend.clone(),1004 deny_unsafe,1005 client: rpc_client.clone(),1006 pool: rpc_pool.clone(),1007 graph: rpc_pool.pool().clone(),1008 1009 enable_dev_signer: false,1010 filter_pool: filter_pool.clone(),1011 network: rpc_network.clone(),1012 select_chain: select_chain.clone(),1013 is_authority: collator,1014 1015 max_past_logs: 10000,1016 block_data_cache: block_data_cache.clone(),1017 fee_history_cache: fee_history_cache.clone(),1018 1019 fee_history_limit: 2048,1020 };10211022 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1023 full_deps,1024 subscription_executor,1025 )1026 .map_err(Into::into)1027 });10281029 sc_service::spawn_tasks(sc_service::SpawnTasksParams {1030 network,1031 client,1032 keystore: keystore_container.sync_keystore(),1033 task_manager: &mut task_manager,1034 transaction_pool,1035 rpc_builder,1036 backend,1037 system_rpc_tx,1038 config,1039 telemetry: None,1040 tx_handler_controller,1041 })?;10421043 network_starter.start_network();1044 Ok(task_manager)1045}