git.delta.rocks / unique-network / refs/commits / 7af7cfe7ae02

difftreelog

source

node/cli/src/service.rs30.3 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// 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// RMRK69use up_data_structs::{70	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,71	RmrkPartType, RmrkTheme,72};7374/// Unique native executor instance.75#[cfg(feature = "unique-runtime")]76pub struct UniqueRuntimeExecutor;7778#[cfg(feature = "quartz-runtime")]79/// Quartz native executor instance.8081pub 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) => Ok((314			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,315			None,316		)),317		None => build_inprocess_relay_chain(318			polkadot_config,319			parachain_config,320			telemetry_worker_handle,321			task_manager,322			hwbench,323		),324	}325}326327/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.328///329/// This is the actual implementation that is abstract over the executor and the runtime api.330#[sc_tracing::logging::prefix_logs_with("Parachain")]331async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(332	parachain_config: Configuration,333	polkadot_config: Configuration,334	collator_options: CollatorOptions,335	id: ParaId,336	build_import_queue: BIQ,337	build_consensus: BIC,338	hwbench: Option<sc_sysinfo::HwBench>,339) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>340where341	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,342	Runtime: RuntimeInstance + Send + Sync + 'static,343	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,344	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,345	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>346		+ Send347		+ Sync348		+ 'static,349	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>350		+ fp_rpc::EthereumRuntimeRPCApi<Block>351		+ fp_rpc::ConvertTransactionRuntimeApi<Block>352		+ sp_session::SessionKeys<Block>353		+ sp_block_builder::BlockBuilder<Block>354		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>355		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>356		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>357		+ rmrk_rpc::RmrkApi<358			Block,359			AccountId,360			RmrkCollectionInfo<AccountId>,361			RmrkInstanceInfo<AccountId>,362			RmrkResourceInfo,363			RmrkPropertyInfo,364			RmrkBaseInfo<AccountId>,365			RmrkPartType,366			RmrkTheme,367		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>368		+ sp_api::Metadata<Block>369		+ sp_offchain::OffchainWorkerApi<Block>370		+ cumulus_primitives_core::CollectCollationInfo<Block>,371	ExecutorDispatch: NativeExecutionDispatch + 'static,372	BIQ: FnOnce(373		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,374		&Configuration,375		Option<TelemetryHandle>,376		&TaskManager,377	) -> Result<378		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,379		sc_service::Error,380	>,381	BIC: FnOnce(382		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,383		Option<&Registry>,384		Option<TelemetryHandle>,385		&TaskManager,386		Arc<dyn RelayChainInterface>,387		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,388		Arc<NetworkService<Block, Hash>>,389		SyncCryptoStorePtr,390		bool,391	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,392{393	if matches!(parachain_config.role, Role::Light) {394		return Err("Light client not supported!".into());395	}396397	let parachain_config = prepare_node_config(parachain_config);398399	let params =400		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;401	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =402		params.other;403404	let client = params.client.clone();405	let backend = params.backend.clone();406	let mut task_manager = params.task_manager;407408	let (relay_chain_interface, collator_key) = build_relay_chain_interface(409		polkadot_config,410		&parachain_config,411		telemetry_worker_handle,412		&mut task_manager,413		collator_options.clone(),414		hwbench.clone(),415	)416	.await417	.map_err(|e| match e {418		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,419		s => s.to_string().into(),420	})?;421422	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);423424	let force_authoring = parachain_config.force_authoring;425	let validator = parachain_config.role.is_authority();426	let prometheus_registry = parachain_config.prometheus_registry().cloned();427	let transaction_pool = params.transaction_pool.clone();428	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);429430	let (network, system_rpc_tx, start_network) =431		sc_service::build_network(sc_service::BuildNetworkParams {432			config: &parachain_config,433			client: client.clone(),434			transaction_pool: transaction_pool.clone(),435			spawn_handle: task_manager.spawn_handle(),436			import_queue: import_queue.clone(),437			block_announce_validator_builder: Some(Box::new(|_| {438				Box::new(block_announce_validator)439			})),440			warp_sync: None,441		})?;442443	let rpc_client = client.clone();444	let rpc_pool = transaction_pool.clone();445	let select_chain = params.select_chain.clone();446	let rpc_network = network.clone();447448	let rpc_frontier_backend = frontier_backend.clone();449450	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(451		task_manager.spawn_handle(),452		overrides_handle::<_, _, Runtime>(client.clone()),453		50,454		50,455		prometheus_registry.clone(),456	));457458	task_manager.spawn_essential_handle().spawn(459		"frontier-mapping-sync-worker",460		None,461		MappingSyncWorker::new(462			client.import_notification_stream(),463			Duration::new(6, 0),464			client.clone(),465			backend.clone(),466			frontier_backend.clone(),467			3,468			0,469			SyncStrategy::Normal,470		)471		.for_each(|()| futures::future::ready(())),472	);473474	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {475		let full_deps = unique_rpc::FullDeps {476			backend: rpc_frontier_backend.clone(),477			deny_unsafe,478			client: rpc_client.clone(),479			pool: rpc_pool.clone(),480			graph: rpc_pool.pool().clone(),481			// TODO: Unhardcode482			enable_dev_signer: false,483			filter_pool: filter_pool.clone(),484			network: rpc_network.clone(),485			select_chain: select_chain.clone(),486			is_authority: validator,487			// TODO: Unhardcode488			max_past_logs: 10000,489			block_data_cache: block_data_cache.clone(),490			fee_history_cache: fee_history_cache.clone(),491			// TODO: Unhardcode492			fee_history_limit: 2048,493		};494495		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(496			full_deps,497			subscription_task_executor,498		)499		.map_err(Into::into)500	});501502	sc_service::spawn_tasks(sc_service::SpawnTasksParams {503		rpc_builder,504		client: client.clone(),505		transaction_pool: transaction_pool.clone(),506		task_manager: &mut task_manager,507		config: parachain_config,508		keystore: params.keystore_container.sync_keystore(),509		backend: backend.clone(),510		network: network.clone(),511		system_rpc_tx,512		telemetry: telemetry.as_mut(),513	})?;514515	if let Some(hwbench) = hwbench {516		sc_sysinfo::print_hwbench(&hwbench);517518		if let Some(ref mut telemetry) = telemetry {519			let telemetry_handle = telemetry.handle();520			task_manager.spawn_handle().spawn(521				"telemetry_hwbench",522				None,523				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),524			);525		}526	}527528	let announce_block = {529		let network = network.clone();530		Arc::new(move |hash, data| network.announce_block(hash, data))531	};532533	let relay_chain_slot_duration = Duration::from_secs(6);534535	if validator {536		let parachain_consensus = build_consensus(537			client.clone(),538			prometheus_registry.as_ref(),539			telemetry.as_ref().map(|t| t.handle()),540			&task_manager,541			relay_chain_interface.clone(),542			transaction_pool,543			network,544			params.keystore_container.sync_keystore(),545			force_authoring,546		)?;547548		let spawner = task_manager.spawn_handle();549550		let params = StartCollatorParams {551			para_id: id,552			block_status: client.clone(),553			announce_block,554			client: client.clone(),555			task_manager: &mut task_manager,556			spawner,557			parachain_consensus,558			import_queue,559			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),560			relay_chain_interface,561			relay_chain_slot_duration,562		};563564		start_collator(params).await?;565	} else {566		let params = StartFullNodeParams {567			client: client.clone(),568			announce_block,569			task_manager: &mut task_manager,570			para_id: id,571			import_queue,572			relay_chain_interface,573			relay_chain_slot_duration,574			collator_options,575		};576577		start_full_node(params)?;578	}579580	start_network.start_network();581582	Ok((task_manager, client))583}584585/// Build the import queue for the the parachain runtime.586pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(587	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,588	config: &Configuration,589	telemetry: Option<TelemetryHandle>,590	task_manager: &TaskManager,591) -> Result<592	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,593	sc_service::Error,594>595where596	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>597		+ Send598		+ Sync599		+ 'static,600	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>601		+ sp_block_builder::BlockBuilder<Block>602		+ sp_consensus_aura::AuraApi<Block, AuraId>603		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,604	ExecutorDispatch: NativeExecutionDispatch + 'static,605{606	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;607608	cumulus_client_consensus_aura::import_queue::<609		sp_consensus_aura::sr25519::AuthorityPair,610		_,611		_,612		_,613		_,614		_,615		_,616	>(cumulus_client_consensus_aura::ImportQueueParams {617		block_import: client.clone(),618		client: client.clone(),619		create_inherent_data_providers: move |_, _| async move {620			let time = sp_timestamp::InherentDataProvider::from_system_time();621622			let slot =623				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(624					*time,625					slot_duration,626				);627628			Ok((time, slot))629		},630		registry: config.prometheus_registry(),631		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),632		spawner: &task_manager.spawn_essential_handle(),633		telemetry,634	})635	.map_err(Into::into)636}637638/// Start a normal parachain node.639pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(640	parachain_config: Configuration,641	polkadot_config: Configuration,642	collator_options: CollatorOptions,643	id: ParaId,644	hwbench: Option<sc_sysinfo::HwBench>,645) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>646where647	Runtime: RuntimeInstance + Send + Sync + 'static,648	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,649	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,650	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>651		+ Send652		+ Sync653		+ 'static,654	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>655		+ fp_rpc::EthereumRuntimeRPCApi<Block>656		+ fp_rpc::ConvertTransactionRuntimeApi<Block>657		+ sp_session::SessionKeys<Block>658		+ sp_block_builder::BlockBuilder<Block>659		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>660		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>661		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>662		+ rmrk_rpc::RmrkApi<663			Block,664			AccountId,665			RmrkCollectionInfo<AccountId>,666			RmrkInstanceInfo<AccountId>,667			RmrkResourceInfo,668			RmrkPropertyInfo,669			RmrkBaseInfo<AccountId>,670			RmrkPartType,671			RmrkTheme,672		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>673		+ sp_api::Metadata<Block>674		+ sp_offchain::OffchainWorkerApi<Block>675		+ cumulus_primitives_core::CollectCollationInfo<Block>676		+ sp_consensus_aura::AuraApi<Block, AuraId>,677	ExecutorDispatch: NativeExecutionDispatch + 'static,678{679	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(680		parachain_config,681		polkadot_config,682		collator_options,683		id,684		parachain_build_import_queue,685		|client,686		 prometheus_registry,687		 telemetry,688		 task_manager,689		 relay_chain_interface,690		 transaction_pool,691		 sync_oracle,692		 keystore,693		 force_authoring| {694			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;695696			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(697				task_manager.spawn_handle(),698				client.clone(),699				transaction_pool,700				prometheus_registry,701				telemetry.clone(),702			);703704			Ok(AuraConsensus::build::<705				sp_consensus_aura::sr25519::AuthorityPair,706				_,707				_,708				_,709				_,710				_,711				_,712			>(BuildAuraConsensusParams {713				proposer_factory,714				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {715					let relay_chain_interface = relay_chain_interface.clone();716					async move {717						let parachain_inherent =718						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(719							relay_parent,720							&relay_chain_interface,721							&validation_data,722							id,723						).await;724725						let time = sp_timestamp::InherentDataProvider::from_system_time();726727						let slot =728						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(729							*time,730							slot_duration,731						);732733						let parachain_inherent = parachain_inherent.ok_or_else(|| {734							Box::<dyn std::error::Error + Send + Sync>::from(735								"Failed to create parachain inherent",736							)737						})?;738						Ok((time, slot, parachain_inherent))739					}740				},741				block_import: client.clone(),742				para_client: client,743				backoff_authoring_blocks: Option::<()>::None,744				sync_oracle,745				keystore,746				force_authoring,747				slot_duration,748				// We got around 500ms for proposing749				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),750				telemetry,751				max_block_proposal_slot_portion: None,752			}))753		},754		hwbench,755	)756	.await757}758759fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(760	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,761	config: &Configuration,762	_: Option<TelemetryHandle>,763	task_manager: &TaskManager,764) -> Result<765	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,766	sc_service::Error,767>768where769	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>770		+ Send771		+ Sync772		+ 'static,773	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>774		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,775	ExecutorDispatch: NativeExecutionDispatch + 'static,776{777	Ok(sc_consensus_manual_seal::import_queue(778		Box::new(client.clone()),779		&task_manager.spawn_essential_handle(),780		config.prometheus_registry(),781	))782}783784/// Builds a new development service. This service uses instant seal, and mocks785/// the parachain inherent786pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(787	config: Configuration,788	autoseal_interval: Duration,789) -> sc_service::error::Result<TaskManager>790where791	Runtime: RuntimeInstance + Send + Sync + 'static,792	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,793	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,794	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>795		+ Send796		+ Sync797		+ 'static,798	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>799		+ fp_rpc::EthereumRuntimeRPCApi<Block>800		+ fp_rpc::ConvertTransactionRuntimeApi<Block>801		+ sp_session::SessionKeys<Block>802		+ sp_block_builder::BlockBuilder<Block>803		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>804		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>805		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>806		+ rmrk_rpc::RmrkApi<807			Block,808			AccountId,809			RmrkCollectionInfo<AccountId>,810			RmrkInstanceInfo<AccountId>,811			RmrkResourceInfo,812			RmrkPropertyInfo,813			RmrkBaseInfo<AccountId>,814			RmrkPartType,815			RmrkTheme,816		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>817		+ sp_api::Metadata<Block>818		+ sp_offchain::OffchainWorkerApi<Block>819		+ cumulus_primitives_core::CollectCollationInfo<Block>820		+ sp_consensus_aura::AuraApi<Block, AuraId>,821	ExecutorDispatch: NativeExecutionDispatch + 'static,822{823	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};824	use fc_consensus::FrontierBlockImport;825	use sc_client_api::HeaderBackend;826827	let sc_service::PartialComponents {828		client,829		backend,830		mut task_manager,831		import_queue,832		keystore_container,833		select_chain: maybe_select_chain,834		transaction_pool,835		other:836			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),837	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(838		&config,839		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,840	)?;841	let prometheus_registry = config.prometheus_registry().cloned();842843	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(844		task_manager.spawn_handle(),845		overrides_handle::<_, _, Runtime>(client.clone()),846		50,847		50,848		prometheus_registry.clone(),849	));850851	let (network, system_rpc_tx, network_starter) =852		sc_service::build_network(sc_service::BuildNetworkParams {853			config: &config,854			client: client.clone(),855			transaction_pool: transaction_pool.clone(),856			spawn_handle: task_manager.spawn_handle(),857			import_queue,858			block_announce_validator_builder: None,859			warp_sync: None,860		})?;861862	if config.offchain_worker.enabled {863		sc_service::build_offchain_workers(864			&config,865			task_manager.spawn_handle(),866			client.clone(),867			network.clone(),868		);869	}870871	let collator = config.role.is_authority();872873	let select_chain = maybe_select_chain.clone();874875	if collator {876		let block_import =877			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());878879		let env = sc_basic_authorship::ProposerFactory::new(880			task_manager.spawn_handle(),881			client.clone(),882			transaction_pool.clone(),883			prometheus_registry.as_ref(),884			telemetry.as_ref().map(|x| x.handle()),885		);886887		let transactions_commands_stream: Box<888			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,889		> = Box::new(890			transaction_pool891				.pool()892				.validated_pool()893				.import_notification_stream()894				.map(|_| EngineCommand::SealNewBlock {895					create_empty: true,896					finalize: false,897					parent_hash: None,898					sender: None,899				}),900		);901902		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));903		let idle_commands_stream: Box<904			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,905		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {906			create_empty: true,907			finalize: false,908			parent_hash: None,909			sender: None,910		}));911912		let commands_stream = select(transactions_commands_stream, idle_commands_stream);913914		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;915		let client_set_aside_for_cidp = client.clone();916917		task_manager.spawn_essential_handle().spawn_blocking(918			"authorship_task",919			Some("block-authoring"),920			run_manual_seal(ManualSealParams {921				block_import,922				env,923				client: client.clone(),924				pool: transaction_pool.clone(),925				commands_stream,926				select_chain: select_chain.clone(),927				consensus_data_provider: None,928				create_inherent_data_providers: move |block: Hash, ()| {929					let current_para_block = client_set_aside_for_cidp930						.number(block)931						.expect("Header lookup should succeed")932						.expect("Header passed in as parent should be present in backend.");933934					let client_for_xcm = client_set_aside_for_cidp.clone();935					async move {936						let time = sp_timestamp::InherentDataProvider::from_system_time();937938						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {939							current_para_block,940							relay_offset: 1000,941							relay_blocks_per_para_block: 2,942							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(943								&*client_for_xcm,944								block,945								Default::default(),946								Default::default(),947							),948							raw_downward_messages: vec![],949							raw_horizontal_messages: vec![],950						};951952						let slot =953						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(954							*time,955							slot_duration,956						);957958						Ok((time, slot, mocked_parachain))959					}960				},961			}),962		);963	}964965	task_manager.spawn_essential_handle().spawn(966		"frontier-mapping-sync-worker",967		Some("block-authoring"),968		MappingSyncWorker::new(969			client.import_notification_stream(),970			Duration::new(6, 0),971			client.clone(),972			backend.clone(),973			frontier_backend.clone(),974			3,975			0,976			SyncStrategy::Normal,977		)978		.for_each(|()| futures::future::ready(())),979	);980981	let rpc_client = client.clone();982	let rpc_pool = transaction_pool.clone();983	let rpc_network = network.clone();984	let rpc_frontier_backend = frontier_backend.clone();985	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {986		let full_deps = unique_rpc::FullDeps {987			backend: rpc_frontier_backend.clone(),988			deny_unsafe,989			client: rpc_client.clone(),990			pool: rpc_pool.clone(),991			graph: rpc_pool.pool().clone(),992			// TODO: Unhardcode993			enable_dev_signer: false,994			filter_pool: filter_pool.clone(),995			network: rpc_network.clone(),996			select_chain: select_chain.clone(),997			is_authority: collator,998			// TODO: Unhardcode999			max_past_logs: 10000,1000			block_data_cache: block_data_cache.clone(),1001			fee_history_cache: fee_history_cache.clone(),1002			// TODO: Unhardcode1003			fee_history_limit: 2048,1004		};10051006		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1007			full_deps,1008			subscription_executor,1009		)1010		.map_err(Into::into)1011	});10121013	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1014		network,1015		client,1016		keystore: keystore_container.sync_keystore(),1017		task_manager: &mut task_manager,1018		transaction_pool,1019		rpc_builder,1020		backend,1021		system_rpc_tx,1022		config,1023		telemetry: None,1024	})?;10251026	network_starter.start_network();1027	Ok(task_manager)1028}