git.delta.rocks / unique-network / refs/commits / b8d2ab11972c

difftreelog

source

node/cli/src/service.rs29.3 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/// Unique native executor instance.71#[cfg(feature = "unique-runtime")]72pub struct UniqueRuntimeExecutor;7374#[cfg(feature = "quartz-runtime")]75/// Quartz native executor instance.7677pub struct QuartzRuntimeExecutor;7879/// Opal native executor instance.80pub struct OpalRuntimeExecutor;8182#[cfg(feature = "unique-runtime")]83impl NativeExecutionDispatch for UniqueRuntimeExecutor {84	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8586	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {87		unique_runtime::api::dispatch(method, data)88	}8990	fn native_version() -> sc_executor::NativeVersion {91		unique_runtime::native_version()92	}93}9495#[cfg(feature = "quartz-runtime")]96impl NativeExecutionDispatch for QuartzRuntimeExecutor {97	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9899	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {100		quartz_runtime::api::dispatch(method, data)101	}102103	fn native_version() -> sc_executor::NativeVersion {104		quartz_runtime::native_version()105	}106}107108impl NativeExecutionDispatch for OpalRuntimeExecutor {109	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;110111	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112		opal_runtime::api::dispatch(method, data)113	}114115	fn native_version() -> sc_executor::NativeVersion {116		opal_runtime::native_version()117	}118}119120pub struct AutosealInterval {121	interval: Interval,122}123124impl AutosealInterval {125	pub fn new(config: &Configuration, interval: Duration) -> Self {126		let _tokio_runtime = config.tokio_handle.enter();127		let interval = tokio::time::interval(interval);128129		Self { interval }130	}131}132133impl Stream for AutosealInterval {134	type Item = tokio::time::Instant;135136	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {137		self.interval.poll_tick(cx).map(Some)138	}139}140141pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {142	let config_dir = config143		.base_path144		.as_ref()145		.map(|base_path| base_path.config_dir(config.chain_spec.id()))146		.unwrap_or_else(|| {147			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())148		});149	let database_dir = config_dir.join("frontier").join("db");150151	Ok(Arc::new(fc_db::Backend::<Block>::new(152		&fc_db::DatabaseSettings {153			source: fc_db::DatabaseSettingsSrc::RocksDb {154				path: database_dir,155				cache_size: 0,156			},157		},158	)?))159}160161type FullClient<RuntimeApi, ExecutorDispatch> =162	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;163type FullBackend = sc_service::TFullBackend<Block>;164type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;165166/// Starts a `ServiceBuilder` for a full service.167///168/// Use this macro if you don't actually need the full service, but just the builder in order to169/// be able to perform chain operations.170#[allow(clippy::type_complexity)]171pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(172	config: &Configuration,173	build_import_queue: BIQ,174) -> Result<175	PartialComponents<176		FullClient<RuntimeApi, ExecutorDispatch>,177		FullBackend,178		FullSelectChain,179		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,180		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,181		(182			Option<Telemetry>,183			Option<FilterPool>,184			Arc<fc_db::Backend<Block>>,185			Option<TelemetryWorkerHandle>,186			FeeHistoryCache,187		),188	>,189	sc_service::Error,190>191where192	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,193	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>194		+ Send195		+ Sync196		+ 'static,197	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,198	ExecutorDispatch: NativeExecutionDispatch + 'static,199	BIQ: FnOnce(200		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,201		&Configuration,202		Option<TelemetryHandle>,203		&TaskManager,204	) -> Result<205		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,206		sc_service::Error,207	>,208{209	let _telemetry = config210		.telemetry_endpoints211		.clone()212		.filter(|x| !x.is_empty())213		.map(|endpoints| -> Result<_, sc_telemetry::Error> {214			let worker = TelemetryWorker::new(16)?;215			let telemetry = worker.handle().new_telemetry(endpoints);216			Ok((worker, telemetry))217		})218		.transpose()?;219220	let telemetry = config221		.telemetry_endpoints222		.clone()223		.filter(|x| !x.is_empty())224		.map(|endpoints| -> Result<_, sc_telemetry::Error> {225			let worker = TelemetryWorker::new(16)?;226			let telemetry = worker.handle().new_telemetry(endpoints);227			Ok((worker, telemetry))228		})229		.transpose()?;230231	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(232		config.wasm_method,233		config.default_heap_pages,234		config.max_runtime_instances,235		config.runtime_cache_size,236	);237238	let (client, backend, keystore_container, task_manager) =239		sc_service::new_full_parts::<Block, RuntimeApi, _>(240			config,241			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),242			executor,243		)?;244	let client = Arc::new(client);245246	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());247248	let telemetry = telemetry.map(|(worker, telemetry)| {249		task_manager250			.spawn_handle()251			.spawn("telemetry", None, worker.run());252		telemetry253	});254255	let select_chain = sc_consensus::LongestChain::new(backend.clone());256257	let transaction_pool = sc_transaction_pool::BasicPool::new_full(258		config.transaction_pool.clone(),259		config.role.is_authority().into(),260		config.prometheus_registry(),261		task_manager.spawn_essential_handle(),262		client.clone(),263	);264265	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));266267	let frontier_backend = open_frontier_backend(config)?;268269	let import_queue = build_import_queue(270		client.clone(),271		config,272		telemetry.as_ref().map(|telemetry| telemetry.handle()),273		&task_manager,274	)?;275	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));276277	let params = PartialComponents {278		backend,279		client,280		import_queue,281		keystore_container,282		task_manager,283		transaction_pool,284		select_chain,285		other: (286			telemetry,287			filter_pool,288			frontier_backend,289			telemetry_worker_handle,290			fee_history_cache,291		),292	};293294	Ok(params)295}296297async fn build_relay_chain_interface(298	polkadot_config: Configuration,299	parachain_config: &Configuration,300	telemetry_worker_handle: Option<TelemetryWorkerHandle>,301	task_manager: &mut TaskManager,302	collator_options: CollatorOptions,303) -> RelayChainResult<(304	Arc<(dyn RelayChainInterface + 'static)>,305	Option<CollatorPair>,306)> {307	match collator_options.relay_chain_rpc_url {308		Some(relay_chain_url) => Ok((309			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,310			None,311		)),312		None => build_inprocess_relay_chain(313			polkadot_config,314			parachain_config,315			telemetry_worker_handle,316			task_manager,317		),318	}319}320321/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.322///323/// This is the actual implementation that is abstract over the executor and the runtime api.324#[sc_tracing::logging::prefix_logs_with("Parachain")]325async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(326	parachain_config: Configuration,327	polkadot_config: Configuration,328	collator_options: CollatorOptions,329	id: ParaId,330	build_import_queue: BIQ,331	build_consensus: BIC,332) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>333where334	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,335	Runtime: RuntimeInstance + Send + Sync + 'static,336	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,337	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,338	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>339		+ Send340		+ Sync341		+ 'static,342	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>343		+ fp_rpc::EthereumRuntimeRPCApi<Block>344		+ fp_rpc::ConvertTransactionRuntimeApi<Block>345		+ sp_session::SessionKeys<Block>346		+ sp_block_builder::BlockBuilder<Block>347		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>348		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>349		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>350		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>351		+ sp_api::Metadata<Block>352		+ sp_offchain::OffchainWorkerApi<Block>353		+ cumulus_primitives_core::CollectCollationInfo<Block>,354	ExecutorDispatch: NativeExecutionDispatch + 'static,355	BIQ: FnOnce(356		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,357		&Configuration,358		Option<TelemetryHandle>,359		&TaskManager,360	) -> Result<361		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,362		sc_service::Error,363	>,364	BIC: FnOnce(365		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,366		Option<&Registry>,367		Option<TelemetryHandle>,368		&TaskManager,369		Arc<dyn RelayChainInterface>,370		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,371		Arc<NetworkService<Block, Hash>>,372		SyncCryptoStorePtr,373		bool,374	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,375{376	if matches!(parachain_config.role, Role::Light) {377		return Err("Light client not supported!".into());378	}379380	let parachain_config = prepare_node_config(parachain_config);381382	let params =383		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;384	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =385		params.other;386387	let client = params.client.clone();388	let backend = params.backend.clone();389	let mut task_manager = params.task_manager;390391	let (relay_chain_interface, collator_key) = build_relay_chain_interface(392		polkadot_config,393		&parachain_config,394		telemetry_worker_handle,395		&mut task_manager,396		collator_options.clone(),397	)398	.await399	.map_err(|e| match e {400		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,401		s => s.to_string().into(),402	})?;403404	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);405406	let force_authoring = parachain_config.force_authoring;407	let validator = parachain_config.role.is_authority();408	let prometheus_registry = parachain_config.prometheus_registry().cloned();409	let transaction_pool = params.transaction_pool.clone();410	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);411412	let (network, system_rpc_tx, start_network) =413		sc_service::build_network(sc_service::BuildNetworkParams {414			config: &parachain_config,415			client: client.clone(),416			transaction_pool: transaction_pool.clone(),417			spawn_handle: task_manager.spawn_handle(),418			import_queue: import_queue.clone(),419			block_announce_validator_builder: Some(Box::new(|_| {420				Box::new(block_announce_validator)421			})),422			warp_sync: None,423		})?;424425	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());426	let rpc_client = client.clone();427	let rpc_pool = transaction_pool.clone();428	let select_chain = params.select_chain.clone();429	let rpc_network = network.clone();430431	let rpc_frontier_backend = frontier_backend.clone();432433	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(434		task_manager.spawn_handle(),435		overrides_handle::<_, _, Runtime>(client.clone()),436		50,437		50,438	));439440	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {441		let full_deps = unique_rpc::FullDeps {442			backend: rpc_frontier_backend.clone(),443			deny_unsafe,444			client: rpc_client.clone(),445			pool: rpc_pool.clone(),446			graph: rpc_pool.pool().clone(),447			// TODO: Unhardcode448			enable_dev_signer: false,449			filter_pool: filter_pool.clone(),450			network: rpc_network.clone(),451			select_chain: select_chain.clone(),452			is_authority: validator,453			// TODO: Unhardcode454			max_past_logs: 10000,455			block_data_cache: block_data_cache.clone(),456			fee_history_cache: fee_history_cache.clone(),457			// TODO: Unhardcode458			fee_history_limit: 2048,459		};460461		Ok(462			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(463				full_deps,464				subscription_executor.clone(),465			),466		)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	sc_service::spawn_tasks(sc_service::SpawnTasksParams {486		rpc_extensions_builder,487		client: client.clone(),488		transaction_pool: transaction_pool.clone(),489		task_manager: &mut task_manager,490		config: parachain_config,491		keystore: params.keystore_container.sync_keystore(),492		backend: backend.clone(),493		network: network.clone(),494		system_rpc_tx,495		telemetry: telemetry.as_mut(),496	})?;497498	let announce_block = {499		let network = network.clone();500		Arc::new(move |hash, data| network.announce_block(hash, data))501	};502503	let relay_chain_slot_duration = Duration::from_secs(6);504505	if validator {506		let parachain_consensus = build_consensus(507			client.clone(),508			prometheus_registry.as_ref(),509			telemetry.as_ref().map(|t| t.handle()),510			&task_manager,511			relay_chain_interface.clone(),512			transaction_pool,513			network,514			params.keystore_container.sync_keystore(),515			force_authoring,516		)?;517518		let spawner = task_manager.spawn_handle();519520		let params = StartCollatorParams {521			para_id: id,522			block_status: client.clone(),523			announce_block,524			client: client.clone(),525			task_manager: &mut task_manager,526			spawner,527			parachain_consensus,528			import_queue,529			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),530			relay_chain_interface,531			relay_chain_slot_duration,532		};533534		start_collator(params).await?;535	} else {536		let params = StartFullNodeParams {537			client: client.clone(),538			announce_block,539			task_manager: &mut task_manager,540			para_id: id,541			import_queue,542			relay_chain_interface,543			relay_chain_slot_duration,544			collator_options,545		};546547		start_full_node(params)?;548	}549550	start_network.start_network();551552	Ok((task_manager, client))553}554555/// Build the import queue for the the parachain runtime.556pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(557	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,558	config: &Configuration,559	telemetry: Option<TelemetryHandle>,560	task_manager: &TaskManager,561) -> Result<562	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,563	sc_service::Error,564>565where566	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>567		+ Send568		+ Sync569		+ 'static,570	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>571		+ sp_block_builder::BlockBuilder<Block>572		+ sp_consensus_aura::AuraApi<Block, AuraId>573		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,574	ExecutorDispatch: NativeExecutionDispatch + 'static,575{576	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;577578	cumulus_client_consensus_aura::import_queue::<579		sp_consensus_aura::sr25519::AuthorityPair,580		_,581		_,582		_,583		_,584		_,585		_,586	>(cumulus_client_consensus_aura::ImportQueueParams {587		block_import: client.clone(),588		client: client.clone(),589		create_inherent_data_providers: move |_, _| async move {590			let time = sp_timestamp::InherentDataProvider::from_system_time();591592			let slot =593				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(594					*time,595					slot_duration,596				);597598			Ok((time, slot))599		},600		registry: config.prometheus_registry(),601		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),602		spawner: &task_manager.spawn_essential_handle(),603		telemetry,604	})605	.map_err(Into::into)606}607608/// Start a normal parachain node.609pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(610	parachain_config: Configuration,611	polkadot_config: Configuration,612	collator_options: CollatorOptions,613	id: ParaId,614) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>615where616	Runtime: RuntimeInstance + Send + Sync + 'static,617	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,618	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,619	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>620		+ Send621		+ Sync622		+ 'static,623	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>624		+ fp_rpc::EthereumRuntimeRPCApi<Block>625		+ fp_rpc::ConvertTransactionRuntimeApi<Block>626		+ sp_session::SessionKeys<Block>627		+ sp_block_builder::BlockBuilder<Block>628		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>629		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>630		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>631		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>632		+ sp_api::Metadata<Block>633		+ sp_offchain::OffchainWorkerApi<Block>634		+ cumulus_primitives_core::CollectCollationInfo<Block>635		+ sp_consensus_aura::AuraApi<Block, AuraId>,636	ExecutorDispatch: NativeExecutionDispatch + 'static,637{638	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(639		parachain_config,640		polkadot_config,641		collator_options,642		id,643		parachain_build_import_queue,644		|client,645		 prometheus_registry,646		 telemetry,647		 task_manager,648		 relay_chain_interface,649		 transaction_pool,650		 sync_oracle,651		 keystore,652		 force_authoring| {653			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;654655			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(656				task_manager.spawn_handle(),657				client.clone(),658				transaction_pool,659				prometheus_registry,660				telemetry.clone(),661			);662663			Ok(AuraConsensus::build::<664				sp_consensus_aura::sr25519::AuthorityPair,665				_,666				_,667				_,668				_,669				_,670				_,671			>(BuildAuraConsensusParams {672				proposer_factory,673				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {674					let relay_chain_interface = relay_chain_interface.clone();675					async move {676						let parachain_inherent =677						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(678							relay_parent,679							&relay_chain_interface,680							&validation_data,681							id,682						).await;683684						let time = sp_timestamp::InherentDataProvider::from_system_time();685686						let slot =687						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(688							*time,689							slot_duration,690						);691692						let parachain_inherent = parachain_inherent.ok_or_else(|| {693							Box::<dyn std::error::Error + Send + Sync>::from(694								"Failed to create parachain inherent",695							)696						})?;697						Ok((time, slot, parachain_inherent))698					}699				},700				block_import: client.clone(),701				para_client: client,702				backoff_authoring_blocks: Option::<()>::None,703				sync_oracle,704				keystore,705				force_authoring,706				slot_duration,707				// We got around 500ms for proposing708				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),709				telemetry,710				max_block_proposal_slot_portion: None,711			}))712		},713	)714	.await715}716717fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(718	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,719	config: &Configuration,720	_: Option<TelemetryHandle>,721	task_manager: &TaskManager,722) -> Result<723	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,724	sc_service::Error,725>726where727	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>728		+ Send729		+ Sync730		+ 'static,731	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>732		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,733	ExecutorDispatch: NativeExecutionDispatch + 'static,734{735	Ok(sc_consensus_manual_seal::import_queue(736		Box::new(client.clone()),737		&task_manager.spawn_essential_handle(),738		config.prometheus_registry(),739	))740}741742/// Builds a new development service. This service uses instant seal, and mocks743/// the parachain inherent744pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(745	config: Configuration,746	autoseal_interval: Duration,747) -> sc_service::error::Result<TaskManager>748where749	Runtime: RuntimeInstance + Send + Sync + 'static,750	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,751	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,752	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>753		+ Send754		+ Sync755		+ 'static,756	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>757		+ fp_rpc::EthereumRuntimeRPCApi<Block>758		+ fp_rpc::ConvertTransactionRuntimeApi<Block>759		+ sp_session::SessionKeys<Block>760		+ sp_block_builder::BlockBuilder<Block>761		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>762		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>763		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>764		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>765		+ sp_api::Metadata<Block>766		+ sp_offchain::OffchainWorkerApi<Block>767		+ cumulus_primitives_core::CollectCollationInfo<Block>768		+ sp_consensus_aura::AuraApi<Block, AuraId>,769	ExecutorDispatch: NativeExecutionDispatch + 'static,770{771	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};772	use fc_consensus::FrontierBlockImport;773	use sc_client_api::HeaderBackend;774775	let sc_service::PartialComponents {776		client,777		backend,778		mut task_manager,779		import_queue,780		keystore_container,781		select_chain: maybe_select_chain,782		transaction_pool,783		other:784			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),785	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(786		&config,787		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,788	)?;789790	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(791		task_manager.spawn_handle(),792		overrides_handle::<_, _, Runtime>(client.clone()),793		50,794		50,795	));796797	let (network, system_rpc_tx, network_starter) =798		sc_service::build_network(sc_service::BuildNetworkParams {799			config: &config,800			client: client.clone(),801			transaction_pool: transaction_pool.clone(),802			spawn_handle: task_manager.spawn_handle(),803			import_queue,804			block_announce_validator_builder: None,805			warp_sync: None,806		})?;807808	if config.offchain_worker.enabled {809		sc_service::build_offchain_workers(810			&config,811			task_manager.spawn_handle(),812			client.clone(),813			network.clone(),814		);815	}816817	let prometheus_registry = config.prometheus_registry().cloned();818	let collator = config.role.is_authority();819820	let select_chain = maybe_select_chain.clone();821822	if collator {823		let block_import =824			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());825826		let env = sc_basic_authorship::ProposerFactory::new(827			task_manager.spawn_handle(),828			client.clone(),829			transaction_pool.clone(),830			prometheus_registry.as_ref(),831			telemetry.as_ref().map(|x| x.handle()),832		);833834		let transactions_commands_stream: Box<835			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,836		> = Box::new(837			transaction_pool838				.pool()839				.validated_pool()840				.import_notification_stream()841				.map(|_| EngineCommand::SealNewBlock {842					create_empty: true,843					finalize: false,844					parent_hash: None,845					sender: None,846				}),847		);848849		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));850		let idle_commands_stream: Box<851			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,852		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {853			create_empty: true,854			finalize: false,855			parent_hash: None,856			sender: None,857		}));858859		let commands_stream = select(transactions_commands_stream, idle_commands_stream);860861		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;862		let client_set_aside_for_cidp = client.clone();863864		task_manager.spawn_essential_handle().spawn_blocking(865			"authorship_task",866			Some("block-authoring"),867			run_manual_seal(ManualSealParams {868				block_import,869				env,870				client: client.clone(),871				pool: transaction_pool.clone(),872				commands_stream,873				select_chain: select_chain.clone(),874				consensus_data_provider: None,875				create_inherent_data_providers: move |block: Hash, ()| {876					let current_para_block = client_set_aside_for_cidp877						.number(block)878						.expect("Header lookup should succeed")879						.expect("Header passed in as parent should be present in backend.");880881					let client_for_xcm = client_set_aside_for_cidp.clone();882					async move {883						let time = sp_timestamp::InherentDataProvider::from_system_time();884885						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {886							current_para_block,887							relay_offset: 1000,888							relay_blocks_per_para_block: 2,889							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(890								&*client_for_xcm,891								block,892								Default::default(),893								Default::default(),894							),895							raw_downward_messages: vec![],896							raw_horizontal_messages: vec![],897						};898899						let slot =900						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(901							*time,902							slot_duration,903						);904905						Ok((time, slot, mocked_parachain))906					}907				},908			}),909		);910	}911912	task_manager.spawn_essential_handle().spawn(913		"frontier-mapping-sync-worker",914		Some("block-authoring"),915		MappingSyncWorker::new(916			client.import_notification_stream(),917			Duration::new(6, 0),918			client.clone(),919			backend.clone(),920			frontier_backend.clone(),921			3,922			0,923			SyncStrategy::Normal,924		)925		.for_each(|()| futures::future::ready(())),926	);927928	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());929	let rpc_client = client.clone();930	let rpc_pool = transaction_pool.clone();931	let rpc_network = network.clone();932	let rpc_frontier_backend = frontier_backend.clone();933	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {934		let full_deps = unique_rpc::FullDeps {935			backend: rpc_frontier_backend.clone(),936			deny_unsafe,937			client: rpc_client.clone(),938			pool: rpc_pool.clone(),939			graph: rpc_pool.pool().clone(),940			// TODO: Unhardcode941			enable_dev_signer: false,942			filter_pool: filter_pool.clone(),943			network: rpc_network.clone(),944			select_chain: select_chain.clone(),945			is_authority: collator,946			// TODO: Unhardcode947			max_past_logs: 10000,948			block_data_cache: block_data_cache.clone(),949			fee_history_cache: fee_history_cache.clone(),950			// TODO: Unhardcode951			fee_history_limit: 2048,952		};953954		Ok(955			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(956				full_deps,957				subscription_executor.clone(),958			),959		)960	});961962	sc_service::spawn_tasks(sc_service::SpawnTasksParams {963		network,964		client,965		keystore: keystore_container.sync_keystore(),966		task_manager: &mut task_manager,967		transaction_pool,968		rpc_extensions_builder,969		backend,970		system_rpc_tx,971		config,972		telemetry: None,973	})?;974975	network_starter.start_network();976	Ok(task_manager)977}