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

difftreelog

source

node/cli/src/service.rs31.4 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, ParachainBlockImport as TParachainBlockImport};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_minimal_node::build_minimal_relay_chain_node;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>;191type ParachainBlockImport<RuntimeApi, ExecutorDispatch> = TParachainBlockImport<Arc<FullClient<RuntimeApi, ExecutorDispatch>>>;192193/// Starts a `ServiceBuilder` for a full service.194///195/// Use this macro if you don't actually need the full service, but just the builder in order to196/// be able to perform chain operations.197#[allow(clippy::type_complexity)]198pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(199	config: &Configuration,200	build_import_queue: BIQ,201) -> Result<202	PartialComponents<203		FullClient<RuntimeApi, ExecutorDispatch>,204		FullBackend,205		FullSelectChain,206		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,207		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,208		(209			Option<Telemetry>,210			Option<FilterPool>,211			Arc<fc_db::Backend<Block>>,212			Option<TelemetryWorkerHandle>,213			FeeHistoryCache,214		),215	>,216	sc_service::Error,217>218where219	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,220	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>221		+ Send222		+ Sync223		+ 'static,224	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,225	ExecutorDispatch: NativeExecutionDispatch + 'static,226	BIQ: FnOnce(227		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,228		&Configuration,229		Option<TelemetryHandle>,230		&TaskManager,231	) -> Result<232		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,233		sc_service::Error,234	>,235{236	let _telemetry = config237		.telemetry_endpoints238		.clone()239		.filter(|x| !x.is_empty())240		.map(|endpoints| -> Result<_, sc_telemetry::Error> {241			let worker = TelemetryWorker::new(16)?;242			let telemetry = worker.handle().new_telemetry(endpoints);243			Ok((worker, telemetry))244		})245		.transpose()?;246247	let telemetry = config248		.telemetry_endpoints249		.clone()250		.filter(|x| !x.is_empty())251		.map(|endpoints| -> Result<_, sc_telemetry::Error> {252			let worker = TelemetryWorker::new(16)?;253			let telemetry = worker.handle().new_telemetry(endpoints);254			Ok((worker, telemetry))255		})256		.transpose()?;257258	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(259		config.wasm_method,260		config.default_heap_pages,261		config.max_runtime_instances,262		config.runtime_cache_size,263	);264265	let (client, backend, keystore_container, task_manager) =266		sc_service::new_full_parts::<Block, RuntimeApi, _>(267			config,268			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),269			executor,270		)?;271	let client = Arc::new(client);272273	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());274275	let telemetry = telemetry.map(|(worker, telemetry)| {276		task_manager277			.spawn_handle()278			.spawn("telemetry", None, worker.run());279		telemetry280	});281282	let select_chain = sc_consensus::LongestChain::new(backend.clone());283284	let transaction_pool = sc_transaction_pool::BasicPool::new_full(285		config.transaction_pool.clone(),286		config.role.is_authority().into(),287		config.prometheus_registry(),288		task_manager.spawn_essential_handle(),289		client.clone(),290	);291292	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));293294	let frontier_backend = open_frontier_backend(client.clone(), config)?;295296	let import_queue = build_import_queue(297		client.clone(),298		config,299		telemetry.as_ref().map(|telemetry| telemetry.handle()),300		&task_manager,301	)?;302	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));303304	let params = PartialComponents {305		backend,306		client,307		import_queue,308		keystore_container,309		task_manager,310		transaction_pool,311		select_chain,312		other: (313			telemetry,314			filter_pool,315			frontier_backend,316			telemetry_worker_handle,317			fee_history_cache,318		),319	};320321	Ok(params)322}323324async fn build_relay_chain_interface(325	polkadot_config: Configuration,326	parachain_config: &Configuration,327	telemetry_worker_handle: Option<TelemetryWorkerHandle>,328	task_manager: &mut TaskManager,329	collator_options: CollatorOptions,330	hwbench: Option<sc_sysinfo::HwBench>,331) -> RelayChainResult<(332	Arc<(dyn RelayChainInterface + 'static)>,333	Option<CollatorPair>,334)> {335	match collator_options.relay_chain_rpc_url {336		Some(relay_chain_url) => build_minimal_relay_chain_node(337			polkadot_config,338			task_manager,339			relay_chain_url,340		).await,341		None => build_inprocess_relay_chain(342			polkadot_config,343			parachain_config,344			telemetry_worker_handle,345			task_manager,346			hwbench,347		),348	}349}350351/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.352///353/// This is the actual implementation that is abstract over the executor and the runtime api.354#[sc_tracing::logging::prefix_logs_with("Parachain")]355async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(356	parachain_config: Configuration,357	polkadot_config: Configuration,358	collator_options: CollatorOptions,359	id: ParaId,360	build_import_queue: BIQ,361	build_consensus: BIC,362	hwbench: Option<sc_sysinfo::HwBench>,363) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>364where365	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,366	Runtime: RuntimeInstance + Send + Sync + 'static,367	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,368	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,369	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>370		+ Send371		+ Sync372		+ 'static,373	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>374		+ fp_rpc::EthereumRuntimeRPCApi<Block>375		+ fp_rpc::ConvertTransactionRuntimeApi<Block>376		+ sp_session::SessionKeys<Block>377		+ sp_block_builder::BlockBuilder<Block>378		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>379		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>380		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>381		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>382		+ rmrk_rpc::RmrkApi<383			Block,384			AccountId,385			RmrkCollectionInfo<AccountId>,386			RmrkInstanceInfo<AccountId>,387			RmrkResourceInfo,388			RmrkPropertyInfo,389			RmrkBaseInfo<AccountId>,390			RmrkPartType,391			RmrkTheme,392		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>393		+ sp_api::Metadata<Block>394		+ sp_offchain::OffchainWorkerApi<Block>395		+ cumulus_primitives_core::CollectCollationInfo<Block>,396	ExecutorDispatch: NativeExecutionDispatch + 'static,397	BIQ: FnOnce(398		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,399		&Configuration,400		Option<TelemetryHandle>,401		&TaskManager,402	) -> Result<403		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,404		sc_service::Error,405	>,406	BIC: FnOnce(407		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,408		Option<&Registry>,409		Option<TelemetryHandle>,410		&TaskManager,411		Arc<dyn RelayChainInterface>,412		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,413		Arc<NetworkService<Block, Hash>>,414		SyncCryptoStorePtr,415		bool,416	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,417{418	let parachain_config = prepare_node_config(parachain_config);419420	let params =421		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;422	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =423		params.other;424425	let client = params.client.clone();426	let backend = params.backend.clone();427	let mut task_manager = params.task_manager;428429	let (relay_chain_interface, collator_key) = build_relay_chain_interface(430		polkadot_config,431		&parachain_config,432		telemetry_worker_handle,433		&mut task_manager,434		collator_options.clone(),435		hwbench.clone(),436	)437	.await438	.map_err(|e| match e {439		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,440		s => s.to_string().into(),441	})?;442443	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);444445	let force_authoring = parachain_config.force_authoring;446	let validator = parachain_config.role.is_authority();447	let prometheus_registry = parachain_config.prometheus_registry().cloned();448	let transaction_pool = params.transaction_pool.clone();449	let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);450451	let (network, system_rpc_tx, tx_handler_controller, start_network) =452		sc_service::build_network(sc_service::BuildNetworkParams {453			config: &parachain_config,454			client: client.clone(),455			transaction_pool: transaction_pool.clone(),456			spawn_handle: task_manager.spawn_handle(),457			import_queue: import_queue.clone(),458			block_announce_validator_builder: Some(Box::new(|_| {459				Box::new(block_announce_validator)460			})),461			warp_sync: None,462		})?;463464	let rpc_client = client.clone();465	let rpc_pool = transaction_pool.clone();466	let select_chain = params.select_chain.clone();467	let rpc_network = network.clone();468469	let rpc_frontier_backend = frontier_backend.clone();470471	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(472		task_manager.spawn_handle(),473		overrides_handle::<_, _, Runtime>(client.clone()),474		50,475		50,476		prometheus_registry.clone(),477	));478479	task_manager.spawn_essential_handle().spawn(480		"frontier-mapping-sync-worker",481		None,482		MappingSyncWorker::new(483			client.import_notification_stream(),484			Duration::new(6, 0),485			client.clone(),486			backend.clone(),487			frontier_backend.clone(),488			3,489			0,490			SyncStrategy::Normal,491		)492		.for_each(|()| futures::future::ready(())),493	);494495	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {496		let full_deps = unique_rpc::FullDeps {497			backend: rpc_frontier_backend.clone(),498			deny_unsafe,499			client: rpc_client.clone(),500			pool: rpc_pool.clone(),501			graph: rpc_pool.pool().clone(),502			// TODO: Unhardcode503			enable_dev_signer: false,504			filter_pool: filter_pool.clone(),505			network: rpc_network.clone(),506			select_chain: select_chain.clone(),507			is_authority: validator,508			// TODO: Unhardcode509			max_past_logs: 10000,510			block_data_cache: block_data_cache.clone(),511			fee_history_cache: fee_history_cache.clone(),512			// TODO: Unhardcode513			fee_history_limit: 2048,514		};515516		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(517			full_deps,518			subscription_task_executor,519		)520		.map_err(Into::into)521	});522523	sc_service::spawn_tasks(sc_service::SpawnTasksParams {524		rpc_builder,525		client: client.clone(),526		transaction_pool: transaction_pool.clone(),527		task_manager: &mut task_manager,528		config: parachain_config,529		keystore: params.keystore_container.sync_keystore(),530		backend: backend.clone(),531		network: network.clone(),532		system_rpc_tx,533		telemetry: telemetry.as_mut(),534		tx_handler_controller,535	})?;536537	if let Some(hwbench) = hwbench {538		sc_sysinfo::print_hwbench(&hwbench);539540		if let Some(ref mut telemetry) = telemetry {541			let telemetry_handle = telemetry.handle();542			task_manager.spawn_handle().spawn(543				"telemetry_hwbench",544				None,545				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),546			);547		}548	}549550	let announce_block = {551		let network = network.clone();552		Arc::new(Box::new(move |hash, data| {553			network.announce_block(hash, data)554		}))555	};556557	let relay_chain_slot_duration = Duration::from_secs(6);558559	if validator {560		let parachain_consensus = build_consensus(561			client.clone(),562			prometheus_registry.as_ref(),563			telemetry.as_ref().map(|t| t.handle()),564			&task_manager,565			relay_chain_interface.clone(),566			transaction_pool,567			network,568			params.keystore_container.sync_keystore(),569			force_authoring,570		)?;571572		let spawner = task_manager.spawn_handle();573574		let params = StartCollatorParams {575			para_id: id,576			block_status: client.clone(),577			announce_block,578			client: client.clone(),579			task_manager: &mut task_manager,580			spawner,581			parachain_consensus,582			import_queue,583			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),584			relay_chain_interface,585			relay_chain_slot_duration,586		};587588		start_collator(params).await?;589	} else {590		let params = StartFullNodeParams {591			client: client.clone(),592			announce_block,593			task_manager: &mut task_manager,594			para_id: id,595			import_queue,596			relay_chain_interface,597			relay_chain_slot_duration,598		};599600		start_full_node(params)?;601	}602603	start_network.start_network();604605	Ok((task_manager, client))606}607608/// Build the import queue for the the parachain runtime.609pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(610	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,611	config: &Configuration,612	telemetry: Option<TelemetryHandle>,613	task_manager: &TaskManager,614) -> Result<615	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,616	sc_service::Error,617>618where619	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>620		+ Send621		+ Sync622		+ 'static,623	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>624		+ sp_block_builder::BlockBuilder<Block>625		+ sp_consensus_aura::AuraApi<Block, AuraId>626		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,627	ExecutorDispatch: NativeExecutionDispatch + 'static,628{629	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;630631	let block_import = ParachainBlockImport::new(client.clone());632633	cumulus_client_consensus_aura::import_queue::<634		sp_consensus_aura::sr25519::AuthorityPair,635		_,636		_,637		_,638		_,639		_,640	>(cumulus_client_consensus_aura::ImportQueueParams {641		block_import,642		client: client.clone(),643		create_inherent_data_providers: move |_, _| async move {644			let time = sp_timestamp::InherentDataProvider::from_system_time();645646			let slot =647				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(648					*time,649					slot_duration,650				);651652			Ok((slot, time))653		},654		registry: config.prometheus_registry(),655		spawner: &task_manager.spawn_essential_handle(),656		telemetry,657	})658	.map_err(Into::into)659}660661/// Start a normal parachain node.662pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(663	parachain_config: Configuration,664	polkadot_config: Configuration,665	collator_options: CollatorOptions,666	id: ParaId,667	hwbench: Option<sc_sysinfo::HwBench>,668) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>669where670	Runtime: RuntimeInstance + Send + Sync + 'static,671	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,672	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,673	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>674		+ Send675		+ Sync676		+ 'static,677	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>678		+ fp_rpc::EthereumRuntimeRPCApi<Block>679		+ fp_rpc::ConvertTransactionRuntimeApi<Block>680		+ sp_session::SessionKeys<Block>681		+ sp_block_builder::BlockBuilder<Block>682		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>683		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>684		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>685		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>686		+ rmrk_rpc::RmrkApi<687			Block,688			AccountId,689			RmrkCollectionInfo<AccountId>,690			RmrkInstanceInfo<AccountId>,691			RmrkResourceInfo,692			RmrkPropertyInfo,693			RmrkBaseInfo<AccountId>,694			RmrkPartType,695			RmrkTheme,696		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>697		+ sp_api::Metadata<Block>698		+ sp_offchain::OffchainWorkerApi<Block>699		+ cumulus_primitives_core::CollectCollationInfo<Block>700		+ sp_consensus_aura::AuraApi<Block, AuraId>,701	ExecutorDispatch: NativeExecutionDispatch + 'static,702{703	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(704		parachain_config,705		polkadot_config,706		collator_options,707		id,708		parachain_build_import_queue,709		|client,710		 prometheus_registry,711		 telemetry,712		 task_manager,713		 relay_chain_interface,714		 transaction_pool,715		 sync_oracle,716		 keystore,717		 force_authoring| {718			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;719720			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(721				task_manager.spawn_handle(),722				client.clone(),723				transaction_pool,724				prometheus_registry,725				telemetry.clone(),726			);727728			let block_import = ParachainBlockImport::new(client.clone());729730			Ok(AuraConsensus::build::<731				sp_consensus_aura::sr25519::AuthorityPair,732				_,733				_,734				_,735				_,736				_,737				_,738			>(BuildAuraConsensusParams {739				proposer_factory,740				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {741					let relay_chain_interface = relay_chain_interface.clone();742					async move {743						let parachain_inherent =744						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(745							relay_parent,746							&relay_chain_interface,747							&validation_data,748							id,749						).await;750751						let time = sp_timestamp::InherentDataProvider::from_system_time();752753						let slot =754						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(755							*time,756							slot_duration,757						);758759						let parachain_inherent = parachain_inherent.ok_or_else(|| {760							Box::<dyn std::error::Error + Send + Sync>::from(761								"Failed to create parachain inherent",762							)763						})?;764						Ok((slot, time, parachain_inherent))765					}766				},767				block_import,768				para_client: client,769				backoff_authoring_blocks: Option::<()>::None,770				sync_oracle,771				keystore,772				force_authoring,773				slot_duration,774				// We got around 500ms for proposing775				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),776				telemetry,777				max_block_proposal_slot_portion: None,778			}))779		},780		hwbench,781	)782	.await783}784785fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(786	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,787	config: &Configuration,788	_: Option<TelemetryHandle>,789	task_manager: &TaskManager,790) -> Result<791	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,792	sc_service::Error,793>794where795	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>796		+ Send797		+ Sync798		+ 'static,799	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>800		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,801	ExecutorDispatch: NativeExecutionDispatch + 'static,802{803	Ok(sc_consensus_manual_seal::import_queue(804		Box::new(client.clone()),805		&task_manager.spawn_essential_handle(),806		config.prometheus_registry(),807	))808}809810/// Builds a new development service. This service uses instant seal, and mocks811/// the parachain inherent812pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(813	config: Configuration,814	autoseal_interval: Duration,815) -> sc_service::error::Result<TaskManager>816where817	Runtime: RuntimeInstance + Send + Sync + 'static,818	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,819	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,820	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>821		+ Send822		+ Sync823		+ 'static,824	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>825		+ fp_rpc::EthereumRuntimeRPCApi<Block>826		+ fp_rpc::ConvertTransactionRuntimeApi<Block>827		+ sp_session::SessionKeys<Block>828		+ sp_block_builder::BlockBuilder<Block>829		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>830		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>831		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>832		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>833		+ rmrk_rpc::RmrkApi<834			Block,835			AccountId,836			RmrkCollectionInfo<AccountId>,837			RmrkInstanceInfo<AccountId>,838			RmrkResourceInfo,839			RmrkPropertyInfo,840			RmrkBaseInfo<AccountId>,841			RmrkPartType,842			RmrkTheme,843		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>844		+ sp_api::Metadata<Block>845		+ sp_offchain::OffchainWorkerApi<Block>846		+ cumulus_primitives_core::CollectCollationInfo<Block>847		+ sp_consensus_aura::AuraApi<Block, AuraId>,848	ExecutorDispatch: NativeExecutionDispatch + 'static,849{850	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};851	use fc_consensus::FrontierBlockImport;852	use sc_client_api::HeaderBackend;853854	let sc_service::PartialComponents {855		client,856		backend,857		mut task_manager,858		import_queue,859		keystore_container,860		select_chain: maybe_select_chain,861		transaction_pool,862		other:863			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),864	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(865		&config,866		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,867	)?;868	let prometheus_registry = config.prometheus_registry().cloned();869870	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(871		task_manager.spawn_handle(),872		overrides_handle::<_, _, Runtime>(client.clone()),873		50,874		50,875		prometheus_registry.clone(),876	));877878	let (network, system_rpc_tx, tx_handler_controller, network_starter) =879		sc_service::build_network(sc_service::BuildNetworkParams {880			config: &config,881			client: client.clone(),882			transaction_pool: transaction_pool.clone(),883			spawn_handle: task_manager.spawn_handle(),884			import_queue,885			block_announce_validator_builder: None,886			warp_sync: None,887		})?;888889	if config.offchain_worker.enabled {890		sc_service::build_offchain_workers(891			&config,892			task_manager.spawn_handle(),893			client.clone(),894			network.clone(),895		);896	}897898	let collator = config.role.is_authority();899900	let select_chain = maybe_select_chain.clone();901902	if collator {903		let block_import =904			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());905906		let env = sc_basic_authorship::ProposerFactory::new(907			task_manager.spawn_handle(),908			client.clone(),909			transaction_pool.clone(),910			prometheus_registry.as_ref(),911			telemetry.as_ref().map(|x| x.handle()),912		);913914		let transactions_commands_stream: Box<915			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,916		> = Box::new(917			transaction_pool918				.pool()919				.validated_pool()920				.import_notification_stream()921				.map(|_| EngineCommand::SealNewBlock {922					create_empty: true,923					finalize: false,924					parent_hash: None,925					sender: None,926				}),927		);928929		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));930		let idle_commands_stream: Box<931			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,932		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {933			create_empty: true,934			finalize: false,935			parent_hash: None,936			sender: None,937		}));938939		let commands_stream = select(transactions_commands_stream, idle_commands_stream);940941		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;942		let client_set_aside_for_cidp = client.clone();943944		task_manager.spawn_essential_handle().spawn_blocking(945			"authorship_task",946			Some("block-authoring"),947			run_manual_seal(ManualSealParams {948				block_import,949				env,950				client: client.clone(),951				pool: transaction_pool.clone(),952				commands_stream,953				select_chain: select_chain.clone(),954				consensus_data_provider: None,955				create_inherent_data_providers: move |block: Hash, ()| {956					let current_para_block = client_set_aside_for_cidp957						.number(block)958						.expect("Header lookup should succeed")959						.expect("Header passed in as parent should be present in backend.");960961					let client_for_xcm = client_set_aside_for_cidp.clone();962					async move {963						let time = sp_timestamp::InherentDataProvider::from_system_time();964965						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {966							current_para_block,967							relay_offset: 1000,968							relay_blocks_per_para_block: 2,969							para_blocks_per_relay_epoch: 0,970							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(971								&*client_for_xcm,972								block,973								Default::default(),974								Default::default(),975							),976							relay_randomness_config: (),977							raw_downward_messages: vec![],978							raw_horizontal_messages: vec![],979						};980981						let slot =982						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(983							*time,984							slot_duration,985						);986987						Ok((time, slot, mocked_parachain))988					}989				},990			}),991		);992	}993994	task_manager.spawn_essential_handle().spawn(995		"frontier-mapping-sync-worker",996		Some("block-authoring"),997		MappingSyncWorker::new(998			client.import_notification_stream(),999			Duration::new(6, 0),1000			client.clone(),1001			backend.clone(),1002			frontier_backend.clone(),1003			3,1004			0,1005			SyncStrategy::Normal,1006		)1007		.for_each(|()| futures::future::ready(())),1008	);10091010	let rpc_client = client.clone();1011	let rpc_pool = transaction_pool.clone();1012	let rpc_network = network.clone();1013	let rpc_frontier_backend = frontier_backend.clone();1014	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1015		let full_deps = unique_rpc::FullDeps {1016			backend: rpc_frontier_backend.clone(),1017			deny_unsafe,1018			client: rpc_client.clone(),1019			pool: rpc_pool.clone(),1020			graph: rpc_pool.pool().clone(),1021			// TODO: Unhardcode1022			enable_dev_signer: false,1023			filter_pool: filter_pool.clone(),1024			network: rpc_network.clone(),1025			select_chain: select_chain.clone(),1026			is_authority: collator,1027			// TODO: Unhardcode1028			max_past_logs: 10000,1029			block_data_cache: block_data_cache.clone(),1030			fee_history_cache: fee_history_cache.clone(),1031			// TODO: Unhardcode1032			fee_history_limit: 2048,1033		};10341035		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1036			full_deps,1037			subscription_executor,1038		)1039		.map_err(Into::into)1040	});10411042	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1043		network,1044		client,1045		keystore: keystore_container.sync_keystore(),1046		task_manager: &mut task_manager,1047		transaction_pool,1048		rpc_builder,1049		backend,1050		system_rpc_tx,1051		config,1052		telemetry: None,1053		tx_handler_controller,1054	})?;10551056	network_starter.start_network();1057	Ok(task_manager)1058}