difftreelog
Adjust node and rpc to work with different runtimes
in: master
7 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11942,6 +11942,7 @@
"opal-runtime",
"pallet-ethereum",
"pallet-transaction-payment-rpc",
+ "pallet-transaction-payment-rpc-runtime-api",
"parity-scale-codec",
"parking_lot 0.11.2",
"polkadot-cli",
@@ -11988,7 +11989,9 @@
"substrate-prometheus-endpoint",
"unique-rpc",
"unique-runtime",
+ "unique-runtime-common",
"up-data-structs",
+ "up-rpc",
]
[[package]]
@@ -12003,12 +12006,11 @@
"futures 0.3.21",
"jsonrpc-core",
"jsonrpc-pubsub",
- "opal-runtime",
+ "pallet-common",
"pallet-ethereum",
"pallet-transaction-payment-rpc",
"pallet-transaction-payment-rpc-runtime-api",
"pallet-unique",
- "quartz-runtime",
"sc-client-api",
"sc-consensus-aura",
"sc-consensus-epochs",
@@ -12020,6 +12022,7 @@
"sc-rpc-api",
"sc-service",
"sc-transaction-pool",
+ "serde",
"sp-api",
"sp-block-builder",
"sp-blockchain",
@@ -12034,7 +12037,7 @@
"substrate-frame-rpc-system",
"tokio 0.2.25",
"uc-rpc",
- "unique-runtime",
+ "unique-runtime-common",
"up-rpc",
]
@@ -12118,10 +12121,13 @@
name = "unique-runtime-common"
version = "0.1.0"
dependencies = [
+ "fp-rpc",
"frame-support",
"frame-system",
+ "pallet-common",
"parity-scale-codec",
"scale-info",
+ "sp-consensus-aura",
"sp-core",
"sp-runtime",
]
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -238,6 +238,10 @@
################################################################################
# Local dependencies
+[dependencies.unique-runtime-common]
+default-features = false
+path = "../../runtime/common"
+
[dependencies.unique-runtime]
path = '../../runtime/unique'
optional = true
@@ -254,6 +258,13 @@
path = "../../primitives/data-structs"
default-features = false
+[dependencies.up-rpc]
+path = "../../primitives/rpc"
+
+[dependencies.pallet-transaction-payment-rpc-runtime-api]
+git = 'https://github.com/paritytech/substrate.git'
+branch = 'polkadot-v0.9.17'
+
################################################################################
# Package
@@ -295,7 +306,7 @@
unique-rpc = { default-features = false, path = "../rpc" }
[features]
-default = ["unique-runtime"]
+default = ["unique-runtime", "quartz-runtime", "opal-runtime"]
runtime-benchmarks = [
'unique-runtime/runtime-benchmarks',
'polkadot-service/runtime-benchmarks',
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -24,20 +24,33 @@
use serde::{Deserialize, Serialize};
use serde_json::map::Map;
-#[cfg(feature = "unique-runtime")]
-use unique_runtime as runtime;
+use unique_runtime_common::types::*;
-#[cfg(feature = "quartz-runtime")]
-use quartz_runtime as runtime;
+/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
+pub type ChainSpec = sc_service::GenericChainSpec<unique_runtime::GenesisConfig, Extensions>;
-#[cfg(feature = "opal-runtime")]
-use opal_runtime as runtime;
+pub trait RuntimeIdentification {
+ fn is_unique(&self) -> bool;
+
+ fn is_quartz(&self) -> bool;
-use runtime::{*, opaque::*};
+ fn is_opal(&self) -> bool;
+}
-/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.
-pub type ChainSpec = sc_service::GenericChainSpec<runtime::GenesisConfig, Extensions>;
+impl RuntimeIdentification for Box<dyn sc_service::ChainSpec> {
+ fn is_unique(&self) -> bool {
+ self.id().starts_with("unique")
+ }
+ fn is_quartz(&self) -> bool {
+ self.id().starts_with("quartz")
+ }
+
+ fn is_opal(&self) -> bool {
+ self.id().starts_with("opal")
+ }
+}
+
/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
@@ -225,10 +238,12 @@
initial_authorities: Vec<AuraId>,
endowed_accounts: Vec<AccountId>,
id: ParaId,
-) -> GenesisConfig {
+) -> unique_runtime::GenesisConfig {
+ use unique_runtime::*;
+
GenesisConfig {
- system: runtime::SystemConfig {
- code: runtime::WASM_BINARY
+ system: SystemConfig {
+ code: WASM_BINARY
.expect("WASM binary was not build, please build it!")
.to_vec(),
},
@@ -245,9 +260,9 @@
key: Some(root_key),
},
vesting: VestingConfig { vesting: vec![] },
- parachain_info: runtime::ParachainInfoConfig { parachain_id: id },
+ parachain_info: ParachainInfoConfig { parachain_id: id },
parachain_system: Default::default(),
- aura: runtime::AuraConfig {
+ aura: AuraConfig {
authorities: initial_authorities,
},
aura_ext: Default::default(),
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -33,10 +33,20 @@
// limitations under the License.
use crate::{
- chain_spec,
+ chain_spec::{self, RuntimeIdentification},
cli::{Cli, RelayChainCli, Subcommand},
- service::{new_partial, ParachainRuntimeExecutor},
+ service::new_partial,
};
+
+#[cfg(feature = "unique-runtime")]
+use crate::service::UniqueRuntimeExecutor;
+
+#[cfg(feature = "quartz-runtime")]
+use crate::service::QuartzRuntimeExecutor;
+
+#[cfg(feature = "opal-runtime")]
+use crate::service::OpalRuntimeExecutor;
+
use codec::Encode;
use cumulus_primitives_core::ParaId;
use cumulus_client_service::genesis::generate_genesis_block;
@@ -53,16 +63,14 @@
use sp_runtime::traits::Block as BlockT;
use std::{io::Write, net::SocketAddr};
-#[cfg(feature = "unique-runtime")]
-use unique_runtime as runtime;
+use unique_runtime_common::types::Block;
-#[cfg(feature = "quartz-runtime")]
-use quartz_runtime as runtime;
-
-#[cfg(feature = "opal-runtime")]
-use opal_runtime as runtime;
-
-use runtime::Block;
+macro_rules! no_runtime_err {
+ ($chain_spec:expr) => {
+ format!("No runtime valid runtime was found, chain id: {}",
+ $chain_spec.id())
+ };
+}
fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
@@ -79,7 +87,7 @@
impl SubstrateCli for Cli {
// TODO use args
fn impl_name() -> String {
- format!("{} Node", runtime::RUNTIME_NAME)
+ "Unique Node".into()
}
fn impl_version() -> String {
@@ -88,11 +96,10 @@
// TODO use args
fn description() -> String {
format!(
- "{} Node\n\nThe command-line arguments provided first will be \
+ "Unique Node\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
{} [parachain-args] -- [relaychain-args]",
- runtime::RUNTIME_NAME,
Self::executable_name()
)
}
@@ -114,15 +121,30 @@
load_spec(id)
}
- fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
- &runtime::VERSION
+ fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {
+ #[cfg(feature = "unique-runtime")]
+ if chain_spec.is_unique() {
+ return &unique_runtime::VERSION;
+ }
+
+ #[cfg(feature = "quartz-runtime")]
+ if chain_spec.is_quartz() {
+ return &quartz_runtime::VERSION;
+ }
+
+ #[cfg(feature = "opal-runtime")]
+ if chain_spec.is_opal() {
+ return &opal_runtime::VERSION;
+ }
+
+ panic!("{}", no_runtime_err!(chain_spec));
}
}
impl SubstrateCli for RelayChainCli {
// TODO use args
fn impl_name() -> String {
- format!("{} Node", runtime::RUNTIME_NAME)
+ "Unique Node".into()
}
fn impl_version() -> String {
@@ -130,13 +152,11 @@
}
// TODO use args
fn description() -> String {
- format!(
- "{} Node\n\nThe command-line arguments provided first will be \
+ "Unique Node\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
- parachain-collator [parachain-args] -- [relaychain-args]",
- runtime::RUNTIME_NAME
- )
+ parachain-collator [parachain-args] -- [relaychain-args]"
+ .into()
}
fn author() -> String {
@@ -173,16 +193,50 @@
macro_rules! construct_async_run {
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
let runner = $cli.create_runner($cmd)?;
- runner.async_run(|$config| {
- let $components = new_partial::<
- _
- >(
- &$config,
- crate::service::parachain_build_import_queue,
- )?;
- let task_manager = $components.task_manager;
- { $( $code )* }.map(|v| (v, task_manager))
- })
+
+ #[cfg(feature = "unique-runtime")]
+ if runner.config().chain_spec.is_unique() {
+ return runner.async_run(|$config| {
+ let $components = new_partial::<
+ unique_runtime::RuntimeApi, UniqueRuntimeExecutor, _
+ >(
+ &$config,
+ crate::service::parachain_build_import_queue,
+ )?;
+ let task_manager = $components.task_manager;
+ { $( $code )* }.map(|v| (v, task_manager))
+ });
+ }
+
+ #[cfg(feature = "quartz-runtime")]
+ if runner.config().chain_spec.is_quartz() {
+ return runner.async_run(|$config| {
+ let $components = new_partial::<
+ quartz_runtime::RuntimeApi, QuartzRuntimeExecutor, _
+ >(
+ &$config,
+ crate::service::parachain_build_import_queue,
+ )?;
+ let task_manager = $components.task_manager;
+ { $( $code )* }.map(|v| (v, task_manager))
+ });
+ }
+
+ #[cfg(feature = "opal-runtime")]
+ if runner.config().chain_spec.is_opal() {
+ return runner.async_run(|$config| {
+ let $components = new_partial::<
+ opal_runtime::RuntimeApi, OpalRuntimeExecutor, _
+ >(
+ &$config,
+ crate::service::parachain_build_import_queue,
+ )?;
+ let task_manager = $components.task_manager;
+ { $( $code )* }.map(|v| (v, task_manager))
+ });
+ }
+
+ Err(no_runtime_err!(runner.config().chain_spec).into())
}}
}
@@ -286,8 +340,24 @@
Some(Subcommand::Benchmark(cmd)) => {
if cfg!(feature = "runtime-benchmarks") {
let runner = cli.create_runner(cmd)?;
+ runner.sync_run(|config| {
+ #[cfg(feature = "unique-runtime")]
+ if config.chain_spec.is_unique() {
+ return cmd.run::<Block, UniqueRuntimeExecutor>(config);
+ }
+
+ #[cfg(feature = "quartz-runtime")]
+ if config.chain_spec.is_quartz() {
+ return cmd.run::<Block, QuartzRuntimeExecutor>(config);
+ }
+
+ #[cfg(feature = "opal-runtime")]
+ if config.chain_spec.is_opal() {
+ return cmd.run::<Block, OpalRuntimeExecutor>(config);
+ }
- runner.sync_run(|config| cmd.run::<Block, ParachainRuntimeExecutor>(config))
+ Err(no_runtime_err!(config.chain_spec).into())
+ })
} else {
Err("Benchmarking wasn't enabled when building the node. \
You can enable it with `--features runtime-benchmarks`."
@@ -341,10 +411,43 @@
}
);
- crate::service::start_node(config, polkadot_config, id)
+ #[cfg(feature = "unique-runtime")]
+ if config.chain_spec.is_unique() {
+ return crate::service::start_node::<
+ unique_runtime::Runtime,
+ unique_runtime::RuntimeApi,
+ UniqueRuntimeExecutor,
+ >(config, polkadot_config, id)
.await
.map(|r| r.0)
- .map_err(Into::into)
+ .map_err(Into::into);
+ }
+
+ #[cfg(feature = "quartz-runtime")]
+ if config.chain_spec.is_quartz() {
+ return crate::service::start_node::<
+ quartz_runtime::Runtime,
+ quartz_runtime::RuntimeApi,
+ QuartzRuntimeExecutor,
+ >(config, polkadot_config, id)
+ .await
+ .map(|r| r.0)
+ .map_err(Into::into);
+ }
+
+ #[cfg(feature = "opal-runtime")]
+ if config.chain_spec.is_opal() {
+ return crate::service::start_node::<
+ opal_runtime::Runtime,
+ opal_runtime::RuntimeApi,
+ OpalRuntimeExecutor,
+ >(config, polkadot_config, id)
+ .await
+ .map(|r| r.0)
+ .map_err(Into::into);
+ }
+
+ Err(no_runtime_err!(config.chain_spec).into())
})
}
}
node/cli/src/service.rsdiffbeforeafterboth1// 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//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.1819// std20use std::sync::Arc;21use std::sync::Mutex;22use std::collections::BTreeMap;23use std::time::Duration;24use fc_rpc_core::types::FeeHistoryCache;25use futures::StreamExt;2627use unique_rpc::overrides_handle;28// Local Runtime Types29#[cfg(feature = "unique-runtime")]30use unique_runtime as runtime;3132#[cfg(feature = "quartz-runtime")]33use quartz_runtime as runtime;3435#[cfg(feature = "opal-runtime")]36use opal_runtime as runtime;3738use runtime::RuntimeApi;3940// Cumulus Imports41use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};42use cumulus_client_consensus_common::ParachainConsensus;43use cumulus_client_service::{44 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,45};46use cumulus_client_network::BlockAnnounceValidator;47use cumulus_primitives_core::ParaId;48use cumulus_relay_chain_interface::RelayChainInterface;49use cumulus_relay_chain_local::build_relay_chain_interface;5051// Substrate Imports52use sc_client_api::ExecutorProvider;53use sc_executor::NativeElseWasmExecutor;54use sc_executor::NativeExecutionDispatch;55use sc_network::NetworkService;56use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};57use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};58use sp_consensus::SlotData;59use sp_keystore::SyncCryptoStorePtr;60use sp_runtime::traits::BlakeTwo256;61use substrate_prometheus_endpoint::Registry;62use sc_client_api::BlockchainEvents;6364// Frontier Imports65use fc_rpc_core::types::FilterPool;66use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};6768// Runtime type overrides69type BlockNumber = u32;70type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>;71pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>;72type Hash = sp_core::H256;7374/// Native executor instance.75pub struct ParachainRuntimeExecutor;7677impl NativeExecutionDispatch for ParachainRuntimeExecutor {78 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;7980 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {81 runtime::api::dispatch(method, data)82 }8384 fn native_version() -> sc_executor::NativeVersion {85 runtime::native_version()86 }87}8889pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {90 let config_dir = config91 .base_path92 .as_ref()93 .map(|base_path| base_path.config_dir(config.chain_spec.id()))94 .unwrap_or_else(|| {95 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())96 });97 let database_dir = config_dir.join("frontier").join("db");9899 Ok(Arc::new(fc_db::Backend::<Block>::new(100 &fc_db::DatabaseSettings {101 source: fc_db::DatabaseSettingsSrc::RocksDb {102 path: database_dir,103 cache_size: 0,104 },105 },106 )?))107}108109type ExecutorDispatch = ParachainRuntimeExecutor;110111type FullClient =112 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;113type FullBackend = sc_service::TFullBackend<Block>;114type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;115116/// Starts a `ServiceBuilder` for a full service.117///118/// Use this macro if you don't actually need the full service, but just the builder in order to119/// be able to perform chain operations.120#[allow(clippy::type_complexity)]121pub fn new_partial<BIQ>(122 config: &Configuration,123 build_import_queue: BIQ,124) -> Result<125 PartialComponents<126 FullClient,127 FullBackend,128 FullSelectChain,129 sc_consensus::DefaultImportQueue<Block, FullClient>,130 sc_transaction_pool::FullPool<Block, FullClient>,131 (132 Option<Telemetry>,133 Option<FilterPool>,134 Arc<fc_db::Backend<Block>>,135 Option<TelemetryWorkerHandle>,136 FeeHistoryCache,137 ),138 >,139 sc_service::Error,140>141where142 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,143 ExecutorDispatch: NativeExecutionDispatch + 'static,144 BIQ: FnOnce(145 Arc<FullClient>,146 &Configuration,147 Option<TelemetryHandle>,148 &TaskManager,149 ) -> Result<sc_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error>,150{151 let _telemetry = config152 .telemetry_endpoints153 .clone()154 .filter(|x| !x.is_empty())155 .map(|endpoints| -> Result<_, sc_telemetry::Error> {156 let worker = TelemetryWorker::new(16)?;157 let telemetry = worker.handle().new_telemetry(endpoints);158 Ok((worker, telemetry))159 })160 .transpose()?;161162 let telemetry = config163 .telemetry_endpoints164 .clone()165 .filter(|x| !x.is_empty())166 .map(|endpoints| -> Result<_, sc_telemetry::Error> {167 let worker = TelemetryWorker::new(16)?;168 let telemetry = worker.handle().new_telemetry(endpoints);169 Ok((worker, telemetry))170 })171 .transpose()?;172173 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(174 config.wasm_method,175 config.default_heap_pages,176 config.max_runtime_instances,177 config.runtime_cache_size,178 );179180 let (client, backend, keystore_container, task_manager) =181 sc_service::new_full_parts::<Block, RuntimeApi, _>(182 config,183 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),184 executor,185 )?;186 let client = Arc::new(client);187188 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());189190 let telemetry = telemetry.map(|(worker, telemetry)| {191 task_manager192 .spawn_handle()193 .spawn("telemetry", None, worker.run());194 telemetry195 });196197 let select_chain = sc_consensus::LongestChain::new(backend.clone());198199 let transaction_pool = sc_transaction_pool::BasicPool::new_full(200 config.transaction_pool.clone(),201 config.role.is_authority().into(),202 config.prometheus_registry(),203 task_manager.spawn_essential_handle(),204 client.clone(),205 );206207 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));208209 let frontier_backend = open_frontier_backend(config)?;210211 let import_queue = build_import_queue(212 client.clone(),213 config,214 telemetry.as_ref().map(|telemetry| telemetry.handle()),215 &task_manager,216 )?;217 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));218219 let params = PartialComponents {220 backend,221 client,222 import_queue,223 keystore_container,224 task_manager,225 transaction_pool,226 select_chain,227 other: (228 telemetry,229 filter_pool,230 frontier_backend,231 telemetry_worker_handle,232 fee_history_cache,233 ),234 };235236 Ok(params)237}238239/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.240///241/// This is the actual implementation that is abstract over the executor and the runtime api.242#[sc_tracing::logging::prefix_logs_with("Parachain")]243async fn start_node_impl<BIQ, BIC>(244 parachain_config: Configuration,245 polkadot_config: Configuration,246 id: ParaId,247 build_import_queue: BIQ,248 build_consensus: BIC,249) -> sc_service::error::Result<(TaskManager, Arc<FullClient>)>250where251 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,252 ExecutorDispatch: NativeExecutionDispatch + 'static,253 BIQ: FnOnce(254 Arc<FullClient>,255 &Configuration,256 Option<TelemetryHandle>,257 &TaskManager,258 ) -> Result<sc_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error>,259 BIC: FnOnce(260 Arc<FullClient>,261 Option<&Registry>,262 Option<TelemetryHandle>,263 &TaskManager,264 Arc<dyn RelayChainInterface>,265 Arc<sc_transaction_pool::FullPool<Block, FullClient>>,266 Arc<NetworkService<Block, Hash>>,267 SyncCryptoStorePtr,268 bool,269 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,270{271 if matches!(parachain_config.role, Role::Light) {272 return Err("Light client not supported!".into());273 }274275 let parachain_config = prepare_node_config(parachain_config);276277 let params = new_partial::<BIQ>(¶chain_config, build_import_queue)?;278 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =279 params.other;280281 let client = params.client.clone();282 let backend = params.backend.clone();283 let mut task_manager = params.task_manager;284285 let (relay_chain_interface, collator_key) =286 build_relay_chain_interface(polkadot_config, telemetry_worker_handle, &mut task_manager)287 .map_err(|e| match e {288 polkadot_service::Error::Sub(x) => x,289 s => format!("{}", s).into(),290 })?;291292 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);293294 let force_authoring = parachain_config.force_authoring;295 let validator = parachain_config.role.is_authority();296 let prometheus_registry = parachain_config.prometheus_registry().cloned();297 let transaction_pool = params.transaction_pool.clone();298 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);299300 let (network, system_rpc_tx, start_network) =301 sc_service::build_network(sc_service::BuildNetworkParams {302 config: ¶chain_config,303 client: client.clone(),304 transaction_pool: transaction_pool.clone(),305 spawn_handle: task_manager.spawn_handle(),306 import_queue: import_queue.clone(),307 block_announce_validator_builder: Some(Box::new(|_| {308 Box::new(block_announce_validator)309 })),310 warp_sync: None,311 })?;312313 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());314 let rpc_client = client.clone();315 let rpc_pool = transaction_pool.clone();316 let select_chain = params.select_chain.clone();317 let rpc_network = network.clone();318319 let rpc_frontier_backend = frontier_backend.clone();320321 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(322 task_manager.spawn_handle(),323 overrides_handle(client.clone()),324 50,325 50,326 ));327328 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {329 let full_deps = unique_rpc::FullDeps {330 backend: rpc_frontier_backend.clone(),331 deny_unsafe,332 client: rpc_client.clone(),333 pool: rpc_pool.clone(),334 graph: rpc_pool.pool().clone(),335 // TODO: Unhardcode336 enable_dev_signer: false,337 filter_pool: filter_pool.clone(),338 network: rpc_network.clone(),339 select_chain: select_chain.clone(),340 is_authority: validator,341 // TODO: Unhardcode342 max_past_logs: 10000,343 block_data_cache: block_data_cache.clone(),344 fee_history_cache: fee_history_cache.clone(),345 // TODO: Unhardcode346 fee_history_limit: 2048,347 };348349 Ok(unique_rpc::create_full::<_, _, _, _, RuntimeApi, _>(350 full_deps,351 subscription_executor.clone(),352 ))353 });354355 task_manager.spawn_essential_handle().spawn(356 "frontier-mapping-sync-worker",357 None,358 MappingSyncWorker::new(359 client.import_notification_stream(),360 Duration::new(6, 0),361 client.clone(),362 backend.clone(),363 frontier_backend.clone(),364 SyncStrategy::Normal,365 )366 .for_each(|()| futures::future::ready(())),367 );368369 sc_service::spawn_tasks(sc_service::SpawnTasksParams {370 rpc_extensions_builder,371 client: client.clone(),372 transaction_pool: transaction_pool.clone(),373 task_manager: &mut task_manager,374 config: parachain_config,375 keystore: params.keystore_container.sync_keystore(),376 backend: backend.clone(),377 network: network.clone(),378 system_rpc_tx,379 telemetry: telemetry.as_mut(),380 })?;381382 let announce_block = {383 let network = network.clone();384 Arc::new(move |hash, data| network.announce_block(hash, data))385 };386387 let relay_chain_slot_duration = Duration::from_secs(6);388389 if validator {390 let parachain_consensus = build_consensus(391 client.clone(),392 prometheus_registry.as_ref(),393 telemetry.as_ref().map(|t| t.handle()),394 &task_manager,395 relay_chain_interface.clone(),396 transaction_pool,397 network,398 params.keystore_container.sync_keystore(),399 force_authoring,400 )?;401402 let spawner = task_manager.spawn_handle();403404 let params = StartCollatorParams {405 para_id: id,406 block_status: client.clone(),407 announce_block,408 client: client.clone(),409 task_manager: &mut task_manager,410 spawner,411 parachain_consensus,412 import_queue,413 collator_key,414 relay_chain_interface,415 relay_chain_slot_duration,416 };417418 start_collator(params).await?;419 } else {420 let params = StartFullNodeParams {421 client: client.clone(),422 announce_block,423 task_manager: &mut task_manager,424 para_id: id,425 import_queue,426 relay_chain_interface,427 relay_chain_slot_duration,428 };429430 start_full_node(params)?;431 }432433 start_network.start_network();434435 Ok((task_manager, client))436}437438/// Build the import queue for the the parachain runtime.439pub fn parachain_build_import_queue(440 client: Arc<FullClient>,441 config: &Configuration,442 telemetry: Option<TelemetryHandle>,443 task_manager: &TaskManager,444) -> Result<sc_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error> {445 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;446447 cumulus_client_consensus_aura::import_queue::<448 sp_consensus_aura::sr25519::AuthorityPair,449 _,450 _,451 _,452 _,453 _,454 _,455 >(cumulus_client_consensus_aura::ImportQueueParams {456 block_import: client.clone(),457 client: client.clone(),458 create_inherent_data_providers: move |_, _| async move {459 let time = sp_timestamp::InherentDataProvider::from_system_time();460461 let slot =462 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(463 *time,464 slot_duration.slot_duration(),465 );466467 Ok((time, slot))468 },469 registry: config.prometheus_registry(),470 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),471 spawner: &task_manager.spawn_essential_handle(),472 telemetry,473 })474 .map_err(Into::into)475}476477/// Start a normal parachain node.478pub async fn start_node(479 parachain_config: Configuration,480 polkadot_config: Configuration,481 id: ParaId,482) -> sc_service::error::Result<(TaskManager, Arc<FullClient>)> {483 start_node_impl::<_, _>(484 parachain_config,485 polkadot_config,486 id,487 parachain_build_import_queue,488 |client,489 prometheus_registry,490 telemetry,491 task_manager,492 relay_chain_interface,493 transaction_pool,494 sync_oracle,495 keystore,496 force_authoring| {497 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;498499 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(500 task_manager.spawn_handle(),501 client.clone(),502 transaction_pool,503 prometheus_registry,504 telemetry.clone(),505 );506507 Ok(AuraConsensus::build::<508 sp_consensus_aura::sr25519::AuthorityPair,509 _,510 _,511 _,512 _,513 _,514 _,515 >(BuildAuraConsensusParams {516 proposer_factory,517 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {518 let relay_chain_interface = relay_chain_interface.clone();519 async move {520 let parachain_inherent =521 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(522 relay_parent,523 &relay_chain_interface,524 &validation_data,525 id,526 ).await;527528 let time = sp_timestamp::InherentDataProvider::from_system_time();529530 let slot =531 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(532 *time,533 slot_duration.slot_duration(),534 );535536 let parachain_inherent = parachain_inherent.ok_or_else(|| {537 Box::<dyn std::error::Error + Send + Sync>::from(538 "Failed to create parachain inherent",539 )540 })?;541 Ok((time, slot, parachain_inherent))542 }543 },544 block_import: client.clone(),545 para_client: client,546 backoff_authoring_blocks: Option::<()>::None,547 sync_oracle,548 keystore,549 force_authoring,550 slot_duration: *slot_duration,551 // We got around 500ms for proposing552 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),553 telemetry,554 max_block_proposal_slot_portion: None,555 }))556 },557 )558 .await559}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//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.1819// std20use std::sync::Arc;21use std::sync::Mutex;22use std::collections::BTreeMap;23use std::time::Duration;24use fc_rpc_core::types::FeeHistoryCache;25use futures::StreamExt;2627use unique_rpc::overrides_handle;2829use serde::{Serialize, Deserialize};3031// Cumulus Imports32use cumulus_client_consensus_aura::{AuraConsensus, BuildAuraConsensusParams, SlotProportion};33use cumulus_client_consensus_common::ParachainConsensus;34use cumulus_client_service::{35 prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams,36};37use cumulus_client_network::BlockAnnounceValidator;38use cumulus_primitives_core::ParaId;39use cumulus_relay_chain_interface::RelayChainInterface;40use cumulus_relay_chain_local::build_relay_chain_interface;4142// Substrate Imports43use sc_client_api::ExecutorProvider;44use sc_executor::NativeElseWasmExecutor;45use sc_executor::NativeExecutionDispatch;46use sc_network::NetworkService;47use sc_service::{BasePath, Configuration, PartialComponents, Role, TaskManager};48use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};49use sp_consensus::SlotData;50use sp_keystore::SyncCryptoStorePtr;51use sp_runtime::traits::BlakeTwo256;52use substrate_prometheus_endpoint::Registry;53use sc_client_api::BlockchainEvents;5455// Frontier Imports56use fc_rpc_core::types::FilterPool;57use fc_mapping_sync::{MappingSyncWorker, SyncStrategy};5859// Runtime type overrides60type BlockNumber = u32;61type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>;62pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>;63type Hash = sp_core::H256;6465use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index};6667/// Native executor instance.68pub struct UniqueRuntimeExecutor;69pub struct QuartzRuntimeExecutor;70pub struct OpalRuntimeExecutor;7172impl NativeExecutionDispatch for UniqueRuntimeExecutor {73 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;7475 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {76 unique_runtime::api::dispatch(method, data)77 }7879 fn native_version() -> sc_executor::NativeVersion {80 unique_runtime::native_version()81 }82}8384impl NativeExecutionDispatch for QuartzRuntimeExecutor {85 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8687 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {88 unique_runtime::api::dispatch(method, data)89 }9091 fn native_version() -> sc_executor::NativeVersion {92 unique_runtime::native_version()93 }94}9596impl NativeExecutionDispatch for OpalRuntimeExecutor {97 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9899 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {100 unique_runtime::api::dispatch(method, data)101 }102103 fn native_version() -> sc_executor::NativeVersion {104 unique_runtime::native_version()105 }106}107108pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {109 let config_dir = config110 .base_path111 .as_ref()112 .map(|base_path| base_path.config_dir(config.chain_spec.id()))113 .unwrap_or_else(|| {114 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())115 });116 let database_dir = config_dir.join("frontier").join("db");117118 Ok(Arc::new(fc_db::Backend::<Block>::new(119 &fc_db::DatabaseSettings {120 source: fc_db::DatabaseSettingsSrc::RocksDb {121 path: database_dir,122 cache_size: 0,123 },124 },125 )?))126}127128type FullClient<RuntimeApi, ExecutorDispatch> =129 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;130type FullBackend = sc_service::TFullBackend<Block>;131type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;132133/// Starts a `ServiceBuilder` for a full service.134///135/// Use this macro if you don't actually need the full service, but just the builder in order to136/// be able to perform chain operations.137#[allow(clippy::type_complexity)]138pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(139 config: &Configuration,140 build_import_queue: BIQ,141) -> Result<142 PartialComponents<143 FullClient<RuntimeApi, ExecutorDispatch>,144 FullBackend,145 FullSelectChain,146 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,147 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,148 (149 Option<Telemetry>,150 Option<FilterPool>,151 Arc<fc_db::Backend<Block>>,152 Option<TelemetryWorkerHandle>,153 FeeHistoryCache,154 ),155 >,156 sc_service::Error,157>158where159 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,160 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>161 + Send162 + Sync163 + 'static,164 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,165 ExecutorDispatch: NativeExecutionDispatch + 'static,166 BIQ: FnOnce(167 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,168 &Configuration,169 Option<TelemetryHandle>,170 &TaskManager,171 ) -> Result<172 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,173 sc_service::Error,174 >,175{176 let _telemetry = config177 .telemetry_endpoints178 .clone()179 .filter(|x| !x.is_empty())180 .map(|endpoints| -> Result<_, sc_telemetry::Error> {181 let worker = TelemetryWorker::new(16)?;182 let telemetry = worker.handle().new_telemetry(endpoints);183 Ok((worker, telemetry))184 })185 .transpose()?;186187 let telemetry = config188 .telemetry_endpoints189 .clone()190 .filter(|x| !x.is_empty())191 .map(|endpoints| -> Result<_, sc_telemetry::Error> {192 let worker = TelemetryWorker::new(16)?;193 let telemetry = worker.handle().new_telemetry(endpoints);194 Ok((worker, telemetry))195 })196 .transpose()?;197198 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(199 config.wasm_method,200 config.default_heap_pages,201 config.max_runtime_instances,202 config.runtime_cache_size,203 );204205 let (client, backend, keystore_container, task_manager) =206 sc_service::new_full_parts::<Block, RuntimeApi, _>(207 config,208 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),209 executor,210 )?;211 let client = Arc::new(client);212213 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());214215 let telemetry = telemetry.map(|(worker, telemetry)| {216 task_manager217 .spawn_handle()218 .spawn("telemetry", None, worker.run());219 telemetry220 });221222 let select_chain = sc_consensus::LongestChain::new(backend.clone());223224 let transaction_pool = sc_transaction_pool::BasicPool::new_full(225 config.transaction_pool.clone(),226 config.role.is_authority().into(),227 config.prometheus_registry(),228 task_manager.spawn_essential_handle(),229 client.clone(),230 );231232 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));233234 let frontier_backend = open_frontier_backend(config)?;235236 let import_queue = build_import_queue(237 client.clone(),238 config,239 telemetry.as_ref().map(|telemetry| telemetry.handle()),240 &task_manager,241 )?;242 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));243244 let params = PartialComponents {245 backend,246 client,247 import_queue,248 keystore_container,249 task_manager,250 transaction_pool,251 select_chain,252 other: (253 telemetry,254 filter_pool,255 frontier_backend,256 telemetry_worker_handle,257 fee_history_cache,258 ),259 };260261 Ok(params)262}263264/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.265///266/// This is the actual implementation that is abstract over the executor and the runtime api.267#[sc_tracing::logging::prefix_logs_with("Parachain")]268async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(269 parachain_config: Configuration,270 polkadot_config: Configuration,271 id: ParaId,272 build_import_queue: BIQ,273 build_consensus: BIC,274) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>275where276 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,277 Runtime: RuntimeInstance + Send + Sync + 'static,278 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,279 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,280 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>281 + Send282 + Sync283 + 'static,284 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>285 + fp_rpc::EthereumRuntimeRPCApi<Block>286 + sp_session::SessionKeys<Block>287 + sp_block_builder::BlockBuilder<Block>288 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>289 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>290 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>291 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>292 + sp_api::Metadata<Block>293 + sp_offchain::OffchainWorkerApi<Block>294 + cumulus_primitives_core::CollectCollationInfo<Block>,295 ExecutorDispatch: NativeExecutionDispatch + 'static,296 BIQ: FnOnce(297 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,298 &Configuration,299 Option<TelemetryHandle>,300 &TaskManager,301 ) -> Result<302 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,303 sc_service::Error,304 >,305 BIC: FnOnce(306 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,307 Option<&Registry>,308 Option<TelemetryHandle>,309 &TaskManager,310 Arc<dyn RelayChainInterface>,311 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,312 Arc<NetworkService<Block, Hash>>,313 SyncCryptoStorePtr,314 bool,315 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,316{317 if matches!(parachain_config.role, Role::Light) {318 return Err("Light client not supported!".into());319 }320321 let parachain_config = prepare_node_config(parachain_config);322323 let params =324 new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(¶chain_config, build_import_queue)?;325 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =326 params.other;327328 let client = params.client.clone();329 let backend = params.backend.clone();330 let mut task_manager = params.task_manager;331332 let (relay_chain_interface, collator_key) =333 build_relay_chain_interface(polkadot_config, telemetry_worker_handle, &mut task_manager)334 .map_err(|e| match e {335 polkadot_service::Error::Sub(x) => x,336 s => format!("{}", s).into(),337 })?;338339 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);340341 let force_authoring = parachain_config.force_authoring;342 let validator = parachain_config.role.is_authority();343 let prometheus_registry = parachain_config.prometheus_registry().cloned();344 let transaction_pool = params.transaction_pool.clone();345 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);346347 let (network, system_rpc_tx, start_network) =348 sc_service::build_network(sc_service::BuildNetworkParams {349 config: ¶chain_config,350 client: client.clone(),351 transaction_pool: transaction_pool.clone(),352 spawn_handle: task_manager.spawn_handle(),353 import_queue: import_queue.clone(),354 block_announce_validator_builder: Some(Box::new(|_| {355 Box::new(block_announce_validator)356 })),357 warp_sync: None,358 })?;359360 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());361 let rpc_client = client.clone();362 let rpc_pool = transaction_pool.clone();363 let select_chain = params.select_chain.clone();364 let rpc_network = network.clone();365366 let rpc_frontier_backend = frontier_backend.clone();367368 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(369 task_manager.spawn_handle(),370 overrides_handle::<_, _, Runtime>(client.clone()),371 50,372 50,373 ));374375 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {376 let full_deps = unique_rpc::FullDeps {377 backend: rpc_frontier_backend.clone(),378 deny_unsafe,379 client: rpc_client.clone(),380 pool: rpc_pool.clone(),381 graph: rpc_pool.pool().clone(),382 // TODO: Unhardcode383 enable_dev_signer: false,384 filter_pool: filter_pool.clone(),385 network: rpc_network.clone(),386 select_chain: select_chain.clone(),387 is_authority: validator,388 // TODO: Unhardcode389 max_past_logs: 10000,390 block_data_cache: block_data_cache.clone(),391 fee_history_cache: fee_history_cache.clone(),392 // TODO: Unhardcode393 fee_history_limit: 2048,394 };395396 Ok(397 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(398 full_deps,399 subscription_executor.clone(),400 ),401 )402 });403404 task_manager.spawn_essential_handle().spawn(405 "frontier-mapping-sync-worker",406 None,407 MappingSyncWorker::new(408 client.import_notification_stream(),409 Duration::new(6, 0),410 client.clone(),411 backend.clone(),412 frontier_backend.clone(),413 SyncStrategy::Normal,414 )415 .for_each(|()| futures::future::ready(())),416 );417418 sc_service::spawn_tasks(sc_service::SpawnTasksParams {419 rpc_extensions_builder,420 client: client.clone(),421 transaction_pool: transaction_pool.clone(),422 task_manager: &mut task_manager,423 config: parachain_config,424 keystore: params.keystore_container.sync_keystore(),425 backend: backend.clone(),426 network: network.clone(),427 system_rpc_tx,428 telemetry: telemetry.as_mut(),429 })?;430431 let announce_block = {432 let network = network.clone();433 Arc::new(move |hash, data| network.announce_block(hash, data))434 };435436 let relay_chain_slot_duration = Duration::from_secs(6);437438 if validator {439 let parachain_consensus = build_consensus(440 client.clone(),441 prometheus_registry.as_ref(),442 telemetry.as_ref().map(|t| t.handle()),443 &task_manager,444 relay_chain_interface.clone(),445 transaction_pool,446 network,447 params.keystore_container.sync_keystore(),448 force_authoring,449 )?;450451 let spawner = task_manager.spawn_handle();452453 let params = StartCollatorParams {454 para_id: id,455 block_status: client.clone(),456 announce_block,457 client: client.clone(),458 task_manager: &mut task_manager,459 spawner,460 parachain_consensus,461 import_queue,462 collator_key,463 relay_chain_interface,464 relay_chain_slot_duration,465 };466467 start_collator(params).await?;468 } else {469 let params = StartFullNodeParams {470 client: client.clone(),471 announce_block,472 task_manager: &mut task_manager,473 para_id: id,474 import_queue,475 relay_chain_interface,476 relay_chain_slot_duration,477 };478479 start_full_node(params)?;480 }481482 start_network.start_network();483484 Ok((task_manager, client))485}486487/// Build the import queue for the the parachain runtime.488pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(489 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,490 config: &Configuration,491 telemetry: Option<TelemetryHandle>,492 task_manager: &TaskManager,493) -> Result<494 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,495 sc_service::Error,496>497where498 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>499 + Send500 + Sync501 + 'static,502 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>503 + sp_block_builder::BlockBuilder<Block>504 + sp_consensus_aura::AuraApi<Block, AuraId>505 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,506 ExecutorDispatch: NativeExecutionDispatch + 'static,507{508 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;509510 cumulus_client_consensus_aura::import_queue::<511 sp_consensus_aura::sr25519::AuthorityPair,512 _,513 _,514 _,515 _,516 _,517 _,518 >(cumulus_client_consensus_aura::ImportQueueParams {519 block_import: client.clone(),520 client: client.clone(),521 create_inherent_data_providers: move |_, _| async move {522 let time = sp_timestamp::InherentDataProvider::from_system_time();523524 let slot =525 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(526 *time,527 slot_duration.slot_duration(),528 );529530 Ok((time, slot))531 },532 registry: config.prometheus_registry(),533 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),534 spawner: &task_manager.spawn_essential_handle(),535 telemetry,536 })537 .map_err(Into::into)538}539540/// Start a normal parachain node.541pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(542 parachain_config: Configuration,543 polkadot_config: Configuration,544 id: ParaId,545) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>546where547 Runtime: RuntimeInstance + Send + Sync + 'static,548 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,549 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,550 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>551 + Send552 + Sync553 + 'static,554 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>555 + fp_rpc::EthereumRuntimeRPCApi<Block>556 + sp_session::SessionKeys<Block>557 + sp_block_builder::BlockBuilder<Block>558 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>559 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>560 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>561 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>562 + sp_api::Metadata<Block>563 + sp_offchain::OffchainWorkerApi<Block>564 + cumulus_primitives_core::CollectCollationInfo<Block>565 + sp_consensus_aura::AuraApi<Block, AuraId>,566 ExecutorDispatch: NativeExecutionDispatch + 'static,567{568 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(569 parachain_config,570 polkadot_config,571 id,572 parachain_build_import_queue,573 |client,574 prometheus_registry,575 telemetry,576 task_manager,577 relay_chain_interface,578 transaction_pool,579 sync_oracle,580 keystore,581 force_authoring| {582 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;583584 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(585 task_manager.spawn_handle(),586 client.clone(),587 transaction_pool,588 prometheus_registry,589 telemetry.clone(),590 );591592 Ok(AuraConsensus::build::<593 sp_consensus_aura::sr25519::AuthorityPair,594 _,595 _,596 _,597 _,598 _,599 _,600 >(BuildAuraConsensusParams {601 proposer_factory,602 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {603 let relay_chain_interface = relay_chain_interface.clone();604 async move {605 let parachain_inherent =606 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(607 relay_parent,608 &relay_chain_interface,609 &validation_data,610 id,611 ).await;612613 let time = sp_timestamp::InherentDataProvider::from_system_time();614615 let slot =616 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(617 *time,618 slot_duration.slot_duration(),619 );620621 let parachain_inherent = parachain_inherent.ok_or_else(|| {622 Box::<dyn std::error::Error + Send + Sync>::from(623 "Failed to create parachain inherent",624 )625 })?;626 Ok((time, slot, parachain_inherent))627 }628 },629 block_import: client.clone(),630 para_client: client,631 backoff_authoring_blocks: Option::<()>::None,632 sync_oracle,633 keystore,634 force_authoring,635 slot_duration: *slot_duration,636 // We got around 500ms for proposing637 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),638 telemetry,639 max_block_proposal_slot_portion: None,640 }))641 },642 )643 .await644}node/rpc/Cargo.tomldiffbeforeafterboth--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -48,13 +48,16 @@
fc-db = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.17" }
fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.17" }
+pallet-common = { default-features = false, path = "../../pallets/common" }
+unique-runtime-common = { default-features = false, path = "../../runtime/common" }
pallet-unique = { path = "../../pallets/unique" }
uc-rpc = { path = "../../client/rpc" }
up-rpc = { path = "../../primitives/rpc" }
-unique-runtime = { path = "../../runtime/unique", optional = true }
-quartz-runtime = { path = "../../runtime/quartz", optional = true }
-opal-runtime = { path = "../../runtime/opal", optional = true }
+[dependencies.serde]
+features = ['derive']
+version = '1.0.130'
+
[features]
-default = ["unique-runtime"]
+default = []
std = []
node/rpc/src/lib.rsdiffbeforeafterboth--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -40,16 +40,9 @@
use sc_service::TransactionPool;
use std::{collections::BTreeMap, marker::PhantomData, sync::Arc};
-#[cfg(feature = "unique-runtime")]
-use unique_runtime as runtime;
-
-#[cfg(feature = "quartz-runtime")]
-use quartz_runtime as runtime;
-
-#[cfg(feature = "opal-runtime")]
-use opal_runtime as runtime;
-
-use runtime::opaque::{Hash, AccountId, CrossAccountId, Index, Block, BlockNumber, Balance};
+use unique_runtime_common::types::{
+ Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance,
+};
/// Public io handler for exporting into other modules
pub type IoHandler = jsonrpc_core::IoHandler<sc_rpc::Metadata>;
@@ -100,29 +93,33 @@
pub block_data_cache: Arc<EthBlockDataCache<Block>>,
}
-struct AccountCodes<C, B> {
+struct AccountCodes<C, B, R> {
client: Arc<C>,
- _marker: PhantomData<B>,
+ _blk_marker: PhantomData<B>,
+ _runtime_marker: PhantomData<R>,
}
-impl<C, Block> AccountCodes<C, Block>
+impl<C, Block, R> AccountCodes<C, Block, R>
where
Block: sp_api::BlockT,
C: ProvideRuntimeApi<Block>,
+ R: RuntimeInstance,
{
fn new(client: Arc<C>) -> Self {
Self {
client,
- _marker: PhantomData,
+ _blk_marker: PhantomData,
+ _runtime_marker: PhantomData,
}
}
}
-impl<C, Block> fc_rpc::AccountCodeProvider<Block> for AccountCodes<C, Block>
+impl<C, Block, Runtime> fc_rpc::AccountCodeProvider<Block> for AccountCodes<C, Block, Runtime>
where
Block: sp_api::BlockT,
C: ProvideRuntimeApi<Block>,
- C::Api: up_rpc::UniqueApi<Block, CrossAccountId, AccountId>,
+ C::Api: up_rpc::UniqueApi<Block, <Runtime as RuntimeInstance>::CrossAccountId, AccountId>,
+ Runtime: RuntimeInstance,
{
fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {
use up_rpc::UniqueApi;
@@ -134,22 +131,23 @@
}
}
-pub fn overrides_handle<C, BE>(client: Arc<C>) -> Arc<OverrideHandle<Block>>
+pub fn overrides_handle<C, BE, R>(client: Arc<C>) -> Arc<OverrideHandle<Block>>
where
C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,
C: Send + Sync + 'static,
C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
- C::Api: up_rpc::UniqueApi<Block, CrossAccountId, AccountId>,
+ C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,
BE: Backend<Block> + 'static,
BE::State: StateBackend<BlakeTwo256>,
+ R: RuntimeInstance + Send + Sync + 'static,
{
let mut overrides_map = BTreeMap::new();
overrides_map.insert(
EthereumStorageSchema::V1,
Box::new(SchemaV1Override::new_with_code_provider(
client.clone(),
- Arc::new(AccountCodes::<C, Block>::new(client.clone())),
+ Arc::new(AccountCodes::<C, Block, R>::new(client.clone())),
)) as Box<dyn StorageOverride<_> + Send + Sync>,
);
overrides_map.insert(
@@ -170,7 +168,7 @@
}
/// Instantiate all Full RPC extensions.
-pub fn create_full<C, P, SC, CA, A, B>(
+pub fn create_full<C, P, SC, CA, R, A, B>(
deps: FullDeps<C, P, SC, CA>,
subscription_task_executor: SubscriptionTaskExecutor,
) -> jsonrpc_core::IoHandler<sc_rpc_api::Metadata>
@@ -184,11 +182,14 @@
// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,
C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,
C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
- C::Api: up_rpc::UniqueApi<Block, CrossAccountId, AccountId>,
+ C::Api: up_rpc::UniqueApi<Block, <R as RuntimeInstance>::CrossAccountId, AccountId>,
B: sc_client_api::Backend<Block> + Send + Sync + 'static,
B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,
P: TransactionPool<Block = Block> + 'static,
CA: ChainApi<Block = Block> + 'static,
+ R: RuntimeInstance + Send + Sync + 'static,
+ <R as RuntimeInstance>::CrossAccountId: serde::Serialize,
+ for<'de> <R as RuntimeInstance>::CrossAccountId: serde::Deserialize<'de>,
{
use fc_rpc::{
EthApi, EthApiServer, EthDevSigner, EthFilterApi, EthFilterApiServer, EthPubSubApi,
@@ -235,13 +236,13 @@
signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);
}
- let overrides = overrides_handle(client.clone());
+ let overrides = overrides_handle::<_, _, R>(client.clone());
io.extend_with(EthApiServer::to_delegate(EthApi::new(
client.clone(),
pool.clone(),
graph,
- runtime::TransactionConverter,
+ <R as RuntimeInstance>::get_transaction_converter(),
network.clone(),
signers,
overrides.clone(),