git.delta.rocks / unique-network / refs/commits / 3cd2ab66d9c6

difftreelog

source

node/cli/src/service.rs30.1 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// RMRK71use 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		+ rmrk_rpc::RmrkApi<357			Block,358			AccountId,359			RmrkCollectionInfo<AccountId>,360			RmrkInstanceInfo<AccountId>,361			RmrkResourceInfo,362			RmrkPropertyInfo,363			RmrkBaseInfo<AccountId>,364			RmrkPartType,365			RmrkTheme,366		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>367		+ sp_api::Metadata<Block>368		+ sp_offchain::OffchainWorkerApi<Block>369		+ cumulus_primitives_core::CollectCollationInfo<Block>,370	ExecutorDispatch: NativeExecutionDispatch + 'static,371	BIQ: FnOnce(372		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,373		&Configuration,374		Option<TelemetryHandle>,375		&TaskManager,376	) -> Result<377		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,378		sc_service::Error,379	>,380	BIC: FnOnce(381		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,382		Option<&Registry>,383		Option<TelemetryHandle>,384		&TaskManager,385		Arc<dyn RelayChainInterface>,386		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,387		Arc<NetworkService<Block, Hash>>,388		SyncCryptoStorePtr,389		bool,390	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,391{392	if matches!(parachain_config.role, Role::Light) {393		return Err("Light client not supported!".into());394	}395396	let parachain_config = prepare_node_config(parachain_config);397398	let params =399		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;400	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =401		params.other;402403	let client = params.client.clone();404	let backend = params.backend.clone();405	let mut task_manager = params.task_manager;406407	let (relay_chain_interface, collator_key) = build_relay_chain_interface(408		polkadot_config,409		&parachain_config,410		telemetry_worker_handle,411		&mut task_manager,412		collator_options.clone(),413	)414	.await415	.map_err(|e| match e {416		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,417		s => s.to_string().into(),418	})?;419420	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);421422	let force_authoring = parachain_config.force_authoring;423	let validator = parachain_config.role.is_authority();424	let prometheus_registry = parachain_config.prometheus_registry().cloned();425	let transaction_pool = params.transaction_pool.clone();426	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);427428	let (network, system_rpc_tx, start_network) =429		sc_service::build_network(sc_service::BuildNetworkParams {430			config: &parachain_config,431			client: client.clone(),432			transaction_pool: transaction_pool.clone(),433			spawn_handle: task_manager.spawn_handle(),434			import_queue: import_queue.clone(),435			block_announce_validator_builder: Some(Box::new(|_| {436				Box::new(block_announce_validator)437			})),438			warp_sync: None,439		})?;440441	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());442	let rpc_client = client.clone();443	let rpc_pool = transaction_pool.clone();444	let select_chain = params.select_chain.clone();445	let rpc_network = network.clone();446447	let rpc_frontier_backend = frontier_backend.clone();448449	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(450		task_manager.spawn_handle(),451		overrides_handle::<_, _, Runtime>(client.clone()),452		50,453		50,454	));455456	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {457		let full_deps = unique_rpc::FullDeps {458			backend: rpc_frontier_backend.clone(),459			deny_unsafe,460			client: rpc_client.clone(),461			pool: rpc_pool.clone(),462			graph: rpc_pool.pool().clone(),463			// TODO: Unhardcode464			enable_dev_signer: false,465			filter_pool: filter_pool.clone(),466			network: rpc_network.clone(),467			select_chain: select_chain.clone(),468			is_authority: validator,469			// TODO: Unhardcode470			max_past_logs: 10000,471			block_data_cache: block_data_cache.clone(),472			fee_history_cache: fee_history_cache.clone(),473			// TODO: Unhardcode474			fee_history_limit: 2048,475		};476477		Ok(478			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(479				full_deps,480				subscription_executor.clone(),481			),482		)483	});484485	task_manager.spawn_essential_handle().spawn(486		"frontier-mapping-sync-worker",487		None,488		MappingSyncWorker::new(489			client.import_notification_stream(),490			Duration::new(6, 0),491			client.clone(),492			backend.clone(),493			frontier_backend.clone(),494			3,495			0,496			SyncStrategy::Normal,497		)498		.for_each(|()| futures::future::ready(())),499	);500501	sc_service::spawn_tasks(sc_service::SpawnTasksParams {502		rpc_extensions_builder,503		client: client.clone(),504		transaction_pool: transaction_pool.clone(),505		task_manager: &mut task_manager,506		config: parachain_config,507		keystore: params.keystore_container.sync_keystore(),508		backend: backend.clone(),509		network: network.clone(),510		system_rpc_tx,511		telemetry: telemetry.as_mut(),512	})?;513514	let announce_block = {515		let network = network.clone();516		Arc::new(move |hash, data| network.announce_block(hash, data))517	};518519	let relay_chain_slot_duration = Duration::from_secs(6);520521	if validator {522		let parachain_consensus = build_consensus(523			client.clone(),524			prometheus_registry.as_ref(),525			telemetry.as_ref().map(|t| t.handle()),526			&task_manager,527			relay_chain_interface.clone(),528			transaction_pool,529			network,530			params.keystore_container.sync_keystore(),531			force_authoring,532		)?;533534		let spawner = task_manager.spawn_handle();535536		let params = StartCollatorParams {537			para_id: id,538			block_status: client.clone(),539			announce_block,540			client: client.clone(),541			task_manager: &mut task_manager,542			spawner,543			parachain_consensus,544			import_queue,545			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),546			relay_chain_interface,547			relay_chain_slot_duration,548		};549550		start_collator(params).await?;551	} else {552		let params = StartFullNodeParams {553			client: client.clone(),554			announce_block,555			task_manager: &mut task_manager,556			para_id: id,557			import_queue,558			relay_chain_interface,559			relay_chain_slot_duration,560			collator_options,561		};562563		start_full_node(params)?;564	}565566	start_network.start_network();567568	Ok((task_manager, client))569}570571/// Build the import queue for the the parachain runtime.572pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(573	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,574	config: &Configuration,575	telemetry: Option<TelemetryHandle>,576	task_manager: &TaskManager,577) -> Result<578	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,579	sc_service::Error,580>581where582	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>583		+ Send584		+ Sync585		+ 'static,586	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>587		+ sp_block_builder::BlockBuilder<Block>588		+ sp_consensus_aura::AuraApi<Block, AuraId>589		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,590	ExecutorDispatch: NativeExecutionDispatch + 'static,591{592	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;593594	cumulus_client_consensus_aura::import_queue::<595		sp_consensus_aura::sr25519::AuthorityPair,596		_,597		_,598		_,599		_,600		_,601		_,602	>(cumulus_client_consensus_aura::ImportQueueParams {603		block_import: client.clone(),604		client: client.clone(),605		create_inherent_data_providers: move |_, _| async move {606			let time = sp_timestamp::InherentDataProvider::from_system_time();607608			let slot =609				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(610					*time,611					slot_duration,612				);613614			Ok((time, slot))615		},616		registry: config.prometheus_registry(),617		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),618		spawner: &task_manager.spawn_essential_handle(),619		telemetry,620	})621	.map_err(Into::into)622}623624/// Start a normal parachain node.625pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(626	parachain_config: Configuration,627	polkadot_config: Configuration,628	collator_options: CollatorOptions,629	id: ParaId,630) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>631where632	Runtime: RuntimeInstance + Send + Sync + 'static,633	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,634	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,635	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>636		+ Send637		+ Sync638		+ 'static,639	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>640		+ fp_rpc::EthereumRuntimeRPCApi<Block>641		+ fp_rpc::ConvertTransactionRuntimeApi<Block>642		+ sp_session::SessionKeys<Block>643		+ sp_block_builder::BlockBuilder<Block>644		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>645		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>646		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>647		+ rmrk_rpc::RmrkApi<648			Block,649			AccountId,650			RmrkCollectionInfo<AccountId>,651			RmrkInstanceInfo<AccountId>,652			RmrkResourceInfo,653			RmrkPropertyInfo,654			RmrkBaseInfo<AccountId>,655			RmrkPartType,656			RmrkTheme,657		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>658		+ sp_api::Metadata<Block>659		+ sp_offchain::OffchainWorkerApi<Block>660		+ cumulus_primitives_core::CollectCollationInfo<Block>661		+ sp_consensus_aura::AuraApi<Block, AuraId>,662	ExecutorDispatch: NativeExecutionDispatch + 'static,663{664	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(665		parachain_config,666		polkadot_config,667		collator_options,668		id,669		parachain_build_import_queue,670		|client,671		 prometheus_registry,672		 telemetry,673		 task_manager,674		 relay_chain_interface,675		 transaction_pool,676		 sync_oracle,677		 keystore,678		 force_authoring| {679			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;680681			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(682				task_manager.spawn_handle(),683				client.clone(),684				transaction_pool,685				prometheus_registry,686				telemetry.clone(),687			);688689			Ok(AuraConsensus::build::<690				sp_consensus_aura::sr25519::AuthorityPair,691				_,692				_,693				_,694				_,695				_,696				_,697			>(BuildAuraConsensusParams {698				proposer_factory,699				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {700					let relay_chain_interface = relay_chain_interface.clone();701					async move {702						let parachain_inherent =703						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(704							relay_parent,705							&relay_chain_interface,706							&validation_data,707							id,708						).await;709710						let time = sp_timestamp::InherentDataProvider::from_system_time();711712						let slot =713						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(714							*time,715							slot_duration,716						);717718						let parachain_inherent = parachain_inherent.ok_or_else(|| {719							Box::<dyn std::error::Error + Send + Sync>::from(720								"Failed to create parachain inherent",721							)722						})?;723						Ok((time, slot, parachain_inherent))724					}725				},726				block_import: client.clone(),727				para_client: client,728				backoff_authoring_blocks: Option::<()>::None,729				sync_oracle,730				keystore,731				force_authoring,732				slot_duration,733				// We got around 500ms for proposing734				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),735				telemetry,736				max_block_proposal_slot_portion: None,737			}))738		},739	)740	.await741}742743fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(744	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,745	config: &Configuration,746	_: Option<TelemetryHandle>,747	task_manager: &TaskManager,748) -> Result<749	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,750	sc_service::Error,751>752where753	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>754		+ Send755		+ Sync756		+ 'static,757	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>758		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,759	ExecutorDispatch: NativeExecutionDispatch + 'static,760{761	Ok(sc_consensus_manual_seal::import_queue(762		Box::new(client.clone()),763		&task_manager.spawn_essential_handle(),764		config.prometheus_registry(),765	))766}767768/// Builds a new development service. This service uses instant seal, and mocks769/// the parachain inherent770pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(771	config: Configuration,772	autoseal_interval: Duration,773) -> sc_service::error::Result<TaskManager>774where775	Runtime: RuntimeInstance + Send + Sync + 'static,776	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,777	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,778	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>779		+ Send780		+ Sync781		+ 'static,782	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>783		+ fp_rpc::EthereumRuntimeRPCApi<Block>784		+ fp_rpc::ConvertTransactionRuntimeApi<Block>785		+ sp_session::SessionKeys<Block>786		+ sp_block_builder::BlockBuilder<Block>787		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>788		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>789		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>790		+ rmrk_rpc::RmrkApi<791			Block,792			AccountId,793			RmrkCollectionInfo<AccountId>,794			RmrkInstanceInfo<AccountId>,795			RmrkResourceInfo,796			RmrkPropertyInfo,797			RmrkBaseInfo<AccountId>,798			RmrkPartType,799			RmrkTheme,800		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>801		+ sp_api::Metadata<Block>802		+ sp_offchain::OffchainWorkerApi<Block>803		+ cumulus_primitives_core::CollectCollationInfo<Block>804		+ sp_consensus_aura::AuraApi<Block, AuraId>,805	ExecutorDispatch: NativeExecutionDispatch + 'static,806{807	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};808	use fc_consensus::FrontierBlockImport;809	use sc_client_api::HeaderBackend;810811	let sc_service::PartialComponents {812		client,813		backend,814		mut task_manager,815		import_queue,816		keystore_container,817		select_chain: maybe_select_chain,818		transaction_pool,819		other:820			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),821	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(822		&config,823		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,824	)?;825826	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(827		task_manager.spawn_handle(),828		overrides_handle::<_, _, Runtime>(client.clone()),829		50,830		50,831	));832833	let (network, system_rpc_tx, network_starter) =834		sc_service::build_network(sc_service::BuildNetworkParams {835			config: &config,836			client: client.clone(),837			transaction_pool: transaction_pool.clone(),838			spawn_handle: task_manager.spawn_handle(),839			import_queue,840			block_announce_validator_builder: None,841			warp_sync: None,842		})?;843844	if config.offchain_worker.enabled {845		sc_service::build_offchain_workers(846			&config,847			task_manager.spawn_handle(),848			client.clone(),849			network.clone(),850		);851	}852853	let prometheus_registry = config.prometheus_registry().cloned();854	let collator = config.role.is_authority();855856	let select_chain = maybe_select_chain.clone();857858	if collator {859		let block_import =860			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());861862		let env = sc_basic_authorship::ProposerFactory::new(863			task_manager.spawn_handle(),864			client.clone(),865			transaction_pool.clone(),866			prometheus_registry.as_ref(),867			telemetry.as_ref().map(|x| x.handle()),868		);869870		let transactions_commands_stream: Box<871			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,872		> = Box::new(873			transaction_pool874				.pool()875				.validated_pool()876				.import_notification_stream()877				.map(|_| EngineCommand::SealNewBlock {878					create_empty: true,879					finalize: false,880					parent_hash: None,881					sender: None,882				}),883		);884885		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));886		let idle_commands_stream: Box<887			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,888		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {889			create_empty: true,890			finalize: false,891			parent_hash: None,892			sender: None,893		}));894895		let commands_stream = select(transactions_commands_stream, idle_commands_stream);896897		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;898		let client_set_aside_for_cidp = client.clone();899900		task_manager.spawn_essential_handle().spawn_blocking(901			"authorship_task",902			Some("block-authoring"),903			run_manual_seal(ManualSealParams {904				block_import,905				env,906				client: client.clone(),907				pool: transaction_pool.clone(),908				commands_stream,909				select_chain: select_chain.clone(),910				consensus_data_provider: None,911				create_inherent_data_providers: move |block: Hash, ()| {912					let current_para_block = client_set_aside_for_cidp913						.number(block)914						.expect("Header lookup should succeed")915						.expect("Header passed in as parent should be present in backend.");916917					let client_for_xcm = client_set_aside_for_cidp.clone();918					async move {919						let time = sp_timestamp::InherentDataProvider::from_system_time();920921						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {922							current_para_block,923							relay_offset: 1000,924							relay_blocks_per_para_block: 2,925							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(926								&*client_for_xcm,927								block,928								Default::default(),929								Default::default(),930							),931							raw_downward_messages: vec![],932							raw_horizontal_messages: vec![],933						};934935						let slot =936						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(937							*time,938							slot_duration,939						);940941						Ok((time, slot, mocked_parachain))942					}943				},944			}),945		);946	}947948	task_manager.spawn_essential_handle().spawn(949		"frontier-mapping-sync-worker",950		Some("block-authoring"),951		MappingSyncWorker::new(952			client.import_notification_stream(),953			Duration::new(6, 0),954			client.clone(),955			backend.clone(),956			frontier_backend.clone(),957			3,958			0,959			SyncStrategy::Normal,960		)961		.for_each(|()| futures::future::ready(())),962	);963964	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());965	let rpc_client = client.clone();966	let rpc_pool = transaction_pool.clone();967	let rpc_network = network.clone();968	let rpc_frontier_backend = frontier_backend.clone();969	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {970		let full_deps = unique_rpc::FullDeps {971			backend: rpc_frontier_backend.clone(),972			deny_unsafe,973			client: rpc_client.clone(),974			pool: rpc_pool.clone(),975			graph: rpc_pool.pool().clone(),976			// TODO: Unhardcode977			enable_dev_signer: false,978			filter_pool: filter_pool.clone(),979			network: rpc_network.clone(),980			select_chain: select_chain.clone(),981			is_authority: collator,982			// TODO: Unhardcode983			max_past_logs: 10000,984			block_data_cache: block_data_cache.clone(),985			fee_history_cache: fee_history_cache.clone(),986			// TODO: Unhardcode987			fee_history_limit: 2048,988		};989990		Ok(991			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(992				full_deps,993				subscription_executor.clone(),994			),995		)996	});997998	sc_service::spawn_tasks(sc_service::SpawnTasksParams {999		network,1000		client,1001		keystore: keystore_container.sync_keystore(),1002		task_manager: &mut task_manager,1003		transaction_pool,1004		rpc_extensions_builder,1005		backend,1006		system_rpc_tx,1007		config,1008		telemetry: None,1009	})?;10101011	network_starter.start_network();1012	Ok(task_manager)1013}