git.delta.rocks / unique-network / refs/commits / 85b56f6a5869

difftreelog

source

node/cli/src/service.rs30.9 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, 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 up_common::types::opaque::{67	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,68};6970// RMRK71use up_data_structs::{72	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,73	RmrkPartType, RmrkTheme,74};7576/// Unique native executor instance.77#[cfg(feature = "unique-runtime")]78pub struct UniqueRuntimeExecutor;7980#[cfg(feature = "quartz-runtime")]81/// Quartz native executor instance.82pub struct QuartzRuntimeExecutor;8384/// Opal native executor instance.85pub struct OpalRuntimeExecutor;8687#[cfg(feature = "unique-runtime")]88pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8990#[cfg(all(not(feature = "unique-runtime"), feature = "quartz-runtime"))]91pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9293#[cfg(all(not(feature = "unique-runtime"), not(feature = "quartz-runtime")))]94pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;9596#[cfg(feature = "unique-runtime")]97impl NativeExecutionDispatch for UniqueRuntimeExecutor {98	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;99100	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {101		unique_runtime::api::dispatch(method, data)102	}103104	fn native_version() -> sc_executor::NativeVersion {105		unique_runtime::native_version()106	}107}108109#[cfg(feature = "quartz-runtime")]110impl NativeExecutionDispatch for QuartzRuntimeExecutor {111	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112113	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {114		quartz_runtime::api::dispatch(method, data)115	}116117	fn native_version() -> sc_executor::NativeVersion {118		quartz_runtime::native_version()119	}120}121122impl NativeExecutionDispatch for OpalRuntimeExecutor {123	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;124125	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {126		opal_runtime::api::dispatch(method, data)127	}128129	fn native_version() -> sc_executor::NativeVersion {130		opal_runtime::native_version()131	}132}133134pub struct AutosealInterval {135	interval: Interval,136}137138impl AutosealInterval {139	pub fn new(config: &Configuration, interval: Duration) -> Self {140		let _tokio_runtime = config.tokio_handle.enter();141		let interval = tokio::time::interval(interval);142143		Self { interval }144	}145}146147impl Stream for AutosealInterval {148	type Item = tokio::time::Instant;149150	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {151		self.interval.poll_tick(cx).map(Some)152	}153}154155pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {156	let config_dir = config157		.base_path158		.as_ref()159		.map(|base_path| base_path.config_dir(config.chain_spec.id()))160		.unwrap_or_else(|| {161			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())162		});163	let database_dir = config_dir.join("frontier").join("db");164165	Ok(Arc::new(fc_db::Backend::<Block>::new(166		&fc_db::DatabaseSettings {167			source: fc_db::DatabaseSource::RocksDb {168				path: database_dir,169				cache_size: 0,170			},171		},172	)?))173}174175type FullClient<RuntimeApi, ExecutorDispatch> =176	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;177type FullBackend = sc_service::TFullBackend<Block>;178type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;179180/// Starts a `ServiceBuilder` for a full service.181///182/// Use this macro if you don't actually need the full service, but just the builder in order to183/// be able to perform chain operations.184#[allow(clippy::type_complexity)]185pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(186	config: &Configuration,187	build_import_queue: BIQ,188) -> Result<189	PartialComponents<190		FullClient<RuntimeApi, ExecutorDispatch>,191		FullBackend,192		FullSelectChain,193		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,194		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,195		(196			Option<Telemetry>,197			Option<FilterPool>,198			Arc<fc_db::Backend<Block>>,199			Option<TelemetryWorkerHandle>,200			FeeHistoryCache,201		),202	>,203	sc_service::Error,204>205where206	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,207	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>208		+ Send209		+ Sync210		+ 'static,211	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,212	ExecutorDispatch: NativeExecutionDispatch + 'static,213	BIQ: FnOnce(214		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,215		&Configuration,216		Option<TelemetryHandle>,217		&TaskManager,218	) -> Result<219		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,220		sc_service::Error,221	>,222{223	let _telemetry = config224		.telemetry_endpoints225		.clone()226		.filter(|x| !x.is_empty())227		.map(|endpoints| -> Result<_, sc_telemetry::Error> {228			let worker = TelemetryWorker::new(16)?;229			let telemetry = worker.handle().new_telemetry(endpoints);230			Ok((worker, telemetry))231		})232		.transpose()?;233234	let telemetry = config235		.telemetry_endpoints236		.clone()237		.filter(|x| !x.is_empty())238		.map(|endpoints| -> Result<_, sc_telemetry::Error> {239			let worker = TelemetryWorker::new(16)?;240			let telemetry = worker.handle().new_telemetry(endpoints);241			Ok((worker, telemetry))242		})243		.transpose()?;244245	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(246		config.wasm_method,247		config.default_heap_pages,248		config.max_runtime_instances,249		config.runtime_cache_size,250	);251252	let (client, backend, keystore_container, task_manager) =253		sc_service::new_full_parts::<Block, RuntimeApi, _>(254			config,255			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),256			executor,257		)?;258	let client = Arc::new(client);259260	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());261262	let telemetry = telemetry.map(|(worker, telemetry)| {263		task_manager264			.spawn_handle()265			.spawn("telemetry", None, worker.run());266		telemetry267	});268269	let select_chain = sc_consensus::LongestChain::new(backend.clone());270271	let transaction_pool = sc_transaction_pool::BasicPool::new_full(272		config.transaction_pool.clone(),273		config.role.is_authority().into(),274		config.prometheus_registry(),275		task_manager.spawn_essential_handle(),276		client.clone(),277	);278279	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));280281	let frontier_backend = open_frontier_backend(config)?;282283	let import_queue = build_import_queue(284		client.clone(),285		config,286		telemetry.as_ref().map(|telemetry| telemetry.handle()),287		&task_manager,288	)?;289	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));290291	let params = PartialComponents {292		backend,293		client,294		import_queue,295		keystore_container,296		task_manager,297		transaction_pool,298		select_chain,299		other: (300			telemetry,301			filter_pool,302			frontier_backend,303			telemetry_worker_handle,304			fee_history_cache,305		),306	};307308	Ok(params)309}310311async fn build_relay_chain_interface(312	polkadot_config: Configuration,313	parachain_config: &Configuration,314	telemetry_worker_handle: Option<TelemetryWorkerHandle>,315	task_manager: &mut TaskManager,316	collator_options: CollatorOptions,317	hwbench: Option<sc_sysinfo::HwBench>,318) -> RelayChainResult<(319	Arc<(dyn RelayChainInterface + 'static)>,320	Option<CollatorPair>,321)> {322	match collator_options.relay_chain_rpc_url {323		Some(relay_chain_url) => Ok((324			Arc::new(RelayChainRPCInterface::new(relay_chain_url).await?) as Arc<_>,325			None,326		)),327		None => build_inprocess_relay_chain(328			polkadot_config,329			parachain_config,330			telemetry_worker_handle,331			task_manager,332			hwbench,333		),334	}335}336337/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.338///339/// This is the actual implementation that is abstract over the executor and the runtime api.340#[sc_tracing::logging::prefix_logs_with("Parachain")]341async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(342	parachain_config: Configuration,343	polkadot_config: Configuration,344	collator_options: CollatorOptions,345	id: ParaId,346	build_import_queue: BIQ,347	build_consensus: BIC,348	hwbench: Option<sc_sysinfo::HwBench>,349) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>350where351	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,352	Runtime: RuntimeInstance + Send + Sync + 'static,353	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,354	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,355	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>356		+ Send357		+ Sync358		+ 'static,359	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>360		+ fp_rpc::EthereumRuntimeRPCApi<Block>361		+ fp_rpc::ConvertTransactionRuntimeApi<Block>362		+ sp_session::SessionKeys<Block>363		+ sp_block_builder::BlockBuilder<Block>364		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>365		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>366		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>367		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>368		+ rmrk_rpc::RmrkApi<369			Block,370			AccountId,371			RmrkCollectionInfo<AccountId>,372			RmrkInstanceInfo<AccountId>,373			RmrkResourceInfo,374			RmrkPropertyInfo,375			RmrkBaseInfo<AccountId>,376			RmrkPartType,377			RmrkTheme,378		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>379		+ sp_api::Metadata<Block>380		+ sp_offchain::OffchainWorkerApi<Block>381		+ cumulus_primitives_core::CollectCollationInfo<Block>,382	ExecutorDispatch: NativeExecutionDispatch + 'static,383	BIQ: FnOnce(384		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,385		&Configuration,386		Option<TelemetryHandle>,387		&TaskManager,388	) -> Result<389		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,390		sc_service::Error,391	>,392	BIC: FnOnce(393		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,394		Option<&Registry>,395		Option<TelemetryHandle>,396		&TaskManager,397		Arc<dyn RelayChainInterface>,398		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,399		Arc<NetworkService<Block, Hash>>,400		SyncCryptoStorePtr,401		bool,402	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,403{404	let parachain_config = prepare_node_config(parachain_config);405406	let params =407		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;408	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =409		params.other;410411	let client = params.client.clone();412	let backend = params.backend.clone();413	let mut task_manager = params.task_manager;414415	let (relay_chain_interface, collator_key) = build_relay_chain_interface(416		polkadot_config,417		&parachain_config,418		telemetry_worker_handle,419		&mut task_manager,420		collator_options.clone(),421		hwbench.clone(),422	)423	.await424	.map_err(|e| match e {425		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,426		s => s.to_string().into(),427	})?;428429	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);430431	let force_authoring = parachain_config.force_authoring;432	let validator = parachain_config.role.is_authority();433	let prometheus_registry = parachain_config.prometheus_registry().cloned();434	let transaction_pool = params.transaction_pool.clone();435	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);436437	let (network, system_rpc_tx, start_network) =438		sc_service::build_network(sc_service::BuildNetworkParams {439			config: &parachain_config,440			client: client.clone(),441			transaction_pool: transaction_pool.clone(),442			spawn_handle: task_manager.spawn_handle(),443			import_queue: import_queue.clone(),444			block_announce_validator_builder: Some(Box::new(|_| {445				Box::new(block_announce_validator)446			})),447			warp_sync: None,448		})?;449450	let rpc_client = client.clone();451	let rpc_pool = transaction_pool.clone();452	let select_chain = params.select_chain.clone();453	let rpc_network = network.clone();454455	let rpc_frontier_backend = frontier_backend.clone();456457	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(458		task_manager.spawn_handle(),459		overrides_handle::<_, _, Runtime>(client.clone()),460		50,461		50,462		prometheus_registry.clone(),463	));464465	task_manager.spawn_essential_handle().spawn(466		"frontier-mapping-sync-worker",467		None,468		MappingSyncWorker::new(469			client.import_notification_stream(),470			Duration::new(6, 0),471			client.clone(),472			backend.clone(),473			frontier_backend.clone(),474			3,475			0,476			SyncStrategy::Normal,477		)478		.for_each(|()| futures::future::ready(())),479	);480481	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {482		let full_deps = unique_rpc::FullDeps {483			backend: rpc_frontier_backend.clone(),484			deny_unsafe,485			client: rpc_client.clone(),486			pool: rpc_pool.clone(),487			graph: rpc_pool.pool().clone(),488			// TODO: Unhardcode489			enable_dev_signer: false,490			filter_pool: filter_pool.clone(),491			network: rpc_network.clone(),492			select_chain: select_chain.clone(),493			is_authority: validator,494			// TODO: Unhardcode495			max_past_logs: 10000,496			block_data_cache: block_data_cache.clone(),497			fee_history_cache: fee_history_cache.clone(),498			// TODO: Unhardcode499			fee_history_limit: 2048,500		};501502		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(503			full_deps,504			subscription_task_executor,505		)506		.map_err(Into::into)507	});508509	sc_service::spawn_tasks(sc_service::SpawnTasksParams {510		rpc_builder,511		client: client.clone(),512		transaction_pool: transaction_pool.clone(),513		task_manager: &mut task_manager,514		config: parachain_config,515		keystore: params.keystore_container.sync_keystore(),516		backend: backend.clone(),517		network: network.clone(),518		system_rpc_tx,519		telemetry: telemetry.as_mut(),520	})?;521522	if let Some(hwbench) = hwbench {523		sc_sysinfo::print_hwbench(&hwbench);524525		if let Some(ref mut telemetry) = telemetry {526			let telemetry_handle = telemetry.handle();527			task_manager.spawn_handle().spawn(528				"telemetry_hwbench",529				None,530				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),531			);532		}533	}534535	let announce_block = {536		let network = network.clone();537		Arc::new(move |hash, data| network.announce_block(hash, data))538	};539540	let relay_chain_slot_duration = Duration::from_secs(6);541542	if validator {543		let parachain_consensus = build_consensus(544			client.clone(),545			prometheus_registry.as_ref(),546			telemetry.as_ref().map(|t| t.handle()),547			&task_manager,548			relay_chain_interface.clone(),549			transaction_pool,550			network,551			params.keystore_container.sync_keystore(),552			force_authoring,553		)?;554555		let spawner = task_manager.spawn_handle();556557		let params = StartCollatorParams {558			para_id: id,559			block_status: client.clone(),560			announce_block,561			client: client.clone(),562			task_manager: &mut task_manager,563			spawner,564			parachain_consensus,565			import_queue,566			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),567			relay_chain_interface,568			relay_chain_slot_duration,569		};570571		start_collator(params).await?;572	} else {573		let params = StartFullNodeParams {574			client: client.clone(),575			announce_block,576			task_manager: &mut task_manager,577			para_id: id,578			import_queue,579			relay_chain_interface,580			relay_chain_slot_duration,581			collator_options,582		};583584		start_full_node(params)?;585	}586587	start_network.start_network();588589	Ok((task_manager, client))590}591592/// Build the import queue for the the parachain runtime.593pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(594	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,595	config: &Configuration,596	telemetry: Option<TelemetryHandle>,597	task_manager: &TaskManager,598) -> Result<599	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,600	sc_service::Error,601>602where603	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>604		+ Send605		+ Sync606		+ 'static,607	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>608		+ sp_block_builder::BlockBuilder<Block>609		+ sp_consensus_aura::AuraApi<Block, AuraId>610		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,611	ExecutorDispatch: NativeExecutionDispatch + 'static,612{613	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;614615	cumulus_client_consensus_aura::import_queue::<616		sp_consensus_aura::sr25519::AuthorityPair,617		_,618		_,619		_,620		_,621		_,622		_,623	>(cumulus_client_consensus_aura::ImportQueueParams {624		block_import: client.clone(),625		client: client.clone(),626		create_inherent_data_providers: move |_, _| async move {627			let time = sp_timestamp::InherentDataProvider::from_system_time();628629			let slot =630				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(631					*time,632					slot_duration,633				);634635			Ok((time, slot))636		},637		registry: config.prometheus_registry(),638		can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),639		spawner: &task_manager.spawn_essential_handle(),640		telemetry,641	})642	.map_err(Into::into)643}644645/// Start a normal parachain node.646pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(647	parachain_config: Configuration,648	polkadot_config: Configuration,649	collator_options: CollatorOptions,650	id: ParaId,651	hwbench: Option<sc_sysinfo::HwBench>,652) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>653where654	Runtime: RuntimeInstance + Send + Sync + 'static,655	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,656	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,657	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>658		+ Send659		+ Sync660		+ 'static,661	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>662		+ fp_rpc::EthereumRuntimeRPCApi<Block>663		+ fp_rpc::ConvertTransactionRuntimeApi<Block>664		+ sp_session::SessionKeys<Block>665		+ sp_block_builder::BlockBuilder<Block>666		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>667		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>668		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>669		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>670		+ rmrk_rpc::RmrkApi<671			Block,672			AccountId,673			RmrkCollectionInfo<AccountId>,674			RmrkInstanceInfo<AccountId>,675			RmrkResourceInfo,676			RmrkPropertyInfo,677			RmrkBaseInfo<AccountId>,678			RmrkPartType,679			RmrkTheme,680		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>681		+ sp_api::Metadata<Block>682		+ sp_offchain::OffchainWorkerApi<Block>683		+ cumulus_primitives_core::CollectCollationInfo<Block>684		+ sp_consensus_aura::AuraApi<Block, AuraId>,685	ExecutorDispatch: NativeExecutionDispatch + 'static,686{687	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(688		parachain_config,689		polkadot_config,690		collator_options,691		id,692		parachain_build_import_queue,693		|client,694		 prometheus_registry,695		 telemetry,696		 task_manager,697		 relay_chain_interface,698		 transaction_pool,699		 sync_oracle,700		 keystore,701		 force_authoring| {702			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;703704			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(705				task_manager.spawn_handle(),706				client.clone(),707				transaction_pool,708				prometheus_registry,709				telemetry.clone(),710			);711712			Ok(AuraConsensus::build::<713				sp_consensus_aura::sr25519::AuthorityPair,714				_,715				_,716				_,717				_,718				_,719				_,720			>(BuildAuraConsensusParams {721				proposer_factory,722				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {723					let relay_chain_interface = relay_chain_interface.clone();724					async move {725						let parachain_inherent =726						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(727							relay_parent,728							&relay_chain_interface,729							&validation_data,730							id,731						).await;732733						let time = sp_timestamp::InherentDataProvider::from_system_time();734735						let slot =736						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(737							*time,738							slot_duration,739						);740741						let parachain_inherent = parachain_inherent.ok_or_else(|| {742							Box::<dyn std::error::Error + Send + Sync>::from(743								"Failed to create parachain inherent",744							)745						})?;746						Ok((time, slot, parachain_inherent))747					}748				},749				block_import: client.clone(),750				para_client: client,751				backoff_authoring_blocks: Option::<()>::None,752				sync_oracle,753				keystore,754				force_authoring,755				slot_duration,756				// We got around 500ms for proposing757				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),758				telemetry,759				max_block_proposal_slot_portion: None,760			}))761		},762		hwbench,763	)764	.await765}766767fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(768	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,769	config: &Configuration,770	_: Option<TelemetryHandle>,771	task_manager: &TaskManager,772) -> Result<773	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,774	sc_service::Error,775>776where777	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>778		+ Send779		+ Sync780		+ 'static,781	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>782		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,783	ExecutorDispatch: NativeExecutionDispatch + 'static,784{785	Ok(sc_consensus_manual_seal::import_queue(786		Box::new(client.clone()),787		&task_manager.spawn_essential_handle(),788		config.prometheus_registry(),789	))790}791792/// Builds a new development service. This service uses instant seal, and mocks793/// the parachain inherent794pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(795	config: Configuration,796	autoseal_interval: Duration,797) -> sc_service::error::Result<TaskManager>798where799	Runtime: RuntimeInstance + Send + Sync + 'static,800	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,801	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,802	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>803		+ Send804		+ Sync805		+ 'static,806	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>807		+ fp_rpc::EthereumRuntimeRPCApi<Block>808		+ fp_rpc::ConvertTransactionRuntimeApi<Block>809		+ sp_session::SessionKeys<Block>810		+ sp_block_builder::BlockBuilder<Block>811		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>812		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>813		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>814		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>815		+ rmrk_rpc::RmrkApi<816			Block,817			AccountId,818			RmrkCollectionInfo<AccountId>,819			RmrkInstanceInfo<AccountId>,820			RmrkResourceInfo,821			RmrkPropertyInfo,822			RmrkBaseInfo<AccountId>,823			RmrkPartType,824			RmrkTheme,825		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>826		+ sp_api::Metadata<Block>827		+ sp_offchain::OffchainWorkerApi<Block>828		+ cumulus_primitives_core::CollectCollationInfo<Block>829		+ sp_consensus_aura::AuraApi<Block, AuraId>,830	ExecutorDispatch: NativeExecutionDispatch + 'static,831{832	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};833	use fc_consensus::FrontierBlockImport;834	use sc_client_api::HeaderBackend;835836	let sc_service::PartialComponents {837		client,838		backend,839		mut task_manager,840		import_queue,841		keystore_container,842		select_chain: maybe_select_chain,843		transaction_pool,844		other:845			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),846	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(847		&config,848		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,849	)?;850	let prometheus_registry = config.prometheus_registry().cloned();851852	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(853		task_manager.spawn_handle(),854		overrides_handle::<_, _, Runtime>(client.clone()),855		50,856		50,857		prometheus_registry.clone(),858	));859860	let (network, system_rpc_tx, network_starter) =861		sc_service::build_network(sc_service::BuildNetworkParams {862			config: &config,863			client: client.clone(),864			transaction_pool: transaction_pool.clone(),865			spawn_handle: task_manager.spawn_handle(),866			import_queue,867			block_announce_validator_builder: None,868			warp_sync: None,869		})?;870871	if config.offchain_worker.enabled {872		sc_service::build_offchain_workers(873			&config,874			task_manager.spawn_handle(),875			client.clone(),876			network.clone(),877		);878	}879880	let collator = config.role.is_authority();881882	let select_chain = maybe_select_chain.clone();883884	if collator {885		let block_import =886			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());887888		let env = sc_basic_authorship::ProposerFactory::new(889			task_manager.spawn_handle(),890			client.clone(),891			transaction_pool.clone(),892			prometheus_registry.as_ref(),893			telemetry.as_ref().map(|x| x.handle()),894		);895896		let transactions_commands_stream: Box<897			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,898		> = Box::new(899			transaction_pool900				.pool()901				.validated_pool()902				.import_notification_stream()903				.map(|_| EngineCommand::SealNewBlock {904					create_empty: true,905					finalize: false,906					parent_hash: None,907					sender: None,908				}),909		);910911		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));912		let idle_commands_stream: Box<913			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,914		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {915			create_empty: true,916			finalize: false,917			parent_hash: None,918			sender: None,919		}));920921		let commands_stream = select(transactions_commands_stream, idle_commands_stream);922923		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;924		let client_set_aside_for_cidp = client.clone();925926		task_manager.spawn_essential_handle().spawn_blocking(927			"authorship_task",928			Some("block-authoring"),929			run_manual_seal(ManualSealParams {930				block_import,931				env,932				client: client.clone(),933				pool: transaction_pool.clone(),934				commands_stream,935				select_chain: select_chain.clone(),936				consensus_data_provider: None,937				create_inherent_data_providers: move |block: Hash, ()| {938					let current_para_block = client_set_aside_for_cidp939						.number(block)940						.expect("Header lookup should succeed")941						.expect("Header passed in as parent should be present in backend.");942943					let client_for_xcm = client_set_aside_for_cidp.clone();944					async move {945						let time = sp_timestamp::InherentDataProvider::from_system_time();946947						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {948							current_para_block,949							relay_offset: 1000,950							relay_blocks_per_para_block: 2,951							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(952								&*client_for_xcm,953								block,954								Default::default(),955								Default::default(),956							),957							raw_downward_messages: vec![],958							raw_horizontal_messages: vec![],959						};960961						let slot =962						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(963							*time,964							slot_duration,965						);966967						Ok((time, slot, mocked_parachain))968					}969				},970			}),971		);972	}973974	task_manager.spawn_essential_handle().spawn(975		"frontier-mapping-sync-worker",976		Some("block-authoring"),977		MappingSyncWorker::new(978			client.import_notification_stream(),979			Duration::new(6, 0),980			client.clone(),981			backend.clone(),982			frontier_backend.clone(),983			3,984			0,985			SyncStrategy::Normal,986		)987		.for_each(|()| futures::future::ready(())),988	);989990	let rpc_client = client.clone();991	let rpc_pool = transaction_pool.clone();992	let rpc_network = network.clone();993	let rpc_frontier_backend = frontier_backend.clone();994	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {995		let full_deps = unique_rpc::FullDeps {996			backend: rpc_frontier_backend.clone(),997			deny_unsafe,998			client: rpc_client.clone(),999			pool: rpc_pool.clone(),1000			graph: rpc_pool.pool().clone(),1001			// TODO: Unhardcode1002			enable_dev_signer: false,1003			filter_pool: filter_pool.clone(),1004			network: rpc_network.clone(),1005			select_chain: select_chain.clone(),1006			is_authority: collator,1007			// TODO: Unhardcode1008			max_past_logs: 10000,1009			block_data_cache: block_data_cache.clone(),1010			fee_history_cache: fee_history_cache.clone(),1011			// TODO: Unhardcode1012			fee_history_limit: 2048,1013		};10141015		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1016			full_deps,1017			subscription_executor,1018		)1019		.map_err(Into::into)1020	});10211022	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1023		network,1024		client,1025		keystore: keystore_container.sync_keystore(),1026		task_manager: &mut task_manager,1027		transaction_pool,1028		rpc_builder,1029		backend,1030		system_rpc_tx,1031		config,1032		telemetry: None,1033	})?;10341035	network_starter.start_network();1036	Ok(task_manager)1037}