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

difftreelog

source

node/cli/src/service.rs31.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, create_client_and_start_worker};4748// Substrate Imports49use sp_api::BlockT;50use sc_executor::NativeElseWasmExecutor;51use sc_executor::NativeExecutionDispatch;52use sc_network::{NetworkService, NetworkBlock};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(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]88pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;8990#[cfg(all(91	not(feature = "unique-runtime"),92	feature = "quartz-runtime",93	feature = "runtime-benchmarks"94))]95pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;9697#[cfg(all(98	not(feature = "unique-runtime"),99	not(feature = "quartz-runtime"),100	feature = "runtime-benchmarks"101))]102pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;103104#[cfg(feature = "unique-runtime")]105impl NativeExecutionDispatch for UniqueRuntimeExecutor {106	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;107108	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {109		unique_runtime::api::dispatch(method, data)110	}111112	fn native_version() -> sc_executor::NativeVersion {113		unique_runtime::native_version()114	}115}116117#[cfg(feature = "quartz-runtime")]118impl NativeExecutionDispatch for QuartzRuntimeExecutor {119	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;120121	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {122		quartz_runtime::api::dispatch(method, data)123	}124125	fn native_version() -> sc_executor::NativeVersion {126		quartz_runtime::native_version()127	}128}129130impl NativeExecutionDispatch for OpalRuntimeExecutor {131	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;132133	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {134		opal_runtime::api::dispatch(method, data)135	}136137	fn native_version() -> sc_executor::NativeVersion {138		opal_runtime::native_version()139	}140}141142pub struct AutosealInterval {143	interval: Interval,144}145146impl AutosealInterval {147	pub fn new(config: &Configuration, interval: Duration) -> Self {148		let _tokio_runtime = config.tokio_handle.enter();149		let interval = tokio::time::interval(interval);150151		Self { interval }152	}153}154155impl Stream for AutosealInterval {156	type Item = tokio::time::Instant;157158	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {159		self.interval.poll_tick(cx).map(Some)160	}161}162163pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(164	client: Arc<C>,165	config: &Configuration,166) -> Result<Arc<fc_db::Backend<Block>>, String> {167	let config_dir = config168		.base_path169		.as_ref()170		.map(|base_path| base_path.config_dir(config.chain_spec.id()))171		.unwrap_or_else(|| {172			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())173		});174	let database_dir = config_dir.join("frontier").join("db");175176	Ok(Arc::new(fc_db::Backend::<Block>::new(177		client,178		&fc_db::DatabaseSettings {179			source: fc_db::DatabaseSource::RocksDb {180				path: database_dir,181				cache_size: 0,182			},183		},184	)?))185}186187type FullClient<RuntimeApi, ExecutorDispatch> =188	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;189type FullBackend = sc_service::TFullBackend<Block>;190type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;191192/// Starts a `ServiceBuilder` for a full service.193///194/// Use this macro if you don't actually need the full service, but just the builder in order to195/// be able to perform chain operations.196#[allow(clippy::type_complexity)]197pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(198	config: &Configuration,199	build_import_queue: BIQ,200) -> Result<201	PartialComponents<202		FullClient<RuntimeApi, ExecutorDispatch>,203		FullBackend,204		FullSelectChain,205		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,206		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,207		(208			Option<Telemetry>,209			Option<FilterPool>,210			Arc<fc_db::Backend<Block>>,211			Option<TelemetryWorkerHandle>,212			FeeHistoryCache,213		),214	>,215	sc_service::Error,216>217where218	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,219	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>220		+ Send221		+ Sync222		+ 'static,223	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,224	ExecutorDispatch: NativeExecutionDispatch + 'static,225	BIQ: FnOnce(226		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,227		&Configuration,228		Option<TelemetryHandle>,229		&TaskManager,230	) -> Result<231		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,232		sc_service::Error,233	>,234{235	let _telemetry = config236		.telemetry_endpoints237		.clone()238		.filter(|x| !x.is_empty())239		.map(|endpoints| -> Result<_, sc_telemetry::Error> {240			let worker = TelemetryWorker::new(16)?;241			let telemetry = worker.handle().new_telemetry(endpoints);242			Ok((worker, telemetry))243		})244		.transpose()?;245246	let telemetry = config247		.telemetry_endpoints248		.clone()249		.filter(|x| !x.is_empty())250		.map(|endpoints| -> Result<_, sc_telemetry::Error> {251			let worker = TelemetryWorker::new(16)?;252			let telemetry = worker.handle().new_telemetry(endpoints);253			Ok((worker, telemetry))254		})255		.transpose()?;256257	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(258		config.wasm_method,259		config.default_heap_pages,260		config.max_runtime_instances,261		config.runtime_cache_size,262	);263264	let (client, backend, keystore_container, task_manager) =265		sc_service::new_full_parts::<Block, RuntimeApi, _>(266			config,267			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),268			executor,269		)?;270	let client = Arc::new(client);271272	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());273274	let telemetry = telemetry.map(|(worker, telemetry)| {275		task_manager276			.spawn_handle()277			.spawn("telemetry", None, worker.run());278		telemetry279	});280281	let select_chain = sc_consensus::LongestChain::new(backend.clone());282283	let transaction_pool = sc_transaction_pool::BasicPool::new_full(284		config.transaction_pool.clone(),285		config.role.is_authority().into(),286		config.prometheus_registry(),287		task_manager.spawn_essential_handle(),288		client.clone(),289	);290291	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));292293	let frontier_backend = open_frontier_backend(client.clone(), config)?;294295	let import_queue = build_import_queue(296		client.clone(),297		config,298		telemetry.as_ref().map(|telemetry| telemetry.handle()),299		&task_manager,300	)?;301	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));302303	let params = PartialComponents {304		backend,305		client,306		import_queue,307		keystore_container,308		task_manager,309		transaction_pool,310		select_chain,311		other: (312			telemetry,313			filter_pool,314			frontier_backend,315			telemetry_worker_handle,316			fee_history_cache,317		),318	};319320	Ok(params)321}322323async fn build_relay_chain_interface(324	polkadot_config: Configuration,325	parachain_config: &Configuration,326	telemetry_worker_handle: Option<TelemetryWorkerHandle>,327	task_manager: &mut TaskManager,328	collator_options: CollatorOptions,329	hwbench: Option<sc_sysinfo::HwBench>,330) -> RelayChainResult<(331	Arc<(dyn RelayChainInterface + 'static)>,332	Option<CollatorPair>,333)> {334	match collator_options.relay_chain_rpc_url {335		Some(relay_chain_url) => {336			let rpc_client = create_client_and_start_worker(relay_chain_url, task_manager).await?;337338			Ok((339				Arc::new(RelayChainRpcInterface::new(rpc_client)) as Arc<_>,340				None,341			))342		}343		None => build_inprocess_relay_chain(344			polkadot_config,345			parachain_config,346			telemetry_worker_handle,347			task_manager,348			hwbench,349		),350	}351}352353/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.354///355/// This is the actual implementation that is abstract over the executor and the runtime api.356#[sc_tracing::logging::prefix_logs_with("Parachain")]357async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(358	parachain_config: Configuration,359	polkadot_config: Configuration,360	collator_options: CollatorOptions,361	id: ParaId,362	build_import_queue: BIQ,363	build_consensus: BIC,364	hwbench: Option<sc_sysinfo::HwBench>,365) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>366where367	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,368	Runtime: RuntimeInstance + Send + Sync + 'static,369	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,370	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,371	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>372		+ Send373		+ Sync374		+ 'static,375	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>376		+ fp_rpc::EthereumRuntimeRPCApi<Block>377		+ fp_rpc::ConvertTransactionRuntimeApi<Block>378		+ sp_session::SessionKeys<Block>379		+ sp_block_builder::BlockBuilder<Block>380		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>381		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>382		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>383		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>384		+ rmrk_rpc::RmrkApi<385			Block,386			AccountId,387			RmrkCollectionInfo<AccountId>,388			RmrkInstanceInfo<AccountId>,389			RmrkResourceInfo,390			RmrkPropertyInfo,391			RmrkBaseInfo<AccountId>,392			RmrkPartType,393			RmrkTheme,394		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>395		+ sp_api::Metadata<Block>396		+ sp_offchain::OffchainWorkerApi<Block>397		+ cumulus_primitives_core::CollectCollationInfo<Block>,398	ExecutorDispatch: NativeExecutionDispatch + 'static,399	BIQ: FnOnce(400		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,401		&Configuration,402		Option<TelemetryHandle>,403		&TaskManager,404	) -> Result<405		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,406		sc_service::Error,407	>,408	BIC: FnOnce(409		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,410		Option<&Registry>,411		Option<TelemetryHandle>,412		&TaskManager,413		Arc<dyn RelayChainInterface>,414		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,415		Arc<NetworkService<Block, Hash>>,416		SyncCryptoStorePtr,417		bool,418	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,419{420	let parachain_config = prepare_node_config(parachain_config);421422	let params =423		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;424	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =425		params.other;426427	let client = params.client.clone();428	let backend = params.backend.clone();429	let mut task_manager = params.task_manager;430431	let (relay_chain_interface, collator_key) = build_relay_chain_interface(432		polkadot_config,433		&parachain_config,434		telemetry_worker_handle,435		&mut task_manager,436		collator_options.clone(),437		hwbench.clone(),438	)439	.await440	.map_err(|e| match e {441		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,442		s => s.to_string().into(),443	})?;444445	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);446447	let force_authoring = parachain_config.force_authoring;448	let validator = parachain_config.role.is_authority();449	let prometheus_registry = parachain_config.prometheus_registry().cloned();450	let transaction_pool = params.transaction_pool.clone();451	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);452453	let (network, system_rpc_tx, tx_handler_controller, start_network) =454		sc_service::build_network(sc_service::BuildNetworkParams {455			config: &parachain_config,456			client: client.clone(),457			transaction_pool: transaction_pool.clone(),458			spawn_handle: task_manager.spawn_handle(),459			import_queue: import_queue.clone(),460			block_announce_validator_builder: Some(Box::new(|_| {461				Box::new(block_announce_validator)462			})),463			warp_sync: None,464		})?;465466	let rpc_client = client.clone();467	let rpc_pool = transaction_pool.clone();468	let select_chain = params.select_chain.clone();469	let rpc_network = network.clone();470471	let rpc_frontier_backend = frontier_backend.clone();472473	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(474		task_manager.spawn_handle(),475		overrides_handle::<_, _, Runtime>(client.clone()),476		50,477		50,478		prometheus_registry.clone(),479	));480481	task_manager.spawn_essential_handle().spawn(482		"frontier-mapping-sync-worker",483		None,484		MappingSyncWorker::new(485			client.import_notification_stream(),486			Duration::new(6, 0),487			client.clone(),488			backend.clone(),489			frontier_backend.clone(),490			3,491			0,492			SyncStrategy::Normal,493		)494		.for_each(|()| futures::future::ready(())),495	);496497	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {498		let full_deps = unique_rpc::FullDeps {499			backend: rpc_frontier_backend.clone(),500			deny_unsafe,501			client: rpc_client.clone(),502			pool: rpc_pool.clone(),503			graph: rpc_pool.pool().clone(),504			// TODO: Unhardcode505			enable_dev_signer: false,506			filter_pool: filter_pool.clone(),507			network: rpc_network.clone(),508			select_chain: select_chain.clone(),509			is_authority: validator,510			// TODO: Unhardcode511			max_past_logs: 10000,512			block_data_cache: block_data_cache.clone(),513			fee_history_cache: fee_history_cache.clone(),514			// TODO: Unhardcode515			fee_history_limit: 2048,516		};517518		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(519			full_deps,520			subscription_task_executor,521		)522		.map_err(Into::into)523	});524525	sc_service::spawn_tasks(sc_service::SpawnTasksParams {526		rpc_builder,527		client: client.clone(),528		transaction_pool: transaction_pool.clone(),529		task_manager: &mut task_manager,530		config: parachain_config,531		keystore: params.keystore_container.sync_keystore(),532		backend: backend.clone(),533		network: network.clone(),534		system_rpc_tx,535		telemetry: telemetry.as_mut(),536		tx_handler_controller,537	})?;538539	if let Some(hwbench) = hwbench {540		sc_sysinfo::print_hwbench(&hwbench);541542		if let Some(ref mut telemetry) = telemetry {543			let telemetry_handle = telemetry.handle();544			task_manager.spawn_handle().spawn(545				"telemetry_hwbench",546				None,547				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),548			);549		}550	}551552	let announce_block = {553		let network = network.clone();554		Arc::new(Box::new(move |hash, data| {555			network.announce_block(hash, data)556		}))557	};558559	let relay_chain_slot_duration = Duration::from_secs(6);560561	if validator {562		let parachain_consensus = build_consensus(563			client.clone(),564			prometheus_registry.as_ref(),565			telemetry.as_ref().map(|t| t.handle()),566			&task_manager,567			relay_chain_interface.clone(),568			transaction_pool,569			network,570			params.keystore_container.sync_keystore(),571			force_authoring,572		)?;573574		let spawner = task_manager.spawn_handle();575576		let params = StartCollatorParams {577			para_id: id,578			block_status: client.clone(),579			announce_block,580			client: client.clone(),581			task_manager: &mut task_manager,582			spawner,583			parachain_consensus,584			import_queue,585			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),586			relay_chain_interface,587			relay_chain_slot_duration,588		};589590		start_collator(params).await?;591	} else {592		let params = StartFullNodeParams {593			client: client.clone(),594			announce_block,595			task_manager: &mut task_manager,596			para_id: id,597			import_queue,598			relay_chain_interface,599			relay_chain_slot_duration,600			collator_options,601		};602603		start_full_node(params)?;604	}605606	start_network.start_network();607608	Ok((task_manager, client))609}610611/// Build the import queue for the the parachain runtime.612pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(613	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,614	config: &Configuration,615	telemetry: Option<TelemetryHandle>,616	task_manager: &TaskManager,617) -> Result<618	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,619	sc_service::Error,620>621where622	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>623		+ Send624		+ Sync625		+ 'static,626	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>627		+ sp_block_builder::BlockBuilder<Block>628		+ sp_consensus_aura::AuraApi<Block, AuraId>629		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,630	ExecutorDispatch: NativeExecutionDispatch + 'static,631{632	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;633634	cumulus_client_consensus_aura::import_queue::<635		sp_consensus_aura::sr25519::AuthorityPair,636		_,637		_,638		_,639		_,640		_,641	>(cumulus_client_consensus_aura::ImportQueueParams {642		block_import: client.clone(),643		client: client.clone(),644		create_inherent_data_providers: move |_, _| async move {645			let time = sp_timestamp::InherentDataProvider::from_system_time();646647			let slot =648				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(649					*time,650					slot_duration,651				);652653			Ok((slot, time))654		},655		registry: config.prometheus_registry(),656		spawner: &task_manager.spawn_essential_handle(),657		telemetry,658	})659	.map_err(Into::into)660}661662/// Start a normal parachain node.663pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(664	parachain_config: Configuration,665	polkadot_config: Configuration,666	collator_options: CollatorOptions,667	id: ParaId,668	hwbench: Option<sc_sysinfo::HwBench>,669) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>670where671	Runtime: RuntimeInstance + Send + Sync + 'static,672	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,673	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,674	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>675		+ Send676		+ Sync677		+ 'static,678	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>679		+ fp_rpc::EthereumRuntimeRPCApi<Block>680		+ fp_rpc::ConvertTransactionRuntimeApi<Block>681		+ sp_session::SessionKeys<Block>682		+ sp_block_builder::BlockBuilder<Block>683		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>684		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>685		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>686		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>687		+ rmrk_rpc::RmrkApi<688			Block,689			AccountId,690			RmrkCollectionInfo<AccountId>,691			RmrkInstanceInfo<AccountId>,692			RmrkResourceInfo,693			RmrkPropertyInfo,694			RmrkBaseInfo<AccountId>,695			RmrkPartType,696			RmrkTheme,697		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>698		+ sp_api::Metadata<Block>699		+ sp_offchain::OffchainWorkerApi<Block>700		+ cumulus_primitives_core::CollectCollationInfo<Block>701		+ sp_consensus_aura::AuraApi<Block, AuraId>,702	ExecutorDispatch: NativeExecutionDispatch + 'static,703{704	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(705		parachain_config,706		polkadot_config,707		collator_options,708		id,709		parachain_build_import_queue,710		|client,711		 prometheus_registry,712		 telemetry,713		 task_manager,714		 relay_chain_interface,715		 transaction_pool,716		 sync_oracle,717		 keystore,718		 force_authoring| {719			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;720721			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(722				task_manager.spawn_handle(),723				client.clone(),724				transaction_pool,725				prometheus_registry,726				telemetry.clone(),727			);728729			Ok(AuraConsensus::build::<730				sp_consensus_aura::sr25519::AuthorityPair,731				_,732				_,733				_,734				_,735				_,736				_,737			>(BuildAuraConsensusParams {738				proposer_factory,739				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {740					let relay_chain_interface = relay_chain_interface.clone();741					async move {742						let parachain_inherent =743						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(744							relay_parent,745							&relay_chain_interface,746							&validation_data,747							id,748						).await;749750						let time = sp_timestamp::InherentDataProvider::from_system_time();751752						let slot =753						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(754							*time,755							slot_duration,756						);757758						let parachain_inherent = parachain_inherent.ok_or_else(|| {759							Box::<dyn std::error::Error + Send + Sync>::from(760								"Failed to create parachain inherent",761							)762						})?;763						Ok((slot, time, parachain_inherent))764					}765				},766				block_import: client.clone(),767				para_client: client,768				backoff_authoring_blocks: Option::<()>::None,769				sync_oracle,770				keystore,771				force_authoring,772				slot_duration,773				// We got around 500ms for proposing774				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),775				telemetry,776				max_block_proposal_slot_portion: None,777			}))778		},779		hwbench,780	)781	.await782}783784fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(785	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,786	config: &Configuration,787	_: Option<TelemetryHandle>,788	task_manager: &TaskManager,789) -> Result<790	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,791	sc_service::Error,792>793where794	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>795		+ Send796		+ Sync797		+ 'static,798	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>799		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,800	ExecutorDispatch: NativeExecutionDispatch + 'static,801{802	Ok(sc_consensus_manual_seal::import_queue(803		Box::new(client.clone()),804		&task_manager.spawn_essential_handle(),805		config.prometheus_registry(),806	))807}808809/// Builds a new development service. This service uses instant seal, and mocks810/// the parachain inherent811pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(812	config: Configuration,813	autoseal_interval: Duration,814) -> sc_service::error::Result<TaskManager>815where816	Runtime: RuntimeInstance + Send + Sync + 'static,817	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,818	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,819	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>820		+ Send821		+ Sync822		+ 'static,823	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>824		+ fp_rpc::EthereumRuntimeRPCApi<Block>825		+ fp_rpc::ConvertTransactionRuntimeApi<Block>826		+ sp_session::SessionKeys<Block>827		+ sp_block_builder::BlockBuilder<Block>828		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>829		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>830		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>831		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>832		+ rmrk_rpc::RmrkApi<833			Block,834			AccountId,835			RmrkCollectionInfo<AccountId>,836			RmrkInstanceInfo<AccountId>,837			RmrkResourceInfo,838			RmrkPropertyInfo,839			RmrkBaseInfo<AccountId>,840			RmrkPartType,841			RmrkTheme,842		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>843		+ sp_api::Metadata<Block>844		+ sp_offchain::OffchainWorkerApi<Block>845		+ cumulus_primitives_core::CollectCollationInfo<Block>846		+ sp_consensus_aura::AuraApi<Block, AuraId>,847	ExecutorDispatch: NativeExecutionDispatch + 'static,848{849	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};850	use fc_consensus::FrontierBlockImport;851	use sc_client_api::HeaderBackend;852853	let sc_service::PartialComponents {854		client,855		backend,856		mut task_manager,857		import_queue,858		keystore_container,859		select_chain: maybe_select_chain,860		transaction_pool,861		other:862			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),863	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(864		&config,865		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,866	)?;867	let prometheus_registry = config.prometheus_registry().cloned();868869	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(870		task_manager.spawn_handle(),871		overrides_handle::<_, _, Runtime>(client.clone()),872		50,873		50,874		prometheus_registry.clone(),875	));876877	let (network, system_rpc_tx, tx_handler_controller, network_starter) =878		sc_service::build_network(sc_service::BuildNetworkParams {879			config: &config,880			client: client.clone(),881			transaction_pool: transaction_pool.clone(),882			spawn_handle: task_manager.spawn_handle(),883			import_queue,884			block_announce_validator_builder: None,885			warp_sync: None,886		})?;887888	if config.offchain_worker.enabled {889		sc_service::build_offchain_workers(890			&config,891			task_manager.spawn_handle(),892			client.clone(),893			network.clone(),894		);895	}896897	let collator = config.role.is_authority();898899	let select_chain = maybe_select_chain.clone();900901	if collator {902		let block_import =903			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());904905		let env = sc_basic_authorship::ProposerFactory::new(906			task_manager.spawn_handle(),907			client.clone(),908			transaction_pool.clone(),909			prometheus_registry.as_ref(),910			telemetry.as_ref().map(|x| x.handle()),911		);912913		let transactions_commands_stream: Box<914			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,915		> = Box::new(916			transaction_pool917				.pool()918				.validated_pool()919				.import_notification_stream()920				.map(|_| EngineCommand::SealNewBlock {921					create_empty: true,922					finalize: false,923					parent_hash: None,924					sender: None,925				}),926		);927928		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));929		let idle_commands_stream: Box<930			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,931		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {932			create_empty: true,933			finalize: false,934			parent_hash: None,935			sender: None,936		}));937938		let commands_stream = select(transactions_commands_stream, idle_commands_stream);939940		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;941		let client_set_aside_for_cidp = client.clone();942943		task_manager.spawn_essential_handle().spawn_blocking(944			"authorship_task",945			Some("block-authoring"),946			run_manual_seal(ManualSealParams {947				block_import,948				env,949				client: client.clone(),950				pool: transaction_pool.clone(),951				commands_stream,952				select_chain: select_chain.clone(),953				consensus_data_provider: None,954				create_inherent_data_providers: move |block: Hash, ()| {955					let current_para_block = client_set_aside_for_cidp956						.number(block)957						.expect("Header lookup should succeed")958						.expect("Header passed in as parent should be present in backend.");959960					let client_for_xcm = client_set_aside_for_cidp.clone();961					async move {962						let time = sp_timestamp::InherentDataProvider::from_system_time();963964						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {965							current_para_block,966							relay_offset: 1000,967							relay_blocks_per_para_block: 2,968							para_blocks_per_relay_epoch: 0,969							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(970								&*client_for_xcm,971								block,972								Default::default(),973								Default::default(),974							),975							relay_randomness_config: (),976							raw_downward_messages: vec![],977							raw_horizontal_messages: vec![],978						};979980						let slot =981						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(982							*time,983							slot_duration,984						);985986						Ok((time, slot, mocked_parachain))987					}988				},989			}),990		);991	}992993	task_manager.spawn_essential_handle().spawn(994		"frontier-mapping-sync-worker",995		Some("block-authoring"),996		MappingSyncWorker::new(997			client.import_notification_stream(),998			Duration::new(6, 0),999			client.clone(),1000			backend.clone(),1001			frontier_backend.clone(),1002			3,1003			0,1004			SyncStrategy::Normal,1005		)1006		.for_each(|()| futures::future::ready(())),1007	);10081009	let rpc_client = client.clone();1010	let rpc_pool = transaction_pool.clone();1011	let rpc_network = network.clone();1012	let rpc_frontier_backend = frontier_backend.clone();1013	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1014		let full_deps = unique_rpc::FullDeps {1015			backend: rpc_frontier_backend.clone(),1016			deny_unsafe,1017			client: rpc_client.clone(),1018			pool: rpc_pool.clone(),1019			graph: rpc_pool.pool().clone(),1020			// TODO: Unhardcode1021			enable_dev_signer: false,1022			filter_pool: filter_pool.clone(),1023			network: rpc_network.clone(),1024			select_chain: select_chain.clone(),1025			is_authority: collator,1026			// TODO: Unhardcode1027			max_past_logs: 10000,1028			block_data_cache: block_data_cache.clone(),1029			fee_history_cache: fee_history_cache.clone(),1030			// TODO: Unhardcode1031			fee_history_limit: 2048,1032		};10331034		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1035			full_deps,1036			subscription_executor,1037		)1038		.map_err(Into::into)1039	});10401041	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1042		network,1043		client,1044		keystore: keystore_container.sync_keystore(),1045		task_manager: &mut task_manager,1046		transaction_pool,1047		rpc_builder,1048		backend,1049		system_rpc_tx,1050		config,1051		telemetry: None,1052		tx_handler_controller,1053	})?;10541055	network_starter.start_network();1056	Ok(task_manager)1057}