git.delta.rocks / unique-network / refs/commits / 6a612620e37d

difftreelog

source

node/cli/src/service.rs30.2 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.1819// std20use std::sync::Arc;21use std::sync::Mutex;22use std::collections::BTreeMap;23use std::time::Duration;24use std::pin::Pin;25use fc_rpc_core::types::FeeHistoryCache;26use futures::{27	Stream, StreamExt,28	stream::select,29	task::{Context, Poll},30};31use tokio::time::Interval;3233use unique_rpc::overrides_handle;3435use serde::{Serialize, Deserialize};3637// Cumulus Imports38use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};39use cumulus_client_consensus_common::ParachainConsensus;40use cumulus_client_service::{41	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;4950// Substrate Imports51use sc_client_api::ExecutorProvider;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::NetworkService;55use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;6162use polkadot_service::CollatorPair;6364// Frontier Imports65use fc_rpc_core::types::FilterPool;66use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6768use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};6970// RMRK71/* TODO free RMRK! use up_data_structs::{72	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,73	RmrkPartType, RmrkTheme,74};*/7576/// Unique native executor instance.77#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]81/// Quartz native executor instance.8283pub struct QuartzRuntimeExecutor;8485/// Opal native executor instance.86pub struct OpalRuntimeExecutor;8788#[cfg(feature = "unique-runtime")]89impl NativeExecutionDispatch for UniqueRuntimeExecutor {90	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9192	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {93		unique_runtime::api::dispatch(method, data)94	}9596	fn native_version() -> sc_executor::NativeVersion {97		unique_runtime::native_version()98	}99}100101#[cfg(feature = "quartz-runtime")]102impl NativeExecutionDispatch for QuartzRuntimeExecutor {103	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;104105	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {106		quartz_runtime::api::dispatch(method, data)107	}108109	fn native_version() -> sc_executor::NativeVersion {110		quartz_runtime::native_version()111	}112}113114impl NativeExecutionDispatch for OpalRuntimeExecutor {115	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;116117	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {118		opal_runtime::api::dispatch(method, data)119	}120121	fn native_version() -> sc_executor::NativeVersion {122		opal_runtime::native_version()123	}124}125126pub struct AutosealInterval {127	interval: Interval,128}129130impl AutosealInterval {131	pub fn new(config: &Configuration, interval: Duration) -> Self {132		let _tokio_runtime = config.tokio_handle.enter();133		let interval = tokio::time::interval(interval);134135		Self { interval }136	}137}138139impl Stream for AutosealInterval {140	type Item = tokio::time::Instant;141142	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {143		self.interval.poll_tick(cx).map(Some)144	}145}146147pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {148	let config_dir = config149		.base_path150		.as_ref()151		.map(|base_path| base_path.config_dir(config.chain_spec.id()))152		.unwrap_or_else(|| {153			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())154		});155	let database_dir = config_dir.join("frontier").join("db");156157	Ok(Arc::new(fc_db::Backend::<Block>::new(158		&fc_db::DatabaseSettings {159			source: fc_db::DatabaseSettingsSrc::RocksDb {160				path: database_dir,161				cache_size: 0,162			},163		},164	)?))165}166167type FullClient<RuntimeApi, ExecutorDispatch> =168	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;169type FullBackend = sc_service::TFullBackend<Block>;170type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;171172/// Starts a `ServiceBuilder` for a full service.173///174/// Use this macro if you don't actually need the full service, but just the builder in order to175/// be able to perform chain operations.176#[allow(clippy::type_complexity)]177pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(178	config: &Configuration,179	build_import_queue: BIQ,180) -> Result<181	PartialComponents<182		FullClient<RuntimeApi, ExecutorDispatch>,183		FullBackend,184		FullSelectChain,185		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,186		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,187		(188			Option<Telemetry>,189			Option<FilterPool>,190			Arc<fc_db::Backend<Block>>,191			Option<TelemetryWorkerHandle>,192			FeeHistoryCache,193		),194	>,195	sc_service::Error,196>197where198	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,199	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>200		+ Send201		+ Sync202		+ 'static,203	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,204	ExecutorDispatch: NativeExecutionDispatch + 'static,205	BIQ: FnOnce(206		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,207		&Configuration,208		Option<TelemetryHandle>,209		&TaskManager,210	) -> Result<211		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,212		sc_service::Error,213	>,214{215	let _telemetry = config216		.telemetry_endpoints217		.clone()218		.filter(|x| !x.is_empty())219		.map(|endpoints| -> Result<_, sc_telemetry::Error> {220			let worker = TelemetryWorker::new(16)?;221			let telemetry = worker.handle().new_telemetry(endpoints);222			Ok((worker, telemetry))223		})224		.transpose()?;225226	let telemetry = config227		.telemetry_endpoints228		.clone()229		.filter(|x| !x.is_empty())230		.map(|endpoints| -> Result<_, sc_telemetry::Error> {231			let worker = TelemetryWorker::new(16)?;232			let telemetry = worker.handle().new_telemetry(endpoints);233			Ok((worker, telemetry))234		})235		.transpose()?;236237	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(238		config.wasm_method,239		config.default_heap_pages,240		config.max_runtime_instances,241		config.runtime_cache_size,242	);243244	let (client, backend, keystore_container, task_manager) =245		sc_service::new_full_parts::<Block, RuntimeApi, _>(246			config,247			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),248			executor,249		)?;250	let client = Arc::new(client);251252	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());253254	let telemetry = telemetry.map(|(worker, telemetry)| {255		task_manager256			.spawn_handle()257			.spawn("telemetry", None, worker.run());258		telemetry259	});260261	let select_chain = sc_consensus::LongestChain::new(backend.clone());262263	let transaction_pool = sc_transaction_pool::BasicPool::new_full(264		config.transaction_pool.clone(),265		config.role.is_authority().into(),266		config.prometheus_registry(),267		task_manager.spawn_essential_handle(),268		client.clone(),269	);270271	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));272273	let frontier_backend = open_frontier_backend(config)?;274275	let import_queue = build_import_queue(276		client.clone(),277		config,278		telemetry.as_ref().map(|telemetry| telemetry.handle()),279		&task_manager,280	)?;281	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));282283	let params = PartialComponents {284		backend,285		client,286		import_queue,287		keystore_container,288		task_manager,289		transaction_pool,290		select_chain,291		other: (292			telemetry,293			filter_pool,294			frontier_backend,295			telemetry_worker_handle,296			fee_history_cache,297		),298	};299300	Ok(params)301}302303async fn build_relay_chain_interface(304	polkadot_config: Configuration,305	parachain_config: &Configuration,306	telemetry_worker_handle: Option<TelemetryWorkerHandle>,307	task_manager: &mut TaskManager,308	collator_options: CollatorOptions,309) -> RelayChainResult<(310	Arc<(dyn RelayChainInterface + 'static)>,311	Option<CollatorPair>,312)> {313	match collator_options.relay_chain_rpc_url {314		Some(relay_chain_url) => Ok((315			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,316			None,317		)),318		None => build_inprocess_relay_chain(319			polkadot_config,320			parachain_config,321			telemetry_worker_handle,322			task_manager,323		),324	}325}326327/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.328///329/// This is the actual implementation that is abstract over the executor and the runtime api.330#[sc_tracing::logging::prefix_logs_with("Parachain")]331async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(332	parachain_config: Configuration,333	polkadot_config: Configuration,334	collator_options: CollatorOptions,335	id: ParaId,336	build_import_queue: BIQ,337	build_consensus: BIC,338) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>339where340	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,341	Runtime: RuntimeInstance + Send + Sync + 'static,342	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,343	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,344	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>345		+ Send346		+ Sync347		+ 'static,348	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>349		+ fp_rpc::EthereumRuntimeRPCApi<Block>350		+ fp_rpc::ConvertTransactionRuntimeApi<Block>351		+ sp_session::SessionKeys<Block>352		+ sp_block_builder::BlockBuilder<Block>353		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>354		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>355		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>356		/* TODO free RMRK!357		+ rmrk_rpc::RmrkApi<358			Block,359			AccountId,360			RmrkCollectionInfo<AccountId>,361			RmrkInstanceInfo<AccountId>,362			RmrkResourceInfo,363			RmrkPropertyInfo,364			RmrkBaseInfo<AccountId>,365			RmrkPartType,366			RmrkTheme,367		>*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>368		+ sp_api::Metadata<Block>369		+ sp_offchain::OffchainWorkerApi<Block>370		+ cumulus_primitives_core::CollectCollationInfo<Block>,371	ExecutorDispatch: NativeExecutionDispatch + 'static,372	BIQ: FnOnce(373		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,374		&Configuration,375		Option<TelemetryHandle>,376		&TaskManager,377	) -> Result<378		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,379		sc_service::Error,380	>,381	BIC: FnOnce(382		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,383		Option<&Registry>,384		Option<TelemetryHandle>,385		&TaskManager,386		Arc<dyn RelayChainInterface>,387		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,388		Arc<NetworkService<Block, Hash>>,389		SyncCryptoStorePtr,390		bool,391	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,392{393	if matches!(parachain_config.role, Role::Light) {394		return Err("Light client not supported!".into());395	}396397	let parachain_config = prepare_node_config(parachain_config);398399	let params =400		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;401	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =402		params.other;403404	let client = params.client.clone();405	let backend = params.backend.clone();406	let mut task_manager = params.task_manager;407408	let (relay_chain_interface, collator_key) = build_relay_chain_interface(409		polkadot_config,410		&parachain_config,411		telemetry_worker_handle,412		&mut task_manager,413		collator_options.clone(),414	)415	.await416	.map_err(|e| match e {417		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,418		s => s.to_string().into(),419	})?;420421	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);422423	let force_authoring = parachain_config.force_authoring;424	let validator = parachain_config.role.is_authority();425	let prometheus_registry = parachain_config.prometheus_registry().cloned();426	let transaction_pool = params.transaction_pool.clone();427	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);428429	let (network, system_rpc_tx, start_network) =430		sc_service::build_network(sc_service::BuildNetworkParams {431			config: &parachain_config,432			client: client.clone(),433			transaction_pool: transaction_pool.clone(),434			spawn_handle: task_manager.spawn_handle(),435			import_queue: import_queue.clone(),436			block_announce_validator_builder: Some(Box::new(|_| {437				Box::new(block_announce_validator)438			})),439			warp_sync: None,440		})?;441442	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());443	let rpc_client = client.clone();444	let rpc_pool = transaction_pool.clone();445	let select_chain = params.select_chain.clone();446	let rpc_network = network.clone();447448	let rpc_frontier_backend = frontier_backend.clone();449450	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(451		task_manager.spawn_handle(),452		overrides_handle::<_, _, Runtime>(client.clone()),453		50,454		50,455	));456457	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {458		let full_deps = unique_rpc::FullDeps {459			backend: rpc_frontier_backend.clone(),460			deny_unsafe,461			client: rpc_client.clone(),462			pool: rpc_pool.clone(),463			graph: rpc_pool.pool().clone(),464			// TODO: Unhardcode465			enable_dev_signer: false,466			filter_pool: filter_pool.clone(),467			network: rpc_network.clone(),468			select_chain: select_chain.clone(),469			is_authority: validator,470			// TODO: Unhardcode471			max_past_logs: 10000,472			block_data_cache: block_data_cache.clone(),473			fee_history_cache: fee_history_cache.clone(),474			// TODO: Unhardcode475			fee_history_limit: 2048,476		};477478		Ok(479			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(480				full_deps,481				subscription_executor.clone(),482			),483		)484	});485486	task_manager.spawn_essential_handle().spawn(487		"frontier-mapping-sync-worker",488		None,489		MappingSyncWorker::new(490			client.import_notification_stream(),491			Duration::new(6, 0),492			client.clone(),493			backend.clone(),494			frontier_backend.clone(),495			3,496			0,497			SyncStrategy::Normal,498		)499		.for_each(|()| futures::future::ready(())),500	);501502	sc_service::spawn_tasks(sc_service::SpawnTasksParams {503		rpc_extensions_builder,504		client: client.clone(),505		transaction_pool: transaction_pool.clone(),506		task_manager: &mut task_manager,507		config: parachain_config,508		keystore: params.keystore_container.sync_keystore(),509		backend: backend.clone(),510		network: network.clone(),511		system_rpc_tx,512		telemetry: telemetry.as_mut(),513	})?;514515	let announce_block = {516		let network = network.clone();517		Arc::new(move |hash, data| network.announce_block(hash, data))518	};519520	let relay_chain_slot_duration = Duration::from_secs(6);521522	if validator {523		let parachain_consensus = build_consensus(524			client.clone(),525			prometheus_registry.as_ref(),526			telemetry.as_ref().map(|t| t.handle()),527			&task_manager,528			relay_chain_interface.clone(),529			transaction_pool,530			network,531			params.keystore_container.sync_keystore(),532			force_authoring,533		)?;534535		let spawner = task_manager.spawn_handle();536537		let params = StartCollatorParams {538			para_id: id,539			block_status: client.clone(),540			announce_block,541			client: client.clone(),542			task_manager: &mut task_manager,543			spawner,544			parachain_consensus,545			import_queue,546			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),547			relay_chain_interface,548			relay_chain_slot_duration,549		};550551		start_collator(params).await?;552	} else {553		let params = StartFullNodeParams {554			client: client.clone(),555			announce_block,556			task_manager: &mut task_manager,557			para_id: id,558			import_queue,559			relay_chain_interface,560			relay_chain_slot_duration,561			collator_options,562		};563564		start_full_node(params)?;565	}566567	start_network.start_network();568569	Ok((task_manager, client))570}571572/// Build the import queue for the the parachain runtime.573pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(574	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,575	config: &Configuration,576	telemetry: Option<TelemetryHandle>,577	task_manager: &TaskManager,578) -> Result<579	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,580	sc_service::Error,581>582where583	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>584		+ Send585		+ Sync586		+ 'static,587	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>588		+ sp_block_builder::BlockBuilder<Block>589		+ sp_consensus_aura::AuraApi<Block, AuraId>590		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,591	ExecutorDispatch: NativeExecutionDispatch + 'static,592{593	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;594595	cumulus_client_consensus_aura::import_queue::<596		sp_consensus_aura::sr25519::AuthorityPair,597		_,598		_,599		_,600		_,601		_,602		_,603	>(cumulus_client_consensus_aura::ImportQueueParams {604		block_import: client.clone(),605		client: client.clone(),606		create_inherent_data_providers: move |_, _| async move {607			let time = sp_timestamp::InherentDataProvider::from_system_time();608609			let slot =610				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(611					*time,612					slot_duration,613				);614615			Ok((time, slot))616		},617		registry: config.prometheus_registry(),618		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),619		spawner: &task_manager.spawn_essential_handle(),620		telemetry,621	})622	.map_err(Into::into)623}624625/// Start a normal parachain node.626pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(627	parachain_config: Configuration,628	polkadot_config: Configuration,629	collator_options: CollatorOptions,630	id: ParaId,631) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>632where633	Runtime: RuntimeInstance + Send + Sync + 'static,634	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,635	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,636	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>637		+ Send638		+ Sync639		+ 'static,640	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>641		+ fp_rpc::EthereumRuntimeRPCApi<Block>642		+ fp_rpc::ConvertTransactionRuntimeApi<Block>643		+ sp_session::SessionKeys<Block>644		+ sp_block_builder::BlockBuilder<Block>645		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>646		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>647		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>648		/* TODO free RMRK!649		+ rmrk_rpc::RmrkApi<650			Block,651			AccountId,652			RmrkCollectionInfo<AccountId>,653			RmrkInstanceInfo<AccountId>,654			RmrkResourceInfo,655			RmrkPropertyInfo,656			RmrkBaseInfo<AccountId>,657			RmrkPartType,658			RmrkTheme,659		>*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>660		+ sp_api::Metadata<Block>661		+ sp_offchain::OffchainWorkerApi<Block>662		+ cumulus_primitives_core::CollectCollationInfo<Block>663		+ sp_consensus_aura::AuraApi<Block, AuraId>,664	ExecutorDispatch: NativeExecutionDispatch + 'static,665{666	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(667		parachain_config,668		polkadot_config,669		collator_options,670		id,671		parachain_build_import_queue,672		|client,673		 prometheus_registry,674		 telemetry,675		 task_manager,676		 relay_chain_interface,677		 transaction_pool,678		 sync_oracle,679		 keystore,680		 force_authoring| {681			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;682683			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(684				task_manager.spawn_handle(),685				client.clone(),686				transaction_pool,687				prometheus_registry,688				telemetry.clone(),689			);690691			Ok(AuraConsensus::build::<692				sp_consensus_aura::sr25519::AuthorityPair,693				_,694				_,695				_,696				_,697				_,698				_,699			>(BuildAuraConsensusParams {700				proposer_factory,701				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {702					let relay_chain_interface = relay_chain_interface.clone();703					async move {704						let parachain_inherent =705						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(706							relay_parent,707							&relay_chain_interface,708							&validation_data,709							id,710						).await;711712						let time = sp_timestamp::InherentDataProvider::from_system_time();713714						let slot =715						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(716							*time,717							slot_duration,718						);719720						let parachain_inherent = parachain_inherent.ok_or_else(|| {721							Box::<dyn std::error::Error + Send + Sync>::from(722								"Failed to create parachain inherent",723							)724						})?;725						Ok((time, slot, parachain_inherent))726					}727				},728				block_import: client.clone(),729				para_client: client,730				backoff_authoring_blocks: Option::<()>::None,731				sync_oracle,732				keystore,733				force_authoring,734				slot_duration,735				// We got around 500ms for proposing736				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),737				telemetry,738				max_block_proposal_slot_portion: None,739			}))740		},741	)742	.await743}744745fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(746	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,747	config: &Configuration,748	_: Option<TelemetryHandle>,749	task_manager: &TaskManager,750) -> Result<751	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,752	sc_service::Error,753>754where755	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>756		+ Send757		+ Sync758		+ 'static,759	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>760		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,761	ExecutorDispatch: NativeExecutionDispatch + 'static,762{763	Ok(sc_consensus_manual_seal::import_queue(764		Box::new(client.clone()),765		&task_manager.spawn_essential_handle(),766		config.prometheus_registry(),767	))768}769770/// Builds a new development service. This service uses instant seal, and mocks771/// the parachain inherent772pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(773	config: Configuration,774	autoseal_interval: Duration,775) -> sc_service::error::Result<TaskManager>776where777	Runtime: RuntimeInstance + Send + Sync + 'static,778	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,779	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,780	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>781		+ Send782		+ Sync783		+ 'static,784	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>785		+ fp_rpc::EthereumRuntimeRPCApi<Block>786		+ fp_rpc::ConvertTransactionRuntimeApi<Block>787		+ sp_session::SessionKeys<Block>788		+ sp_block_builder::BlockBuilder<Block>789		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>790		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>791		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>792		/* TODO free RMRK!793		+ rmrk_rpc::RmrkApi<794			Block,795			AccountId,796			RmrkCollectionInfo<AccountId>,797			RmrkInstanceInfo<AccountId>,798			RmrkResourceInfo,799			RmrkPropertyInfo,800			RmrkBaseInfo<AccountId>,801			RmrkPartType,802			RmrkTheme,803		>*/ + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>804		+ sp_api::Metadata<Block>805		+ sp_offchain::OffchainWorkerApi<Block>806		+ cumulus_primitives_core::CollectCollationInfo<Block>807		+ sp_consensus_aura::AuraApi<Block, AuraId>,808	ExecutorDispatch: NativeExecutionDispatch + 'static,809{810	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};811	use fc_consensus::FrontierBlockImport;812	use sc_client_api::HeaderBackend;813814	let sc_service::PartialComponents {815		client,816		backend,817		mut task_manager,818		import_queue,819		keystore_container,820		select_chain: maybe_select_chain,821		transaction_pool,822		other:823			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),824	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(825		&config,826		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,827	)?;828829	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(830		task_manager.spawn_handle(),831		overrides_handle::<_, _, Runtime>(client.clone()),832		50,833		50,834	));835836	let (network, system_rpc_tx, network_starter) =837		sc_service::build_network(sc_service::BuildNetworkParams {838			config: &config,839			client: client.clone(),840			transaction_pool: transaction_pool.clone(),841			spawn_handle: task_manager.spawn_handle(),842			import_queue,843			block_announce_validator_builder: None,844			warp_sync: None,845		})?;846847	if config.offchain_worker.enabled {848		sc_service::build_offchain_workers(849			&config,850			task_manager.spawn_handle(),851			client.clone(),852			network.clone(),853		);854	}855856	let prometheus_registry = config.prometheus_registry().cloned();857	let collator = config.role.is_authority();858859	let select_chain = maybe_select_chain.clone();860861	if collator {862		let block_import =863			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());864865		let env = sc_basic_authorship::ProposerFactory::new(866			task_manager.spawn_handle(),867			client.clone(),868			transaction_pool.clone(),869			prometheus_registry.as_ref(),870			telemetry.as_ref().map(|x| x.handle()),871		);872873		let transactions_commands_stream: Box<874			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,875		> = Box::new(876			transaction_pool877				.pool()878				.validated_pool()879				.import_notification_stream()880				.map(|_| EngineCommand::SealNewBlock {881					create_empty: true,882					finalize: false,883					parent_hash: None,884					sender: None,885				}),886		);887888		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));889		let idle_commands_stream: Box<890			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,891		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {892			create_empty: true,893			finalize: false,894			parent_hash: None,895			sender: None,896		}));897898		let commands_stream = select(transactions_commands_stream, idle_commands_stream);899900		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;901		let client_set_aside_for_cidp = client.clone();902903		task_manager.spawn_essential_handle().spawn_blocking(904			"authorship_task",905			Some("block-authoring"),906			run_manual_seal(ManualSealParams {907				block_import,908				env,909				client: client.clone(),910				pool: transaction_pool.clone(),911				commands_stream,912				select_chain: select_chain.clone(),913				consensus_data_provider: None,914				create_inherent_data_providers: move |block: Hash, ()| {915					let current_para_block = client_set_aside_for_cidp916						.number(block)917						.expect("Header lookup should succeed")918						.expect("Header passed in as parent should be present in backend.");919920					let client_for_xcm = client_set_aside_for_cidp.clone();921					async move {922						let time = sp_timestamp::InherentDataProvider::from_system_time();923924						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {925							current_para_block,926							relay_offset: 1000,927							relay_blocks_per_para_block: 2,928							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(929								&*client_for_xcm,930								block,931								Default::default(),932								Default::default(),933							),934							raw_downward_messages: vec![],935							raw_horizontal_messages: vec![],936						};937938						let slot =939						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(940							*time,941							slot_duration,942						);943944						Ok((time, slot, mocked_parachain))945					}946				},947			}),948		);949	}950951	task_manager.spawn_essential_handle().spawn(952		"frontier-mapping-sync-worker",953		Some("block-authoring"),954		MappingSyncWorker::new(955			client.import_notification_stream(),956			Duration::new(6, 0),957			client.clone(),958			backend.clone(),959			frontier_backend.clone(),960			3,961			0,962			SyncStrategy::Normal,963		)964		.for_each(|()| futures::future::ready(())),965	);966967	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());968	let rpc_client = client.clone();969	let rpc_pool = transaction_pool.clone();970	let rpc_network = network.clone();971	let rpc_frontier_backend = frontier_backend.clone();972	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {973		let full_deps = unique_rpc::FullDeps {974			backend: rpc_frontier_backend.clone(),975			deny_unsafe,976			client: rpc_client.clone(),977			pool: rpc_pool.clone(),978			graph: rpc_pool.pool().clone(),979			// TODO: Unhardcode980			enable_dev_signer: false,981			filter_pool: filter_pool.clone(),982			network: rpc_network.clone(),983			select_chain: select_chain.clone(),984			is_authority: collator,985			// TODO: Unhardcode986			max_past_logs: 10000,987			block_data_cache: block_data_cache.clone(),988			fee_history_cache: fee_history_cache.clone(),989			// TODO: Unhardcode990			fee_history_limit: 2048,991		};992993		Ok(994			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(995				full_deps,996				subscription_executor.clone(),997			),998		)999	});10001001	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1002		network,1003		client,1004		keystore: keystore_container.sync_keystore(),1005		task_manager: &mut task_manager,1006		transaction_pool,1007		rpc_extensions_builder,1008		backend,1009		system_rpc_tx,1010		config,1011		telemetry: None,1012	})?;10131014	network_starter.start_network();1015	Ok(task_manager)1016}