git.delta.rocks / unique-network / refs/commits / 5b25acafc6fa

difftreelog

source

node/cli/src/service.rs29.0 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// std18use std::sync::Arc;19use std::sync::Mutex;20use std::collections::BTreeMap;21use std::time::Duration;22use std::pin::Pin;23use fc_rpc_core::types::FeeHistoryCache;24use futures::{25	Stream, StreamExt,26	stream::select,27	task::{Context, Poll},28};29use tokio::time::Interval;3031use unique_rpc::overrides_handle;3233use serde::{Serialize, Deserialize};3435// Cumulus Imports36use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};37use cumulus_client_consensus_common::ParachainConsensus;38use cumulus_client_service::{39	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,40};41use cumulus_client_cli::CollatorOptions;42use cumulus_client_network::BlockAnnounceValidator;43use cumulus_primitives_core::ParaId;44use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;45use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};46use cumulus_relay_chain_rpc_interface::RelayChainRPCInterface;4748// Substrate Imports49use sc_client_api::ExecutorProvider;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::NetworkService;53use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};54use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};55use sp_keystore::SyncCryptoStorePtr;56use sp_runtime::traits::BlakeTwo256;57use substrate_prometheus_endpoint::Registry;58use sc_client_api::BlockchainEvents;5960use polkadot_service::CollatorPair;6162// Frontier Imports63use fc_rpc_core::types::FilterPool;64use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6566use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};6768/// Unique native executor instance.69#[cfg(feature = "unique-runtime")]70pub struct UniqueRuntimeExecutor;7172#[cfg(feature = "quartz-runtime")]73/// Quartz native executor instance.7475pub struct QuartzRuntimeExecutor;7677/// Opal native executor instance.78pub struct OpalRuntimeExecutor;7980#[cfg(feature = "unique-runtime")]81impl NativeExecutionDispatch for UniqueRuntimeExecutor {82	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8384	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {85		unique_runtime::api::dispatch(method, data)86	}8788	fn native_version() -> sc_executor::NativeVersion {89		unique_runtime::native_version()90	}91}9293#[cfg(feature = "quartz-runtime")]94impl NativeExecutionDispatch for QuartzRuntimeExecutor {95	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9697	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {98		quartz_runtime::api::dispatch(method, data)99	}100101	fn native_version() -> sc_executor::NativeVersion {102		quartz_runtime::native_version()103	}104}105106impl NativeExecutionDispatch for OpalRuntimeExecutor {107	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;108109	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {110		opal_runtime::api::dispatch(method, data)111	}112113	fn native_version() -> sc_executor::NativeVersion {114		opal_runtime::native_version()115	}116}117118pub struct AutosealInterval {119	interval: Interval,120}121122impl AutosealInterval {123	pub fn new(config: &Configuration, interval: Duration) -> Self {124		let _tokio_runtime = config.tokio_handle.enter();125		let interval = tokio::time::interval(interval);126127		Self { interval }128	}129}130131impl Stream for AutosealInterval {132	type Item = tokio::time::Instant;133134	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {135		self.interval.poll_tick(cx).map(Some)136	}137}138139pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {140	let config_dir = config141		.base_path142		.as_ref()143		.map(|base_path| base_path.config_dir(config.chain_spec.id()))144		.unwrap_or_else(|| {145			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())146		});147	let database_dir = config_dir.join("frontier").join("db");148149	Ok(Arc::new(fc_db::Backend::<Block>::new(150		&fc_db::DatabaseSettings {151			source: fc_db::DatabaseSettingsSrc::RocksDb {152				path: database_dir,153				cache_size: 0,154			},155		},156	)?))157}158159type FullClient<RuntimeApi, ExecutorDispatch> =160	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;161type FullBackend = sc_service::TFullBackend<Block>;162type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;163164/// Starts a `ServiceBuilder` for a full service.165///166/// Use this macro if you don't actually need the full service, but just the builder in order to167/// be able to perform chain operations.168#[allow(clippy::type_complexity)]169pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(170	config: &Configuration,171	build_import_queue: BIQ,172) -> Result<173	PartialComponents<174		FullClient<RuntimeApi, ExecutorDispatch>,175		FullBackend,176		FullSelectChain,177		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,178		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,179		(180			Option<Telemetry>,181			Option<FilterPool>,182			Arc<fc_db::Backend<Block>>,183			Option<TelemetryWorkerHandle>,184			FeeHistoryCache,185		),186	>,187	sc_service::Error,188>189where190	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,191	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>192		+ Send193		+ Sync194		+ 'static,195	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,196	ExecutorDispatch: NativeExecutionDispatch + 'static,197	BIQ: FnOnce(198		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,199		&Configuration,200		Option<TelemetryHandle>,201		&TaskManager,202	) -> Result<203		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,204		sc_service::Error,205	>,206{207	let _telemetry = config208		.telemetry_endpoints209		.clone()210		.filter(|x| !x.is_empty())211		.map(|endpoints| -> Result<_, sc_telemetry::Error> {212			let worker = TelemetryWorker::new(16)?;213			let telemetry = worker.handle().new_telemetry(endpoints);214			Ok((worker, telemetry))215		})216		.transpose()?;217218	let telemetry = config219		.telemetry_endpoints220		.clone()221		.filter(|x| !x.is_empty())222		.map(|endpoints| -> Result<_, sc_telemetry::Error> {223			let worker = TelemetryWorker::new(16)?;224			let telemetry = worker.handle().new_telemetry(endpoints);225			Ok((worker, telemetry))226		})227		.transpose()?;228229	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(230		config.wasm_method,231		config.default_heap_pages,232		config.max_runtime_instances,233		config.runtime_cache_size,234	);235236	let (client, backend, keystore_container, task_manager) =237		sc_service::new_full_parts::<Block, RuntimeApi, _>(238			config,239			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),240			executor,241		)?;242	let client = Arc::new(client);243244	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());245246	let telemetry = telemetry.map(|(worker, telemetry)| {247		task_manager248			.spawn_handle()249			.spawn("telemetry", None, worker.run());250		telemetry251	});252253	let select_chain = sc_consensus::LongestChain::new(backend.clone());254255	let transaction_pool = sc_transaction_pool::BasicPool::new_full(256		config.transaction_pool.clone(),257		config.role.is_authority().into(),258		config.prometheus_registry(),259		task_manager.spawn_essential_handle(),260		client.clone(),261	);262263	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));264265	let frontier_backend = open_frontier_backend(config)?;266267	let import_queue = build_import_queue(268		client.clone(),269		config,270		telemetry.as_ref().map(|telemetry| telemetry.handle()),271		&task_manager,272	)?;273	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));274275	let params = PartialComponents {276		backend,277		client,278		import_queue,279		keystore_container,280		task_manager,281		transaction_pool,282		select_chain,283		other: (284			telemetry,285			filter_pool,286			frontier_backend,287			telemetry_worker_handle,288			fee_history_cache,289		),290	};291292	Ok(params)293}294295async fn build_relay_chain_interface(296	polkadot_config: Configuration,297	parachain_config: &Configuration,298	telemetry_worker_handle: Option<TelemetryWorkerHandle>,299	task_manager: &mut TaskManager,300	collator_options: CollatorOptions,301) -> RelayChainResult<(302	Arc<(dyn RelayChainInterface + 'static)>,303	Option<CollatorPair>,304)> {305	match collator_options.relay_chain_rpc_url {306		Some(relay_chain_url) => Ok((307			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,308			None,309		)),310		None => build_inprocess_relay_chain(311			polkadot_config,312			parachain_config,313			telemetry_worker_handle,314			task_manager,315		),316	}317}318319/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.320///321/// This is the actual implementation that is abstract over the executor and the runtime api.322#[sc_tracing::logging::prefix_logs_with("Parachain")]323async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(324	parachain_config: Configuration,325	polkadot_config: Configuration,326	collator_options: CollatorOptions,327	id: ParaId,328	build_import_queue: BIQ,329	build_consensus: BIC,330) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>331where332	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,333	Runtime: RuntimeInstance + Send + Sync + 'static,334	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,335	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,336	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>337		+ Send338		+ Sync339		+ 'static,340	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>341		+ fp_rpc::EthereumRuntimeRPCApi<Block>342		+ sp_session::SessionKeys<Block>343		+ sp_block_builder::BlockBuilder<Block>344		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>345		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>346		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>347		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>348		+ sp_api::Metadata<Block>349		+ sp_offchain::OffchainWorkerApi<Block>350		+ cumulus_primitives_core::CollectCollationInfo<Block>,351	ExecutorDispatch: NativeExecutionDispatch + 'static,352	BIQ: FnOnce(353		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,354		&Configuration,355		Option<TelemetryHandle>,356		&TaskManager,357	) -> Result<358		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,359		sc_service::Error,360	>,361	BIC: FnOnce(362		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,363		Option<&Registry>,364		Option<TelemetryHandle>,365		&TaskManager,366		Arc<dyn RelayChainInterface>,367		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,368		Arc<NetworkService<Block, Hash>>,369		SyncCryptoStorePtr,370		bool,371	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,372{373	if matches!(parachain_config.role, Role::Light) {374		return Err("Light client not supported!".into());375	}376377	let parachain_config = prepare_node_config(parachain_config);378379	let params =380		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;381	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =382		params.other;383384	let client = params.client.clone();385	let backend = params.backend.clone();386	let mut task_manager = params.task_manager;387388	let (relay_chain_interface, collator_key) = build_relay_chain_interface(389		polkadot_config,390		&parachain_config,391		telemetry_worker_handle,392		&mut task_manager,393		collator_options.clone(),394	)395	.await396	.map_err(|e| match e {397		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,398		s => s.to_string().into(),399	})?;400401	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);402403	let force_authoring = parachain_config.force_authoring;404	let validator = parachain_config.role.is_authority();405	let prometheus_registry = parachain_config.prometheus_registry().cloned();406	let transaction_pool = params.transaction_pool.clone();407	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);408409	let (network, system_rpc_tx, start_network) =410		sc_service::build_network(sc_service::BuildNetworkParams {411			config: &parachain_config,412			client: client.clone(),413			transaction_pool: transaction_pool.clone(),414			spawn_handle: task_manager.spawn_handle(),415			import_queue: import_queue.clone(),416			block_announce_validator_builder: Some(Box::new(|_| {417				Box::new(block_announce_validator)418			})),419			warp_sync: None,420		})?;421422	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());423	let rpc_client = client.clone();424	let rpc_pool = transaction_pool.clone();425	let select_chain = params.select_chain.clone();426	let rpc_network = network.clone();427428	let rpc_frontier_backend = frontier_backend.clone();429430	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(431		task_manager.spawn_handle(),432		overrides_handle::<_, _, Runtime>(client.clone()),433		50,434		50,435	));436437	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {438		let full_deps = unique_rpc::FullDeps {439			backend: rpc_frontier_backend.clone(),440			deny_unsafe,441			client: rpc_client.clone(),442			pool: rpc_pool.clone(),443			graph: rpc_pool.pool().clone(),444			// TODO: Unhardcode445			enable_dev_signer: false,446			filter_pool: filter_pool.clone(),447			network: rpc_network.clone(),448			select_chain: select_chain.clone(),449			is_authority: validator,450			// TODO: Unhardcode451			max_past_logs: 10000,452			block_data_cache: block_data_cache.clone(),453			fee_history_cache: fee_history_cache.clone(),454			// TODO: Unhardcode455			fee_history_limit: 2048,456		};457458		Ok(459			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(460				full_deps,461				subscription_executor.clone(),462			),463		)464	});465466	task_manager.spawn_essential_handle().spawn(467		"frontier-mapping-sync-worker",468		None,469		MappingSyncWorker::new(470			client.import_notification_stream(),471			Duration::new(6, 0),472			client.clone(),473			backend.clone(),474			frontier_backend.clone(),475			SyncStrategy::Normal,476		)477		.for_each(|()| futures::future::ready(())),478	);479480	sc_service::spawn_tasks(sc_service::SpawnTasksParams {481		rpc_extensions_builder,482		client: client.clone(),483		transaction_pool: transaction_pool.clone(),484		task_manager: &mut task_manager,485		config: parachain_config,486		keystore: params.keystore_container.sync_keystore(),487		backend: backend.clone(),488		network: network.clone(),489		system_rpc_tx,490		telemetry: telemetry.as_mut(),491	})?;492493	let announce_block = {494		let network = network.clone();495		Arc::new(move |hash, data| network.announce_block(hash, data))496	};497498	let relay_chain_slot_duration = Duration::from_secs(6);499500	if validator {501		let parachain_consensus = build_consensus(502			client.clone(),503			prometheus_registry.as_ref(),504			telemetry.as_ref().map(|t| t.handle()),505			&task_manager,506			relay_chain_interface.clone(),507			transaction_pool,508			network,509			params.keystore_container.sync_keystore(),510			force_authoring,511		)?;512513		let spawner = task_manager.spawn_handle();514515		let params = StartCollatorParams {516			para_id: id,517			block_status: client.clone(),518			announce_block,519			client: client.clone(),520			task_manager: &mut task_manager,521			spawner,522			parachain_consensus,523			import_queue,524			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),525			relay_chain_interface,526			relay_chain_slot_duration,527		};528529		start_collator(params).await?;530	} else {531		let params = StartFullNodeParams {532			client: client.clone(),533			announce_block,534			task_manager: &mut task_manager,535			para_id: id,536			import_queue,537			relay_chain_interface,538			relay_chain_slot_duration,539			collator_options,540		};541542		start_full_node(params)?;543	}544545	start_network.start_network();546547	Ok((task_manager, client))548}549550/// Build the import queue for the the parachain runtime.551pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(552	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,553	config: &Configuration,554	telemetry: Option<TelemetryHandle>,555	task_manager: &TaskManager,556) -> Result<557	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,558	sc_service::Error,559>560where561	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>562		+ Send563		+ Sync564		+ 'static,565	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>566		+ sp_block_builder::BlockBuilder<Block>567		+ sp_consensus_aura::AuraApi<Block, AuraId>568		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,569	ExecutorDispatch: NativeExecutionDispatch + 'static,570{571	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;572573	cumulus_client_consensus_aura::import_queue::<574		sp_consensus_aura::sr25519::AuthorityPair,575		_,576		_,577		_,578		_,579		_,580		_,581	>(cumulus_client_consensus_aura::ImportQueueParams {582		block_import: client.clone(),583		client: client.clone(),584		create_inherent_data_providers: move |_, _| async move {585			let time = sp_timestamp::InherentDataProvider::from_system_time();586587			let slot =588				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(589					*time,590					slot_duration,591				);592593			Ok((time, slot))594		},595		registry: config.prometheus_registry(),596		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),597		spawner: &task_manager.spawn_essential_handle(),598		telemetry,599	})600	.map_err(Into::into)601}602603/// Start a normal parachain node.604pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(605	parachain_config: Configuration,606	polkadot_config: Configuration,607	collator_options: CollatorOptions,608	id: ParaId,609) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>610where611	Runtime: RuntimeInstance + Send + Sync + 'static,612	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,613	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,614	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>615		+ Send616		+ Sync617		+ 'static,618	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>619		+ fp_rpc::EthereumRuntimeRPCApi<Block>620		+ sp_session::SessionKeys<Block>621		+ sp_block_builder::BlockBuilder<Block>622		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>623		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>624		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>625		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>626		+ sp_api::Metadata<Block>627		+ sp_offchain::OffchainWorkerApi<Block>628		+ cumulus_primitives_core::CollectCollationInfo<Block>629		+ sp_consensus_aura::AuraApi<Block, AuraId>,630	ExecutorDispatch: NativeExecutionDispatch + 'static,631{632	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(633		parachain_config,634		polkadot_config,635		collator_options,636		id,637		parachain_build_import_queue,638		|client,639		 prometheus_registry,640		 telemetry,641		 task_manager,642		 relay_chain_interface,643		 transaction_pool,644		 sync_oracle,645		 keystore,646		 force_authoring| {647			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;648649			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(650				task_manager.spawn_handle(),651				client.clone(),652				transaction_pool,653				prometheus_registry,654				telemetry.clone(),655			);656657			Ok(AuraConsensus::build::<658				sp_consensus_aura::sr25519::AuthorityPair,659				_,660				_,661				_,662				_,663				_,664				_,665			>(BuildAuraConsensusParams {666				proposer_factory,667				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {668					let relay_chain_interface = relay_chain_interface.clone();669					async move {670						let parachain_inherent =671						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(672							relay_parent,673							&relay_chain_interface,674							&validation_data,675							id,676						).await;677678						let time = sp_timestamp::InherentDataProvider::from_system_time();679680						let slot =681						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(682							*time,683							slot_duration,684						);685686						let parachain_inherent = parachain_inherent.ok_or_else(|| {687							Box::<dyn std::error::Error + Send + Sync>::from(688								"Failed to create parachain inherent",689							)690						})?;691						Ok((time, slot, parachain_inherent))692					}693				},694				block_import: client.clone(),695				para_client: client,696				backoff_authoring_blocks: Option::<()>::None,697				sync_oracle,698				keystore,699				force_authoring,700				slot_duration,701				// We got around 500ms for proposing702				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),703				telemetry,704				max_block_proposal_slot_portion: None,705			}))706		},707	)708	.await709}710711fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(712	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,713	config: &Configuration,714	_: Option<TelemetryHandle>,715	task_manager: &TaskManager,716) -> Result<717	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,718	sc_service::Error,719>720where721	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>722		+ Send723		+ Sync724		+ 'static,725	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>726		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,727	ExecutorDispatch: NativeExecutionDispatch + 'static,728{729	Ok(sc_consensus_manual_seal::import_queue(730		Box::new(client.clone()),731		&task_manager.spawn_essential_handle(),732		config.prometheus_registry(),733	))734}735736/// Builds a new development service. This service uses instant seal, and mocks737/// the parachain inherent738pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(739	config: Configuration,740	autoseal_interval: Duration,741) -> sc_service::error::Result<TaskManager>742where743	Runtime: RuntimeInstance + Send + Sync + 'static,744	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,745	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,746	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>747		+ Send748		+ Sync749		+ 'static,750	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>751		+ fp_rpc::EthereumRuntimeRPCApi<Block>752		+ sp_session::SessionKeys<Block>753		+ sp_block_builder::BlockBuilder<Block>754		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>755		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>756		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>757		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>758		+ sp_api::Metadata<Block>759		+ sp_offchain::OffchainWorkerApi<Block>760		+ cumulus_primitives_core::CollectCollationInfo<Block>761		+ sp_consensus_aura::AuraApi<Block, AuraId>,762	ExecutorDispatch: NativeExecutionDispatch + 'static,763{764	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};765	use fc_consensus::FrontierBlockImport;766	use sc_client_api::HeaderBackend;767768	let sc_service::PartialComponents {769		client,770		backend,771		mut task_manager,772		import_queue,773		keystore_container,774		select_chain: maybe_select_chain,775		transaction_pool,776		other:777			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),778	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(779		&config,780		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,781	)?;782783	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(784		task_manager.spawn_handle(),785		overrides_handle::<_, _, Runtime>(client.clone()),786		50,787		50,788	));789790	let (network, system_rpc_tx, network_starter) =791		sc_service::build_network(sc_service::BuildNetworkParams {792			config: &config,793			client: client.clone(),794			transaction_pool: transaction_pool.clone(),795			spawn_handle: task_manager.spawn_handle(),796			import_queue,797			block_announce_validator_builder: None,798			warp_sync: None,799		})?;800801	if config.offchain_worker.enabled {802		sc_service::build_offchain_workers(803			&config,804			task_manager.spawn_handle(),805			client.clone(),806			network.clone(),807		);808	}809810	let prometheus_registry = config.prometheus_registry().cloned();811	let collator = config.role.is_authority();812813	let select_chain = maybe_select_chain.clone();814815	if collator {816		let block_import =817			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());818819		let env = sc_basic_authorship::ProposerFactory::new(820			task_manager.spawn_handle(),821			client.clone(),822			transaction_pool.clone(),823			prometheus_registry.as_ref(),824			telemetry.as_ref().map(|x| x.handle()),825		);826827		let transactions_commands_stream: Box<828			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,829		> = Box::new(830			transaction_pool831				.pool()832				.validated_pool()833				.import_notification_stream()834				.map(|_| EngineCommand::SealNewBlock {835					create_empty: true,836					finalize: false,837					parent_hash: None,838					sender: None,839				}),840		);841842		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));843		let idle_commands_stream: Box<844			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,845		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {846			create_empty: true,847			finalize: false,848			parent_hash: None,849			sender: None,850		}));851852		let commands_stream = select(transactions_commands_stream, idle_commands_stream);853854		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;855		let client_set_aside_for_cidp = client.clone();856857		task_manager.spawn_essential_handle().spawn_blocking(858			"authorship_task",859			Some("block-authoring"),860			run_manual_seal(ManualSealParams {861				block_import,862				env,863				client: client.clone(),864				pool: transaction_pool.clone(),865				commands_stream,866				select_chain: select_chain.clone(),867				consensus_data_provider: None,868				create_inherent_data_providers: move |block: Hash, ()| {869					let current_para_block = client_set_aside_for_cidp870						.number(block)871						.expect("Header lookup should succeed")872						.expect("Header passed in as parent should be present in backend.");873874					let client_for_xcm = client_set_aside_for_cidp.clone();875					async move {876						let time = sp_timestamp::InherentDataProvider::from_system_time();877878						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {879							current_para_block,880							relay_offset: 1000,881							relay_blocks_per_para_block: 2,882							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(883								&*client_for_xcm,884								block,885								Default::default(),886								Default::default(),887							),888							raw_downward_messages: vec![],889							raw_horizontal_messages: vec![],890						};891892						let slot =893						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(894							*time,895							slot_duration,896						);897898						Ok((time, slot, mocked_parachain))899					}900				},901			}),902		);903	}904905	task_manager.spawn_essential_handle().spawn(906		"frontier-mapping-sync-worker",907		Some("block-authoring"),908		MappingSyncWorker::new(909			client.import_notification_stream(),910			Duration::new(6, 0),911			client.clone(),912			backend.clone(),913			frontier_backend.clone(),914			SyncStrategy::Normal,915		)916		.for_each(|()| futures::future::ready(())),917	);918919	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());920	let rpc_client = client.clone();921	let rpc_pool = transaction_pool.clone();922	let rpc_network = network.clone();923	let rpc_frontier_backend = frontier_backend.clone();924	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {925		let full_deps = unique_rpc::FullDeps {926			backend: rpc_frontier_backend.clone(),927			deny_unsafe,928			client: rpc_client.clone(),929			pool: rpc_pool.clone(),930			graph: rpc_pool.pool().clone(),931			// TODO: Unhardcode932			enable_dev_signer: false,933			filter_pool: filter_pool.clone(),934			network: rpc_network.clone(),935			select_chain: select_chain.clone(),936			is_authority: collator,937			// TODO: Unhardcode938			max_past_logs: 10000,939			block_data_cache: block_data_cache.clone(),940			fee_history_cache: fee_history_cache.clone(),941			// TODO: Unhardcode942			fee_history_limit: 2048,943		};944945		Ok(946			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(947				full_deps,948				subscription_executor.clone(),949			),950		)951	});952953	sc_service::spawn_tasks(sc_service::SpawnTasksParams {954		network,955		client,956		keystore: keystore_container.sync_keystore(),957		task_manager: &mut task_manager,958		transaction_pool,959		rpc_extensions_builder,960		backend,961		system_rpc_tx,962		config,963		telemetry: None,964	})?;965966	network_starter.start_network();967	Ok(task_manager)968}