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

difftreelog

feat add cli param disable-autoseal-on-tx

Daniel Shiposha2023-10-02parent: #74a28c8.patch.diff
in: master

3 files changed

modifiednode/cli/src/cli.rsdiffbeforeafterboth
--- a/node/cli/src/cli.rs
+++ b/node/cli/src/cli.rs
@@ -84,6 +84,10 @@
 	#[structopt(default_value = "500", long)]
 	pub idle_autoseal_interval: u64,
 
+	/// Disable auto-sealing blocks on new transactions in the `--dev` mode.
+	#[structopt(long)]
+	pub disable_autoseal_on_tx: bool,
+
 	/// Disable automatic hardware benchmarks.
 	///
 	/// By default these benchmarks are automatically ran at startup and measure
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -488,7 +488,7 @@
 					config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);
 
 					return start_node_using_chain_runtime! {
-						start_dev_node(config, autoseal_interval).map_err(Into::into)
+						start_dev_node(config, autoseal_interval, cli.disable_autoseal_on_tx).map_err(Into::into)
 					};
 				};
 
modifiednode/cli/src/service.rsdiffbeforeafterboth
before · node/cli/src/service.rs
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_mapping_sync::EthereumBlockNotificationSinks;24use fc_rpc::EthBlockDataCacheTask;25use fc_rpc::EthTask;26use fc_rpc_core::types::FeeHistoryCache;27use futures::{28	Stream, StreamExt,29	stream::select,30	task::{Context, Poll},31};32use sc_rpc::SubscriptionTaskExecutor;33use sp_keystore::KeystorePtr;34use tokio::time::Interval;35use jsonrpsee::RpcModule;3637use serde::{Serialize, Deserialize};3839// Cumulus Imports40use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};41use cumulus_client_consensus_common::{42	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,43};44use cumulus_client_service::{45	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,46};47use cumulus_client_cli::CollatorOptions;48use cumulus_client_network::BlockAnnounceValidator;49use cumulus_primitives_core::ParaId;50use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;51use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};52use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5354// Substrate Imports55use sp_api::{BlockT, HeaderT, ProvideRuntimeApi, StateBackend};56use sc_executor::NativeElseWasmExecutor;57use sc_executor::NativeExecutionDispatch;58use sc_network::NetworkBlock;59use sc_network_sync::SyncingService;60use sc_service::{Configuration, PartialComponents, TaskManager};61use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};62use sp_runtime::traits::BlakeTwo256;63use substrate_prometheus_endpoint::Registry;64use sc_client_api::{BlockchainEvents, BlockOf, Backend, AuxStore, StorageProvider};65use sp_blockchain::{HeaderBackend, HeaderMetadata, Error as BlockChainError};66use sc_consensus::ImportQueue;67use sp_core::H256;68use sp_block_builder::BlockBuilder;6970use polkadot_service::CollatorPair;7172// Frontier Imports73use fc_rpc_core::types::FilterPool;74use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};75use fc_rpc::{76	StorageOverride, OverrideHandle, SchemaV1Override, SchemaV2Override, SchemaV3Override,77	RuntimeApiStorageOverride,78};79use fp_rpc::EthereumRuntimeRPCApi;80use fp_storage::EthereumStorageSchema;8182use up_common::types::opaque::*;8384use crate::chain_spec::RuntimeIdentification;8586/// Unique native executor instance.87#[cfg(feature = "unique-runtime")]88pub struct UniqueRuntimeExecutor;8990#[cfg(feature = "quartz-runtime")]91/// Quartz native executor instance.92pub struct QuartzRuntimeExecutor;9394/// Opal native executor instance.95pub struct OpalRuntimeExecutor;9697#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]98pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	feature = "quartz-runtime",103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;106107#[cfg(all(108	not(feature = "unique-runtime"),109	not(feature = "quartz-runtime"),110	feature = "runtime-benchmarks"111))]112pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;113114#[cfg(feature = "unique-runtime")]115impl NativeExecutionDispatch for UniqueRuntimeExecutor {116	/// Only enable the benchmarking host functions when we actually want to benchmark.117	#[cfg(feature = "runtime-benchmarks")]118	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;119	/// Otherwise we only use the default Substrate host functions.120	#[cfg(not(feature = "runtime-benchmarks"))]121	type ExtendHostFunctions = ();122123	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124		unique_runtime::api::dispatch(method, data)125	}126127	fn native_version() -> sc_executor::NativeVersion {128		unique_runtime::native_version()129	}130}131132#[cfg(feature = "quartz-runtime")]133impl NativeExecutionDispatch for QuartzRuntimeExecutor {134	/// Only enable the benchmarking host functions when we actually want to benchmark.135	#[cfg(feature = "runtime-benchmarks")]136	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;137	/// Otherwise we only use the default Substrate host functions.138	#[cfg(not(feature = "runtime-benchmarks"))]139	type ExtendHostFunctions = ();140141	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {142		quartz_runtime::api::dispatch(method, data)143	}144145	fn native_version() -> sc_executor::NativeVersion {146		quartz_runtime::native_version()147	}148}149150impl NativeExecutionDispatch for OpalRuntimeExecutor {151	/// Only enable the benchmarking host functions when we actually want to benchmark.152	#[cfg(feature = "runtime-benchmarks")]153	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;154	/// Otherwise we only use the default Substrate host functions.155	#[cfg(not(feature = "runtime-benchmarks"))]156	type ExtendHostFunctions = ();157158	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {159		opal_runtime::api::dispatch(method, data)160	}161162	fn native_version() -> sc_executor::NativeVersion {163		opal_runtime::native_version()164	}165}166167pub struct AutosealInterval {168	interval: Interval,169}170171impl AutosealInterval {172	pub fn new(config: &Configuration, interval: Duration) -> Self {173		let _tokio_runtime = config.tokio_handle.enter();174		let interval = tokio::time::interval(interval);175176		Self { interval }177	}178}179180impl Stream for AutosealInterval {181	type Item = tokio::time::Instant;182183	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {184		self.interval.poll_tick(cx).map(Some)185	}186}187188pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(189	client: Arc<C>,190	config: &Configuration,191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {192	let config_dir = config.base_path.config_dir(config.chain_spec.id());193	let database_dir = config_dir.join("frontier").join("db");194195	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(196		client,197		&fc_db::kv::DatabaseSettings {198			source: fc_db::DatabaseSource::RocksDb {199				path: database_dir,200				cache_size: 0,201			},202		},203	)?))204}205206type FullClient<RuntimeApi, ExecutorDispatch> =207	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;208type FullBackend = sc_service::TFullBackend<Block>;209type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =211	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;212213/// Starts a `ServiceBuilder` for a full service.214///215/// Use this macro if you don't actually need the full service, but just the builder in order to216/// be able to perform chain operations.217#[allow(clippy::type_complexity)]218pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(219	config: &Configuration,220	build_import_queue: BIQ,221) -> Result<222	PartialComponents<223		FullClient<RuntimeApi, ExecutorDispatch>,224		FullBackend,225		FullSelectChain,226		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,228		OtherPartial,229	>,230	sc_service::Error,231>232where233	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,234	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>235		+ Send236		+ Sync237		+ 'static,238	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,239	ExecutorDispatch: NativeExecutionDispatch + 'static,240	BIQ: FnOnce(241		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,242		Arc<FullBackend>,243		&Configuration,244		Option<TelemetryHandle>,245		&TaskManager,246	) -> Result<247		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,248		sc_service::Error,249	>,250{251	let telemetry = config252		.telemetry_endpoints253		.clone()254		.filter(|x| !x.is_empty())255		.map(|endpoints| -> Result<_, sc_telemetry::Error> {256			let worker = TelemetryWorker::new(16)?;257			let telemetry = worker.handle().new_telemetry(endpoints);258			Ok((worker, telemetry))259		})260		.transpose()?;261262	let executor = sc_service::new_native_or_wasm_executor(config);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 eth_filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));292293	let eth_backend = open_frontier_backend(client.clone(), config)?;294295	let import_queue = build_import_queue(296		client.clone(),297		backend.clone(),298		config,299		telemetry.as_ref().map(|telemetry| telemetry.handle()),300		&task_manager,301	)?;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: OtherPartial {312			telemetry,313			eth_filter_pool,314			eth_backend,315			telemetry_worker_handle,316		},317	};318319	Ok(params)320}321322async fn build_relay_chain_interface(323	polkadot_config: Configuration,324	parachain_config: &Configuration,325	telemetry_worker_handle: Option<TelemetryWorkerHandle>,326	task_manager: &mut TaskManager,327	collator_options: CollatorOptions,328	hwbench: Option<sc_sysinfo::HwBench>,329) -> RelayChainResult<(330	Arc<(dyn RelayChainInterface + 'static)>,331	Option<CollatorPair>,332)> {333	if collator_options.relay_chain_rpc_urls.is_empty() {334		build_inprocess_relay_chain(335			polkadot_config,336			parachain_config,337			telemetry_worker_handle,338			task_manager,339			hwbench,340		)341	} else {342		build_minimal_relay_chain_node(343			polkadot_config,344			task_manager,345			collator_options.relay_chain_rpc_urls,346		)347		.await348	}349}350351macro_rules! clone {352    ($($i:ident),* $(,)?) => {353		$(354			let $i = $i.clone();355		)*356    };357}358359/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.360///361/// This is the actual implementation that is abstract over the executor and the runtime api.362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364	parachain_config: Configuration,365	polkadot_config: Configuration,366	collator_options: CollatorOptions,367	id: ParaId,368	build_import_queue: BIQ,369	build_consensus: BIC,370	hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374	Runtime: RuntimeInstance + Send + Sync + 'static,375	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,376	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378		+ Send379		+ Sync380		+ 'static,381	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382		+ fp_rpc::EthereumRuntimeRPCApi<Block>383		+ fp_rpc::ConvertTransactionRuntimeApi<Block>384		+ sp_session::SessionKeys<Block>385		+ sp_block_builder::BlockBuilder<Block>386		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390		+ up_pov_estimate_rpc::PovEstimateApi<Block>391		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>392		+ sp_api::Metadata<Block>393		+ sp_offchain::OffchainWorkerApi<Block>394		+ cumulus_primitives_core::CollectCollationInfo<Block>,395	ExecutorDispatch: NativeExecutionDispatch + 'static,396	BIQ: FnOnce(397		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,398		Arc<FullBackend>,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		Arc<FullBackend>,409		Option<&Registry>,410		Option<TelemetryHandle>,411		&TaskManager,412		Arc<dyn RelayChainInterface>,413		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,414		Arc<SyncingService<Block>>,415		KeystorePtr,416		bool,417	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,418{419	let parachain_config = prepare_node_config(parachain_config);420421	let params =422		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;423	let OtherPartial {424		mut telemetry,425		telemetry_worker_handle,426		eth_filter_pool,427		eth_backend,428	} = params.other;429	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);430431	let client = params.client.clone();432	let backend = params.backend.clone();433	let mut task_manager = params.task_manager;434435	let (relay_chain_interface, collator_key) = build_relay_chain_interface(436		polkadot_config,437		&parachain_config,438		telemetry_worker_handle,439		&mut task_manager,440		collator_options.clone(),441		hwbench.clone(),442	)443	.await444	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;445446	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);447448	let force_authoring = parachain_config.force_authoring;449	let validator = parachain_config.role.is_authority();450	let prometheus_registry = parachain_config.prometheus_registry().cloned();451	let transaction_pool = params.transaction_pool.clone();452	let import_queue_service = params.import_queue.service();453454	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =455		sc_service::build_network(sc_service::BuildNetworkParams {456			config: &parachain_config,457			net_config,458			client: client.clone(),459			transaction_pool: transaction_pool.clone(),460			spawn_handle: task_manager.spawn_handle(),461			import_queue: params.import_queue,462			block_announce_validator_builder: Some(Box::new(|_| {463				Box::new(block_announce_validator)464			})),465			warp_sync_params: None,466		})?;467468	let select_chain = params.select_chain.clone();469470	let runtime_id = parachain_config.chain_spec.runtime_id();471472	// Frontier473	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));474	let fee_history_limit = 2048;475476	let eth_pubsub_notification_sinks: Arc<477		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,478	> = Default::default();479480	let overrides = overrides_handle(client.clone());481	let eth_block_data_cache = spawn_frontier_tasks(482		FrontierTaskParams {483			client: client.clone(),484			substrate_backend: backend.clone(),485			eth_filter_pool: eth_filter_pool.clone(),486			eth_backend: eth_backend.clone(),487			fee_history_limit,488			fee_history_cache: fee_history_cache.clone(),489			task_manager: &task_manager,490			prometheus_registry: prometheus_registry.clone(),491			overrides: overrides.clone(),492			sync_strategy: SyncStrategy::Parachain,493		},494		sync_service.clone(),495		eth_pubsub_notification_sinks.clone(),496	);497498	// Rpc499	let rpc_builder = Box::new({500		clone!(501			client,502			backend,503			eth_backend,504			eth_pubsub_notification_sinks,505			fee_history_cache,506			eth_block_data_cache,507			overrides,508			transaction_pool,509			network,510			sync_service,511		);512		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {513			clone!(514				backend,515				eth_block_data_cache,516				client,517				eth_backend,518				eth_filter_pool,519				eth_pubsub_notification_sinks,520				fee_history_cache,521				eth_block_data_cache,522				network,523				runtime_id,524				transaction_pool,525				select_chain,526				overrides,527			);528529			#[cfg(not(feature = "pov-estimate"))]530			let _ = backend;531532			let mut rpc_handle = RpcModule::new(());533534			let full_deps = unique_rpc::FullDeps {535				client: client.clone(),536				runtime_id,537538				#[cfg(feature = "pov-estimate")]539				exec_params: uc_rpc::pov_estimate::ExecutorParams {540					wasm_method: parachain_config.wasm_method,541					default_heap_pages: parachain_config.default_heap_pages,542					max_runtime_instances: parachain_config.max_runtime_instances,543					runtime_cache_size: parachain_config.runtime_cache_size,544				},545546				#[cfg(feature = "pov-estimate")]547				backend,548549				deny_unsafe,550				pool: transaction_pool.clone(),551				select_chain,552			};553554			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;555556			let eth_deps = unique_rpc::EthDeps {557				client,558				graph: transaction_pool.pool().clone(),559				pool: transaction_pool,560				is_authority: validator,561				network,562				eth_backend,563				// TODO: Unhardcode564				max_past_logs: 10000,565				fee_history_limit,566				fee_history_cache,567				eth_block_data_cache,568				// TODO: Unhardcode569				enable_dev_signer: false,570				eth_filter_pool,571				eth_pubsub_notification_sinks,572				overrides,573				sync: sync_service.clone(),574			};575576			unique_rpc::create_eth(577				&mut rpc_handle,578				eth_deps,579				subscription_task_executor.clone(),580			)?;581582			Ok(rpc_handle)583		}584	});585586	sc_service::spawn_tasks(sc_service::SpawnTasksParams {587		rpc_builder,588		client: client.clone(),589		transaction_pool: transaction_pool.clone(),590		task_manager: &mut task_manager,591		config: parachain_config,592		keystore: params.keystore_container.keystore(),593		backend: backend.clone(),594		network: network.clone(),595		sync_service: sync_service.clone(),596		system_rpc_tx,597		telemetry: telemetry.as_mut(),598		tx_handler_controller,599	})?;600601	if let Some(hwbench) = hwbench {602		sc_sysinfo::print_hwbench(&hwbench);603604		if let Some(ref mut telemetry) = telemetry {605			let telemetry_handle = telemetry.handle();606			task_manager.spawn_handle().spawn(607				"telemetry_hwbench",608				None,609				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),610			);611		}612	}613614	let announce_block = {615		let sync_service = sync_service.clone();616		Arc::new(Box::new(move |hash, data| {617			sync_service.announce_block(hash, data)618		}))619	};620621	let relay_chain_slot_duration = Duration::from_secs(6);622623	let overseer_handle = relay_chain_interface624		.overseer_handle()625		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;626627	if validator {628		let parachain_consensus = build_consensus(629			client.clone(),630			backend.clone(),631			prometheus_registry.as_ref(),632			telemetry.as_ref().map(|t| t.handle()),633			&task_manager,634			relay_chain_interface.clone(),635			transaction_pool,636			sync_service.clone(),637			params.keystore_container.keystore(),638			force_authoring,639		)?;640641		let spawner = task_manager.spawn_handle();642643		let params = StartCollatorParams {644			para_id: id,645			block_status: client.clone(),646			announce_block,647			client: client.clone(),648			task_manager: &mut task_manager,649			spawner,650			parachain_consensus,651			import_queue: import_queue_service,652			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),653			relay_chain_interface,654			relay_chain_slot_duration,655			recovery_handle: Box::new(overseer_handle),656			sync_service,657		};658659		start_collator(params).await?;660	} else {661		let params = StartFullNodeParams {662			client: client.clone(),663			announce_block,664			task_manager: &mut task_manager,665			para_id: id,666			import_queue: import_queue_service,667			relay_chain_interface,668			relay_chain_slot_duration,669			recovery_handle: Box::new(overseer_handle),670			sync_service,671		};672673		start_full_node(params)?;674	}675676	start_network.start_network();677678	Ok((task_manager, client))679}680681/// Build the import queue for the the parachain runtime.682pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(683	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,684	backend: Arc<FullBackend>,685	config: &Configuration,686	telemetry: Option<TelemetryHandle>,687	task_manager: &TaskManager,688) -> Result<689	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,690	sc_service::Error,691>692where693	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>694		+ Send695		+ Sync696		+ 'static,697	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>698		+ sp_block_builder::BlockBuilder<Block>699		+ sp_consensus_aura::AuraApi<Block, AuraId>700		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,701	ExecutorDispatch: NativeExecutionDispatch + 'static,702{703	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;704705	let block_import = ParachainBlockImport::new(client.clone(), backend);706707	cumulus_client_consensus_aura::import_queue::<708		sp_consensus_aura::sr25519::AuthorityPair,709		_,710		_,711		_,712		_,713		_,714	>(cumulus_client_consensus_aura::ImportQueueParams {715		block_import,716		client,717		create_inherent_data_providers: move |_, _| async move {718			let time = sp_timestamp::InherentDataProvider::from_system_time();719720			let slot =721				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(722					*time,723					slot_duration,724				);725726			Ok((slot, time))727		},728		registry: config.prometheus_registry(),729		spawner: &task_manager.spawn_essential_handle(),730		telemetry,731	})732	.map_err(Into::into)733}734735/// Start a normal parachain node.736pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(737	parachain_config: Configuration,738	polkadot_config: Configuration,739	collator_options: CollatorOptions,740	id: ParaId,741	hwbench: Option<sc_sysinfo::HwBench>,742) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>743where744	Runtime: RuntimeInstance + Send + Sync + 'static,745	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,746	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,747	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>748		+ Send749		+ Sync750		+ 'static,751	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>752		+ fp_rpc::EthereumRuntimeRPCApi<Block>753		+ fp_rpc::ConvertTransactionRuntimeApi<Block>754		+ sp_session::SessionKeys<Block>755		+ sp_block_builder::BlockBuilder<Block>756		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>757		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>758		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>759		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>760		+ up_pov_estimate_rpc::PovEstimateApi<Block>761		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>762		+ sp_api::Metadata<Block>763		+ sp_offchain::OffchainWorkerApi<Block>764		+ cumulus_primitives_core::CollectCollationInfo<Block>765		+ sp_consensus_aura::AuraApi<Block, AuraId>,766	ExecutorDispatch: NativeExecutionDispatch + 'static,767{768	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(769		parachain_config,770		polkadot_config,771		collator_options,772		id,773		parachain_build_import_queue,774		|client,775		 backend,776		 prometheus_registry,777		 telemetry,778		 task_manager,779		 relay_chain_interface,780		 transaction_pool,781		 sync_oracle,782		 keystore,783		 force_authoring| {784			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;785786			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(787				task_manager.spawn_handle(),788				client.clone(),789				transaction_pool,790				prometheus_registry,791				telemetry.clone(),792			);793794			let block_import = ParachainBlockImport::new(client.clone(), backend);795796			Ok(AuraConsensus::build::<797				sp_consensus_aura::sr25519::AuthorityPair,798				_,799				_,800				_,801				_,802				_,803				_,804			>(BuildAuraConsensusParams {805				proposer_factory,806				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {807					let relay_chain_interface = relay_chain_interface.clone();808					async move {809						let parachain_inherent =810						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(811							relay_parent,812							&relay_chain_interface,813							&validation_data,814							id,815						).await;816817						let time = sp_timestamp::InherentDataProvider::from_system_time();818819						let slot =820						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(821							*time,822							slot_duration,823						);824825						let parachain_inherent = parachain_inherent.ok_or_else(|| {826							Box::<dyn std::error::Error + Send + Sync>::from(827								"Failed to create parachain inherent",828							)829						})?;830						Ok((slot, time, parachain_inherent))831					}832				},833				block_import,834				para_client: client,835				backoff_authoring_blocks: Option::<()>::None,836				sync_oracle,837				keystore,838				force_authoring,839				slot_duration,840				// We got around 500ms for proposing841				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),842				telemetry,843				max_block_proposal_slot_portion: None,844			}))845		},846		hwbench,847	)848	.await849}850851fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(852	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,853	_: Arc<FullBackend>,854	config: &Configuration,855	_: Option<TelemetryHandle>,856	task_manager: &TaskManager,857) -> Result<858	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,859	sc_service::Error,860>861where862	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>863		+ Send864		+ Sync865		+ 'static,866	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>867		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,868	ExecutorDispatch: NativeExecutionDispatch + 'static,869{870	Ok(sc_consensus_manual_seal::import_queue(871		Box::new(client),872		&task_manager.spawn_essential_handle(),873		config.prometheus_registry(),874	))875}876877pub struct OtherPartial {878	pub telemetry: Option<Telemetry>,879	pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,880	pub eth_filter_pool: Option<FilterPool>,881	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,882}883884/// Builds a new development service. This service uses instant seal, and mocks885/// the parachain inherent886pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(887	config: Configuration,888	autoseal_interval: Duration,889) -> sc_service::error::Result<TaskManager>890where891	Runtime: RuntimeInstance + Send + Sync + 'static,892	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,893	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,894	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>895		+ Send896		+ Sync897		+ 'static,898	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>899		+ fp_rpc::EthereumRuntimeRPCApi<Block>900		+ fp_rpc::ConvertTransactionRuntimeApi<Block>901		+ sp_session::SessionKeys<Block>902		+ sp_block_builder::BlockBuilder<Block>903		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>904		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>905		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>906		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>907		+ up_pov_estimate_rpc::PovEstimateApi<Block>908		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>909		+ sp_api::Metadata<Block>910		+ sp_offchain::OffchainWorkerApi<Block>911		+ cumulus_primitives_core::CollectCollationInfo<Block>912		+ sp_consensus_aura::AuraApi<Block, AuraId>,913	ExecutorDispatch: NativeExecutionDispatch + 'static,914{915	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};916	use fc_consensus::FrontierBlockImport;917918	let sc_service::PartialComponents {919		client,920		backend,921		mut task_manager,922		import_queue,923		keystore_container,924		select_chain: maybe_select_chain,925		transaction_pool,926		other:927			OtherPartial {928				telemetry,929				eth_filter_pool,930				eth_backend,931				telemetry_worker_handle: _,932			},933	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(934		&config,935		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,936	)?;937	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);938	let prometheus_registry = config.prometheus_registry().cloned();939940	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =941		sc_service::build_network(sc_service::BuildNetworkParams {942			config: &config,943			net_config,944			client: client.clone(),945			transaction_pool: transaction_pool.clone(),946			spawn_handle: task_manager.spawn_handle(),947			import_queue,948			block_announce_validator_builder: None,949			warp_sync_params: None,950		})?;951952	if config.offchain_worker.enabled {953		sc_service::build_offchain_workers(954			&config,955			task_manager.spawn_handle(),956			client.clone(),957			network.clone(),958		);959	}960961	let collator = config.role.is_authority();962963	let select_chain = maybe_select_chain;964965	if collator {966		let block_import = FrontierBlockImport::new(client.clone(), client.clone());967968		let env = sc_basic_authorship::ProposerFactory::new(969			task_manager.spawn_handle(),970			client.clone(),971			transaction_pool.clone(),972			prometheus_registry.as_ref(),973			telemetry.as_ref().map(|x| x.handle()),974		);975976		let transactions_commands_stream: Box<977			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,978		> = Box::new(979			transaction_pool980				.pool()981				.validated_pool()982				.import_notification_stream()983				.map(|_| EngineCommand::SealNewBlock {984					create_empty: true,985					finalize: false, // todo:collator finalize true986					parent_hash: None,987					sender: None,988				}),989		);990991		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));992		let idle_commands_stream: Box<993			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,994		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {995			create_empty: true,996			finalize: false, // todo:collator finalize true997			parent_hash: None,998			sender: None,999		}));10001001		let commands_stream = select(transactions_commands_stream, idle_commands_stream);10021003		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;1004		let client_set_aside_for_cidp = client.clone();10051006		task_manager.spawn_essential_handle().spawn_blocking(1007			"authorship_task",1008			Some("block-authoring"),1009			run_manual_seal(ManualSealParams {1010				block_import,1011				env,1012				client: client.clone(),1013				pool: transaction_pool.clone(),1014				commands_stream,1015				select_chain: select_chain.clone(),1016				consensus_data_provider: None,1017				create_inherent_data_providers: move |block: Hash, ()| {1018					let current_para_block = client_set_aside_for_cidp1019						.number(block)1020						.expect("Header lookup should succeed")1021						.expect("Header passed in as parent should be present in backend.");10221023					let client_for_xcm = client_set_aside_for_cidp.clone();1024					async move {1025						let time = sp_timestamp::InherentDataProvider::from_system_time();10261027						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1028							current_para_block,1029							relay_offset: 1000,1030							relay_blocks_per_para_block: 2,1031							para_blocks_per_relay_epoch: 0,1032							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1033								&*client_for_xcm,1034								block,1035								Default::default(),1036								Default::default(),1037							),1038							relay_randomness_config: (),1039							raw_downward_messages: vec![],1040							raw_horizontal_messages: vec![],1041						};10421043						let slot =1044						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1045							*time,1046							slot_duration,1047						);10481049						Ok((time, slot, mocked_parachain))1050					}1051				},1052			}),1053		);1054	}10551056	#[cfg(feature = "pov-estimate")]1057	let rpc_backend = backend.clone();10581059	let runtime_id = config.chain_spec.runtime_id();10601061	// Frontier1062	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));1063	let fee_history_limit = 2048;10641065	let eth_pubsub_notification_sinks: Arc<1066		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,1067	> = Default::default();10681069	let overrides = overrides_handle(client.clone());1070	let eth_block_data_cache = spawn_frontier_tasks(1071		FrontierTaskParams {1072			client: client.clone(),1073			substrate_backend: backend.clone(),1074			eth_filter_pool: eth_filter_pool.clone(),1075			eth_backend: eth_backend.clone(),1076			fee_history_limit,1077			fee_history_cache: fee_history_cache.clone(),1078			task_manager: &task_manager,1079			prometheus_registry,1080			overrides: overrides.clone(),1081			sync_strategy: SyncStrategy::Normal,1082		},1083		sync_service.clone(),1084		eth_pubsub_notification_sinks.clone(),1085	);10861087	// Rpc1088	let rpc_builder = Box::new({1089		clone!(1090			client,1091			backend,1092			eth_backend,1093			eth_pubsub_notification_sinks,1094			fee_history_cache,1095			eth_block_data_cache,1096			overrides,1097			transaction_pool,1098			network,1099			sync_service,1100		);1101		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {1102			clone!(1103				backend,1104				eth_block_data_cache,1105				client,1106				eth_backend,1107				eth_filter_pool,1108				eth_pubsub_notification_sinks,1109				fee_history_cache,1110				eth_block_data_cache,1111				network,1112				runtime_id,1113				transaction_pool,1114				select_chain,1115				overrides,1116			);11171118			#[cfg(not(feature = "pov-estimate"))]1119			let _ = backend;11201121			let mut rpc_module = RpcModule::new(());11221123			let full_deps = unique_rpc::FullDeps {1124				runtime_id,11251126				#[cfg(feature = "pov-estimate")]1127				exec_params: uc_rpc::pov_estimate::ExecutorParams {1128					wasm_method: config.wasm_method,1129					default_heap_pages: config.default_heap_pages,1130					max_runtime_instances: config.max_runtime_instances,1131					runtime_cache_size: config.runtime_cache_size,1132				},11331134				#[cfg(feature = "pov-estimate")]1135				backend,1136				// eth_backend,1137				deny_unsafe,1138				client: client.clone(),1139				pool: transaction_pool.clone(),1140				select_chain,1141			};11421143			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;11441145			let eth_deps = unique_rpc::EthDeps {1146				client,1147				graph: transaction_pool.pool().clone(),1148				pool: transaction_pool,1149				is_authority: true,1150				network,1151				eth_backend,1152				// TODO: Unhardcode1153				max_past_logs: 10000,1154				fee_history_limit,1155				fee_history_cache,1156				eth_block_data_cache,1157				// TODO: Unhardcode1158				enable_dev_signer: false,1159				eth_filter_pool,1160				eth_pubsub_notification_sinks,1161				overrides,1162				sync: sync_service.clone(),1163			};11641165			unique_rpc::create_eth(1166				&mut rpc_module,1167				eth_deps,1168				subscription_task_executor.clone(),1169			)?;11701171			Ok(rpc_module)1172		}1173	});11741175	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1176		network,1177		sync_service,1178		client,1179		keystore: keystore_container.keystore(),1180		task_manager: &mut task_manager,1181		transaction_pool,1182		rpc_builder,1183		backend,1184		system_rpc_tx,1185		config,1186		telemetry: None,1187		tx_handler_controller,1188	})?;11891190	network_starter.start_network();1191	Ok(task_manager)1192}11931194fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>1195where1196	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,1197	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,1198	C: Send + Sync + 'static,1199	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,1200	BE: Backend<Block> + 'static,1201	BE::State: StateBackend<BlakeTwo256>,1202{1203	let mut overrides_map = BTreeMap::new();1204	overrides_map.insert(1205		EthereumStorageSchema::V1,1206		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1207	);1208	overrides_map.insert(1209		EthereumStorageSchema::V2,1210		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1211	);1212	overrides_map.insert(1213		EthereumStorageSchema::V3,1214		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1215	);12161217	Arc::new(OverrideHandle {1218		schemas: overrides_map,1219		fallback: Box::new(RuntimeApiStorageOverride::new(client)),1220	})1221}12221223pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {1224	pub task_manager: &'a TaskManager,1225	pub client: Arc<C>,1226	pub substrate_backend: Arc<BE>,1227	pub eth_backend: Arc<fc_db::kv::Backend<B>>,1228	pub eth_filter_pool: Option<FilterPool>,1229	pub overrides: Arc<OverrideHandle<B>>,1230	pub fee_history_limit: u64,1231	pub fee_history_cache: FeeHistoryCache,1232	pub sync_strategy: SyncStrategy,1233	pub prometheus_registry: Option<Registry>,1234}12351236pub fn spawn_frontier_tasks<B, C, BE>(1237	params: FrontierTaskParams<B, C, BE>,1238	sync: Arc<SyncingService<B>>,1239	pubsub_notification_sinks: Arc<1240		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,1241	>,1242) -> Arc<EthBlockDataCacheTask<B>>1243where1244	C: ProvideRuntimeApi<B> + BlockOf,1245	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,1246	C: BlockchainEvents<B> + StorageProvider<B, BE>,1247	C: Send + Sync + 'static,1248	C::Api: EthereumRuntimeRPCApi<B>,1249	C::Api: BlockBuilder<B>,1250	B: BlockT<Hash = H256> + Send + Sync + 'static,1251	B::Header: HeaderT<Number = u32>,1252	BE: Backend<B> + 'static,1253	BE::State: StateBackend<BlakeTwo256>,1254{1255	let FrontierTaskParams {1256		task_manager,1257		client,1258		substrate_backend,1259		eth_backend,1260		eth_filter_pool,1261		overrides,1262		fee_history_limit,1263		fee_history_cache,1264		sync_strategy,1265		prometheus_registry,1266	} = params;1267	// Frontier offchain DB task. Essential.1268	// Maps emulated ethereum data to substrate native data.1269	params.task_manager.spawn_essential_handle().spawn(1270		"frontier-mapping-sync-worker",1271		Some("frontier"),1272		MappingSyncWorker::new(1273			client.import_notification_stream(),1274			Duration::new(6, 0),1275			client.clone(),1276			substrate_backend,1277			overrides.clone(),1278			eth_backend,1279			3,1280			0,1281			sync_strategy,1282			sync,1283			pubsub_notification_sinks,1284		)1285		.for_each(|()| futures::future::ready(())),1286	);12871288	// Frontier `EthFilterApi` maintenance.1289	// Manages the pool of user-created Filters.1290	if let Some(eth_filter_pool) = eth_filter_pool {1291		// Each filter is allowed to stay in the pool for 100 blocks.1292		const FILTER_RETAIN_THRESHOLD: u64 = 100;1293		params.task_manager.spawn_essential_handle().spawn(1294			"frontier-filter-pool",1295			Some("frontier"),1296			EthTask::filter_pool_task(client.clone(), eth_filter_pool, FILTER_RETAIN_THRESHOLD),1297		);1298	}12991300	// Spawn Frontier FeeHistory cache maintenance task.1301	params.task_manager.spawn_essential_handle().spawn(1302		"frontier-fee-history",1303		Some("frontier"),1304		EthTask::fee_history_task(1305			client,1306			overrides.clone(),1307			fee_history_cache,1308			fee_history_limit,1309		),1310	);13111312	Arc::new(EthBlockDataCacheTask::new(1313		task_manager.spawn_handle(),1314		overrides,1315		50,1316		50,1317		prometheus_registry,1318	))1319}
after · node/cli/src/service.rs
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_mapping_sync::EthereumBlockNotificationSinks;24use fc_rpc::EthBlockDataCacheTask;25use fc_rpc::EthTask;26use fc_rpc_core::types::FeeHistoryCache;27use futures::{28	Stream, StreamExt,29	stream::select,30	task::{Context, Poll},31};32use sc_rpc::SubscriptionTaskExecutor;33use sp_keystore::KeystorePtr;34use tokio::time::Interval;35use jsonrpsee::RpcModule;3637use serde::{Serialize, Deserialize};3839// Cumulus Imports40use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};41use cumulus_client_consensus_common::{42	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,43};44use cumulus_client_service::{45	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,46};47use cumulus_client_cli::CollatorOptions;48use cumulus_client_network::BlockAnnounceValidator;49use cumulus_primitives_core::ParaId;50use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;51use cumulus_relay_chain_interface::{RelayChainInterface, RelayChainResult};52use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;5354// Substrate Imports55use sp_api::{BlockT, HeaderT, ProvideRuntimeApi, StateBackend};56use sc_executor::NativeElseWasmExecutor;57use sc_executor::NativeExecutionDispatch;58use sc_network::NetworkBlock;59use sc_network_sync::SyncingService;60use sc_service::{Configuration, PartialComponents, TaskManager};61use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};62use sp_runtime::traits::BlakeTwo256;63use substrate_prometheus_endpoint::Registry;64use sc_client_api::{BlockchainEvents, BlockOf, Backend, AuxStore, StorageProvider};65use sp_blockchain::{HeaderBackend, HeaderMetadata, Error as BlockChainError};66use sc_consensus::ImportQueue;67use sp_core::H256;68use sp_block_builder::BlockBuilder;6970use polkadot_service::CollatorPair;7172// Frontier Imports73use fc_rpc_core::types::FilterPool;74use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};75use fc_rpc::{76	StorageOverride, OverrideHandle, SchemaV1Override, SchemaV2Override, SchemaV3Override,77	RuntimeApiStorageOverride,78};79use fp_rpc::EthereumRuntimeRPCApi;80use fp_storage::EthereumStorageSchema;8182use up_common::types::opaque::*;8384use crate::chain_spec::RuntimeIdentification;8586/// Unique native executor instance.87#[cfg(feature = "unique-runtime")]88pub struct UniqueRuntimeExecutor;8990#[cfg(feature = "quartz-runtime")]91/// Quartz native executor instance.92pub struct QuartzRuntimeExecutor;9394/// Opal native executor instance.95pub struct OpalRuntimeExecutor;9697#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]98pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	feature = "quartz-runtime",103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;106107#[cfg(all(108	not(feature = "unique-runtime"),109	not(feature = "quartz-runtime"),110	feature = "runtime-benchmarks"111))]112pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;113114#[cfg(feature = "unique-runtime")]115impl NativeExecutionDispatch for UniqueRuntimeExecutor {116	/// Only enable the benchmarking host functions when we actually want to benchmark.117	#[cfg(feature = "runtime-benchmarks")]118	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;119	/// Otherwise we only use the default Substrate host functions.120	#[cfg(not(feature = "runtime-benchmarks"))]121	type ExtendHostFunctions = ();122123	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {124		unique_runtime::api::dispatch(method, data)125	}126127	fn native_version() -> sc_executor::NativeVersion {128		unique_runtime::native_version()129	}130}131132#[cfg(feature = "quartz-runtime")]133impl NativeExecutionDispatch for QuartzRuntimeExecutor {134	/// Only enable the benchmarking host functions when we actually want to benchmark.135	#[cfg(feature = "runtime-benchmarks")]136	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;137	/// Otherwise we only use the default Substrate host functions.138	#[cfg(not(feature = "runtime-benchmarks"))]139	type ExtendHostFunctions = ();140141	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {142		quartz_runtime::api::dispatch(method, data)143	}144145	fn native_version() -> sc_executor::NativeVersion {146		quartz_runtime::native_version()147	}148}149150impl NativeExecutionDispatch for OpalRuntimeExecutor {151	/// Only enable the benchmarking host functions when we actually want to benchmark.152	#[cfg(feature = "runtime-benchmarks")]153	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;154	/// Otherwise we only use the default Substrate host functions.155	#[cfg(not(feature = "runtime-benchmarks"))]156	type ExtendHostFunctions = ();157158	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {159		opal_runtime::api::dispatch(method, data)160	}161162	fn native_version() -> sc_executor::NativeVersion {163		opal_runtime::native_version()164	}165}166167pub struct AutosealInterval {168	interval: Interval,169}170171impl AutosealInterval {172	pub fn new(config: &Configuration, interval: Duration) -> Self {173		let _tokio_runtime = config.tokio_handle.enter();174		let interval = tokio::time::interval(interval);175176		Self { interval }177	}178}179180impl Stream for AutosealInterval {181	type Item = tokio::time::Instant;182183	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {184		self.interval.poll_tick(cx).map(Some)185	}186}187188pub fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(189	client: Arc<C>,190	config: &Configuration,191) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {192	let config_dir = config.base_path.config_dir(config.chain_spec.id());193	let database_dir = config_dir.join("frontier").join("db");194195	Ok(Arc::new(fc_db::kv::Backend::<Block>::new(196		client,197		&fc_db::kv::DatabaseSettings {198			source: fc_db::DatabaseSource::RocksDb {199				path: database_dir,200				cache_size: 0,201			},202		},203	)?))204}205206type FullClient<RuntimeApi, ExecutorDispatch> =207	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;208type FullBackend = sc_service::TFullBackend<Block>;209type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;210type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =211	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;212213/// Starts a `ServiceBuilder` for a full service.214///215/// Use this macro if you don't actually need the full service, but just the builder in order to216/// be able to perform chain operations.217#[allow(clippy::type_complexity)]218pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(219	config: &Configuration,220	build_import_queue: BIQ,221) -> Result<222	PartialComponents<223		FullClient<RuntimeApi, ExecutorDispatch>,224		FullBackend,225		FullSelectChain,226		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,228		OtherPartial,229	>,230	sc_service::Error,231>232where233	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,234	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>235		+ Send236		+ Sync237		+ 'static,238	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,239	ExecutorDispatch: NativeExecutionDispatch + 'static,240	BIQ: FnOnce(241		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,242		Arc<FullBackend>,243		&Configuration,244		Option<TelemetryHandle>,245		&TaskManager,246	) -> Result<247		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,248		sc_service::Error,249	>,250{251	let telemetry = config252		.telemetry_endpoints253		.clone()254		.filter(|x| !x.is_empty())255		.map(|endpoints| -> Result<_, sc_telemetry::Error> {256			let worker = TelemetryWorker::new(16)?;257			let telemetry = worker.handle().new_telemetry(endpoints);258			Ok((worker, telemetry))259		})260		.transpose()?;261262	let executor = sc_service::new_native_or_wasm_executor(config);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 eth_filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));292293	let eth_backend = open_frontier_backend(client.clone(), config)?;294295	let import_queue = build_import_queue(296		client.clone(),297		backend.clone(),298		config,299		telemetry.as_ref().map(|telemetry| telemetry.handle()),300		&task_manager,301	)?;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: OtherPartial {312			telemetry,313			eth_filter_pool,314			eth_backend,315			telemetry_worker_handle,316		},317	};318319	Ok(params)320}321322async fn build_relay_chain_interface(323	polkadot_config: Configuration,324	parachain_config: &Configuration,325	telemetry_worker_handle: Option<TelemetryWorkerHandle>,326	task_manager: &mut TaskManager,327	collator_options: CollatorOptions,328	hwbench: Option<sc_sysinfo::HwBench>,329) -> RelayChainResult<(330	Arc<(dyn RelayChainInterface + 'static)>,331	Option<CollatorPair>,332)> {333	if collator_options.relay_chain_rpc_urls.is_empty() {334		build_inprocess_relay_chain(335			polkadot_config,336			parachain_config,337			telemetry_worker_handle,338			task_manager,339			hwbench,340		)341	} else {342		build_minimal_relay_chain_node(343			polkadot_config,344			task_manager,345			collator_options.relay_chain_rpc_urls,346		)347		.await348	}349}350351macro_rules! clone {352    ($($i:ident),* $(,)?) => {353		$(354			let $i = $i.clone();355		)*356    };357}358359/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.360///361/// This is the actual implementation that is abstract over the executor and the runtime api.362#[sc_tracing::logging::prefix_logs_with("Parachain")]363async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(364	parachain_config: Configuration,365	polkadot_config: Configuration,366	collator_options: CollatorOptions,367	id: ParaId,368	build_import_queue: BIQ,369	build_consensus: BIC,370	hwbench: Option<sc_sysinfo::HwBench>,371) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>372where373	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,374	Runtime: RuntimeInstance + Send + Sync + 'static,375	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,376	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,377	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>378		+ Send379		+ Sync380		+ 'static,381	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>382		+ fp_rpc::EthereumRuntimeRPCApi<Block>383		+ fp_rpc::ConvertTransactionRuntimeApi<Block>384		+ sp_session::SessionKeys<Block>385		+ sp_block_builder::BlockBuilder<Block>386		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>387		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>388		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>389		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>390		+ up_pov_estimate_rpc::PovEstimateApi<Block>391		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>392		+ sp_api::Metadata<Block>393		+ sp_offchain::OffchainWorkerApi<Block>394		+ cumulus_primitives_core::CollectCollationInfo<Block>,395	ExecutorDispatch: NativeExecutionDispatch + 'static,396	BIQ: FnOnce(397		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,398		Arc<FullBackend>,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		Arc<FullBackend>,409		Option<&Registry>,410		Option<TelemetryHandle>,411		&TaskManager,412		Arc<dyn RelayChainInterface>,413		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,414		Arc<SyncingService<Block>>,415		KeystorePtr,416		bool,417	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,418{419	let parachain_config = prepare_node_config(parachain_config);420421	let params =422		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;423	let OtherPartial {424		mut telemetry,425		telemetry_worker_handle,426		eth_filter_pool,427		eth_backend,428	} = params.other;429	let net_config = sc_network::config::FullNetworkConfiguration::new(&parachain_config.network);430431	let client = params.client.clone();432	let backend = params.backend.clone();433	let mut task_manager = params.task_manager;434435	let (relay_chain_interface, collator_key) = build_relay_chain_interface(436		polkadot_config,437		&parachain_config,438		telemetry_worker_handle,439		&mut task_manager,440		collator_options.clone(),441		hwbench.clone(),442	)443	.await444	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;445446	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);447448	let force_authoring = parachain_config.force_authoring;449	let validator = parachain_config.role.is_authority();450	let prometheus_registry = parachain_config.prometheus_registry().cloned();451	let transaction_pool = params.transaction_pool.clone();452	let import_queue_service = params.import_queue.service();453454	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =455		sc_service::build_network(sc_service::BuildNetworkParams {456			config: &parachain_config,457			net_config,458			client: client.clone(),459			transaction_pool: transaction_pool.clone(),460			spawn_handle: task_manager.spawn_handle(),461			import_queue: params.import_queue,462			block_announce_validator_builder: Some(Box::new(|_| {463				Box::new(block_announce_validator)464			})),465			warp_sync_params: None,466		})?;467468	let select_chain = params.select_chain.clone();469470	let runtime_id = parachain_config.chain_spec.runtime_id();471472	// Frontier473	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));474	let fee_history_limit = 2048;475476	let eth_pubsub_notification_sinks: Arc<477		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,478	> = Default::default();479480	let overrides = overrides_handle(client.clone());481	let eth_block_data_cache = spawn_frontier_tasks(482		FrontierTaskParams {483			client: client.clone(),484			substrate_backend: backend.clone(),485			eth_filter_pool: eth_filter_pool.clone(),486			eth_backend: eth_backend.clone(),487			fee_history_limit,488			fee_history_cache: fee_history_cache.clone(),489			task_manager: &task_manager,490			prometheus_registry: prometheus_registry.clone(),491			overrides: overrides.clone(),492			sync_strategy: SyncStrategy::Parachain,493		},494		sync_service.clone(),495		eth_pubsub_notification_sinks.clone(),496	);497498	// Rpc499	let rpc_builder = Box::new({500		clone!(501			client,502			backend,503			eth_backend,504			eth_pubsub_notification_sinks,505			fee_history_cache,506			eth_block_data_cache,507			overrides,508			transaction_pool,509			network,510			sync_service,511		);512		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {513			clone!(514				backend,515				eth_block_data_cache,516				client,517				eth_backend,518				eth_filter_pool,519				eth_pubsub_notification_sinks,520				fee_history_cache,521				eth_block_data_cache,522				network,523				runtime_id,524				transaction_pool,525				select_chain,526				overrides,527			);528529			#[cfg(not(feature = "pov-estimate"))]530			let _ = backend;531532			let mut rpc_handle = RpcModule::new(());533534			let full_deps = unique_rpc::FullDeps {535				client: client.clone(),536				runtime_id,537538				#[cfg(feature = "pov-estimate")]539				exec_params: uc_rpc::pov_estimate::ExecutorParams {540					wasm_method: parachain_config.wasm_method,541					default_heap_pages: parachain_config.default_heap_pages,542					max_runtime_instances: parachain_config.max_runtime_instances,543					runtime_cache_size: parachain_config.runtime_cache_size,544				},545546				#[cfg(feature = "pov-estimate")]547				backend,548549				deny_unsafe,550				pool: transaction_pool.clone(),551				select_chain,552			};553554			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_handle, full_deps)?;555556			let eth_deps = unique_rpc::EthDeps {557				client,558				graph: transaction_pool.pool().clone(),559				pool: transaction_pool,560				is_authority: validator,561				network,562				eth_backend,563				// TODO: Unhardcode564				max_past_logs: 10000,565				fee_history_limit,566				fee_history_cache,567				eth_block_data_cache,568				// TODO: Unhardcode569				enable_dev_signer: false,570				eth_filter_pool,571				eth_pubsub_notification_sinks,572				overrides,573				sync: sync_service.clone(),574			};575576			unique_rpc::create_eth(577				&mut rpc_handle,578				eth_deps,579				subscription_task_executor.clone(),580			)?;581582			Ok(rpc_handle)583		}584	});585586	sc_service::spawn_tasks(sc_service::SpawnTasksParams {587		rpc_builder,588		client: client.clone(),589		transaction_pool: transaction_pool.clone(),590		task_manager: &mut task_manager,591		config: parachain_config,592		keystore: params.keystore_container.keystore(),593		backend: backend.clone(),594		network: network.clone(),595		sync_service: sync_service.clone(),596		system_rpc_tx,597		telemetry: telemetry.as_mut(),598		tx_handler_controller,599	})?;600601	if let Some(hwbench) = hwbench {602		sc_sysinfo::print_hwbench(&hwbench);603604		if let Some(ref mut telemetry) = telemetry {605			let telemetry_handle = telemetry.handle();606			task_manager.spawn_handle().spawn(607				"telemetry_hwbench",608				None,609				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),610			);611		}612	}613614	let announce_block = {615		let sync_service = sync_service.clone();616		Arc::new(Box::new(move |hash, data| {617			sync_service.announce_block(hash, data)618		}))619	};620621	let relay_chain_slot_duration = Duration::from_secs(6);622623	let overseer_handle = relay_chain_interface624		.overseer_handle()625		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;626627	if validator {628		let parachain_consensus = build_consensus(629			client.clone(),630			backend.clone(),631			prometheus_registry.as_ref(),632			telemetry.as_ref().map(|t| t.handle()),633			&task_manager,634			relay_chain_interface.clone(),635			transaction_pool,636			sync_service.clone(),637			params.keystore_container.keystore(),638			force_authoring,639		)?;640641		let spawner = task_manager.spawn_handle();642643		let params = StartCollatorParams {644			para_id: id,645			block_status: client.clone(),646			announce_block,647			client: client.clone(),648			task_manager: &mut task_manager,649			spawner,650			parachain_consensus,651			import_queue: import_queue_service,652			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),653			relay_chain_interface,654			relay_chain_slot_duration,655			recovery_handle: Box::new(overseer_handle),656			sync_service,657		};658659		start_collator(params).await?;660	} else {661		let params = StartFullNodeParams {662			client: client.clone(),663			announce_block,664			task_manager: &mut task_manager,665			para_id: id,666			import_queue: import_queue_service,667			relay_chain_interface,668			relay_chain_slot_duration,669			recovery_handle: Box::new(overseer_handle),670			sync_service,671		};672673		start_full_node(params)?;674	}675676	start_network.start_network();677678	Ok((task_manager, client))679}680681/// Build the import queue for the the parachain runtime.682pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(683	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,684	backend: Arc<FullBackend>,685	config: &Configuration,686	telemetry: Option<TelemetryHandle>,687	task_manager: &TaskManager,688) -> Result<689	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,690	sc_service::Error,691>692where693	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>694		+ Send695		+ Sync696		+ 'static,697	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>698		+ sp_block_builder::BlockBuilder<Block>699		+ sp_consensus_aura::AuraApi<Block, AuraId>700		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,701	ExecutorDispatch: NativeExecutionDispatch + 'static,702{703	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;704705	let block_import = ParachainBlockImport::new(client.clone(), backend);706707	cumulus_client_consensus_aura::import_queue::<708		sp_consensus_aura::sr25519::AuthorityPair,709		_,710		_,711		_,712		_,713		_,714	>(cumulus_client_consensus_aura::ImportQueueParams {715		block_import,716		client,717		create_inherent_data_providers: move |_, _| async move {718			let time = sp_timestamp::InherentDataProvider::from_system_time();719720			let slot =721				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(722					*time,723					slot_duration,724				);725726			Ok((slot, time))727		},728		registry: config.prometheus_registry(),729		spawner: &task_manager.spawn_essential_handle(),730		telemetry,731	})732	.map_err(Into::into)733}734735/// Start a normal parachain node.736pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(737	parachain_config: Configuration,738	polkadot_config: Configuration,739	collator_options: CollatorOptions,740	id: ParaId,741	hwbench: Option<sc_sysinfo::HwBench>,742) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>743where744	Runtime: RuntimeInstance + Send + Sync + 'static,745	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,746	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,747	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>748		+ Send749		+ Sync750		+ 'static,751	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>752		+ fp_rpc::EthereumRuntimeRPCApi<Block>753		+ fp_rpc::ConvertTransactionRuntimeApi<Block>754		+ sp_session::SessionKeys<Block>755		+ sp_block_builder::BlockBuilder<Block>756		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>757		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>758		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>759		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>760		+ up_pov_estimate_rpc::PovEstimateApi<Block>761		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>762		+ sp_api::Metadata<Block>763		+ sp_offchain::OffchainWorkerApi<Block>764		+ cumulus_primitives_core::CollectCollationInfo<Block>765		+ sp_consensus_aura::AuraApi<Block, AuraId>,766	ExecutorDispatch: NativeExecutionDispatch + 'static,767{768	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(769		parachain_config,770		polkadot_config,771		collator_options,772		id,773		parachain_build_import_queue,774		|client,775		 backend,776		 prometheus_registry,777		 telemetry,778		 task_manager,779		 relay_chain_interface,780		 transaction_pool,781		 sync_oracle,782		 keystore,783		 force_authoring| {784			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;785786			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(787				task_manager.spawn_handle(),788				client.clone(),789				transaction_pool,790				prometheus_registry,791				telemetry.clone(),792			);793794			let block_import = ParachainBlockImport::new(client.clone(), backend);795796			Ok(AuraConsensus::build::<797				sp_consensus_aura::sr25519::AuthorityPair,798				_,799				_,800				_,801				_,802				_,803				_,804			>(BuildAuraConsensusParams {805				proposer_factory,806				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {807					let relay_chain_interface = relay_chain_interface.clone();808					async move {809						let parachain_inherent =810						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(811							relay_parent,812							&relay_chain_interface,813							&validation_data,814							id,815						).await;816817						let time = sp_timestamp::InherentDataProvider::from_system_time();818819						let slot =820						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(821							*time,822							slot_duration,823						);824825						let parachain_inherent = parachain_inherent.ok_or_else(|| {826							Box::<dyn std::error::Error + Send + Sync>::from(827								"Failed to create parachain inherent",828							)829						})?;830						Ok((slot, time, parachain_inherent))831					}832				},833				block_import,834				para_client: client,835				backoff_authoring_blocks: Option::<()>::None,836				sync_oracle,837				keystore,838				force_authoring,839				slot_duration,840				// We got around 500ms for proposing841				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),842				telemetry,843				max_block_proposal_slot_portion: None,844			}))845		},846		hwbench,847	)848	.await849}850851fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(852	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,853	_: Arc<FullBackend>,854	config: &Configuration,855	_: Option<TelemetryHandle>,856	task_manager: &TaskManager,857) -> Result<858	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,859	sc_service::Error,860>861where862	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>863		+ Send864		+ Sync865		+ 'static,866	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>867		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,868	ExecutorDispatch: NativeExecutionDispatch + 'static,869{870	Ok(sc_consensus_manual_seal::import_queue(871		Box::new(client),872		&task_manager.spawn_essential_handle(),873		config.prometheus_registry(),874	))875}876877pub struct OtherPartial {878	pub telemetry: Option<Telemetry>,879	pub telemetry_worker_handle: Option<TelemetryWorkerHandle>,880	pub eth_filter_pool: Option<FilterPool>,881	pub eth_backend: Arc<fc_db::kv::Backend<Block>>,882}883884/// Builds a new development service. This service uses instant seal, and mocks885/// the parachain inherent886pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(887	config: Configuration,888	autoseal_interval: Duration,889	disable_autoseal_on_tx: bool,890) -> sc_service::error::Result<TaskManager>891where892	Runtime: RuntimeInstance + Send + Sync + 'static,893	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,894	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,895	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>896		+ Send897		+ Sync898		+ 'static,899	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>900		+ fp_rpc::EthereumRuntimeRPCApi<Block>901		+ fp_rpc::ConvertTransactionRuntimeApi<Block>902		+ sp_session::SessionKeys<Block>903		+ sp_block_builder::BlockBuilder<Block>904		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>905		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>906		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>907		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>908		+ up_pov_estimate_rpc::PovEstimateApi<Block>909		+ substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>910		+ sp_api::Metadata<Block>911		+ sp_offchain::OffchainWorkerApi<Block>912		+ cumulus_primitives_core::CollectCollationInfo<Block>913		+ sp_consensus_aura::AuraApi<Block, AuraId>,914	ExecutorDispatch: NativeExecutionDispatch + 'static,915{916	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};917	use fc_consensus::FrontierBlockImport;918919	let sc_service::PartialComponents {920		client,921		backend,922		mut task_manager,923		import_queue,924		keystore_container,925		select_chain: maybe_select_chain,926		transaction_pool,927		other:928			OtherPartial {929				telemetry,930				eth_filter_pool,931				eth_backend,932				telemetry_worker_handle: _,933			},934	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(935		&config,936		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,937	)?;938	let net_config = sc_network::config::FullNetworkConfiguration::new(&config.network);939	let prometheus_registry = config.prometheus_registry().cloned();940941	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =942		sc_service::build_network(sc_service::BuildNetworkParams {943			config: &config,944			net_config,945			client: client.clone(),946			transaction_pool: transaction_pool.clone(),947			spawn_handle: task_manager.spawn_handle(),948			import_queue,949			block_announce_validator_builder: None,950			warp_sync_params: None,951		})?;952953	if config.offchain_worker.enabled {954		sc_service::build_offchain_workers(955			&config,956			task_manager.spawn_handle(),957			client.clone(),958			network.clone(),959		);960	}961962	let collator = config.role.is_authority();963964	let select_chain = maybe_select_chain;965966	if collator {967		let block_import = FrontierBlockImport::new(client.clone(), client.clone());968969		let env = sc_basic_authorship::ProposerFactory::new(970			task_manager.spawn_handle(),971			client.clone(),972			transaction_pool.clone(),973			prometheus_registry.as_ref(),974			telemetry.as_ref().map(|x| x.handle()),975		);976977		let transactions_commands_stream: Box<978			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,979		> = Box::new(980			transaction_pool981				.pool()982				.validated_pool()983				.import_notification_stream()984				.filter(move |_| futures::future::ready(!disable_autoseal_on_tx))985				.map(|_| EngineCommand::SealNewBlock {986					create_empty: true,987					finalize: false, // todo:collator finalize true988					parent_hash: None,989					sender: None,990				}),991		);992993		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));994		let idle_commands_stream: Box<995			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,996		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {997			create_empty: true,998			finalize: false, // todo:collator finalize true999			parent_hash: None,1000			sender: None,1001		}));10021003		let commands_stream = select(transactions_commands_stream, idle_commands_stream);10041005		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;1006		let client_set_aside_for_cidp = client.clone();10071008		task_manager.spawn_essential_handle().spawn_blocking(1009			"authorship_task",1010			Some("block-authoring"),1011			run_manual_seal(ManualSealParams {1012				block_import,1013				env,1014				client: client.clone(),1015				pool: transaction_pool.clone(),1016				commands_stream,1017				select_chain: select_chain.clone(),1018				consensus_data_provider: None,1019				create_inherent_data_providers: move |block: Hash, ()| {1020					let current_para_block = client_set_aside_for_cidp1021						.number(block)1022						.expect("Header lookup should succeed")1023						.expect("Header passed in as parent should be present in backend.");10241025					let client_for_xcm = client_set_aside_for_cidp.clone();1026					async move {1027						let time = sp_timestamp::InherentDataProvider::from_system_time();10281029						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {1030							current_para_block,1031							relay_offset: 1000,1032							relay_blocks_per_para_block: 2,1033							para_blocks_per_relay_epoch: 0,1034							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1035								&*client_for_xcm,1036								block,1037								Default::default(),1038								Default::default(),1039							),1040							relay_randomness_config: (),1041							raw_downward_messages: vec![],1042							raw_horizontal_messages: vec![],1043						};10441045						let slot =1046						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1047							*time,1048							slot_duration,1049						);10501051						Ok((time, slot, mocked_parachain))1052					}1053				},1054			}),1055		);1056	}10571058	#[cfg(feature = "pov-estimate")]1059	let rpc_backend = backend.clone();10601061	let runtime_id = config.chain_spec.runtime_id();10621063	// Frontier1064	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));1065	let fee_history_limit = 2048;10661067	let eth_pubsub_notification_sinks: Arc<1068		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<Block>>,1069	> = Default::default();10701071	let overrides = overrides_handle(client.clone());1072	let eth_block_data_cache = spawn_frontier_tasks(1073		FrontierTaskParams {1074			client: client.clone(),1075			substrate_backend: backend.clone(),1076			eth_filter_pool: eth_filter_pool.clone(),1077			eth_backend: eth_backend.clone(),1078			fee_history_limit,1079			fee_history_cache: fee_history_cache.clone(),1080			task_manager: &task_manager,1081			prometheus_registry,1082			overrides: overrides.clone(),1083			sync_strategy: SyncStrategy::Normal,1084		},1085		sync_service.clone(),1086		eth_pubsub_notification_sinks.clone(),1087	);10881089	// Rpc1090	let rpc_builder = Box::new({1091		clone!(1092			client,1093			backend,1094			eth_backend,1095			eth_pubsub_notification_sinks,1096			fee_history_cache,1097			eth_block_data_cache,1098			overrides,1099			transaction_pool,1100			network,1101			sync_service,1102		);1103		move |deny_unsafe, subscription_task_executor: SubscriptionTaskExecutor| {1104			clone!(1105				backend,1106				eth_block_data_cache,1107				client,1108				eth_backend,1109				eth_filter_pool,1110				eth_pubsub_notification_sinks,1111				fee_history_cache,1112				eth_block_data_cache,1113				network,1114				runtime_id,1115				transaction_pool,1116				select_chain,1117				overrides,1118			);11191120			#[cfg(not(feature = "pov-estimate"))]1121			let _ = backend;11221123			let mut rpc_module = RpcModule::new(());11241125			let full_deps = unique_rpc::FullDeps {1126				runtime_id,11271128				#[cfg(feature = "pov-estimate")]1129				exec_params: uc_rpc::pov_estimate::ExecutorParams {1130					wasm_method: config.wasm_method,1131					default_heap_pages: config.default_heap_pages,1132					max_runtime_instances: config.max_runtime_instances,1133					runtime_cache_size: config.runtime_cache_size,1134				},11351136				#[cfg(feature = "pov-estimate")]1137				backend,1138				// eth_backend,1139				deny_unsafe,1140				client: client.clone(),1141				pool: transaction_pool.clone(),1142				select_chain,1143			};11441145			unique_rpc::create_full::<_, _, _, Runtime, RuntimeApi, _>(&mut rpc_module, full_deps)?;11461147			let eth_deps = unique_rpc::EthDeps {1148				client,1149				graph: transaction_pool.pool().clone(),1150				pool: transaction_pool,1151				is_authority: true,1152				network,1153				eth_backend,1154				// TODO: Unhardcode1155				max_past_logs: 10000,1156				fee_history_limit,1157				fee_history_cache,1158				eth_block_data_cache,1159				// TODO: Unhardcode1160				enable_dev_signer: false,1161				eth_filter_pool,1162				eth_pubsub_notification_sinks,1163				overrides,1164				sync: sync_service.clone(),1165			};11661167			unique_rpc::create_eth(1168				&mut rpc_module,1169				eth_deps,1170				subscription_task_executor.clone(),1171			)?;11721173			Ok(rpc_module)1174		}1175	});11761177	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1178		network,1179		sync_service,1180		client,1181		keystore: keystore_container.keystore(),1182		task_manager: &mut task_manager,1183		transaction_pool,1184		rpc_builder,1185		backend,1186		system_rpc_tx,1187		config,1188		telemetry: None,1189		tx_handler_controller,1190	})?;11911192	network_starter.start_network();1193	Ok(task_manager)1194}11951196fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>1197where1198	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,1199	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,1200	C: Send + Sync + 'static,1201	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,1202	BE: Backend<Block> + 'static,1203	BE::State: StateBackend<BlakeTwo256>,1204{1205	let mut overrides_map = BTreeMap::new();1206	overrides_map.insert(1207		EthereumStorageSchema::V1,1208		Box::new(SchemaV1Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1209	);1210	overrides_map.insert(1211		EthereumStorageSchema::V2,1212		Box::new(SchemaV2Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1213	);1214	overrides_map.insert(1215		EthereumStorageSchema::V3,1216		Box::new(SchemaV3Override::new(client.clone())) as Box<dyn StorageOverride<_> + 'static>,1217	);12181219	Arc::new(OverrideHandle {1220		schemas: overrides_map,1221		fallback: Box::new(RuntimeApiStorageOverride::new(client)),1222	})1223}12241225pub struct FrontierTaskParams<'a, B: BlockT, C, BE> {1226	pub task_manager: &'a TaskManager,1227	pub client: Arc<C>,1228	pub substrate_backend: Arc<BE>,1229	pub eth_backend: Arc<fc_db::kv::Backend<B>>,1230	pub eth_filter_pool: Option<FilterPool>,1231	pub overrides: Arc<OverrideHandle<B>>,1232	pub fee_history_limit: u64,1233	pub fee_history_cache: FeeHistoryCache,1234	pub sync_strategy: SyncStrategy,1235	pub prometheus_registry: Option<Registry>,1236}12371238pub fn spawn_frontier_tasks<B, C, BE>(1239	params: FrontierTaskParams<B, C, BE>,1240	sync: Arc<SyncingService<B>>,1241	pubsub_notification_sinks: Arc<1242		EthereumBlockNotificationSinks<fc_mapping_sync::EthereumBlockNotification<B>>,1243	>,1244) -> Arc<EthBlockDataCacheTask<B>>1245where1246	C: ProvideRuntimeApi<B> + BlockOf,1247	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,1248	C: BlockchainEvents<B> + StorageProvider<B, BE>,1249	C: Send + Sync + 'static,1250	C::Api: EthereumRuntimeRPCApi<B>,1251	C::Api: BlockBuilder<B>,1252	B: BlockT<Hash = H256> + Send + Sync + 'static,1253	B::Header: HeaderT<Number = u32>,1254	BE: Backend<B> + 'static,1255	BE::State: StateBackend<BlakeTwo256>,1256{1257	let FrontierTaskParams {1258		task_manager,1259		client,1260		substrate_backend,1261		eth_backend,1262		eth_filter_pool,1263		overrides,1264		fee_history_limit,1265		fee_history_cache,1266		sync_strategy,1267		prometheus_registry,1268	} = params;1269	// Frontier offchain DB task. Essential.1270	// Maps emulated ethereum data to substrate native data.1271	params.task_manager.spawn_essential_handle().spawn(1272		"frontier-mapping-sync-worker",1273		Some("frontier"),1274		MappingSyncWorker::new(1275			client.import_notification_stream(),1276			Duration::new(6, 0),1277			client.clone(),1278			substrate_backend,1279			overrides.clone(),1280			eth_backend,1281			3,1282			0,1283			sync_strategy,1284			sync,1285			pubsub_notification_sinks,1286		)1287		.for_each(|()| futures::future::ready(())),1288	);12891290	// Frontier `EthFilterApi` maintenance.1291	// Manages the pool of user-created Filters.1292	if let Some(eth_filter_pool) = eth_filter_pool {1293		// Each filter is allowed to stay in the pool for 100 blocks.1294		const FILTER_RETAIN_THRESHOLD: u64 = 100;1295		params.task_manager.spawn_essential_handle().spawn(1296			"frontier-filter-pool",1297			Some("frontier"),1298			EthTask::filter_pool_task(client.clone(), eth_filter_pool, FILTER_RETAIN_THRESHOLD),1299		);1300	}13011302	// Spawn Frontier FeeHistory cache maintenance task.1303	params.task_manager.spawn_essential_handle().spawn(1304		"frontier-fee-history",1305		Some("frontier"),1306		EthTask::fee_history_task(1307			client,1308			overrides.clone(),1309			fee_history_cache,1310			fee_history_limit,1311		),1312	);13131314	Arc::new(EthBlockDataCacheTask::new(1315		task_manager.spawn_handle(),1316		overrides,1317		50,1318		50,1319		prometheus_registry,1320	))1321}