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

difftreelog

Merge pull request #808 from UniqueNetwork/fix/try-runtime-0.9.36

Yaroslav Bolyukin2022-12-23parents: #507b779 #13872be.patch.diff
in: master

9 files changed

modified.docker/Dockerfile-try-runtimediffbeforeafterboth
--- a/.docker/Dockerfile-try-runtime
+++ b/.docker/Dockerfile-try-runtime
@@ -46,4 +46,4 @@
     echo "Fork from: $REPLICA_FROM\n" && \
     cargo build --features=try-runtime,${NETWORK}-runtime --release
 
-CMD cargo run --features=try-runtime,${NETWORK}-runtime --release -- try-runtime -ltry-runtime::cli=debug --no-spec-check-panic on-runtime-upgrade live --uri $REPLICA_FROM
+CMD cargo run --release --features ${NETWORK}-runtime,try-runtime -- try-runtime --runtime target/release/wbuild/${NETWORK}-runtime/${NETWORK}_runtime.compact.compressed.wasm -lruntime=debug -ltry-runtime::cli=debug on-runtime-upgrade --checks live --uri $REPLICA_FROM
modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2467,7 +2467,7 @@
 [[package]]
 name = "fc-consensus"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "async-trait",
  "fc-db",
@@ -2486,7 +2486,7 @@
 [[package]]
 name = "fc-db"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "fp-storage",
  "kvdb-rocksdb",
@@ -2505,7 +2505,7 @@
 [[package]]
 name = "fc-mapping-sync"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "fc-db",
  "fp-consensus",
@@ -2522,7 +2522,7 @@
 [[package]]
 name = "fc-rpc"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2565,7 +2565,7 @@
 [[package]]
 name = "fc-rpc-core"
 version = "1.1.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2730,7 +2730,7 @@
 [[package]]
 name = "fp-consensus"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "parity-scale-codec 3.2.1",
@@ -2742,7 +2742,7 @@
 [[package]]
 name = "fp-ethereum"
 version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2757,7 +2757,7 @@
 [[package]]
 name = "fp-evm"
 version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "evm",
  "frame-support",
@@ -2771,7 +2771,7 @@
 [[package]]
 name = "fp-evm-mapping"
 version = "0.1.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "frame-support",
  "sp-core",
@@ -2780,7 +2780,7 @@
 [[package]]
 name = "fp-rpc"
 version = "3.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -2797,7 +2797,7 @@
 [[package]]
 name = "fp-self-contained"
 version = "1.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "frame-support",
@@ -2810,7 +2810,7 @@
 [[package]]
 name = "fp-storage"
 version = "2.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "parity-scale-codec 3.2.1",
  "serde",
@@ -5682,7 +5682,7 @@
 [[package]]
 name = "pallet-base-fee"
 version = "1.0.0"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "fp-evm",
  "frame-support",
@@ -5918,7 +5918,7 @@
 [[package]]
 name = "pallet-ethereum"
 version = "4.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "ethereum 0.14.0",
  "ethereum-types 0.14.1",
@@ -5946,7 +5946,7 @@
 [[package]]
 name = "pallet-evm"
 version = "6.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "environmental",
  "evm",
@@ -6032,7 +6032,7 @@
 [[package]]
 name = "pallet-evm-precompile-simple"
 version = "2.0.0-dev"
-source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#db60b911813df1d82e60e0de7f3dfa290e60d2f0"
+source = "git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.36#cf1894629c7df1c4dafe58aa773627a3d940da14"
 dependencies = [
  "fp-evm",
  "ripemd",
@@ -12965,6 +12965,7 @@
  "sp-core",
  "sp-finality-grandpa",
  "sp-inherents",
+ "sp-io",
  "sp-keystore",
  "sp-offchain",
  "sp-runtime",
modifiednode/cli/Cargo.tomldiffbeforeafterboth
--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -122,6 +122,10 @@
 git = "https://github.com/paritytech/substrate"
 branch = "polkadot-v0.9.36"
 
+[dependencies.sp-io]
+git = "https://github.com/paritytech/substrate"
+branch = "polkadot-v0.9.36"
+
 [dependencies.sp-finality-grandpa]
 git = "https://github.com/paritytech/substrate"
 branch = "polkadot-v0.9.36"
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -412,6 +412,7 @@
 		#[cfg(feature = "try-runtime")]
 		Some(Subcommand::TryRuntime(cmd)) => {
 			use std::{future::Future, pin::Pin};
+			use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
 
 			let runner = cli.create_runner(cmd)?;
 
@@ -429,12 +430,21 @@
 				Ok((
 					match config.chain_spec.runtime_id() {
 						#[cfg(feature = "unique-runtime")]
-						RuntimeId::Unique => Box::pin(cmd.run::<Block, UniqueRuntimeExecutor>(config)),
+						RuntimeId::Unique => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+							sp_io::SubstrateHostFunctions,
+							<UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+						>>()),
 
 						#[cfg(feature = "quartz-runtime")]
-						RuntimeId::Quartz => Box::pin(cmd.run::<Block, QuartzRuntimeExecutor>(config)),
+						RuntimeId::Quartz => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+							sp_io::SubstrateHostFunctions,
+							<QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+						>>()),
 
-						RuntimeId::Opal => Box::pin(cmd.run::<Block, OpalRuntimeExecutor>(config)),
+						RuntimeId::Opal => Box::pin(cmd.run::<Block, ExtendedHostFunctions<
+							sp_io::SubstrateHostFunctions,
+							<OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,
+						>>()),
 						RuntimeId::Unknown(chain) => return Err(no_runtime_err!(chain).into()),
 					},
 					task_manager,
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_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::{38	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,39};40use cumulus_client_service::{41	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;4950// Substrate Imports51use sp_api::BlockT;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::{NetworkService, NetworkBlock};55use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;61use sc_consensus::ImportQueue;6263use polkadot_service::CollatorPair;6465// Frontier Imports66use fc_rpc_core::types::FilterPool;67use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6869use up_common::types::opaque::{70	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,71};7273// RMRK74use up_data_structs::{75	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,76	RmrkPartType, RmrkTheme,77};7879/// Unique native executor instance.80#[cfg(feature = "unique-runtime")]81pub struct UniqueRuntimeExecutor;8283#[cfg(feature = "quartz-runtime")]84/// Quartz native executor instance.85pub struct QuartzRuntimeExecutor;8687/// Opal native executor instance.88pub struct OpalRuntimeExecutor;8990#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]91pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9293#[cfg(all(94	not(feature = "unique-runtime"),95	feature = "quartz-runtime",96	feature = "runtime-benchmarks"97))]98pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	not(feature = "quartz-runtime"),103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;106107#[cfg(feature = "unique-runtime")]108impl NativeExecutionDispatch for UniqueRuntimeExecutor {109	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;110111	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {112		unique_runtime::api::dispatch(method, data)113	}114115	fn native_version() -> sc_executor::NativeVersion {116		unique_runtime::native_version()117	}118}119120#[cfg(feature = "quartz-runtime")]121impl NativeExecutionDispatch for QuartzRuntimeExecutor {122	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;123124	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {125		quartz_runtime::api::dispatch(method, data)126	}127128	fn native_version() -> sc_executor::NativeVersion {129		quartz_runtime::native_version()130	}131}132133impl NativeExecutionDispatch for OpalRuntimeExecutor {134	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;135136	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {137		opal_runtime::api::dispatch(method, data)138	}139140	fn native_version() -> sc_executor::NativeVersion {141		opal_runtime::native_version()142	}143}144145pub struct AutosealInterval {146	interval: Interval,147}148149impl AutosealInterval {150	pub fn new(config: &Configuration, interval: Duration) -> Self {151		let _tokio_runtime = config.tokio_handle.enter();152		let interval = tokio::time::interval(interval);153154		Self { interval }155	}156}157158impl Stream for AutosealInterval {159	type Item = tokio::time::Instant;160161	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {162		self.interval.poll_tick(cx).map(Some)163	}164}165166pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(167	client: Arc<C>,168	config: &Configuration,169) -> Result<Arc<fc_db::Backend<Block>>, String> {170	let config_dir = config171		.base_path172		.as_ref()173		.map(|base_path| base_path.config_dir(config.chain_spec.id()))174		.unwrap_or_else(|| {175			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())176		});177	let database_dir = config_dir.join("frontier").join("db");178179	Ok(Arc::new(fc_db::Backend::<Block>::new(180		client,181		&fc_db::DatabaseSettings {182			source: fc_db::DatabaseSource::RocksDb {183				path: database_dir,184				cache_size: 0,185			},186		},187	)?))188}189190type FullClient<RuntimeApi, ExecutorDispatch> =191	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;192type FullBackend = sc_service::TFullBackend<Block>;193type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;194type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =195	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;196197/// Starts a `ServiceBuilder` for a full service.198///199/// Use this macro if you don't actually need the full service, but just the builder in order to200/// be able to perform chain operations.201#[allow(clippy::type_complexity)]202pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(203	config: &Configuration,204	build_import_queue: BIQ,205) -> Result<206	PartialComponents<207		FullClient<RuntimeApi, ExecutorDispatch>,208		FullBackend,209		FullSelectChain,210		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,211		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,212		(213			Option<Telemetry>,214			Option<FilterPool>,215			Arc<fc_db::Backend<Block>>,216			Option<TelemetryWorkerHandle>,217			FeeHistoryCache,218		),219	>,220	sc_service::Error,221>222where223	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,224	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>225		+ Send226		+ Sync227		+ 'static,228	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,229	ExecutorDispatch: NativeExecutionDispatch + 'static,230	BIQ: FnOnce(231		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,232		Arc<FullBackend>,233		&Configuration,234		Option<TelemetryHandle>,235		&TaskManager,236	) -> Result<237		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,238		sc_service::Error,239	>,240{241	let _telemetry = config242		.telemetry_endpoints243		.clone()244		.filter(|x| !x.is_empty())245		.map(|endpoints| -> Result<_, sc_telemetry::Error> {246			let worker = TelemetryWorker::new(16)?;247			let telemetry = worker.handle().new_telemetry(endpoints);248			Ok((worker, telemetry))249		})250		.transpose()?;251252	let telemetry = config253		.telemetry_endpoints254		.clone()255		.filter(|x| !x.is_empty())256		.map(|endpoints| -> Result<_, sc_telemetry::Error> {257			let worker = TelemetryWorker::new(16)?;258			let telemetry = worker.handle().new_telemetry(endpoints);259			Ok((worker, telemetry))260		})261		.transpose()?;262263	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(264		config.wasm_method,265		config.default_heap_pages,266		config.max_runtime_instances,267		config.runtime_cache_size,268	);269270	let (client, backend, keystore_container, task_manager) =271		sc_service::new_full_parts::<Block, RuntimeApi, _>(272			config,273			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),274			executor,275		)?;276	let client = Arc::new(client);277278	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());279280	let telemetry = telemetry.map(|(worker, telemetry)| {281		task_manager282			.spawn_handle()283			.spawn("telemetry", None, worker.run());284		telemetry285	});286287	let select_chain = sc_consensus::LongestChain::new(backend.clone());288289	let transaction_pool = sc_transaction_pool::BasicPool::new_full(290		config.transaction_pool.clone(),291		config.role.is_authority().into(),292		config.prometheus_registry(),293		task_manager.spawn_essential_handle(),294		client.clone(),295	);296297	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));298299	let frontier_backend = open_frontier_backend(client.clone(), config)?;300301	let import_queue = build_import_queue(302		client.clone(),303		backend.clone(),304		config,305		telemetry.as_ref().map(|telemetry| telemetry.handle()),306		&task_manager,307	)?;308	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));309310	let params = PartialComponents {311		backend,312		client,313		import_queue,314		keystore_container,315		task_manager,316		transaction_pool,317		select_chain,318		other: (319			telemetry,320			filter_pool,321			frontier_backend,322			telemetry_worker_handle,323			fee_history_cache,324		),325	};326327	Ok(params)328}329330async fn build_relay_chain_interface(331	polkadot_config: Configuration,332	parachain_config: &Configuration,333	telemetry_worker_handle: Option<TelemetryWorkerHandle>,334	task_manager: &mut TaskManager,335	collator_options: CollatorOptions,336	hwbench: Option<sc_sysinfo::HwBench>,337) -> RelayChainResult<(338	Arc<(dyn RelayChainInterface + 'static)>,339	Option<CollatorPair>,340)> {341	if collator_options.relay_chain_rpc_urls.is_empty() {342		build_inprocess_relay_chain(343			polkadot_config,344			parachain_config,345			telemetry_worker_handle,346			task_manager,347			hwbench,348		)349	} else {350		build_minimal_relay_chain_node(351			polkadot_config,352			task_manager,353			collator_options.relay_chain_rpc_urls,354		)355		.await356	}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		+ rmrk_rpc::RmrkApi<391			Block,392			AccountId,393			RmrkCollectionInfo<AccountId>,394			RmrkInstanceInfo<AccountId>,395			RmrkResourceInfo,396			RmrkPropertyInfo,397			RmrkBaseInfo<AccountId>,398			RmrkPartType,399			RmrkTheme,400		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>401		+ sp_api::Metadata<Block>402		+ sp_offchain::OffchainWorkerApi<Block>403		+ cumulus_primitives_core::CollectCollationInfo<Block>,404	ExecutorDispatch: NativeExecutionDispatch + 'static,405	BIQ: FnOnce(406		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,407		Arc<FullBackend>,408		&Configuration,409		Option<TelemetryHandle>,410		&TaskManager,411	) -> Result<412		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,413		sc_service::Error,414	>,415	BIC: FnOnce(416		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,417		Arc<FullBackend>,418		Option<&Registry>,419		Option<TelemetryHandle>,420		&TaskManager,421		Arc<dyn RelayChainInterface>,422		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,423		Arc<NetworkService<Block, Hash>>,424		SyncCryptoStorePtr,425		bool,426	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,427{428	let parachain_config = prepare_node_config(parachain_config);429430	let params =431		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;432	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =433		params.other;434435	let client = params.client.clone();436	let backend = params.backend.clone();437	let mut task_manager = params.task_manager;438439	let (relay_chain_interface, collator_key) = build_relay_chain_interface(440		polkadot_config,441		&parachain_config,442		telemetry_worker_handle,443		&mut task_manager,444		collator_options.clone(),445		hwbench.clone(),446	)447	.await448	.map_err(|e| match e {449		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,450		s => s.to_string().into(),451	})?;452453	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);454455	let force_authoring = parachain_config.force_authoring;456	let validator = parachain_config.role.is_authority();457	let prometheus_registry = parachain_config.prometheus_registry().cloned();458	let transaction_pool = params.transaction_pool.clone();459	let import_queue_service = params.import_queue.service();460461	let (network, system_rpc_tx, tx_handler_controller, start_network) =462		sc_service::build_network(sc_service::BuildNetworkParams {463			config: &parachain_config,464			client: client.clone(),465			transaction_pool: transaction_pool.clone(),466			spawn_handle: task_manager.spawn_handle(),467			import_queue: params.import_queue,468			block_announce_validator_builder: Some(Box::new(|_| {469				Box::new(block_announce_validator)470			})),471			warp_sync: None,472		})?;473474	let rpc_client = client.clone();475	let rpc_pool = transaction_pool.clone();476	let select_chain = params.select_chain.clone();477	let rpc_network = network.clone();478479	let rpc_frontier_backend = frontier_backend.clone();480481	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(482		task_manager.spawn_handle(),483		overrides_handle::<_, _, Runtime>(client.clone()),484		50,485		50,486		prometheus_registry.clone(),487	));488489	task_manager.spawn_essential_handle().spawn(490		"frontier-mapping-sync-worker",491		None,492		MappingSyncWorker::new(493			client.import_notification_stream(),494			Duration::new(6, 0),495			client.clone(),496			backend.clone(),497			frontier_backend.clone(),498			3,499			0,500			SyncStrategy::Normal,501		)502		.for_each(|()| futures::future::ready(())),503	);504505	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {506		let full_deps = unique_rpc::FullDeps {507			backend: rpc_frontier_backend.clone(),508			deny_unsafe,509			client: rpc_client.clone(),510			pool: rpc_pool.clone(),511			graph: rpc_pool.pool().clone(),512			// TODO: Unhardcode513			enable_dev_signer: false,514			filter_pool: filter_pool.clone(),515			network: rpc_network.clone(),516			select_chain: select_chain.clone(),517			is_authority: validator,518			// TODO: Unhardcode519			max_past_logs: 10000,520			block_data_cache: block_data_cache.clone(),521			fee_history_cache: fee_history_cache.clone(),522			// TODO: Unhardcode523			fee_history_limit: 2048,524		};525526		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(527			full_deps,528			subscription_task_executor,529		)530		.map_err(Into::into)531	});532533	sc_service::spawn_tasks(sc_service::SpawnTasksParams {534		rpc_builder,535		client: client.clone(),536		transaction_pool: transaction_pool.clone(),537		task_manager: &mut task_manager,538		config: parachain_config,539		keystore: params.keystore_container.sync_keystore(),540		backend: backend.clone(),541		network: network.clone(),542		system_rpc_tx,543		telemetry: telemetry.as_mut(),544		tx_handler_controller,545	})?;546547	if let Some(hwbench) = hwbench {548		sc_sysinfo::print_hwbench(&hwbench);549550		if let Some(ref mut telemetry) = telemetry {551			let telemetry_handle = telemetry.handle();552			task_manager.spawn_handle().spawn(553				"telemetry_hwbench",554				None,555				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),556			);557		}558	}559560	let announce_block = {561		let network = network.clone();562		Arc::new(Box::new(move |hash, data| {563			network.announce_block(hash, data)564		}))565	};566567	let relay_chain_slot_duration = Duration::from_secs(6);568569	if validator {570		let parachain_consensus = build_consensus(571			client.clone(),572			backend.clone(),573			prometheus_registry.as_ref(),574			telemetry.as_ref().map(|t| t.handle()),575			&task_manager,576			relay_chain_interface.clone(),577			transaction_pool,578			network,579			params.keystore_container.sync_keystore(),580			force_authoring,581		)?;582583		let spawner = task_manager.spawn_handle();584585		let params = StartCollatorParams {586			para_id: id,587			block_status: client.clone(),588			announce_block,589			client: client.clone(),590			task_manager: &mut task_manager,591			spawner,592			parachain_consensus,593			import_queue: import_queue_service,594			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),595			relay_chain_interface,596			relay_chain_slot_duration,597		};598599		start_collator(params).await?;600	} else {601		let params = StartFullNodeParams {602			client: client.clone(),603			announce_block,604			task_manager: &mut task_manager,605			para_id: id,606			import_queue: import_queue_service,607			relay_chain_interface,608			relay_chain_slot_duration,609		};610611		start_full_node(params)?;612	}613614	start_network.start_network();615616	Ok((task_manager, client))617}618619/// Build the import queue for the the parachain runtime.620pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(621	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,622	backend: Arc<FullBackend>,623	config: &Configuration,624	telemetry: Option<TelemetryHandle>,625	task_manager: &TaskManager,626) -> Result<627	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,628	sc_service::Error,629>630where631	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>632		+ Send633		+ Sync634		+ 'static,635	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>636		+ sp_block_builder::BlockBuilder<Block>637		+ sp_consensus_aura::AuraApi<Block, AuraId>638		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,639	ExecutorDispatch: NativeExecutionDispatch + 'static,640{641	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;642643	let block_import = ParachainBlockImport::new(client.clone(), backend.clone());644645	cumulus_client_consensus_aura::import_queue::<646		sp_consensus_aura::sr25519::AuthorityPair,647		_,648		_,649		_,650		_,651		_,652	>(cumulus_client_consensus_aura::ImportQueueParams {653		block_import,654		client: client.clone(),655		create_inherent_data_providers: move |_, _| async move {656			let time = sp_timestamp::InherentDataProvider::from_system_time();657658			let slot =659				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(660					*time,661					slot_duration,662				);663664			Ok((slot, time))665		},666		registry: config.prometheus_registry(),667		spawner: &task_manager.spawn_essential_handle(),668		telemetry,669	})670	.map_err(Into::into)671}672673/// Start a normal parachain node.674pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(675	parachain_config: Configuration,676	polkadot_config: Configuration,677	collator_options: CollatorOptions,678	id: ParaId,679	hwbench: Option<sc_sysinfo::HwBench>,680) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>681where682	Runtime: RuntimeInstance + Send + Sync + 'static,683	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,684	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,685	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>686		+ Send687		+ Sync688		+ 'static,689	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>690		+ fp_rpc::EthereumRuntimeRPCApi<Block>691		+ fp_rpc::ConvertTransactionRuntimeApi<Block>692		+ sp_session::SessionKeys<Block>693		+ sp_block_builder::BlockBuilder<Block>694		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>695		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>696		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>697		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>698		+ rmrk_rpc::RmrkApi<699			Block,700			AccountId,701			RmrkCollectionInfo<AccountId>,702			RmrkInstanceInfo<AccountId>,703			RmrkResourceInfo,704			RmrkPropertyInfo,705			RmrkBaseInfo<AccountId>,706			RmrkPartType,707			RmrkTheme,708		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>709		+ sp_api::Metadata<Block>710		+ sp_offchain::OffchainWorkerApi<Block>711		+ cumulus_primitives_core::CollectCollationInfo<Block>712		+ sp_consensus_aura::AuraApi<Block, AuraId>,713	ExecutorDispatch: NativeExecutionDispatch + 'static,714{715	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(716		parachain_config,717		polkadot_config,718		collator_options,719		id,720		parachain_build_import_queue,721		|client,722		 backend,723		 prometheus_registry,724		 telemetry,725		 task_manager,726		 relay_chain_interface,727		 transaction_pool,728		 sync_oracle,729		 keystore,730		 force_authoring| {731			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;732733			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(734				task_manager.spawn_handle(),735				client.clone(),736				transaction_pool,737				prometheus_registry,738				telemetry.clone(),739			);740741			let block_import = ParachainBlockImport::new(client.clone(), backend.clone());742743			Ok(AuraConsensus::build::<744				sp_consensus_aura::sr25519::AuthorityPair,745				_,746				_,747				_,748				_,749				_,750				_,751			>(BuildAuraConsensusParams {752				proposer_factory,753				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {754					let relay_chain_interface = relay_chain_interface.clone();755					async move {756						let parachain_inherent =757						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(758							relay_parent,759							&relay_chain_interface,760							&validation_data,761							id,762						).await;763764						let time = sp_timestamp::InherentDataProvider::from_system_time();765766						let slot =767						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(768							*time,769							slot_duration,770						);771772						let parachain_inherent = parachain_inherent.ok_or_else(|| {773							Box::<dyn std::error::Error + Send + Sync>::from(774								"Failed to create parachain inherent",775							)776						})?;777						Ok((slot, time, parachain_inherent))778					}779				},780				block_import,781				para_client: client,782				backoff_authoring_blocks: Option::<()>::None,783				sync_oracle,784				keystore,785				force_authoring,786				slot_duration,787				// We got around 500ms for proposing788				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),789				telemetry,790				max_block_proposal_slot_portion: None,791			}))792		},793		hwbench,794	)795	.await796}797798fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(799	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,800	_: Arc<FullBackend>,801	config: &Configuration,802	_: Option<TelemetryHandle>,803	task_manager: &TaskManager,804) -> Result<805	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,806	sc_service::Error,807>808where809	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>810		+ Send811		+ Sync812		+ 'static,813	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>814		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,815	ExecutorDispatch: NativeExecutionDispatch + 'static,816{817	Ok(sc_consensus_manual_seal::import_queue(818		Box::new(client.clone()),819		&task_manager.spawn_essential_handle(),820		config.prometheus_registry(),821	))822}823824/// Builds a new development service. This service uses instant seal, and mocks825/// the parachain inherent826pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(827	config: Configuration,828	autoseal_interval: Duration,829) -> sc_service::error::Result<TaskManager>830where831	Runtime: RuntimeInstance + Send + Sync + 'static,832	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,833	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,834	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>835		+ Send836		+ Sync837		+ 'static,838	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>839		+ fp_rpc::EthereumRuntimeRPCApi<Block>840		+ fp_rpc::ConvertTransactionRuntimeApi<Block>841		+ sp_session::SessionKeys<Block>842		+ sp_block_builder::BlockBuilder<Block>843		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>844		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>845		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>846		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>847		+ rmrk_rpc::RmrkApi<848			Block,849			AccountId,850			RmrkCollectionInfo<AccountId>,851			RmrkInstanceInfo<AccountId>,852			RmrkResourceInfo,853			RmrkPropertyInfo,854			RmrkBaseInfo<AccountId>,855			RmrkPartType,856			RmrkTheme,857		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>858		+ sp_api::Metadata<Block>859		+ sp_offchain::OffchainWorkerApi<Block>860		+ cumulus_primitives_core::CollectCollationInfo<Block>861		+ sp_consensus_aura::AuraApi<Block, AuraId>,862	ExecutorDispatch: NativeExecutionDispatch + 'static,863{864	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};865	use fc_consensus::FrontierBlockImport;866	use sc_client_api::HeaderBackend;867868	let sc_service::PartialComponents {869		client,870		backend,871		mut task_manager,872		import_queue,873		keystore_container,874		select_chain: maybe_select_chain,875		transaction_pool,876		other:877			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),878	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(879		&config,880		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,881	)?;882	let prometheus_registry = config.prometheus_registry().cloned();883884	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(885		task_manager.spawn_handle(),886		overrides_handle::<_, _, Runtime>(client.clone()),887		50,888		50,889		prometheus_registry.clone(),890	));891892	let (network, system_rpc_tx, tx_handler_controller, network_starter) =893		sc_service::build_network(sc_service::BuildNetworkParams {894			config: &config,895			client: client.clone(),896			transaction_pool: transaction_pool.clone(),897			spawn_handle: task_manager.spawn_handle(),898			import_queue,899			block_announce_validator_builder: None,900			warp_sync: None,901		})?;902903	if config.offchain_worker.enabled {904		sc_service::build_offchain_workers(905			&config,906			task_manager.spawn_handle(),907			client.clone(),908			network.clone(),909		);910	}911912	let collator = config.role.is_authority();913914	let select_chain = maybe_select_chain.clone();915916	if collator {917		let block_import =918			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());919920		let env = sc_basic_authorship::ProposerFactory::new(921			task_manager.spawn_handle(),922			client.clone(),923			transaction_pool.clone(),924			prometheus_registry.as_ref(),925			telemetry.as_ref().map(|x| x.handle()),926		);927928		let transactions_commands_stream: Box<929			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,930		> = Box::new(931			transaction_pool932				.pool()933				.validated_pool()934				.import_notification_stream()935				.map(|_| EngineCommand::SealNewBlock {936					create_empty: true,937					finalize: false,938					parent_hash: None,939					sender: None,940				}),941		);942943		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));944		let idle_commands_stream: Box<945			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,946		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {947			create_empty: true,948			finalize: false,949			parent_hash: None,950			sender: None,951		}));952953		let commands_stream = select(transactions_commands_stream, idle_commands_stream);954955		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;956		let client_set_aside_for_cidp = client.clone();957958		task_manager.spawn_essential_handle().spawn_blocking(959			"authorship_task",960			Some("block-authoring"),961			run_manual_seal(ManualSealParams {962				block_import,963				env,964				client: client.clone(),965				pool: transaction_pool.clone(),966				commands_stream,967				select_chain: select_chain.clone(),968				consensus_data_provider: None,969				create_inherent_data_providers: move |block: Hash, ()| {970					let current_para_block = client_set_aside_for_cidp971						.number(block)972						.expect("Header lookup should succeed")973						.expect("Header passed in as parent should be present in backend.");974975					let client_for_xcm = client_set_aside_for_cidp.clone();976					async move {977						let time = sp_timestamp::InherentDataProvider::from_system_time();978979						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {980							current_para_block,981							relay_offset: 1000,982							relay_blocks_per_para_block: 2,983							para_blocks_per_relay_epoch: 0,984							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(985								&*client_for_xcm,986								block,987								Default::default(),988								Default::default(),989							),990							relay_randomness_config: (),991							raw_downward_messages: vec![],992							raw_horizontal_messages: vec![],993						};994995						let slot =996						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(997							*time,998							slot_duration,999						);10001001						Ok((time, slot, mocked_parachain))1002					}1003				},1004			}),1005		);1006	}10071008	task_manager.spawn_essential_handle().spawn(1009		"frontier-mapping-sync-worker",1010		Some("block-authoring"),1011		MappingSyncWorker::new(1012			client.import_notification_stream(),1013			Duration::new(6, 0),1014			client.clone(),1015			backend.clone(),1016			frontier_backend.clone(),1017			3,1018			0,1019			SyncStrategy::Normal,1020		)1021		.for_each(|()| futures::future::ready(())),1022	);10231024	let rpc_client = client.clone();1025	let rpc_pool = transaction_pool.clone();1026	let rpc_network = network.clone();1027	let rpc_frontier_backend = frontier_backend.clone();1028	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1029		let full_deps = unique_rpc::FullDeps {1030			backend: rpc_frontier_backend.clone(),1031			deny_unsafe,1032			client: rpc_client.clone(),1033			pool: rpc_pool.clone(),1034			graph: rpc_pool.pool().clone(),1035			// TODO: Unhardcode1036			enable_dev_signer: false,1037			filter_pool: filter_pool.clone(),1038			network: rpc_network.clone(),1039			select_chain: select_chain.clone(),1040			is_authority: collator,1041			// TODO: Unhardcode1042			max_past_logs: 10000,1043			block_data_cache: block_data_cache.clone(),1044			fee_history_cache: fee_history_cache.clone(),1045			// TODO: Unhardcode1046			fee_history_limit: 2048,1047		};10481049		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1050			full_deps,1051			subscription_executor,1052		)1053		.map_err(Into::into)1054	});10551056	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1057		network,1058		client,1059		keystore: keystore_container.sync_keystore(),1060		task_manager: &mut task_manager,1061		transaction_pool,1062		rpc_builder,1063		backend,1064		system_rpc_tx,1065		config,1066		telemetry: None,1067		tx_handler_controller,1068	})?;10691070	network_starter.start_network();1071	Ok(task_manager)1072}
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_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::{38	ParachainConsensus, ParachainBlockImport as TParachainBlockImport,39};40use cumulus_client_service::{41	prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,42};43use cumulus_client_cli::CollatorOptions;44use cumulus_client_network::BlockAnnounceValidator;45use cumulus_primitives_core::ParaId;46use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;47use cumulus_relay_chain_interface::{RelayChainError, RelayChainInterface, RelayChainResult};48use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node;4950// Substrate Imports51use sp_api::BlockT;52use sc_executor::NativeElseWasmExecutor;53use sc_executor::NativeExecutionDispatch;54use sc_network::{NetworkService, NetworkBlock};55use sc_service::{BasePath, Configuration, PartialComponents, TaskManager};56use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};57use sp_keystore::SyncCryptoStorePtr;58use sp_runtime::traits::BlakeTwo256;59use substrate_prometheus_endpoint::Registry;60use sc_client_api::BlockchainEvents;61use sc_consensus::ImportQueue;6263use polkadot_service::CollatorPair;6465// Frontier Imports66use fc_rpc_core::types::FilterPool;67use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6869use up_common::types::opaque::{70	AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block, BlockNumber,71};7273// RMRK74use up_data_structs::{75	RmrkCollectionInfo, RmrkInstanceInfo, RmrkResourceInfo, RmrkPropertyInfo, RmrkBaseInfo,76	RmrkPartType, RmrkTheme,77};7879/// Unique native executor instance.80#[cfg(feature = "unique-runtime")]81pub struct UniqueRuntimeExecutor;8283#[cfg(feature = "quartz-runtime")]84/// Quartz native executor instance.85pub struct QuartzRuntimeExecutor;8687/// Opal native executor instance.88pub struct OpalRuntimeExecutor;8990#[cfg(all(feature = "unique-runtime", feature = "runtime-benchmarks"))]91pub type DefaultRuntimeExecutor = UniqueRuntimeExecutor;9293#[cfg(all(94	not(feature = "unique-runtime"),95	feature = "quartz-runtime",96	feature = "runtime-benchmarks"97))]98pub type DefaultRuntimeExecutor = QuartzRuntimeExecutor;99100#[cfg(all(101	not(feature = "unique-runtime"),102	not(feature = "quartz-runtime"),103	feature = "runtime-benchmarks"104))]105pub type DefaultRuntimeExecutor = OpalRuntimeExecutor;106107#[cfg(feature = "unique-runtime")]108impl NativeExecutionDispatch for UniqueRuntimeExecutor {109	/// Only enable the benchmarking host functions when we actually want to benchmark.110	#[cfg(feature = "runtime-benchmarks")]111	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;112	/// Otherwise we only use the default Substrate host functions.113	#[cfg(not(feature = "runtime-benchmarks"))]114	type ExtendHostFunctions = ();115116	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {117		unique_runtime::api::dispatch(method, data)118	}119120	fn native_version() -> sc_executor::NativeVersion {121		unique_runtime::native_version()122	}123}124125#[cfg(feature = "quartz-runtime")]126impl NativeExecutionDispatch for QuartzRuntimeExecutor {127	/// Only enable the benchmarking host functions when we actually want to benchmark.128	#[cfg(feature = "runtime-benchmarks")]129	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;130	/// Otherwise we only use the default Substrate host functions.131	#[cfg(not(feature = "runtime-benchmarks"))]132	type ExtendHostFunctions = ();133134	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {135		quartz_runtime::api::dispatch(method, data)136	}137138	fn native_version() -> sc_executor::NativeVersion {139		quartz_runtime::native_version()140	}141}142143impl NativeExecutionDispatch for OpalRuntimeExecutor {144	/// Only enable the benchmarking host functions when we actually want to benchmark.145	#[cfg(feature = "runtime-benchmarks")]146	type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;147	/// Otherwise we only use the default Substrate host functions.148	#[cfg(not(feature = "runtime-benchmarks"))]149	type ExtendHostFunctions = ();150151	fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {152		opal_runtime::api::dispatch(method, data)153	}154155	fn native_version() -> sc_executor::NativeVersion {156		opal_runtime::native_version()157	}158}159160pub struct AutosealInterval {161	interval: Interval,162}163164impl AutosealInterval {165	pub fn new(config: &Configuration, interval: Duration) -> Self {166		let _tokio_runtime = config.tokio_handle.enter();167		let interval = tokio::time::interval(interval);168169		Self { interval }170	}171}172173impl Stream for AutosealInterval {174	type Item = tokio::time::Instant;175176	fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {177		self.interval.poll_tick(cx).map(Some)178	}179}180181pub fn open_frontier_backend<Block: BlockT, C: sp_blockchain::HeaderBackend<Block>>(182	client: Arc<C>,183	config: &Configuration,184) -> Result<Arc<fc_db::Backend<Block>>, String> {185	let config_dir = config186		.base_path187		.as_ref()188		.map(|base_path| base_path.config_dir(config.chain_spec.id()))189		.unwrap_or_else(|| {190			BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())191		});192	let database_dir = config_dir.join("frontier").join("db");193194	Ok(Arc::new(fc_db::Backend::<Block>::new(195		client,196		&fc_db::DatabaseSettings {197			source: fc_db::DatabaseSource::RocksDb {198				path: database_dir,199				cache_size: 0,200			},201		},202	)?))203}204205type FullClient<RuntimeApi, ExecutorDispatch> =206	sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;207type FullBackend = sc_service::TFullBackend<Block>;208type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;209type ParachainBlockImport<RuntimeApi, ExecutorDispatch> =210	TParachainBlockImport<Block, Arc<FullClient<RuntimeApi, ExecutorDispatch>>, FullBackend>;211212/// Starts a `ServiceBuilder` for a full service.213///214/// Use this macro if you don't actually need the full service, but just the builder in order to215/// be able to perform chain operations.216#[allow(clippy::type_complexity)]217pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(218	config: &Configuration,219	build_import_queue: BIQ,220) -> Result<221	PartialComponents<222		FullClient<RuntimeApi, ExecutorDispatch>,223		FullBackend,224		FullSelectChain,225		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,226		sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,227		(228			Option<Telemetry>,229			Option<FilterPool>,230			Arc<fc_db::Backend<Block>>,231			Option<TelemetryWorkerHandle>,232			FeeHistoryCache,233		),234	>,235	sc_service::Error,236>237where238	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,239	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>240		+ Send241		+ Sync242		+ 'static,243	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,244	ExecutorDispatch: NativeExecutionDispatch + 'static,245	BIQ: FnOnce(246		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,247		Arc<FullBackend>,248		&Configuration,249		Option<TelemetryHandle>,250		&TaskManager,251	) -> Result<252		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,253		sc_service::Error,254	>,255{256	let _telemetry = config257		.telemetry_endpoints258		.clone()259		.filter(|x| !x.is_empty())260		.map(|endpoints| -> Result<_, sc_telemetry::Error> {261			let worker = TelemetryWorker::new(16)?;262			let telemetry = worker.handle().new_telemetry(endpoints);263			Ok((worker, telemetry))264		})265		.transpose()?;266267	let telemetry = config268		.telemetry_endpoints269		.clone()270		.filter(|x| !x.is_empty())271		.map(|endpoints| -> Result<_, sc_telemetry::Error> {272			let worker = TelemetryWorker::new(16)?;273			let telemetry = worker.handle().new_telemetry(endpoints);274			Ok((worker, telemetry))275		})276		.transpose()?;277278	let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(279		config.wasm_method,280		config.default_heap_pages,281		config.max_runtime_instances,282		config.runtime_cache_size,283	);284285	let (client, backend, keystore_container, task_manager) =286		sc_service::new_full_parts::<Block, RuntimeApi, _>(287			config,288			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),289			executor,290		)?;291	let client = Arc::new(client);292293	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());294295	let telemetry = telemetry.map(|(worker, telemetry)| {296		task_manager297			.spawn_handle()298			.spawn("telemetry", None, worker.run());299		telemetry300	});301302	let select_chain = sc_consensus::LongestChain::new(backend.clone());303304	let transaction_pool = sc_transaction_pool::BasicPool::new_full(305		config.transaction_pool.clone(),306		config.role.is_authority().into(),307		config.prometheus_registry(),308		task_manager.spawn_essential_handle(),309		client.clone(),310	);311312	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));313314	let frontier_backend = open_frontier_backend(client.clone(), config)?;315316	let import_queue = build_import_queue(317		client.clone(),318		backend.clone(),319		config,320		telemetry.as_ref().map(|telemetry| telemetry.handle()),321		&task_manager,322	)?;323	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));324325	let params = PartialComponents {326		backend,327		client,328		import_queue,329		keystore_container,330		task_manager,331		transaction_pool,332		select_chain,333		other: (334			telemetry,335			filter_pool,336			frontier_backend,337			telemetry_worker_handle,338			fee_history_cache,339		),340	};341342	Ok(params)343}344345async fn build_relay_chain_interface(346	polkadot_config: Configuration,347	parachain_config: &Configuration,348	telemetry_worker_handle: Option<TelemetryWorkerHandle>,349	task_manager: &mut TaskManager,350	collator_options: CollatorOptions,351	hwbench: Option<sc_sysinfo::HwBench>,352) -> RelayChainResult<(353	Arc<(dyn RelayChainInterface + 'static)>,354	Option<CollatorPair>,355)> {356	if collator_options.relay_chain_rpc_urls.is_empty() {357		build_inprocess_relay_chain(358			polkadot_config,359			parachain_config,360			telemetry_worker_handle,361			task_manager,362			hwbench,363		)364	} else {365		build_minimal_relay_chain_node(366			polkadot_config,367			task_manager,368			collator_options.relay_chain_rpc_urls,369		)370		.await371	}372}373374/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.375///376/// This is the actual implementation that is abstract over the executor and the runtime api.377#[sc_tracing::logging::prefix_logs_with("Parachain")]378async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(379	parachain_config: Configuration,380	polkadot_config: Configuration,381	collator_options: CollatorOptions,382	id: ParaId,383	build_import_queue: BIQ,384	build_consensus: BIC,385	hwbench: Option<sc_sysinfo::HwBench>,386) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>387where388	sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,389	Runtime: RuntimeInstance + Send + Sync + 'static,390	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,391	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,392	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>393		+ Send394		+ Sync395		+ 'static,396	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>397		+ fp_rpc::EthereumRuntimeRPCApi<Block>398		+ fp_rpc::ConvertTransactionRuntimeApi<Block>399		+ sp_session::SessionKeys<Block>400		+ sp_block_builder::BlockBuilder<Block>401		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>402		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>403		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>404		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>405		+ rmrk_rpc::RmrkApi<406			Block,407			AccountId,408			RmrkCollectionInfo<AccountId>,409			RmrkInstanceInfo<AccountId>,410			RmrkResourceInfo,411			RmrkPropertyInfo,412			RmrkBaseInfo<AccountId>,413			RmrkPartType,414			RmrkTheme,415		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>416		+ sp_api::Metadata<Block>417		+ sp_offchain::OffchainWorkerApi<Block>418		+ cumulus_primitives_core::CollectCollationInfo<Block>,419	ExecutorDispatch: NativeExecutionDispatch + 'static,420	BIQ: FnOnce(421		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,422		Arc<FullBackend>,423		&Configuration,424		Option<TelemetryHandle>,425		&TaskManager,426	) -> Result<427		sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,428		sc_service::Error,429	>,430	BIC: FnOnce(431		Arc<FullClient<RuntimeApi, ExecutorDispatch>>,432		Arc<FullBackend>,433		Option<&Registry>,434		Option<TelemetryHandle>,435		&TaskManager,436		Arc<dyn RelayChainInterface>,437		Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,438		Arc<NetworkService<Block, Hash>>,439		SyncCryptoStorePtr,440		bool,441	) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,442{443	let parachain_config = prepare_node_config(parachain_config);444445	let params =446		new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(&parachain_config, build_import_queue)?;447	let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =448		params.other;449450	let client = params.client.clone();451	let backend = params.backend.clone();452	let mut task_manager = params.task_manager;453454	let (relay_chain_interface, collator_key) = build_relay_chain_interface(455		polkadot_config,456		&parachain_config,457		telemetry_worker_handle,458		&mut task_manager,459		collator_options.clone(),460		hwbench.clone(),461	)462	.await463	.map_err(|e| match e {464		RelayChainError::ServiceError(polkadot_service::Error::Sub(x)) => x,465		s => s.to_string().into(),466	})?;467468	let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);469470	let force_authoring = parachain_config.force_authoring;471	let validator = parachain_config.role.is_authority();472	let prometheus_registry = parachain_config.prometheus_registry().cloned();473	let transaction_pool = params.transaction_pool.clone();474	let import_queue_service = params.import_queue.service();475476	let (network, system_rpc_tx, tx_handler_controller, start_network) =477		sc_service::build_network(sc_service::BuildNetworkParams {478			config: &parachain_config,479			client: client.clone(),480			transaction_pool: transaction_pool.clone(),481			spawn_handle: task_manager.spawn_handle(),482			import_queue: params.import_queue,483			block_announce_validator_builder: Some(Box::new(|_| {484				Box::new(block_announce_validator)485			})),486			warp_sync: None,487		})?;488489	let rpc_client = client.clone();490	let rpc_pool = transaction_pool.clone();491	let select_chain = params.select_chain.clone();492	let rpc_network = network.clone();493494	let rpc_frontier_backend = frontier_backend.clone();495496	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(497		task_manager.spawn_handle(),498		overrides_handle::<_, _, Runtime>(client.clone()),499		50,500		50,501		prometheus_registry.clone(),502	));503504	task_manager.spawn_essential_handle().spawn(505		"frontier-mapping-sync-worker",506		None,507		MappingSyncWorker::new(508			client.import_notification_stream(),509			Duration::new(6, 0),510			client.clone(),511			backend.clone(),512			frontier_backend.clone(),513			3,514			0,515			SyncStrategy::Normal,516		)517		.for_each(|()| futures::future::ready(())),518	);519520	let rpc_builder = Box::new(move |deny_unsafe, subscription_task_executor| {521		let full_deps = unique_rpc::FullDeps {522			backend: rpc_frontier_backend.clone(),523			deny_unsafe,524			client: rpc_client.clone(),525			pool: rpc_pool.clone(),526			graph: rpc_pool.pool().clone(),527			// TODO: Unhardcode528			enable_dev_signer: false,529			filter_pool: filter_pool.clone(),530			network: rpc_network.clone(),531			select_chain: select_chain.clone(),532			is_authority: validator,533			// TODO: Unhardcode534			max_past_logs: 10000,535			block_data_cache: block_data_cache.clone(),536			fee_history_cache: fee_history_cache.clone(),537			// TODO: Unhardcode538			fee_history_limit: 2048,539		};540541		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(542			full_deps,543			subscription_task_executor,544		)545		.map_err(Into::into)546	});547548	sc_service::spawn_tasks(sc_service::SpawnTasksParams {549		rpc_builder,550		client: client.clone(),551		transaction_pool: transaction_pool.clone(),552		task_manager: &mut task_manager,553		config: parachain_config,554		keystore: params.keystore_container.sync_keystore(),555		backend: backend.clone(),556		network: network.clone(),557		system_rpc_tx,558		telemetry: telemetry.as_mut(),559		tx_handler_controller,560	})?;561562	if let Some(hwbench) = hwbench {563		sc_sysinfo::print_hwbench(&hwbench);564565		if let Some(ref mut telemetry) = telemetry {566			let telemetry_handle = telemetry.handle();567			task_manager.spawn_handle().spawn(568				"telemetry_hwbench",569				None,570				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),571			);572		}573	}574575	let announce_block = {576		let network = network.clone();577		Arc::new(Box::new(move |hash, data| {578			network.announce_block(hash, data)579		}))580	};581582	let relay_chain_slot_duration = Duration::from_secs(6);583584	if validator {585		let parachain_consensus = build_consensus(586			client.clone(),587			backend.clone(),588			prometheus_registry.as_ref(),589			telemetry.as_ref().map(|t| t.handle()),590			&task_manager,591			relay_chain_interface.clone(),592			transaction_pool,593			network,594			params.keystore_container.sync_keystore(),595			force_authoring,596		)?;597598		let spawner = task_manager.spawn_handle();599600		let params = StartCollatorParams {601			para_id: id,602			block_status: client.clone(),603			announce_block,604			client: client.clone(),605			task_manager: &mut task_manager,606			spawner,607			parachain_consensus,608			import_queue: import_queue_service,609			collator_key: collator_key.expect("Command line arguments do not allow this. qed"),610			relay_chain_interface,611			relay_chain_slot_duration,612		};613614		start_collator(params).await?;615	} else {616		let params = StartFullNodeParams {617			client: client.clone(),618			announce_block,619			task_manager: &mut task_manager,620			para_id: id,621			import_queue: import_queue_service,622			relay_chain_interface,623			relay_chain_slot_duration,624		};625626		start_full_node(params)?;627	}628629	start_network.start_network();630631	Ok((task_manager, client))632}633634/// Build the import queue for the the parachain runtime.635pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(636	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,637	backend: Arc<FullBackend>,638	config: &Configuration,639	telemetry: Option<TelemetryHandle>,640	task_manager: &TaskManager,641) -> Result<642	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,643	sc_service::Error,644>645where646	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>647		+ Send648		+ Sync649		+ 'static,650	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>651		+ sp_block_builder::BlockBuilder<Block>652		+ sp_consensus_aura::AuraApi<Block, AuraId>653		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,654	ExecutorDispatch: NativeExecutionDispatch + 'static,655{656	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;657658	let block_import = ParachainBlockImport::new(client.clone(), backend.clone());659660	cumulus_client_consensus_aura::import_queue::<661		sp_consensus_aura::sr25519::AuthorityPair,662		_,663		_,664		_,665		_,666		_,667	>(cumulus_client_consensus_aura::ImportQueueParams {668		block_import,669		client: client.clone(),670		create_inherent_data_providers: move |_, _| async move {671			let time = sp_timestamp::InherentDataProvider::from_system_time();672673			let slot =674				sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(675					*time,676					slot_duration,677				);678679			Ok((slot, time))680		},681		registry: config.prometheus_registry(),682		spawner: &task_manager.spawn_essential_handle(),683		telemetry,684	})685	.map_err(Into::into)686}687688/// Start a normal parachain node.689pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(690	parachain_config: Configuration,691	polkadot_config: Configuration,692	collator_options: CollatorOptions,693	id: ParaId,694	hwbench: Option<sc_sysinfo::HwBench>,695) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>696where697	Runtime: RuntimeInstance + Send + Sync + 'static,698	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,699	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,700	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>701		+ Send702		+ Sync703		+ 'static,704	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>705		+ fp_rpc::EthereumRuntimeRPCApi<Block>706		+ fp_rpc::ConvertTransactionRuntimeApi<Block>707		+ sp_session::SessionKeys<Block>708		+ sp_block_builder::BlockBuilder<Block>709		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>710		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>711		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>712		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>713		+ rmrk_rpc::RmrkApi<714			Block,715			AccountId,716			RmrkCollectionInfo<AccountId>,717			RmrkInstanceInfo<AccountId>,718			RmrkResourceInfo,719			RmrkPropertyInfo,720			RmrkBaseInfo<AccountId>,721			RmrkPartType,722			RmrkTheme,723		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>724		+ sp_api::Metadata<Block>725		+ sp_offchain::OffchainWorkerApi<Block>726		+ cumulus_primitives_core::CollectCollationInfo<Block>727		+ sp_consensus_aura::AuraApi<Block, AuraId>,728	ExecutorDispatch: NativeExecutionDispatch + 'static,729{730	start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(731		parachain_config,732		polkadot_config,733		collator_options,734		id,735		parachain_build_import_queue,736		|client,737		 backend,738		 prometheus_registry,739		 telemetry,740		 task_manager,741		 relay_chain_interface,742		 transaction_pool,743		 sync_oracle,744		 keystore,745		 force_authoring| {746			let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;747748			let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(749				task_manager.spawn_handle(),750				client.clone(),751				transaction_pool,752				prometheus_registry,753				telemetry.clone(),754			);755756			let block_import = ParachainBlockImport::new(client.clone(), backend.clone());757758			Ok(AuraConsensus::build::<759				sp_consensus_aura::sr25519::AuthorityPair,760				_,761				_,762				_,763				_,764				_,765				_,766			>(BuildAuraConsensusParams {767				proposer_factory,768				create_inherent_data_providers: move |_, (relay_parent, validation_data)| {769					let relay_chain_interface = relay_chain_interface.clone();770					async move {771						let parachain_inherent =772						cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(773							relay_parent,774							&relay_chain_interface,775							&validation_data,776							id,777						).await;778779						let time = sp_timestamp::InherentDataProvider::from_system_time();780781						let slot =782						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(783							*time,784							slot_duration,785						);786787						let parachain_inherent = parachain_inherent.ok_or_else(|| {788							Box::<dyn std::error::Error + Send + Sync>::from(789								"Failed to create parachain inherent",790							)791						})?;792						Ok((slot, time, parachain_inherent))793					}794				},795				block_import,796				para_client: client,797				backoff_authoring_blocks: Option::<()>::None,798				sync_oracle,799				keystore,800				force_authoring,801				slot_duration,802				// We got around 500ms for proposing803				block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),804				telemetry,805				max_block_proposal_slot_portion: None,806			}))807		},808		hwbench,809	)810	.await811}812813fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(814	client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,815	_: Arc<FullBackend>,816	config: &Configuration,817	_: Option<TelemetryHandle>,818	task_manager: &TaskManager,819) -> Result<820	sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,821	sc_service::Error,822>823where824	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>825		+ Send826		+ Sync827		+ 'static,828	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>829		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,830	ExecutorDispatch: NativeExecutionDispatch + 'static,831{832	Ok(sc_consensus_manual_seal::import_queue(833		Box::new(client.clone()),834		&task_manager.spawn_essential_handle(),835		config.prometheus_registry(),836	))837}838839/// Builds a new development service. This service uses instant seal, and mocks840/// the parachain inherent841pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(842	config: Configuration,843	autoseal_interval: Duration,844) -> sc_service::error::Result<TaskManager>845where846	Runtime: RuntimeInstance + Send + Sync + 'static,847	<Runtime as RuntimeInstance>::CrossAccountId: Serialize,848	for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,849	RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>850		+ Send851		+ Sync852		+ 'static,853	RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>854		+ fp_rpc::EthereumRuntimeRPCApi<Block>855		+ fp_rpc::ConvertTransactionRuntimeApi<Block>856		+ sp_session::SessionKeys<Block>857		+ sp_block_builder::BlockBuilder<Block>858		+ pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>859		+ sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>860		+ up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>861		+ app_promotion_rpc::AppPromotionApi<Block, BlockNumber, Runtime::CrossAccountId, AccountId>862		+ rmrk_rpc::RmrkApi<863			Block,864			AccountId,865			RmrkCollectionInfo<AccountId>,866			RmrkInstanceInfo<AccountId>,867			RmrkResourceInfo,868			RmrkPropertyInfo,869			RmrkBaseInfo<AccountId>,870			RmrkPartType,871			RmrkTheme,872		> + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>873		+ sp_api::Metadata<Block>874		+ sp_offchain::OffchainWorkerApi<Block>875		+ cumulus_primitives_core::CollectCollationInfo<Block>876		+ sp_consensus_aura::AuraApi<Block, AuraId>,877	ExecutorDispatch: NativeExecutionDispatch + 'static,878{879	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};880	use fc_consensus::FrontierBlockImport;881	use sc_client_api::HeaderBackend;882883	let sc_service::PartialComponents {884		client,885		backend,886		mut task_manager,887		import_queue,888		keystore_container,889		select_chain: maybe_select_chain,890		transaction_pool,891		other:892			(telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),893	} = new_partial::<RuntimeApi, ExecutorDispatch, _>(894		&config,895		dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,896	)?;897	let prometheus_registry = config.prometheus_registry().cloned();898899	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(900		task_manager.spawn_handle(),901		overrides_handle::<_, _, Runtime>(client.clone()),902		50,903		50,904		prometheus_registry.clone(),905	));906907	let (network, system_rpc_tx, tx_handler_controller, network_starter) =908		sc_service::build_network(sc_service::BuildNetworkParams {909			config: &config,910			client: client.clone(),911			transaction_pool: transaction_pool.clone(),912			spawn_handle: task_manager.spawn_handle(),913			import_queue,914			block_announce_validator_builder: None,915			warp_sync: None,916		})?;917918	if config.offchain_worker.enabled {919		sc_service::build_offchain_workers(920			&config,921			task_manager.spawn_handle(),922			client.clone(),923			network.clone(),924		);925	}926927	let collator = config.role.is_authority();928929	let select_chain = maybe_select_chain.clone();930931	if collator {932		let block_import =933			FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());934935		let env = sc_basic_authorship::ProposerFactory::new(936			task_manager.spawn_handle(),937			client.clone(),938			transaction_pool.clone(),939			prometheus_registry.as_ref(),940			telemetry.as_ref().map(|x| x.handle()),941		);942943		let transactions_commands_stream: Box<944			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,945		> = Box::new(946			transaction_pool947				.pool()948				.validated_pool()949				.import_notification_stream()950				.map(|_| EngineCommand::SealNewBlock {951					create_empty: true,952					finalize: false,953					parent_hash: None,954					sender: None,955				}),956		);957958		let autoseal_interval = Box::pin(AutosealInterval::new(&config, autoseal_interval));959		let idle_commands_stream: Box<960			dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin,961		> = Box::new(autoseal_interval.map(|_| EngineCommand::SealNewBlock {962			create_empty: true,963			finalize: false,964			parent_hash: None,965			sender: None,966		}));967968		let commands_stream = select(transactions_commands_stream, idle_commands_stream);969970		let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;971		let client_set_aside_for_cidp = client.clone();972973		task_manager.spawn_essential_handle().spawn_blocking(974			"authorship_task",975			Some("block-authoring"),976			run_manual_seal(ManualSealParams {977				block_import,978				env,979				client: client.clone(),980				pool: transaction_pool.clone(),981				commands_stream,982				select_chain: select_chain.clone(),983				consensus_data_provider: None,984				create_inherent_data_providers: move |block: Hash, ()| {985					let current_para_block = client_set_aside_for_cidp986						.number(block)987						.expect("Header lookup should succeed")988						.expect("Header passed in as parent should be present in backend.");989990					let client_for_xcm = client_set_aside_for_cidp.clone();991					async move {992						let time = sp_timestamp::InherentDataProvider::from_system_time();993994						let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {995							current_para_block,996							relay_offset: 1000,997							relay_blocks_per_para_block: 2,998							para_blocks_per_relay_epoch: 0,999							xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(1000								&*client_for_xcm,1001								block,1002								Default::default(),1003								Default::default(),1004							),1005							relay_randomness_config: (),1006							raw_downward_messages: vec![],1007							raw_horizontal_messages: vec![],1008						};10091010						let slot =1011						sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration(1012							*time,1013							slot_duration,1014						);10151016						Ok((time, slot, mocked_parachain))1017					}1018				},1019			}),1020		);1021	}10221023	task_manager.spawn_essential_handle().spawn(1024		"frontier-mapping-sync-worker",1025		Some("block-authoring"),1026		MappingSyncWorker::new(1027			client.import_notification_stream(),1028			Duration::new(6, 0),1029			client.clone(),1030			backend.clone(),1031			frontier_backend.clone(),1032			3,1033			0,1034			SyncStrategy::Normal,1035		)1036		.for_each(|()| futures::future::ready(())),1037	);10381039	let rpc_client = client.clone();1040	let rpc_pool = transaction_pool.clone();1041	let rpc_network = network.clone();1042	let rpc_frontier_backend = frontier_backend.clone();1043	let rpc_builder = Box::new(move |deny_unsafe, subscription_executor| {1044		let full_deps = unique_rpc::FullDeps {1045			backend: rpc_frontier_backend.clone(),1046			deny_unsafe,1047			client: rpc_client.clone(),1048			pool: rpc_pool.clone(),1049			graph: rpc_pool.pool().clone(),1050			// TODO: Unhardcode1051			enable_dev_signer: false,1052			filter_pool: filter_pool.clone(),1053			network: rpc_network.clone(),1054			select_chain: select_chain.clone(),1055			is_authority: collator,1056			// TODO: Unhardcode1057			max_past_logs: 10000,1058			block_data_cache: block_data_cache.clone(),1059			fee_history_cache: fee_history_cache.clone(),1060			// TODO: Unhardcode1061			fee_history_limit: 2048,1062		};10631064		unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(1065			full_deps,1066			subscription_executor,1067		)1068		.map_err(Into::into)1069	});10701071	sc_service::spawn_tasks(sc_service::SpawnTasksParams {1072		network,1073		client,1074		keystore: keystore_container.sync_keystore(),1075		task_manager: &mut task_manager,1076		transaction_pool,1077		rpc_builder,1078		backend,1079		system_rpc_tx,1080		config,1081		telemetry: None,1082		tx_handler_controller,1083	})?;10841085	network_starter.start_network();1086	Ok(task_manager)1087}
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -780,15 +780,16 @@
 
             #[cfg(feature = "try-runtime")]
             impl frame_try_runtime::TryRuntime<Block> for Runtime {
-                fn on_runtime_upgrade() -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {
+                fn on_runtime_upgrade(checks: bool) -> (frame_support::pallet_prelude::Weight, frame_support::pallet_prelude::Weight) {
                     log::info!("try-runtime::on_runtime_upgrade unique-chain.");
-                    let weight = Executive::try_runtime_upgrade().unwrap();
+                    let weight = Executive::try_runtime_upgrade(checks).unwrap();
                     (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)
                 }
 
                 fn execute_block(
                     block: Block,
                     state_root_check: bool,
+                    signature_check: bool,
                     select: frame_try_runtime::TryStateSelect
                 ) -> frame_support::pallet_prelude::Weight {
                     log::info!(
@@ -799,7 +800,7 @@
                         select,
                     );
 
-                    Executive::try_execute_block(block, state_root_check, select).unwrap()
+                    Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
                 }
             }
         }
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -91,6 +91,7 @@
     'pallet-unique-scheduler-v2/try-runtime',
     'pallet-maintenance/try-runtime',
     'pallet-test-utils?/try-runtime',
+    'fp-self-contained/try-runtime',
 ]
 std = [
     'codec/std',
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -86,6 +86,7 @@
     'pallet-evm-transaction-payment/try-runtime',
     'pallet-evm-migration/try-runtime',
     'pallet-maintenance/try-runtime',
+    'fp-self-contained/try-runtime',
 ]
 std = [
     'codec/std',
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -87,6 +87,7 @@
     'pallet-evm-transaction-payment/try-runtime',
     'pallet-evm-migration/try-runtime',
     'pallet-maintenance/try-runtime',
+    'fp-self-contained/try-runtime',
 ]
 std = [
     'codec/std',