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

difftreelog

source

node/cli/src/service.rs30.7 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, create_client_and_start_worker};4748// Substrate Imports49use sc_executor::NativeElseWasmExecutor;50use sc_executor::NativeExecutionDispatch;51use sc_network::{NetworkService, NetworkBlock};52use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};53use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};54use sp_keystore::SyncCryptoStorePtr;55use sp_runtime::traits::BlakeTwo256;56use substrate_prometheus_endpoint::Registry;57use sc_client_api::BlockchainEvents;5859use polkadot_service::CollatorPair;6061// Frontier Imports62use fc_rpc_core::types::FilterPool;63use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6465use up_common::types::opaque::{66	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,67};6869// RMRK70use up_data_structs::{71	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,72	RmrkPartType, RmrkTheme,73};7475/// Unique native executor instance.76#[cfg(feature = "unique-runtime")]77pub struct UniqueRuntimeExecutor;7879#[cfg(feature = "quartz-runtime")]80/// Quartz native executor instance.81pub struct QuartzRuntimeExecutor;8283/// Opal native executor instance.84pub struct OpalRuntimeExecutor;8586#[cfg(feature = "unique-runtime")]87impl NativeExecutionDispatch for UniqueRuntimeExecutor {88	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8990	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {91		unique_runtime::api::dispatch(method, data)92	}9394	fn native_version() -> sc_executor::NativeVersion {95		unique_runtime::native_version()96	}97}9899#[cfg(feature = "quartz-runtime")]100impl NativeExecutionDispatch for QuartzRuntimeExecutor {101	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;102103	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {104		quartz_runtime::api::dispatch(method, data)105	}106107	fn native_version() -> sc_executor::NativeVersion {108		quartz_runtime::native_version()109	}110}111112impl NativeExecutionDispatch for OpalRuntimeExecutor {113	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;114115	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {116		opal_runtime::api::dispatch(method, data)117	}118119	fn native_version() -> sc_executor::NativeVersion {120		opal_runtime::native_version()121	}122}123124pub struct AutosealInterval {125	interval: Interval,126}127128impl AutosealInterval {129	pub fn new(config: &Configuration, interval: Duration) -> Self {130		let _tokio_runtime = config.tokio_handle.enter();131		let interval = tokio::time::interval(interval);132133		Self { interval }134	}135}136137impl Stream for AutosealInterval {138	type Item = tokio::time::Instant;139140	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {141		self.interval.poll_tick(cx).map(Some)142	}143}144145pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {146	let config_dir = config147		.base_path148		.as_ref()149		.map(|base_path| base_path.config_dir(config.chain_spec.id()))150		.unwrap_or_else(|| {151			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())152		});153	let database_dir = config_dir.join("frontier").join("db");154155	Ok(Arc::new(fc_db::Backend::<Block>::new(156		&fc_db::DatabaseSettings {157			source: fc_db::DatabaseSource::RocksDb {158				path: database_dir,159				cache_size: 0,160			},161		},162	)?))163}164165type FullClient<RuntimeApi, ExecutorDispatch> =166	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;167type FullBackend = sc_service::TFullBackend<Block>;168type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;169170/// Starts a `ServiceBuilder` for a full service.171///172/// Use this macro if you don't actually need the full service, but just the builder in order to173/// be able to perform chain operations.174#[allow(clippy::type_complexity)]175pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(176	config: &Configuration,177	build_import_queue: BIQ,178) -> Result<179	PartialComponents<180		FullClient<RuntimeApi, ExecutorDispatch>,181		FullBackend,182		FullSelectChain,183		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,184		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,185		(186			Option<Telemetry>,187			Option<FilterPool>,188			Arc<fc_db::Backend<Block>>,189			Option<TelemetryWorkerHandle>,190			FeeHistoryCache,191		),192	>,193	sc_service::Error,194>195where196	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,197	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>198		+ Send199		+ Sync200		+ 'static,201	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,202	ExecutorDispatch: NativeExecutionDispatch + 'static,203	BIQ: FnOnce(204		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,205		&Configuration,206		Option<TelemetryHandle>,207		&TaskManager,208	) -> Result<209		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,210		sc_service::Error,211	>,212{213	let _telemetry = config214		.telemetry_endpoints215		.clone()216		.filter(|x| !x.is_empty())217		.map(|endpoints| -> Result<_, sc_telemetry::Error> {218			let worker = TelemetryWorker::new(16)?;219			let telemetry = worker.handle().new_telemetry(endpoints);220			Ok((worker, telemetry))221		})222		.transpose()?;223224	let telemetry = config225		.telemetry_endpoints226		.clone()227		.filter(|x| !x.is_empty())228		.map(|endpoints| -> Result<_, sc_telemetry::Error> {229			let worker = TelemetryWorker::new(16)?;230			let telemetry = worker.handle().new_telemetry(endpoints);231			Ok((worker, telemetry))232		})233		.transpose()?;234235	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(236		config.wasm_method,237		config.default_heap_pages,238		config.max_runtime_instances,239		config.runtime_cache_size,240	);241242	let (client, backend, keystore_container, task_manager) =243		sc_service::new_full_parts::<Block, RuntimeApi, _>(244			config,245			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),246			executor,247		)?;248	let client = Arc::new(client);249250	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());251252	let telemetry = telemetry.map(|(worker, telemetry)| {253		task_manager254			.spawn_handle()255			.spawn("telemetry", None, worker.run());256		telemetry257	});258259	let select_chain = sc_consensus::LongestChain::new(backend.clone());260261	let transaction_pool = sc_transaction_pool::BasicPool::new_full(262		config.transaction_pool.clone(),263		config.role.is_authority().into(),264		config.prometheus_registry(),265		task_manager.spawn_essential_handle(),266		client.clone(),267	);268269	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));270271	let frontier_backend = open_frontier_backend(config)?;272273	let import_queue = build_import_queue(274		client.clone(),275		config,276		telemetry.as_ref().map(|telemetry| telemetry.handle()),277		&task_manager,278	)?;279	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));280281	let params = PartialComponents {282		backend,283		client,284		import_queue,285		keystore_container,286		task_manager,287		transaction_pool,288		select_chain,289		other: (290			telemetry,291			filter_pool,292			frontier_backend,293			telemetry_worker_handle,294			fee_history_cache,295		),296	};297298	Ok(params)299}300301async fn build_relay_chain_interface(302	polkadot_config: Configuration,303	parachain_config: &Configuration,304	telemetry_worker_handle: Option<TelemetryWorkerHandle>,305	task_manager: &mut TaskManager,306	collator_options: CollatorOptions,307	hwbench: Option<sc_sysinfo::HwBench>,308) -> RelayChainResult<(309	Arc<(dyn RelayChainInterface + 'static)>,310	Option<CollatorPair>,311)> {312	match collator_options.relay_chain_rpc_url {313		Some(relay_chain_url) => {314			let rpc_client = create_client_and_start_worker(relay_chain_url, task_manager).await?;315316			Ok((317				Arc::new(RelayChainRpcInterface::new(rpc_client)) as Arc<_>,318				None,319			))320		}321		None => build_inprocess_relay_chain(322			polkadot_config,323			parachain_config,324			telemetry_worker_handle,325			task_manager,326			hwbench,327		),328	}329}330331/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.332///333/// This is the actual implementation that is abstract over the executor and the runtime api.334#[sc_tracing::logging::prefix_logs_with("Parachain")]335async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(336	parachain_config: Configuration,337	polkadot_config: Configuration,338	collator_options: CollatorOptions,339	id: ParaId,340	build_import_queue: BIQ,341	build_consensus: BIC,342	hwbench: Option<sc_sysinfo::HwBench>,343) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>344where345	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,346	Runtime: RuntimeInstance + Send + Sync + 'static,347	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,348	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,349	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>350		+ Send351		+ Sync352		+ 'static,353	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>354		+ fp_rpc::EthereumRuntimeRPCApi<Block>355		+ fp_rpc::ConvertTransactionRuntimeApi<Block>356		+ sp_session::SessionKeys<Block>357		+ sp_block_builder::BlockBuilder<Block>358		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>359		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>360		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>361		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>362		+ rmrk_rpc::RmrkApi<363			Block,364			AccountId,365			RmrkCollectionInfo<AccountId>,366			RmrkInstanceInfo<AccountId>,367			RmrkResourceInfo,368			RmrkPropertyInfo,369			RmrkBaseInfo<AccountId>,370			RmrkPartType,371			RmrkTheme,372		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>373		+ sp_api::Metadata<Block>374		+ sp_offchain::OffchainWorkerApi<Block>375		+ cumulus_primitives_core::CollectCollationInfo<Block>,376	ExecutorDispatch: NativeExecutionDispatch + 'static,377	BIQ: FnOnce(378		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,379		&Configuration,380		Option<TelemetryHandle>,381		&TaskManager,382	) -> Result<383		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,384		sc_service::Error,385	>,386	BIC: FnOnce(387		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,388		Option<&Registry>,389		Option<TelemetryHandle>,390		&TaskManager,391		Arc<dyn RelayChainInterface>,392		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,393		Arc<NetworkService<Block, Hash>>,394		SyncCryptoStorePtr,395		bool,396	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,397{398	let parachain_config = prepare_node_config(parachain_config);399400	let params =401		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;402	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =403		params.other;404405	let client = params.client.clone();406	let backend = params.backend.clone();407	let mut task_manager = params.task_manager;408409	let (relay_chain_interface, collator_key) = build_relay_chain_interface(410		polkadot_config,411		&parachain_config,412		telemetry_worker_handle,413		&mut task_manager,414		collator_options.clone(),415		hwbench.clone(),416	)417	.await418	.map_err(|e| match e {419		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,420		s => s.to_string().into(),421	})?;422423	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);424425	let force_authoring = parachain_config.force_authoring;426	let validator = parachain_config.role.is_authority();427	let prometheus_registry = parachain_config.prometheus_registry().cloned();428	let transaction_pool = params.transaction_pool.clone();429	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);430431	let (network, system_rpc_tx, tx_handler_controller, start_network) =432		sc_service::build_network(sc_service::BuildNetworkParams {433			config: &parachain_config,434			client: client.clone(),435			transaction_pool: transaction_pool.clone(),436			spawn_handle: task_manager.spawn_handle(),437			import_queue: import_queue.clone(),438			block_announce_validator_builder: Some(Box::new(|_| {439				Box::new(block_announce_validator)440			})),441			warp_sync: None,442		})?;443444	let rpc_client = client.clone();445	let rpc_pool = transaction_pool.clone();446	let select_chain = params.select_chain.clone();447	let rpc_network = network.clone();448449	let rpc_frontier_backend = frontier_backend.clone();450451	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(452		task_manager.spawn_handle(),453		overrides_handle::<_, _, Runtime>(client.clone()),454		50,455		50,456		prometheus_registry.clone(),457	));458459	task_manager.spawn_essential_handle().spawn(460		"frontier-mapping-sync-worker",461		None,462		MappingSyncWorker::new(463			client.import_notification_stream(),464			Duration::new(6, 0),465			client.clone(),466			backend.clone(),467			frontier_backend.clone(),468			3,469			0,470			SyncStrategy::Normal,471		)472		.for_each(|()| futures::future::ready(())),473	);474475	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {476		let full_deps = unique_rpc::FullDeps {477			backend: rpc_frontier_backend.clone(),478			deny_unsafe,479			client: rpc_client.clone(),480			pool: rpc_pool.clone(),481			graph: rpc_pool.pool().clone(),482			// TODO: Unhardcode483			enable_dev_signer: false,484			filter_pool: filter_pool.clone(),485			network: rpc_network.clone(),486			select_chain: select_chain.clone(),487			is_authority: validator,488			// TODO: Unhardcode489			max_past_logs: 10000,490			block_data_cache: block_data_cache.clone(),491			fee_history_cache: fee_history_cache.clone(),492			// TODO: Unhardcode493			fee_history_limit: 2048,494		};495496		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(497			full_deps,498			subscription_task_executor,499		)500		.map_err(Into::into)501	});502503	sc_service::spawn_tasks(sc_service::SpawnTasksParams {504		rpc_builder,505		client: client.clone(),506		transaction_pool: transaction_pool.clone(),507		task_manager: &mut task_manager,508		config: parachain_config,509		keystore: params.keystore_container.sync_keystore(),510		backend: backend.clone(),511		network: network.clone(),512		system_rpc_tx,513		telemetry: telemetry.as_mut(),514		tx_handler_controller,515	})?;516517	if let Some(hwbench) = hwbench {518		sc_sysinfo::print_hwbench(&hwbench);519520		if let Some(ref mut telemetry) = telemetry {521			let telemetry_handle = telemetry.handle();522			task_manager.spawn_handle().spawn(523				"telemetry_hwbench",524				None,525				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),526			);527		}528	}529530	let announce_block = {531		let network = network.clone();532		Arc::new(Box::new(move |hash, data| {533			network.announce_block(hash, data)534		}))535	};536537	let relay_chain_slot_duration = Duration::from_secs(6);538539	if validator {540		let parachain_consensus = build_consensus(541			client.clone(),542			prometheus_registry.as_ref(),543			telemetry.as_ref().map(|t| t.handle()),544			&task_manager,545			relay_chain_interface.clone(),546			transaction_pool,547			network,548			params.keystore_container.sync_keystore(),549			force_authoring,550		)?;551552		let spawner = task_manager.spawn_handle();553554		let params = StartCollatorParams {555			para_id: id,556			block_status: client.clone(),557			announce_block,558			client: client.clone(),559			task_manager: &mut task_manager,560			spawner,561			parachain_consensus,562			import_queue,563			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),564			relay_chain_interface,565			relay_chain_slot_duration,566		};567568		start_collator(params).await?;569	} else {570		let params = StartFullNodeParams {571			client: client.clone(),572			announce_block,573			task_manager: &mut task_manager,574			para_id: id,575			import_queue,576			relay_chain_interface,577			relay_chain_slot_duration,578			collator_options,579		};580581		start_full_node(params)?;582	}583584	start_network.start_network();585586	Ok((task_manager, client))587}588589/// Build the import queue for the the parachain runtime.590pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(591	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,592	config: &Configuration,593	telemetry: Option<TelemetryHandle>,594	task_manager: &TaskManager,595) -> Result<596	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,597	sc_service::Error,598>599where600	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>601		+ Send602		+ Sync603		+ 'static,604	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>605		+ sp_block_builder::BlockBuilder<Block>606		+ sp_consensus_aura::AuraApi<Block, AuraId>607		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,608	ExecutorDispatch: NativeExecutionDispatch + 'static,609{610	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;611612	cumulus_client_consensus_aura::import_queue::<613		sp_consensus_aura::sr25519::AuthorityPair,614		_,615		_,616		_,617		_,618		_,619	>(cumulus_client_consensus_aura::ImportQueueParams {620		block_import: client.clone(),621		client: client.clone(),622		create_inherent_data_providers: move |_, _| async move {623			let time = sp_timestamp::InherentDataProvider::from_system_time();624625			let slot =626				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(627					*time,628					slot_duration,629				);630631			Ok((slot, time))632		},633		registry: config.prometheus_registry(),634		spawner: &task_manager.spawn_essential_handle(),635		telemetry,636	})637	.map_err(Into::into)638}639640/// Start a normal parachain node.641pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(642	parachain_config: Configuration,643	polkadot_config: Configuration,644	collator_options: CollatorOptions,645	id: ParaId,646	hwbench: Option<sc_sysinfo::HwBench>,647) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>648where649	Runtime: RuntimeInstance + Send + Sync + 'static,650	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,651	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,652	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>653		+ Send654		+ Sync655		+ 'static,656	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>657		+ fp_rpc::EthereumRuntimeRPCApi<Block>658		+ fp_rpc::ConvertTransactionRuntimeApi<Block>659		+ sp_session::SessionKeys<Block>660		+ sp_block_builder::BlockBuilder<Block>661		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>662		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>663		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>664		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>665		+ rmrk_rpc::RmrkApi<666			Block,667			AccountId,668			RmrkCollectionInfo<AccountId>,669			RmrkInstanceInfo<AccountId>,670			RmrkResourceInfo,671			RmrkPropertyInfo,672			RmrkBaseInfo<AccountId>,673			RmrkPartType,674			RmrkTheme,675		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>676		+ sp_api::Metadata<Block>677		+ sp_offchain::OffchainWorkerApi<Block>678		+ cumulus_primitives_core::CollectCollationInfo<Block>679		+ sp_consensus_aura::AuraApi<Block, AuraId>,680	ExecutorDispatch: NativeExecutionDispatch + 'static,681{682	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(683		parachain_config,684		polkadot_config,685		collator_options,686		id,687		parachain_build_import_queue,688		|client,689		 prometheus_registry,690		 telemetry,691		 task_manager,692		 relay_chain_interface,693		 transaction_pool,694		 sync_oracle,695		 keystore,696		 force_authoring| {697			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;698699			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(700				task_manager.spawn_handle(),701				client.clone(),702				transaction_pool,703				prometheus_registry,704				telemetry.clone(),705			);706707			Ok(AuraConsensus::build::<708				sp_consensus_aura::sr25519::AuthorityPair,709				_,710				_,711				_,712				_,713				_,714				_,715			>(BuildAuraConsensusParams {716				proposer_factory,717				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {718					let relay_chain_interface = relay_chain_interface.clone();719					async move {720						let parachain_inherent =721						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(722							relay_parent,723							&relay_chain_interface,724							&validation_data,725							id,726						).await;727728						let time = sp_timestamp::InherentDataProvider::from_system_time();729730						let slot =731						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(732							*time,733							slot_duration,734						);735736						let parachain_inherent = parachain_inherent.ok_or_else(|| {737							Box::<dyn std::error::Error + Send + Sync>::from(738								"Failed to create parachain inherent",739							)740						})?;741						Ok((slot, time, parachain_inherent))742					}743				},744				block_import: client.clone(),745				para_client: client,746				backoff_authoring_blocks: Option::<()>::None,747				sync_oracle,748				keystore,749				force_authoring,750				slot_duration,751				// We got around 500ms for proposing752				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),753				telemetry,754				max_block_proposal_slot_portion: None,755			}))756		},757		hwbench,758	)759	.await760}761762fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(763	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,764	config: &Configuration,765	_: Option<TelemetryHandle>,766	task_manager: &TaskManager,767) -> Result<768	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,769	sc_service::Error,770>771where772	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>773		+ Send774		+ Sync775		+ 'static,776	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>777		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,778	ExecutorDispatch: NativeExecutionDispatch + 'static,779{780	Ok(sc_consensus_manual_seal::import_queue(781		Box::new(client.clone()),782		&task_manager.spawn_essential_handle(),783		config.prometheus_registry(),784	))785}786787/// Builds a new development service. This service uses instant seal, and mocks788/// the parachain inherent789pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(790	config: Configuration,791	autoseal_interval: Duration,792) -> sc_service::error::Result<TaskManager>793where794	Runtime: RuntimeInstance + Send + Sync + 'static,795	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,796	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,797	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>798		+ Send799		+ Sync800		+ 'static,801	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>802		+ fp_rpc::EthereumRuntimeRPCApi<Block>803		+ fp_rpc::ConvertTransactionRuntimeApi<Block>804		+ sp_session::SessionKeys<Block>805		+ sp_block_builder::BlockBuilder<Block>806		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>807		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>808		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>809		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>810		+ rmrk_rpc::RmrkApi<811			Block,812			AccountId,813			RmrkCollectionInfo<AccountId>,814			RmrkInstanceInfo<AccountId>,815			RmrkResourceInfo,816			RmrkPropertyInfo,817			RmrkBaseInfo<AccountId>,818			RmrkPartType,819			RmrkTheme,820		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>821		+ sp_api::Metadata<Block>822		+ sp_offchain::OffchainWorkerApi<Block>823		+ cumulus_primitives_core::CollectCollationInfo<Block>824		+ sp_consensus_aura::AuraApi<Block, AuraId>,825	ExecutorDispatch: NativeExecutionDispatch + 'static,826{827	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};828	use fc_consensus::FrontierBlockImport;829	use sc_client_api::HeaderBackend;830831	let sc_service::PartialComponents {832		client,833		backend,834		mut task_manager,835		import_queue,836		keystore_container,837		select_chain: maybe_select_chain,838		transaction_pool,839		other:840			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),841	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(842		&config,843		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,844	)?;845	let prometheus_registry = config.prometheus_registry().cloned();846847	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(848		task_manager.spawn_handle(),849		overrides_handle::<_, _, Runtime>(client.clone()),850		50,851		50,852		prometheus_registry.clone(),853	));854855	let (network, system_rpc_tx, tx_handler_controller, network_starter) =856		sc_service::build_network(sc_service::BuildNetworkParams {857			config: &config,858			client: client.clone(),859			transaction_pool: transaction_pool.clone(),860			spawn_handle: task_manager.spawn_handle(),861			import_queue,862			block_announce_validator_builder: None,863			warp_sync: None,864		})?;865866	if config.offchain_worker.enabled {867		sc_service::build_offchain_workers(868			&config,869			task_manager.spawn_handle(),870			client.clone(),871			network.clone(),872		);873	}874875	let collator = config.role.is_authority();876877	let select_chain = maybe_select_chain.clone();878879	if collator {880		let block_import =881			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());882883		let env = sc_basic_authorship::ProposerFactory::new(884			task_manager.spawn_handle(),885			client.clone(),886			transaction_pool.clone(),887			prometheus_registry.as_ref(),888			telemetry.as_ref().map(|x| x.handle()),889		);890891		let transactions_commands_stream: Box<892			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,893		> = Box::new(894			transaction_pool895				.pool()896				.validated_pool()897				.import_notification_stream()898				.map(|_| EngineCommand::SealNewBlock {899					create_empty: true,900					finalize: false,901					parent_hash: None,902					sender: None,903				}),904		);905906		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));907		let idle_commands_stream: Box<908			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,909		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {910			create_empty: true,911			finalize: false,912			parent_hash: None,913			sender: None,914		}));915916		let commands_stream = select(transactions_commands_stream, idle_commands_stream);917918		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;919		let client_set_aside_for_cidp = client.clone();920921		task_manager.spawn_essential_handle().spawn_blocking(922			"authorship_task",923			Some("block-authoring"),924			run_manual_seal(ManualSealParams {925				block_import,926				env,927				client: client.clone(),928				pool: transaction_pool.clone(),929				commands_stream,930				select_chain: select_chain.clone(),931				consensus_data_provider: None,932				create_inherent_data_providers: move |block: Hash, ()| {933					let current_para_block = client_set_aside_for_cidp934						.number(block)935						.expect("Header lookup should succeed")936						.expect("Header passed in as parent should be present in backend.");937938					let client_for_xcm = client_set_aside_for_cidp.clone();939					async move {940						let time = sp_timestamp::InherentDataProvider::from_system_time();941942						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {943							current_para_block,944							relay_offset: 1000,945							relay_blocks_per_para_block: 2,946							para_blocks_per_relay_epoch: 0,947							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(948								&*client_for_xcm,949								block,950								Default::default(),951								Default::default(),952							),953							relay_randomness_config: (),954							raw_downward_messages: vec![],955							raw_horizontal_messages: vec![],956						};957958						let slot =959						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(960							*time,961							slot_duration,962						);963964						Ok((time, slot, mocked_parachain))965					}966				},967			}),968		);969	}970971	task_manager.spawn_essential_handle().spawn(972		"frontier-mapping-sync-worker",973		Some("block-authoring"),974		MappingSyncWorker::new(975			client.import_notification_stream(),976			Duration::new(6, 0),977			client.clone(),978			backend.clone(),979			frontier_backend.clone(),980			3,981			0,982			SyncStrategy::Normal,983		)984		.for_each(|()| futures::future::ready(())),985	);986987	let rpc_client = client.clone();988	let rpc_pool = transaction_pool.clone();989	let rpc_network = network.clone();990	let rpc_frontier_backend = frontier_backend.clone();991	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {992		let full_deps = unique_rpc::FullDeps {993			backend: rpc_frontier_backend.clone(),994			deny_unsafe,995			client: rpc_client.clone(),996			pool: rpc_pool.clone(),997			graph: rpc_pool.pool().clone(),998			// TODO: Unhardcode999			enable_dev_signer: false,1000			filter_pool: filter_pool.clone(),1001			network: rpc_network.clone(),1002			select_chain: select_chain.clone(),1003			is_authority: collator,1004			// TODO: Unhardcode1005			max_past_logs: 10000,1006			block_data_cache: block_data_cache.clone(),1007			fee_history_cache: fee_history_cache.clone(),1008			// TODO: Unhardcode1009			fee_history_limit: 2048,1010		};10111012		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1013			full_deps,1014			subscription_executor,1015		)1016		.map_err(Into::into)1017	});10181019	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1020		network,1021		client,1022		keystore: keystore_container.sync_keystore(),1023		task_manager: &mut task_manager,1024		transaction_pool,1025		rpc_builder,1026		backend,1027		system_rpc_tx,1028		config,1029		telemetry: None,1030		tx_handler_controller,1031	})?;10321033	network_starter.start_network();1034	Ok(task_manager)1035}