difftreelog
Fix autoseal, remove obsolete testnet specs
in: master
3 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -216,59 +216,6 @@
)
}
-pub fn local_testnet_westend_config() -> OpalChainSpec {
- OpalChainSpec::from_genesis(
- // Name
- "Local Testnet",
- // ID
- "local_testnet",
- ChainType::Local,
- move || {
- testnet_genesis(
- // Sudo account
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- vec![
- get_from_seed::<AuraId>("Alice"),
- get_from_seed::<AuraId>("Bob"),
- get_from_seed::<AuraId>("Charlie"),
- get_from_seed::<AuraId>("Dave"),
- get_from_seed::<AuraId>("Eve"),
- ],
- // Pre-funded accounts
- vec![
- get_account_id_from_seed::<sr25519::Public>("Alice"),
- get_account_id_from_seed::<sr25519::Public>("Bob"),
- get_account_id_from_seed::<sr25519::Public>("Charlie"),
- get_account_id_from_seed::<sr25519::Public>("Dave"),
- get_account_id_from_seed::<sr25519::Public>("Eve"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie"),
- get_account_id_from_seed::<sr25519::Public>("Alice//stash"),
- get_account_id_from_seed::<sr25519::Public>("Bob//stash"),
- get_account_id_from_seed::<sr25519::Public>("Charlie//stash"),
- get_account_id_from_seed::<sr25519::Public>("Dave//stash"),
- get_account_id_from_seed::<sr25519::Public>("Eve//stash"),
- get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"),
- ],
- 1000.into(),
- )
- },
- // Bootnodes
- vec![],
- // Telemetry
- None,
- // Protocol ID
- None,
- None,
- // Properties
- None,
- // Extensions
- Extensions {
- relay_chain: "westend-local".into(),
- para_id: 1000,
- },
- )
-}
-
fn testnet_genesis(
root_key: AccountId,
initial_authorities: Vec<AuraId>,
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -75,8 +75,6 @@
fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
Ok(match id {
- "westend-local" => Box::new(chain_spec::local_testnet_westend_config()),
- "rococo-local" => Box::new(chain_spec::local_testnet_rococo_config()),
"dev" => Box::new(chain_spec::development_config()),
"" | "local" => Box::new(chain_spec::local_testnet_rococo_config()),
path => {
@@ -402,6 +400,8 @@
|| relay_chain_id == Some("dev-service".into());
if is_dev_service {
+ info!("Running Dev service");
+
return start_node_using_chain_runtime! {
start_dev_node(config).map_err(Into::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;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};5859use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};60use crate::chain_spec::ServiceId;6162/// Native executor instance.63pub struct UniqueRuntimeExecutor;64pub struct QuartzRuntimeExecutor;65pub struct OpalRuntimeExecutor;6667#[cfg(feature = "unique-runtime")]68impl NativeExecutionDispatch for UniqueRuntimeExecutor {69 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;7071 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {72 unique_runtime::api::dispatch(method, data)73 }7475 fn native_version() -> sc_executor::NativeVersion {76 unique_runtime::native_version()77 }78}7980#[cfg(feature = "quartz-runtime")]81impl NativeExecutionDispatch for QuartzRuntimeExecutor {82 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8384 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {85 quartz_runtime::api::dispatch(method, data)86 }8788 fn native_version() -> sc_executor::NativeVersion {89 quartz_runtime::native_version()90 }91}9293impl NativeExecutionDispatch for OpalRuntimeExecutor {94 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9596 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {97 opal_runtime::api::dispatch(method, data)98 }99100 fn native_version() -> sc_executor::NativeVersion {101 opal_runtime::native_version()102 }103}104105pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {106 let config_dir = config107 .base_path108 .as_ref()109 .map(|base_path| base_path.config_dir(config.chain_spec.id()))110 .unwrap_or_else(|| {111 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())112 });113 let database_dir = config_dir.join("frontier").join("db");114115 Ok(Arc::new(fc_db::Backend::<Block>::new(116 &fc_db::DatabaseSettings {117 source: fc_db::DatabaseSettingsSrc::RocksDb {118 path: database_dir,119 cache_size: 0,120 },121 },122 )?))123}124125type FullClient<RuntimeApi, ExecutorDispatch> =126 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;127type FullBackend = sc_service::TFullBackend<Block>;128type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;129type MaybeSelectChain = Option<FullSelectChain>;130131/// Starts a `ServiceBuilder` for a full service.132///133/// Use this macro if you don't actually need the full service, but just the builder in order to134/// be able to perform chain operations.135#[allow(clippy::type_complexity)]136pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(137 config: &Configuration,138 build_import_queue: BIQ,139 service_id: ServiceId,140) -> Result<141 PartialComponents<142 FullClient<RuntimeApi, ExecutorDispatch>,143 FullBackend,144 MaybeSelectChain,145 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,146 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,147 (148 Option<Telemetry>,149 Option<FilterPool>,150 Arc<fc_db::Backend<Block>>,151 Option<TelemetryWorkerHandle>,152 FeeHistoryCache,153 ),154 >,155 sc_service::Error,156>157where158 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,159 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>160 + Send161 + Sync162 + 'static,163 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,164 ExecutorDispatch: NativeExecutionDispatch + 'static,165 BIQ: FnOnce(166 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,167 &Configuration,168 Option<TelemetryHandle>,169 &TaskManager,170 ) -> Result<171 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,172 sc_service::Error,173 >,174{175 let _telemetry = config176 .telemetry_endpoints177 .clone()178 .filter(|x| !x.is_empty())179 .map(|endpoints| -> Result<_, sc_telemetry::Error> {180 let worker = TelemetryWorker::new(16)?;181 let telemetry = worker.handle().new_telemetry(endpoints);182 Ok((worker, telemetry))183 })184 .transpose()?;185186 let telemetry = config187 .telemetry_endpoints188 .clone()189 .filter(|x| !x.is_empty())190 .map(|endpoints| -> Result<_, sc_telemetry::Error> {191 let worker = TelemetryWorker::new(16)?;192 let telemetry = worker.handle().new_telemetry(endpoints);193 Ok((worker, telemetry))194 })195 .transpose()?;196197 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(198 config.wasm_method,199 config.default_heap_pages,200 config.max_runtime_instances,201 config.runtime_cache_size,202 );203204 let (client, backend, keystore_container, task_manager) =205 sc_service::new_full_parts::<Block, RuntimeApi, _>(206 config,207 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),208 executor,209 )?;210 let client = Arc::new(client);211212 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());213214 let telemetry = telemetry.map(|(worker, telemetry)| {215 task_manager216 .spawn_handle()217 .spawn("telemetry", None, worker.run());218 telemetry219 });220221 let select_chain = match service_id {222 ServiceId::Prod => Some(sc_consensus::LongestChain::new(backend.clone())),223 ServiceId::Dev => None,224 };225226 let transaction_pool = sc_transaction_pool::BasicPool::new_full(227 config.transaction_pool.clone(),228 config.role.is_authority().into(),229 config.prometheus_registry(),230 task_manager.spawn_essential_handle(),231 client.clone(),232 );233234 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));235236 let frontier_backend = open_frontier_backend(config)?;237238 let import_queue = build_import_queue(239 client.clone(),240 config,241 telemetry.as_ref().map(|telemetry| telemetry.handle()),242 &task_manager,243 )?;244 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));245246 let params = PartialComponents {247 backend,248 client,249 import_queue,250 keystore_container,251 task_manager,252 transaction_pool,253 select_chain,254 other: (255 telemetry,256 filter_pool,257 frontier_backend,258 telemetry_worker_handle,259 fee_history_cache,260 ),261 };262263 Ok(params)264}265266/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.267///268/// This is the actual implementation that is abstract over the executor and the runtime api.269#[sc_tracing::logging::prefix_logs_with("Parachain")]270async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(271 parachain_config: Configuration,272 polkadot_config: Configuration,273 id: ParaId,274 build_import_queue: BIQ,275 build_consensus: BIC,276) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>277where278 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,279 Runtime: RuntimeInstance + Send + Sync + 'static,280 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,281 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,282 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>283 + Send284 + Sync285 + 'static,286 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>287 + fp_rpc::EthereumRuntimeRPCApi<Block>288 + sp_session::SessionKeys<Block>289 + sp_block_builder::BlockBuilder<Block>290 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>291 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>292 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>293 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>294 + sp_api::Metadata<Block>295 + sp_offchain::OffchainWorkerApi<Block>296 + cumulus_primitives_core::CollectCollationInfo<Block>,297 ExecutorDispatch: NativeExecutionDispatch + 'static,298 BIQ: FnOnce(299 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,300 &Configuration,301 Option<TelemetryHandle>,302 &TaskManager,303 ) -> Result<304 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,305 sc_service::Error,306 >,307 BIC: FnOnce(308 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,309 Option<&Registry>,310 Option<TelemetryHandle>,311 &TaskManager,312 Arc<dyn RelayChainInterface>,313 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,314 Arc<NetworkService<Block, Hash>>,315 SyncCryptoStorePtr,316 bool,317 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,318{319 if matches!(parachain_config.role, Role::Light) {320 return Err("Light client not supported!".into());321 }322323 let parachain_config = prepare_node_config(parachain_config);324325 let params = new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(326 ¶chain_config,327 build_import_queue,328 ServiceId::Prod,329 )?;330 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =331 params.other;332333 let client = params.client.clone();334 let backend = params.backend.clone();335 let mut task_manager = params.task_manager;336337 let (relay_chain_interface, collator_key) =338 build_relay_chain_interface(polkadot_config, telemetry_worker_handle, &mut task_manager)339 .map_err(|e| match e {340 polkadot_service::Error::Sub(x) => x,341 s => format!("{}", s).into(),342 })?;343344 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);345346 let force_authoring = parachain_config.force_authoring;347 let validator = parachain_config.role.is_authority();348 let prometheus_registry = parachain_config.prometheus_registry().cloned();349 let transaction_pool = params.transaction_pool.clone();350 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);351352 let (network, system_rpc_tx, start_network) =353 sc_service::build_network(sc_service::BuildNetworkParams {354 config: ¶chain_config,355 client: client.clone(),356 transaction_pool: transaction_pool.clone(),357 spawn_handle: task_manager.spawn_handle(),358 import_queue: import_queue.clone(),359 block_announce_validator_builder: Some(Box::new(|_| {360 Box::new(block_announce_validator)361 })),362 warp_sync: None,363 })?;364365 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());366 let rpc_client = client.clone();367 let rpc_pool = transaction_pool.clone();368 let select_chain = params369 .select_chain370 .expect("select_chain always exists when running Prod service; qed")371 .clone();372 let rpc_network = network.clone();373374 let rpc_frontier_backend = frontier_backend.clone();375376 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(377 task_manager.spawn_handle(),378 overrides_handle::<_, _, Runtime>(client.clone()),379 50,380 50,381 ));382383 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {384 let full_deps = unique_rpc::FullDeps {385 backend: rpc_frontier_backend.clone(),386 deny_unsafe,387 client: rpc_client.clone(),388 pool: rpc_pool.clone(),389 graph: rpc_pool.pool().clone(),390 // TODO: Unhardcode391 enable_dev_signer: false,392 filter_pool: filter_pool.clone(),393 network: rpc_network.clone(),394 select_chain: select_chain.clone(),395 is_authority: validator,396 // TODO: Unhardcode397 max_past_logs: 10000,398 block_data_cache: block_data_cache.clone(),399 fee_history_cache: fee_history_cache.clone(),400 // TODO: Unhardcode401 fee_history_limit: 2048,402 };403404 Ok(405 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(406 full_deps,407 subscription_executor.clone(),408 ),409 )410 });411412 task_manager.spawn_essential_handle().spawn(413 "frontier-mapping-sync-worker",414 None,415 MappingSyncWorker::new(416 client.import_notification_stream(),417 Duration::new(6, 0),418 client.clone(),419 backend.clone(),420 frontier_backend.clone(),421 SyncStrategy::Normal,422 )423 .for_each(|()| futures::future::ready(())),424 );425426 sc_service::spawn_tasks(sc_service::SpawnTasksParams {427 rpc_extensions_builder,428 client: client.clone(),429 transaction_pool: transaction_pool.clone(),430 task_manager: &mut task_manager,431 config: parachain_config,432 keystore: params.keystore_container.sync_keystore(),433 backend: backend.clone(),434 network: network.clone(),435 system_rpc_tx,436 telemetry: telemetry.as_mut(),437 })?;438439 let announce_block = {440 let network = network.clone();441 Arc::new(move |hash, data| network.announce_block(hash, data))442 };443444 let relay_chain_slot_duration = Duration::from_secs(6);445446 if validator {447 let parachain_consensus = build_consensus(448 client.clone(),449 prometheus_registry.as_ref(),450 telemetry.as_ref().map(|t| t.handle()),451 &task_manager,452 relay_chain_interface.clone(),453 transaction_pool,454 network,455 params.keystore_container.sync_keystore(),456 force_authoring,457 )?;458459 let spawner = task_manager.spawn_handle();460461 let params = StartCollatorParams {462 para_id: id,463 block_status: client.clone(),464 announce_block,465 client: client.clone(),466 task_manager: &mut task_manager,467 spawner,468 parachain_consensus,469 import_queue,470 collator_key,471 relay_chain_interface,472 relay_chain_slot_duration,473 };474475 start_collator(params).await?;476 } else {477 let params = StartFullNodeParams {478 client: client.clone(),479 announce_block,480 task_manager: &mut task_manager,481 para_id: id,482 import_queue,483 relay_chain_interface,484 relay_chain_slot_duration,485 };486487 start_full_node(params)?;488 }489490 start_network.start_network();491492 Ok((task_manager, client))493}494495/// Build the import queue for the the parachain runtime.496pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(497 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,498 config: &Configuration,499 telemetry: Option<TelemetryHandle>,500 task_manager: &TaskManager,501) -> Result<502 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,503 sc_service::Error,504>505where506 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>507 + Send508 + Sync509 + 'static,510 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>511 + sp_block_builder::BlockBuilder<Block>512 + sp_consensus_aura::AuraApi<Block, AuraId>513 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,514 ExecutorDispatch: NativeExecutionDispatch + 'static,515{516 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;517518 cumulus_client_consensus_aura::import_queue::<519 sp_consensus_aura::sr25519::AuthorityPair,520 _,521 _,522 _,523 _,524 _,525 _,526 >(cumulus_client_consensus_aura::ImportQueueParams {527 block_import: client.clone(),528 client: client.clone(),529 create_inherent_data_providers: move |_, _| async move {530 let time = sp_timestamp::InherentDataProvider::from_system_time();531532 let slot =533 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(534 *time,535 slot_duration.slot_duration(),536 );537538 Ok((time, slot))539 },540 registry: config.prometheus_registry(),541 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),542 spawner: &task_manager.spawn_essential_handle(),543 telemetry,544 })545 .map_err(Into::into)546}547548/// Start a normal parachain node.549pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(550 parachain_config: Configuration,551 polkadot_config: Configuration,552 id: ParaId,553) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>554where555 Runtime: RuntimeInstance + Send + Sync + 'static,556 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,557 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,558 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>559 + Send560 + Sync561 + 'static,562 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>563 + fp_rpc::EthereumRuntimeRPCApi<Block>564 + sp_session::SessionKeys<Block>565 + sp_block_builder::BlockBuilder<Block>566 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>567 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>568 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>569 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>570 + sp_api::Metadata<Block>571 + sp_offchain::OffchainWorkerApi<Block>572 + cumulus_primitives_core::CollectCollationInfo<Block>573 + sp_consensus_aura::AuraApi<Block, AuraId>,574 ExecutorDispatch: NativeExecutionDispatch + 'static,575{576 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(577 parachain_config,578 polkadot_config,579 id,580 parachain_build_import_queue,581 |client,582 prometheus_registry,583 telemetry,584 task_manager,585 relay_chain_interface,586 transaction_pool,587 sync_oracle,588 keystore,589 force_authoring| {590 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;591592 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(593 task_manager.spawn_handle(),594 client.clone(),595 transaction_pool,596 prometheus_registry,597 telemetry.clone(),598 );599600 Ok(AuraConsensus::build::<601 sp_consensus_aura::sr25519::AuthorityPair,602 _,603 _,604 _,605 _,606 _,607 _,608 >(BuildAuraConsensusParams {609 proposer_factory,610 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {611 let relay_chain_interface = relay_chain_interface.clone();612 async move {613 let parachain_inherent =614 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(615 relay_parent,616 &relay_chain_interface,617 &validation_data,618 id,619 ).await;620621 let time = sp_timestamp::InherentDataProvider::from_system_time();622623 let slot =624 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(625 *time,626 slot_duration.slot_duration(),627 );628629 let parachain_inherent = parachain_inherent.ok_or_else(|| {630 Box::<dyn std::error::Error + Send + Sync>::from(631 "Failed to create parachain inherent",632 )633 })?;634 Ok((time, slot, parachain_inherent))635 }636 },637 block_import: client.clone(),638 para_client: client,639 backoff_authoring_blocks: Option::<()>::None,640 sync_oracle,641 keystore,642 force_authoring,643 slot_duration: *slot_duration,644 // We got around 500ms for proposing645 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),646 telemetry,647 max_block_proposal_slot_portion: None,648 }))649 },650 )651 .await652}653654fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(655 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,656 config: &Configuration,657 _: Option<TelemetryHandle>,658 task_manager: &TaskManager,659) -> Result<660 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,661 sc_service::Error,662>663where664 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>665 + Send666 + Sync667 + 'static,668 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>669 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,670 ExecutorDispatch: NativeExecutionDispatch + 'static,671{672 Ok(sc_consensus_manual_seal::import_queue(673 Box::new(client.clone()),674 &task_manager.spawn_essential_handle(),675 config.prometheus_registry(),676 ))677}678679/// Builds a new development service. This service uses instant seal, and mocks680/// the parachain inherent681pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(682 config: Configuration,683) -> sc_service::error::Result<TaskManager>684where685 Runtime: RuntimeInstance + Send + Sync + 'static,686 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,687 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,688 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>689 + Send690 + Sync691 + 'static,692 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>693 + fp_rpc::EthereumRuntimeRPCApi<Block>694 + sp_session::SessionKeys<Block>695 + sp_block_builder::BlockBuilder<Block>696 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>697 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>698 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>699 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>700 + sp_api::Metadata<Block>701 + sp_offchain::OffchainWorkerApi<Block>702 + cumulus_primitives_core::CollectCollationInfo<Block>703 + sp_consensus_aura::AuraApi<Block, AuraId>,704 ExecutorDispatch: NativeExecutionDispatch + 'static,705{706 use futures::Stream;707 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};708 use fc_consensus::FrontierBlockImport;709 use sc_client_api::HeaderBackend;710711 let sc_service::PartialComponents {712 client,713 backend,714 mut task_manager,715 import_queue,716 keystore_container,717 select_chain: maybe_select_chain,718 transaction_pool,719 other:720 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),721 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(722 &config,723 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,724 ServiceId::Dev,725 )?;726727 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(728 task_manager.spawn_handle(),729 overrides_handle::<_, _, Runtime>(client.clone()),730 50,731 50,732 ));733734 let (network, system_rpc_tx, network_starter) =735 sc_service::build_network(sc_service::BuildNetworkParams {736 config: &config,737 client: client.clone(),738 transaction_pool: transaction_pool.clone(),739 spawn_handle: task_manager.spawn_handle(),740 import_queue,741 block_announce_validator_builder: None,742 warp_sync: None,743 })?;744745 if config.offchain_worker.enabled {746 sc_service::build_offchain_workers(747 &config,748 task_manager.spawn_handle(),749 client.clone(),750 network.clone(),751 );752 }753754 let prometheus_registry = config.prometheus_registry().cloned();755 let collator = config.role.is_authority();756757 let select_chain = maybe_select_chain.clone().expect(758 "`new_partial` builds a `LongestChainRule` when building dev service.\759 We specified the dev service when calling `new_partial`.\760 Therefore, a `LongestChainRule` is present. qed.",761 );762763 if collator {764 let block_import =765 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());766767 let env = sc_basic_authorship::ProposerFactory::new(768 task_manager.spawn_handle(),769 client.clone(),770 transaction_pool.clone(),771 prometheus_registry.as_ref(),772 telemetry.as_ref().map(|x| x.handle()),773 );774775 let commands_stream: Box<dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin> =776 Box::new(777 // This bit cribbed from the implementation of instant seal.778 transaction_pool779 .pool()780 .validated_pool()781 .import_notification_stream()782 .map(|_| EngineCommand::SealNewBlock {783 create_empty: true, // was false in Moonbeam784 finalize: false,785 parent_hash: None,786 sender: None,787 }),788 );789790 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;791 let client_set_aside_for_cidp = client.clone();792793 task_manager.spawn_essential_handle().spawn_blocking(794 "authorship_task",795 Some("block-authoring"),796 run_manual_seal(ManualSealParams {797 block_import,798 env,799 client: client.clone(),800 pool: transaction_pool.clone(),801 commands_stream,802 select_chain: select_chain.clone(),803 consensus_data_provider: None,804 create_inherent_data_providers: move |block: Hash, ()| {805 let current_para_block = client_set_aside_for_cidp806 .number(block)807 .expect("Header lookup should succeed")808 .expect("Header passed in as parent should be present in backend.");809810 let client_for_xcm = client_set_aside_for_cidp.clone();811 async move {812 let time = sp_timestamp::InherentDataProvider::from_system_time();813814 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {815 current_para_block,816 relay_offset: 1000,817 relay_blocks_per_para_block: 2,818 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(819 &*client_for_xcm,820 block,821 Default::default(),822 Default::default(),823 ),824 raw_downward_messages: vec![],825 raw_horizontal_messages: vec![],826 };827828 let slot =829 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(830 *time,831 slot_duration.slot_duration(),832 );833834 Ok((time, slot, mocked_parachain))835 }836 },837 }),838 );839 }840841 task_manager.spawn_essential_handle().spawn(842 "frontier-mapping-sync-worker",843 Some("block-authoring"),844 MappingSyncWorker::new(845 client.import_notification_stream(),846 Duration::new(6, 0),847 client.clone(),848 backend.clone(),849 frontier_backend.clone(),850 SyncStrategy::Normal,851 )852 .for_each(|()| futures::future::ready(())),853 );854855 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());856 let rpc_client = client.clone();857 let rpc_pool = transaction_pool.clone();858 let rpc_network = network.clone();859 let rpc_frontier_backend = frontier_backend.clone();860 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {861 let full_deps = unique_rpc::FullDeps {862 backend: rpc_frontier_backend.clone(),863 deny_unsafe,864 client: rpc_client.clone(),865 pool: rpc_pool.clone(),866 graph: rpc_pool.pool().clone(),867 // TODO: Unhardcode868 enable_dev_signer: false,869 filter_pool: filter_pool.clone(),870 network: rpc_network.clone(),871 select_chain: select_chain.clone(),872 is_authority: collator,873 // TODO: Unhardcode874 max_past_logs: 10000,875 block_data_cache: block_data_cache.clone(),876 fee_history_cache: fee_history_cache.clone(),877 // TODO: Unhardcode878 fee_history_limit: 2048,879 };880881 Ok(882 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(883 full_deps,884 subscription_executor.clone(),885 ),886 )887 });888889 sc_service::spawn_tasks(sc_service::SpawnTasksParams {890 network,891 client,892 keystore: keystore_container.sync_keystore(),893 task_manager: &mut task_manager,894 transaction_pool,895 rpc_extensions_builder,896 backend,897 system_rpc_tx,898 config,899 telemetry: None,900 })?;901902 network_starter.start_network();903 Ok(task_manager)904}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};5859use unique_runtime_common::types::{AuraId, RuntimeInstance, AccountId, Balance, Index, Hash, Block};60use crate::chain_spec::ServiceId;6162/// Native executor instance.63pub struct UniqueRuntimeExecutor;64pub struct QuartzRuntimeExecutor;65pub struct OpalRuntimeExecutor;6667#[cfg(feature = "unique-runtime")]68impl NativeExecutionDispatch for UniqueRuntimeExecutor {69 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;7071 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {72 unique_runtime::api::dispatch(method, data)73 }7475 fn native_version() -> sc_executor::NativeVersion {76 unique_runtime::native_version()77 }78}7980#[cfg(feature = "quartz-runtime")]81impl NativeExecutionDispatch for QuartzRuntimeExecutor {82 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;8384 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {85 quartz_runtime::api::dispatch(method, data)86 }8788 fn native_version() -> sc_executor::NativeVersion {89 quartz_runtime::native_version()90 }91}9293impl NativeExecutionDispatch for OpalRuntimeExecutor {94 type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions;9596 fn dispatch(method: &str, data: &[u8]) -> Option<Vec<u8>> {97 opal_runtime::api::dispatch(method, data)98 }99100 fn native_version() -> sc_executor::NativeVersion {101 opal_runtime::native_version()102 }103}104105pub fn open_frontier_backend(config: &Configuration) -> Result<Arc<fc_db::Backend<Block>>, String> {106 let config_dir = config107 .base_path108 .as_ref()109 .map(|base_path| base_path.config_dir(config.chain_spec.id()))110 .unwrap_or_else(|| {111 BasePath::from_project("", "", "unique").config_dir(config.chain_spec.id())112 });113 let database_dir = config_dir.join("frontier").join("db");114115 Ok(Arc::new(fc_db::Backend::<Block>::new(116 &fc_db::DatabaseSettings {117 source: fc_db::DatabaseSettingsSrc::RocksDb {118 path: database_dir,119 cache_size: 0,120 },121 },122 )?))123}124125type FullClient<RuntimeApi, ExecutorDispatch> =126 sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<ExecutorDispatch>>;127type FullBackend = sc_service::TFullBackend<Block>;128type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;129130/// Starts a `ServiceBuilder` for a full service.131///132/// Use this macro if you don't actually need the full service, but just the builder in order to133/// be able to perform chain operations.134#[allow(clippy::type_complexity)]135pub fn new_partial<RuntimeApi, ExecutorDispatch, BIQ>(136 config: &Configuration,137 build_import_queue: BIQ,138 service_id: ServiceId,139) -> Result<140 PartialComponents<141 FullClient<RuntimeApi, ExecutorDispatch>,142 FullBackend,143 FullSelectChain,144 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,145 sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>,146 (147 Option<Telemetry>,148 Option<FilterPool>,149 Arc<fc_db::Backend<Block>>,150 Option<TelemetryWorkerHandle>,151 FeeHistoryCache,152 ),153 >,154 sc_service::Error,155>156where157 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,158 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>159 + Send160 + Sync161 + 'static,162 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>,163 ExecutorDispatch: NativeExecutionDispatch + 'static,164 BIQ: FnOnce(165 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,166 &Configuration,167 Option<TelemetryHandle>,168 &TaskManager,169 ) -> Result<170 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,171 sc_service::Error,172 >,173{174 let _telemetry = config175 .telemetry_endpoints176 .clone()177 .filter(|x| !x.is_empty())178 .map(|endpoints| -> Result<_, sc_telemetry::Error> {179 let worker = TelemetryWorker::new(16)?;180 let telemetry = worker.handle().new_telemetry(endpoints);181 Ok((worker, telemetry))182 })183 .transpose()?;184185 let telemetry = config186 .telemetry_endpoints187 .clone()188 .filter(|x| !x.is_empty())189 .map(|endpoints| -> Result<_, sc_telemetry::Error> {190 let worker = TelemetryWorker::new(16)?;191 let telemetry = worker.handle().new_telemetry(endpoints);192 Ok((worker, telemetry))193 })194 .transpose()?;195196 let executor = NativeElseWasmExecutor::<ExecutorDispatch>::new(197 config.wasm_method,198 config.default_heap_pages,199 config.max_runtime_instances,200 config.runtime_cache_size,201 );202203 let (client, backend, keystore_container, task_manager) =204 sc_service::new_full_parts::<Block, RuntimeApi, _>(205 config,206 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),207 executor,208 )?;209 let client = Arc::new(client);210211 let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());212213 let telemetry = telemetry.map(|(worker, telemetry)| {214 task_manager215 .spawn_handle()216 .spawn("telemetry", None, worker.run());217 telemetry218 });219220 let select_chain = sc_consensus::LongestChain::new(backend.clone());221222 let transaction_pool = sc_transaction_pool::BasicPool::new_full(223 config.transaction_pool.clone(),224 config.role.is_authority().into(),225 config.prometheus_registry(),226 task_manager.spawn_essential_handle(),227 client.clone(),228 );229230 let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));231232 let frontier_backend = open_frontier_backend(config)?;233234 let import_queue = build_import_queue(235 client.clone(),236 config,237 telemetry.as_ref().map(|telemetry| telemetry.handle()),238 &task_manager,239 )?;240 let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));241242 let params = PartialComponents {243 backend,244 client,245 import_queue,246 keystore_container,247 task_manager,248 transaction_pool,249 select_chain,250 other: (251 telemetry,252 filter_pool,253 frontier_backend,254 telemetry_worker_handle,255 fee_history_cache,256 ),257 };258259 Ok(params)260}261262/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.263///264/// This is the actual implementation that is abstract over the executor and the runtime api.265#[sc_tracing::logging::prefix_logs_with("Parachain")]266async fn start_node_impl<Runtime, RuntimeApi, ExecutorDispatch, BIQ, BIC>(267 parachain_config: Configuration,268 polkadot_config: Configuration,269 id: ParaId,270 build_import_queue: BIQ,271 build_consensus: BIC,272) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>273where274 sc_client_api::StateBackendFor<FullBackend, Block>: sp_api::StateBackend<BlakeTwo256>,275 Runtime: RuntimeInstance + Send + Sync + 'static,276 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,277 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,278 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>279 + Send280 + Sync281 + 'static,282 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>283 + fp_rpc::EthereumRuntimeRPCApi<Block>284 + sp_session::SessionKeys<Block>285 + sp_block_builder::BlockBuilder<Block>286 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>287 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>288 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>289 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>290 + sp_api::Metadata<Block>291 + sp_offchain::OffchainWorkerApi<Block>292 + cumulus_primitives_core::CollectCollationInfo<Block>,293 ExecutorDispatch: NativeExecutionDispatch + 'static,294 BIQ: FnOnce(295 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,296 &Configuration,297 Option<TelemetryHandle>,298 &TaskManager,299 ) -> Result<300 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,301 sc_service::Error,302 >,303 BIC: FnOnce(304 Arc<FullClient<RuntimeApi, ExecutorDispatch>>,305 Option<&Registry>,306 Option<TelemetryHandle>,307 &TaskManager,308 Arc<dyn RelayChainInterface>,309 Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi, ExecutorDispatch>>>,310 Arc<NetworkService<Block, Hash>>,311 SyncCryptoStorePtr,312 bool,313 ) -> Result<Box<dyn ParachainConsensus<Block>>, sc_service::Error>,314{315 if matches!(parachain_config.role, Role::Light) {316 return Err("Light client not supported!".into());317 }318319 let parachain_config = prepare_node_config(parachain_config);320321 let params = new_partial::<RuntimeApi, ExecutorDispatch, BIQ>(322 ¶chain_config,323 build_import_queue,324 ServiceId::Prod,325 )?;326 let (mut telemetry, filter_pool, frontier_backend, telemetry_worker_handle, fee_history_cache) =327 params.other;328329 let client = params.client.clone();330 let backend = params.backend.clone();331 let mut task_manager = params.task_manager;332333 let (relay_chain_interface, collator_key) =334 build_relay_chain_interface(polkadot_config, telemetry_worker_handle, &mut task_manager)335 .map_err(|e| match e {336 polkadot_service::Error::Sub(x) => x,337 s => format!("{}", s).into(),338 })?;339340 let block_announce_validator = BlockAnnounceValidator::new(relay_chain_interface.clone(), id);341342 let force_authoring = parachain_config.force_authoring;343 let validator = parachain_config.role.is_authority();344 let prometheus_registry = parachain_config.prometheus_registry().cloned();345 let transaction_pool = params.transaction_pool.clone();346 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);347348 let (network, system_rpc_tx, start_network) =349 sc_service::build_network(sc_service::BuildNetworkParams {350 config: ¶chain_config,351 client: client.clone(),352 transaction_pool: transaction_pool.clone(),353 spawn_handle: task_manager.spawn_handle(),354 import_queue: import_queue.clone(),355 block_announce_validator_builder: Some(Box::new(|_| {356 Box::new(block_announce_validator)357 })),358 warp_sync: None,359 })?;360361 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());362 let rpc_client = client.clone();363 let rpc_pool = transaction_pool.clone();364 let select_chain = params365 .select_chain366 .clone();367 let rpc_network = network.clone();368369 let rpc_frontier_backend = frontier_backend.clone();370371 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(372 task_manager.spawn_handle(),373 overrides_handle::<_, _, Runtime>(client.clone()),374 50,375 50,376 ));377378 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {379 let full_deps = unique_rpc::FullDeps {380 backend: rpc_frontier_backend.clone(),381 deny_unsafe,382 client: rpc_client.clone(),383 pool: rpc_pool.clone(),384 graph: rpc_pool.pool().clone(),385 // TODO: Unhardcode386 enable_dev_signer: false,387 filter_pool: filter_pool.clone(),388 network: rpc_network.clone(),389 select_chain: select_chain.clone(),390 is_authority: validator,391 // TODO: Unhardcode392 max_past_logs: 10000,393 block_data_cache: block_data_cache.clone(),394 fee_history_cache: fee_history_cache.clone(),395 // TODO: Unhardcode396 fee_history_limit: 2048,397 };398399 Ok(400 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(401 full_deps,402 subscription_executor.clone(),403 ),404 )405 });406407 task_manager.spawn_essential_handle().spawn(408 "frontier-mapping-sync-worker",409 None,410 MappingSyncWorker::new(411 client.import_notification_stream(),412 Duration::new(6, 0),413 client.clone(),414 backend.clone(),415 frontier_backend.clone(),416 SyncStrategy::Normal,417 )418 .for_each(|()| futures::future::ready(())),419 );420421 sc_service::spawn_tasks(sc_service::SpawnTasksParams {422 rpc_extensions_builder,423 client: client.clone(),424 transaction_pool: transaction_pool.clone(),425 task_manager: &mut task_manager,426 config: parachain_config,427 keystore: params.keystore_container.sync_keystore(),428 backend: backend.clone(),429 network: network.clone(),430 system_rpc_tx,431 telemetry: telemetry.as_mut(),432 })?;433434 let announce_block = {435 let network = network.clone();436 Arc::new(move |hash, data| network.announce_block(hash, data))437 };438439 let relay_chain_slot_duration = Duration::from_secs(6);440441 if validator {442 let parachain_consensus = build_consensus(443 client.clone(),444 prometheus_registry.as_ref(),445 telemetry.as_ref().map(|t| t.handle()),446 &task_manager,447 relay_chain_interface.clone(),448 transaction_pool,449 network,450 params.keystore_container.sync_keystore(),451 force_authoring,452 )?;453454 let spawner = task_manager.spawn_handle();455456 let params = StartCollatorParams {457 para_id: id,458 block_status: client.clone(),459 announce_block,460 client: client.clone(),461 task_manager: &mut task_manager,462 spawner,463 parachain_consensus,464 import_queue,465 collator_key,466 relay_chain_interface,467 relay_chain_slot_duration,468 };469470 start_collator(params).await?;471 } else {472 let params = StartFullNodeParams {473 client: client.clone(),474 announce_block,475 task_manager: &mut task_manager,476 para_id: id,477 import_queue,478 relay_chain_interface,479 relay_chain_slot_duration,480 };481482 start_full_node(params)?;483 }484485 start_network.start_network();486487 Ok((task_manager, client))488}489490/// Build the import queue for the the parachain runtime.491pub fn parachain_build_import_queue<RuntimeApi, ExecutorDispatch>(492 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,493 config: &Configuration,494 telemetry: Option<TelemetryHandle>,495 task_manager: &TaskManager,496) -> Result<497 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,498 sc_service::Error,499>500where501 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>502 + Send503 + Sync504 + 'static,505 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>506 + sp_block_builder::BlockBuilder<Block>507 + sp_consensus_aura::AuraApi<Block, AuraId>508 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,509 ExecutorDispatch: NativeExecutionDispatch + 'static,510{511 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;512513 cumulus_client_consensus_aura::import_queue::<514 sp_consensus_aura::sr25519::AuthorityPair,515 _,516 _,517 _,518 _,519 _,520 _,521 >(cumulus_client_consensus_aura::ImportQueueParams {522 block_import: client.clone(),523 client: client.clone(),524 create_inherent_data_providers: move |_, _| async move {525 let time = sp_timestamp::InherentDataProvider::from_system_time();526527 let slot =528 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(529 *time,530 slot_duration.slot_duration(),531 );532533 Ok((time, slot))534 },535 registry: config.prometheus_registry(),536 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),537 spawner: &task_manager.spawn_essential_handle(),538 telemetry,539 })540 .map_err(Into::into)541}542543/// Start a normal parachain node.544pub async fn start_node<Runtime, RuntimeApi, ExecutorDispatch>(545 parachain_config: Configuration,546 polkadot_config: Configuration,547 id: ParaId,548) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi, ExecutorDispatch>>)>549where550 Runtime: RuntimeInstance + Send + Sync + 'static,551 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,552 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,553 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>554 + Send555 + Sync556 + 'static,557 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>558 + fp_rpc::EthereumRuntimeRPCApi<Block>559 + sp_session::SessionKeys<Block>560 + sp_block_builder::BlockBuilder<Block>561 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>562 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>563 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>564 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>565 + sp_api::Metadata<Block>566 + sp_offchain::OffchainWorkerApi<Block>567 + cumulus_primitives_core::CollectCollationInfo<Block>568 + sp_consensus_aura::AuraApi<Block, AuraId>,569 ExecutorDispatch: NativeExecutionDispatch + 'static,570{571 start_node_impl::<Runtime, RuntimeApi, ExecutorDispatch, _, _>(572 parachain_config,573 polkadot_config,574 id,575 parachain_build_import_queue,576 |client,577 prometheus_registry,578 telemetry,579 task_manager,580 relay_chain_interface,581 transaction_pool,582 sync_oracle,583 keystore,584 force_authoring| {585 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;586587 let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(588 task_manager.spawn_handle(),589 client.clone(),590 transaction_pool,591 prometheus_registry,592 telemetry.clone(),593 );594595 Ok(AuraConsensus::build::<596 sp_consensus_aura::sr25519::AuthorityPair,597 _,598 _,599 _,600 _,601 _,602 _,603 >(BuildAuraConsensusParams {604 proposer_factory,605 create_inherent_data_providers: move |_, (relay_parent, validation_data)| {606 let relay_chain_interface = relay_chain_interface.clone();607 async move {608 let parachain_inherent =609 cumulus_primitives_parachain_inherent::ParachainInherentData::create_at(610 relay_parent,611 &relay_chain_interface,612 &validation_data,613 id,614 ).await;615616 let time = sp_timestamp::InherentDataProvider::from_system_time();617618 let slot =619 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(620 *time,621 slot_duration.slot_duration(),622 );623624 let parachain_inherent = parachain_inherent.ok_or_else(|| {625 Box::<dyn std::error::Error + Send + Sync>::from(626 "Failed to create parachain inherent",627 )628 })?;629 Ok((time, slot, parachain_inherent))630 }631 },632 block_import: client.clone(),633 para_client: client,634 backoff_authoring_blocks: Option::<()>::None,635 sync_oracle,636 keystore,637 force_authoring,638 slot_duration: *slot_duration,639 // We got around 500ms for proposing640 block_proposal_slot_portion: SlotProportion::new(1f32 / 24f32),641 telemetry,642 max_block_proposal_slot_portion: None,643 }))644 },645 )646 .await647}648649fn dev_build_import_queue<RuntimeApi, ExecutorDispatch>(650 client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,651 config: &Configuration,652 _: Option<TelemetryHandle>,653 task_manager: &TaskManager,654) -> Result<655 sc_consensus::DefaultImportQueue<Block, FullClient<RuntimeApi, ExecutorDispatch>>,656 sc_service::Error,657>658where659 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>660 + Send661 + Sync662 + 'static,663 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>664 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>,665 ExecutorDispatch: NativeExecutionDispatch + 'static,666{667 Ok(sc_consensus_manual_seal::import_queue(668 Box::new(client.clone()),669 &task_manager.spawn_essential_handle(),670 config.prometheus_registry(),671 ))672}673674/// Builds a new development service. This service uses instant seal, and mocks675/// the parachain inherent676pub fn start_dev_node<Runtime, RuntimeApi, ExecutorDispatch>(677 config: Configuration,678) -> sc_service::error::Result<TaskManager>679where680 Runtime: RuntimeInstance + Send + Sync + 'static,681 <Runtime as RuntimeInstance>::CrossAccountId: Serialize,682 for<'de> <Runtime as RuntimeInstance>::CrossAccountId: Deserialize<'de>,683 RuntimeApi: sp_api::ConstructRuntimeApi<Block, FullClient<RuntimeApi, ExecutorDispatch>>684 + Send685 + Sync686 + 'static,687 RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block>688 + fp_rpc::EthereumRuntimeRPCApi<Block>689 + sp_session::SessionKeys<Block>690 + sp_block_builder::BlockBuilder<Block>691 + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>692 + sp_api::ApiExt<Block, StateBackend = sc_client_api::StateBackendFor<FullBackend, Block>>693 + up_rpc::UniqueApi<Block, Runtime::CrossAccountId, AccountId>694 + substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>695 + sp_api::Metadata<Block>696 + sp_offchain::OffchainWorkerApi<Block>697 + cumulus_primitives_core::CollectCollationInfo<Block>698 + sp_consensus_aura::AuraApi<Block, AuraId>,699 ExecutorDispatch: NativeExecutionDispatch + 'static,700{701 use futures::Stream;702 use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};703 use fc_consensus::FrontierBlockImport;704 use sc_client_api::HeaderBackend;705706 let sc_service::PartialComponents {707 client,708 backend,709 mut task_manager,710 import_queue,711 keystore_container,712 select_chain: maybe_select_chain,713 transaction_pool,714 other:715 (telemetry, filter_pool, frontier_backend, _telemetry_worker_handle, fee_history_cache),716 } = new_partial::<RuntimeApi, ExecutorDispatch, _>(717 &config,718 dev_build_import_queue::<RuntimeApi, ExecutorDispatch>,719 ServiceId::Dev,720 )?;721722 let block_data_cache = Arc::new(fc_rpc::EthBlockDataCache::new(723 task_manager.spawn_handle(),724 overrides_handle::<_, _, Runtime>(client.clone()),725 50,726 50,727 ));728729 let (network, system_rpc_tx, network_starter) =730 sc_service::build_network(sc_service::BuildNetworkParams {731 config: &config,732 client: client.clone(),733 transaction_pool: transaction_pool.clone(),734 spawn_handle: task_manager.spawn_handle(),735 import_queue,736 block_announce_validator_builder: None,737 warp_sync: None,738 })?;739740 if config.offchain_worker.enabled {741 sc_service::build_offchain_workers(742 &config,743 task_manager.spawn_handle(),744 client.clone(),745 network.clone(),746 );747 }748749 let prometheus_registry = config.prometheus_registry().cloned();750 let collator = config.role.is_authority();751752 let select_chain = maybe_select_chain.clone();753754 if collator {755 let block_import =756 FrontierBlockImport::new(client.clone(), client.clone(), frontier_backend.clone());757758 let env = sc_basic_authorship::ProposerFactory::new(759 task_manager.spawn_handle(),760 client.clone(),761 transaction_pool.clone(),762 prometheus_registry.as_ref(),763 telemetry.as_ref().map(|x| x.handle()),764 );765766 let commands_stream: Box<dyn Stream<Item = EngineCommand<Hash>> + Send + Sync + Unpin> =767 Box::new(768 // This bit cribbed from the implementation of instant seal.769 transaction_pool770 .pool()771 .validated_pool()772 .import_notification_stream()773 .map(|_| EngineCommand::SealNewBlock {774 create_empty: true, // was false in Moonbeam775 finalize: false,776 parent_hash: None,777 sender: None,778 }),779 );780781 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;782 let client_set_aside_for_cidp = client.clone();783784 task_manager.spawn_essential_handle().spawn_blocking(785 "authorship_task",786 Some("block-authoring"),787 run_manual_seal(ManualSealParams {788 block_import,789 env,790 client: client.clone(),791 pool: transaction_pool.clone(),792 commands_stream,793 select_chain: select_chain.clone(),794 consensus_data_provider: None,795 create_inherent_data_providers: move |block: Hash, ()| {796 let current_para_block = client_set_aside_for_cidp797 .number(block)798 .expect("Header lookup should succeed")799 .expect("Header passed in as parent should be present in backend.");800801 let client_for_xcm = client_set_aside_for_cidp.clone();802 async move {803 let time = sp_timestamp::InherentDataProvider::from_system_time();804805 let mocked_parachain = cumulus_primitives_parachain_inherent::MockValidationDataInherentDataProvider {806 current_para_block,807 relay_offset: 1000,808 relay_blocks_per_para_block: 2,809 xcm_config: cumulus_primitives_parachain_inherent::MockXcmConfig::new(810 &*client_for_xcm,811 block,812 Default::default(),813 Default::default(),814 ),815 raw_downward_messages: vec![],816 raw_horizontal_messages: vec![],817 };818819 let slot =820 sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(821 *time,822 slot_duration.slot_duration(),823 );824825 Ok((time, slot, mocked_parachain))826 }827 },828 }),829 );830 }831832 task_manager.spawn_essential_handle().spawn(833 "frontier-mapping-sync-worker",834 Some("block-authoring"),835 MappingSyncWorker::new(836 client.import_notification_stream(),837 Duration::new(6, 0),838 client.clone(),839 backend.clone(),840 frontier_backend.clone(),841 SyncStrategy::Normal,842 )843 .for_each(|()| futures::future::ready(())),844 );845846 let subscription_executor = sc_rpc::SubscriptionTaskExecutor::new(task_manager.spawn_handle());847 let rpc_client = client.clone();848 let rpc_pool = transaction_pool.clone();849 let rpc_network = network.clone();850 let rpc_frontier_backend = frontier_backend.clone();851 let rpc_extensions_builder = Box::new(move |deny_unsafe, _| {852 let full_deps = unique_rpc::FullDeps {853 backend: rpc_frontier_backend.clone(),854 deny_unsafe,855 client: rpc_client.clone(),856 pool: rpc_pool.clone(),857 graph: rpc_pool.pool().clone(),858 // TODO: Unhardcode859 enable_dev_signer: false,860 filter_pool: filter_pool.clone(),861 network: rpc_network.clone(),862 select_chain: select_chain.clone(),863 is_authority: collator,864 // TODO: Unhardcode865 max_past_logs: 10000,866 block_data_cache: block_data_cache.clone(),867 fee_history_cache: fee_history_cache.clone(),868 // TODO: Unhardcode869 fee_history_limit: 2048,870 };871872 Ok(873 unique_rpc::create_full::<_, _, _, _, Runtime, RuntimeApi, _>(874 full_deps,875 subscription_executor.clone(),876 ),877 )878 });879880 sc_service::spawn_tasks(sc_service::SpawnTasksParams {881 network,882 client,883 keystore: keystore_container.sync_keystore(),884 task_manager: &mut task_manager,885 transaction_pool,886 rpc_extensions_builder,887 backend,888 system_rpc_tx,889 config,890 telemetry: None,891 })?;892893 network_starter.start_network();894 Ok(task_manager)895}