git.delta.rocks / unique-network / refs/commits / 9bbb15434bf2

difftreelog

source

node/cli/src/service.rs29.2 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// 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		+ fp_rpc::ConvertTransactionRuntimeApi<Block>343		+ sp_session::SessionKeys<Block>344		+ sp_block_builder::BlockBuilder<Block>345		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>346		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>347		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>348		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>349		+ sp_api::Metadata<Block>350		+ sp_offchain::OffchainWorkerApi<Block>351		+ cumulus_primitives_core::CollectCollationInfo<Block>,352	ExecutorDispatch: NativeExecutionDispatch + 'static,353	BIQ: FnOnce(354		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,355		&Configuration,356		Option<TelemetryHandle>,357		&TaskManager,358	) -> Result<359		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,360		sc_service::Error,361	>,362	BIC: FnOnce(363		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,364		Option<&Registry>,365		Option<TelemetryHandle>,366		&TaskManager,367		Arc<dyn RelayChainInterface>,368		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,369		Arc<NetworkService<Block, Hash>>,370		SyncCryptoStorePtr,371		bool,372	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,373{374	if matches!(parachain_config.role, Role::Light) {375		return Err("Light client not supported!".into());376	}377378	let parachain_config = prepare_node_config(parachain_config);379380	let params =381		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;382	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =383		params.other;384385	let client = params.client.clone();386	let backend = params.backend.clone();387	let mut task_manager = params.task_manager;388389	let (relay_chain_interface, collator_key) = build_relay_chain_interface(390		polkadot_config,391		&parachain_config,392		telemetry_worker_handle,393		&mut task_manager,394		collator_options.clone(),395	)396	.await397	.map_err(|e| match e {398		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,399		s => s.to_string().into(),400	})?;401402	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);403404	let force_authoring = parachain_config.force_authoring;405	let validator = parachain_config.role.is_authority();406	let prometheus_registry = parachain_config.prometheus_registry().cloned();407	let transaction_pool = params.transaction_pool.clone();408	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);409410	let (network, system_rpc_tx, start_network) =411		sc_service::build_network(sc_service::BuildNetworkParams {412			config: &parachain_config,413			client: client.clone(),414			transaction_pool: transaction_pool.clone(),415			spawn_handle: task_manager.spawn_handle(),416			import_queue: import_queue.clone(),417			block_announce_validator_builder: Some(Box::new(|_| {418				Box::new(block_announce_validator)419			})),420			warp_sync: None,421		})?;422423	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());424	let rpc_client = client.clone();425	let rpc_pool = transaction_pool.clone();426	let select_chain = params.select_chain.clone();427	let rpc_network = network.clone();428429	let rpc_frontier_backend = frontier_backend.clone();430431	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(432		task_manager.spawn_handle(),433		overrides_handle::<_, _, Runtime>(client.clone()),434		50,435		50,436	));437438	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {439		let full_deps = unique_rpc::FullDeps {440			backend: rpc_frontier_backend.clone(),441			deny_unsafe,442			client: rpc_client.clone(),443			pool: rpc_pool.clone(),444			graph: rpc_pool.pool().clone(),445			// TODO: Unhardcode446			enable_dev_signer: false,447			filter_pool: filter_pool.clone(),448			network: rpc_network.clone(),449			select_chain: select_chain.clone(),450			is_authority: validator,451			// TODO: Unhardcode452			max_past_logs: 10000,453			block_data_cache: block_data_cache.clone(),454			fee_history_cache: fee_history_cache.clone(),455			// TODO: Unhardcode456			fee_history_limit: 2048,457		};458459		Ok(460			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(461				full_deps,462				subscription_executor.clone(),463			),464		)465	});466467	task_manager.spawn_essential_handle().spawn(468		"frontier-mapping-sync-worker",469		None,470		MappingSyncWorker::new(471			client.import_notification_stream(),472			Duration::new(6, 0),473			client.clone(),474			backend.clone(),475			frontier_backend.clone(),476			3,477			0,478			SyncStrategy::Normal,479		)480		.for_each(|()| futures::future::ready(())),481	);482483	sc_service::spawn_tasks(sc_service::SpawnTasksParams {484		rpc_extensions_builder,485		client: client.clone(),486		transaction_pool: transaction_pool.clone(),487		task_manager: &mut task_manager,488		config: parachain_config,489		keystore: params.keystore_container.sync_keystore(),490		backend: backend.clone(),491		network: network.clone(),492		system_rpc_tx,493		telemetry: telemetry.as_mut(),494	})?;495496	let announce_block = {497		let network = network.clone();498		Arc::new(move |hash, data| network.announce_block(hash, data))499	};500501	let relay_chain_slot_duration = Duration::from_secs(6);502503	if validator {504		let parachain_consensus = build_consensus(505			client.clone(),506			prometheus_registry.as_ref(),507			telemetry.as_ref().map(|t| t.handle()),508			&task_manager,509			relay_chain_interface.clone(),510			transaction_pool,511			network,512			params.keystore_container.sync_keystore(),513			force_authoring,514		)?;515516		let spawner = task_manager.spawn_handle();517518		let params = StartCollatorParams {519			para_id: id,520			block_status: client.clone(),521			announce_block,522			client: client.clone(),523			task_manager: &mut task_manager,524			spawner,525			parachain_consensus,526			import_queue,527			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),528			relay_chain_interface,529			relay_chain_slot_duration,530		};531532		start_collator(params).await?;533	} else {534		let params = StartFullNodeParams {535			client: client.clone(),536			announce_block,537			task_manager: &mut task_manager,538			para_id: id,539			import_queue,540			relay_chain_interface,541			relay_chain_slot_duration,542			collator_options,543		};544545		start_full_node(params)?;546	}547548	start_network.start_network();549550	Ok((task_manager, client))551}552553/// Build the import queue for the the parachain runtime.554pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(555	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,556	config: &Configuration,557	telemetry: Option<TelemetryHandle>,558	task_manager: &TaskManager,559) -> Result<560	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,561	sc_service::Error,562>563where564	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>565		+ Send566		+ Sync567		+ 'static,568	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>569		+ sp_block_builder::BlockBuilder<Block>570		+ sp_consensus_aura::AuraApi<Block, AuraId>571		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,572	ExecutorDispatch: NativeExecutionDispatch + 'static,573{574	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;575576	cumulus_client_consensus_aura::import_queue::<577		sp_consensus_aura::sr25519::AuthorityPair,578		_,579		_,580		_,581		_,582		_,583		_,584	>(cumulus_client_consensus_aura::ImportQueueParams {585		block_import: client.clone(),586		client: client.clone(),587		create_inherent_data_providers: move |_, _| async move {588			let time = sp_timestamp::InherentDataProvider::from_system_time();589590			let slot =591				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(592					*time,593					slot_duration,594				);595596			Ok((time, slot))597		},598		registry: config.prometheus_registry(),599		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),600		spawner: &task_manager.spawn_essential_handle(),601		telemetry,602	})603	.map_err(Into::into)604}605606/// Start a normal parachain node.607pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(608	parachain_config: Configuration,609	polkadot_config: Configuration,610	collator_options: CollatorOptions,611	id: ParaId,612) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>613where614	Runtime: RuntimeInstance + Send + Sync + 'static,615	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,616	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,617	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>618		+ Send619		+ Sync620		+ 'static,621	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>622		+ fp_rpc::EthereumRuntimeRPCApi<Block>623		+ fp_rpc::ConvertTransactionRuntimeApi<Block>624		+ sp_session::SessionKeys<Block>625		+ sp_block_builder::BlockBuilder<Block>626		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>627		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>628		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>629		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>630		+ sp_api::Metadata<Block>631		+ sp_offchain::OffchainWorkerApi<Block>632		+ cumulus_primitives_core::CollectCollationInfo<Block>633		+ sp_consensus_aura::AuraApi<Block, AuraId>,634	ExecutorDispatch: NativeExecutionDispatch + 'static,635{636	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(637		parachain_config,638		polkadot_config,639		collator_options,640		id,641		parachain_build_import_queue,642		|client,643		 prometheus_registry,644		 telemetry,645		 task_manager,646		 relay_chain_interface,647		 transaction_pool,648		 sync_oracle,649		 keystore,650		 force_authoring| {651			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;652653			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(654				task_manager.spawn_handle(),655				client.clone(),656				transaction_pool,657				prometheus_registry,658				telemetry.clone(),659			);660661			Ok(AuraConsensus::build::<662				sp_consensus_aura::sr25519::AuthorityPair,663				_,664				_,665				_,666				_,667				_,668				_,669			>(BuildAuraConsensusParams {670				proposer_factory,671				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {672					let relay_chain_interface = relay_chain_interface.clone();673					async move {674						let parachain_inherent =675						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(676							relay_parent,677							&relay_chain_interface,678							&validation_data,679							id,680						).await;681682						let time = sp_timestamp::InherentDataProvider::from_system_time();683684						let slot =685						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(686							*time,687							slot_duration,688						);689690						let parachain_inherent = parachain_inherent.ok_or_else(|| {691							Box::<dyn std::error::Error + Send + Sync>::from(692								"Failed to create parachain inherent",693							)694						})?;695						Ok((time, slot, parachain_inherent))696					}697				},698				block_import: client.clone(),699				para_client: client,700				backoff_authoring_blocks: Option::<()>::None,701				sync_oracle,702				keystore,703				force_authoring,704				slot_duration,705				// We got around 500ms for proposing706				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),707				telemetry,708				max_block_proposal_slot_portion: None,709			}))710		},711	)712	.await713}714715fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(716	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,717	config: &Configuration,718	_: Option<TelemetryHandle>,719	task_manager: &TaskManager,720) -> Result<721	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,722	sc_service::Error,723>724where725	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>726		+ Send727		+ Sync728		+ 'static,729	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>730		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,731	ExecutorDispatch: NativeExecutionDispatch + 'static,732{733	Ok(sc_consensus_manual_seal::import_queue(734		Box::new(client.clone()),735		&task_manager.spawn_essential_handle(),736		config.prometheus_registry(),737	))738}739740/// Builds a new development service. This service uses instant seal, and mocks741/// the parachain inherent742pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(743	config: Configuration,744	autoseal_interval: Duration,745) -> sc_service::error::Result<TaskManager>746where747	Runtime: RuntimeInstance + Send + Sync + 'static,748	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,749	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,750	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>751		+ Send752		+ Sync753		+ 'static,754	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>755		+ fp_rpc::EthereumRuntimeRPCApi<Block>756		+ fp_rpc::ConvertTransactionRuntimeApi<Block>757		+ sp_session::SessionKeys<Block>758		+ sp_block_builder::BlockBuilder<Block>759		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>760		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>761		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>762		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>763		+ sp_api::Metadata<Block>764		+ sp_offchain::OffchainWorkerApi<Block>765		+ cumulus_primitives_core::CollectCollationInfo<Block>766		+ sp_consensus_aura::AuraApi<Block, AuraId>,767	ExecutorDispatch: NativeExecutionDispatch + 'static,768{769	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};770	use fc_consensus::FrontierBlockImport;771	use sc_client_api::HeaderBackend;772773	let sc_service::PartialComponents {774		client,775		backend,776		mut task_manager,777		import_queue,778		keystore_container,779		select_chain: maybe_select_chain,780		transaction_pool,781		other:782			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),783	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(784		&config,785		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,786	)?;787788	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(789		task_manager.spawn_handle(),790		overrides_handle::<_, _, Runtime>(client.clone()),791		50,792		50,793	));794795	let (network, system_rpc_tx, network_starter) =796		sc_service::build_network(sc_service::BuildNetworkParams {797			config: &config,798			client: client.clone(),799			transaction_pool: transaction_pool.clone(),800			spawn_handle: task_manager.spawn_handle(),801			import_queue,802			block_announce_validator_builder: None,803			warp_sync: None,804		})?;805806	if config.offchain_worker.enabled {807		sc_service::build_offchain_workers(808			&config,809			task_manager.spawn_handle(),810			client.clone(),811			network.clone(),812		);813	}814815	let prometheus_registry = config.prometheus_registry().cloned();816	let collator = config.role.is_authority();817818	let select_chain = maybe_select_chain.clone();819820	if collator {821		let block_import =822			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());823824		let env = sc_basic_authorship::ProposerFactory::new(825			task_manager.spawn_handle(),826			client.clone(),827			transaction_pool.clone(),828			prometheus_registry.as_ref(),829			telemetry.as_ref().map(|x| x.handle()),830		);831832		let transactions_commands_stream: Box<833			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,834		> = Box::new(835			transaction_pool836				.pool()837				.validated_pool()838				.import_notification_stream()839				.map(|_| EngineCommand::SealNewBlock {840					create_empty: true,841					finalize: false,842					parent_hash: None,843					sender: None,844				}),845		);846847		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));848		let idle_commands_stream: Box<849			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,850		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {851			create_empty: true,852			finalize: false,853			parent_hash: None,854			sender: None,855		}));856857		let commands_stream = select(transactions_commands_stream, idle_commands_stream);858859		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;860		let client_set_aside_for_cidp = client.clone();861862		task_manager.spawn_essential_handle().spawn_blocking(863			"authorship_task",864			Some("block-authoring"),865			run_manual_seal(ManualSealParams {866				block_import,867				env,868				client: client.clone(),869				pool: transaction_pool.clone(),870				commands_stream,871				select_chain: select_chain.clone(),872				consensus_data_provider: None,873				create_inherent_data_providers: move |block: Hash, ()| {874					let current_para_block = client_set_aside_for_cidp875						.number(block)876						.expect("Header lookup should succeed")877						.expect("Header passed in as parent should be present in backend.");878879					let client_for_xcm = client_set_aside_for_cidp.clone();880					async move {881						let time = sp_timestamp::InherentDataProvider::from_system_time();882883						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {884							current_para_block,885							relay_offset: 1000,886							relay_blocks_per_para_block: 2,887							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(888								&*client_for_xcm,889								block,890								Default::default(),891								Default::default(),892							),893							raw_downward_messages: vec![],894							raw_horizontal_messages: vec![],895						};896897						let slot =898						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(899							*time,900							slot_duration,901						);902903						Ok((time, slot, mocked_parachain))904					}905				},906			}),907		);908	}909910	task_manager.spawn_essential_handle().spawn(911		"frontier-mapping-sync-worker",912		Some("block-authoring"),913		MappingSyncWorker::new(914			client.import_notification_stream(),915			Duration::new(6, 0),916			client.clone(),917			backend.clone(),918			frontier_backend.clone(),919			3,920			0,921			SyncStrategy::Normal,922		)923		.for_each(|()| futures::future::ready(())),924	);925926	let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());927	let rpc_client = client.clone();928	let rpc_pool = transaction_pool.clone();929	let rpc_network = network.clone();930	let rpc_frontier_backend = frontier_backend.clone();931	let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {932		let full_deps = unique_rpc::FullDeps {933			backend: rpc_frontier_backend.clone(),934			deny_unsafe,935			client: rpc_client.clone(),936			pool: rpc_pool.clone(),937			graph: rpc_pool.pool().clone(),938			// TODO: Unhardcode939			enable_dev_signer: false,940			filter_pool: filter_pool.clone(),941			network: rpc_network.clone(),942			select_chain: select_chain.clone(),943			is_authority: collator,944			// TODO: Unhardcode945			max_past_logs: 10000,946			block_data_cache: block_data_cache.clone(),947			fee_history_cache: fee_history_cache.clone(),948			// TODO: Unhardcode949			fee_history_limit: 2048,950		};951952		Ok(953			unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(954				full_deps,955				subscription_executor.clone(),956			),957		)958	});959960	sc_service::spawn_tasks(sc_service::SpawnTasksParams {961		network,962		client,963		keystore: keystore_container.sync_keystore(),964		task_manager: &mut task_manager,965		transaction_pool,966		rpc_extensions_builder,967		backend,968		system_rpc_tx,969		config,970		telemetry: None,971	})?;972973	network_starter.start_network();974	Ok(task_manager)975}