1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! This module assembles the Moonbeam service components, executes them, and manages communication
18
//! between them. This is the backbone of the client-side node implementation.
19
//!
20
//! This module can assemble:
21
//! PartialComponents: For maintence tasks without a complete node (eg import/export blocks, purge)
22
//! Full Service: A complete parachain node including the pool, rpc, network, embedded relay chain
23
//! Dev Service: A leaner service without the relay chain backing.
24

            
25
pub mod rpc;
26

            
27
use cumulus_client_cli::CollatorOptions;
28
use cumulus_client_collator::service::CollatorService;
29
use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport;
30
use cumulus_client_consensus_proposer::Proposer;
31
use cumulus_client_parachain_inherent::{MockValidationDataInherentDataProvider, MockXcmConfig};
32
use cumulus_client_service::{
33
	prepare_node_config, start_relay_chain_tasks, CollatorSybilResistance, DARecoveryProfile,
34
	ParachainHostFunctions, StartRelayChainTasksParams,
35
};
36
use cumulus_primitives_core::{
37
	relay_chain::{self, well_known_keys, CollatorPair},
38
	CollectCollationInfo, ParaId,
39
};
40
use cumulus_relay_chain_inprocess_interface::build_inprocess_relay_chain;
41
use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface, RelayChainResult};
42
use cumulus_relay_chain_minimal_node::build_minimal_relay_chain_node_with_rpc;
43
use fc_consensus::FrontierBlockImport as TFrontierBlockImport;
44
use fc_db::DatabaseSource;
45
use fc_rpc::StorageOverrideHandler;
46
use fc_rpc_core::types::{FeeHistoryCache, FilterPool};
47
use futures::{FutureExt, StreamExt};
48
use maplit::hashmap;
49
#[cfg(feature = "moonbase-native")]
50
pub use moonbase_runtime;
51
use moonbeam_cli_opt::{EthApi as EthApiCmd, FrontierBackendConfig, RpcConfig};
52
#[cfg(feature = "moonbeam-native")]
53
pub use moonbeam_runtime;
54
use moonbeam_vrf::VrfDigestsProvider;
55
#[cfg(feature = "moonriver-native")]
56
pub use moonriver_runtime;
57
use nimbus_consensus::NimbusManualSealConsensusDataProvider;
58
use nimbus_primitives::{DigestsProvider, NimbusId};
59
use polkadot_primitives::{AbridgedHostConfiguration, AsyncBackingParams, Slot, UpgradeGoAhead};
60
use sc_client_api::{
61
	backend::{AuxStore, Backend, StateBackend, StorageProvider},
62
	ExecutorProvider,
63
};
64
use sc_consensus::ImportQueue;
65
use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
66
use sc_network::{config::FullNetworkConfiguration, NetworkBackend, NetworkBlock};
67
use sc_service::config::PrometheusConfig;
68
use sc_service::{
69
	error::Error as ServiceError, ChainSpec, Configuration, PartialComponents, TFullBackend,
70
	TFullClient, TaskManager,
71
};
72
use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle};
73
use sc_transaction_pool_api::{OffchainTransactionPoolFactory, TransactionPool};
74
use session_keys_primitives::VrfApi;
75
use sp_api::{ConstructRuntimeApi, ProvideRuntimeApi};
76
use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
77
use sp_consensus::SyncOracle;
78
use sp_core::{ByteArray, Encode, H256};
79
use sp_keystore::{Keystore, KeystorePtr};
80
use std::str::FromStr;
81
use std::sync::atomic::{AtomicU64, Ordering};
82
use std::sync::Arc;
83
use std::{collections::BTreeMap, path::Path, sync::Mutex, time::Duration};
84
use substrate_prometheus_endpoint::Registry;
85

            
86
pub use client::*;
87
pub mod chain_spec;
88
mod client;
89
#[cfg(feature = "lazy-loading")]
90
pub mod lazy_loading;
91

            
92
type FullClient<RuntimeApi> = TFullClient<Block, RuntimeApi, WasmExecutor<HostFunctions>>;
93
type FullBackend = TFullBackend<Block>;
94

            
95
type MaybeSelectChain<Backend> = Option<sc_consensus::LongestChain<Backend, Block>>;
96
type FrontierBlockImport<Client> = TFrontierBlockImport<Block, Arc<Client>, Client>;
97
type ParachainBlockImport<Client, Backend> =
98
	TParachainBlockImport<Block, FrontierBlockImport<Client>, Backend>;
99
type PartialComponentsResult<Client, Backend> = Result<
100
	PartialComponents<
101
		Client,
102
		Backend,
103
		MaybeSelectChain<Backend>,
104
		sc_consensus::DefaultImportQueue<Block>,
105
		sc_transaction_pool::TransactionPoolHandle<Block, Client>,
106
		(
107
			BlockImportPipeline<FrontierBlockImport<Client>, ParachainBlockImport<Client, Backend>>,
108
			Option<FilterPool>,
109
			Option<Telemetry>,
110
			Option<TelemetryWorkerHandle>,
111
			Arc<fc_db::Backend<Block, Client>>,
112
			FeeHistoryCache,
113
		),
114
	>,
115
	ServiceError,
116
>;
117

            
118
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6_000;
119

            
120
static TIMESTAMP: AtomicU64 = AtomicU64::new(0);
121

            
122
/// Provide a mock duration starting at 0 in millisecond for timestamp inherent.
123
/// Each call will increment timestamp by slot_duration making Aura think time has passed.
124
struct MockTimestampInherentDataProvider;
125
#[async_trait::async_trait]
126
impl sp_inherents::InherentDataProvider for MockTimestampInherentDataProvider {
127
	async fn provide_inherent_data(
128
		&self,
129
		inherent_data: &mut sp_inherents::InherentData,
130
26898
	) -> Result<(), sp_inherents::Error> {
131
26898
		TIMESTAMP.fetch_add(RELAY_CHAIN_SLOT_DURATION_MILLIS, Ordering::SeqCst);
132
26898
		inherent_data.put_data(
133
26898
			sp_timestamp::INHERENT_IDENTIFIER,
134
26898
			&TIMESTAMP.load(Ordering::SeqCst),
135
26898
		)
136
53796
	}
137

            
138
	async fn try_handle_error(
139
		&self,
140
		_identifier: &sp_inherents::InherentIdentifier,
141
		_error: &[u8],
142
	) -> Option<Result<(), sp_inherents::Error>> {
143
		// The pallet never reports error.
144
		None
145
	}
146
}
147

            
148
#[cfg(feature = "runtime-benchmarks")]
149
pub type HostFunctions = (
150
	frame_benchmarking::benchmarking::HostFunctions,
151
	ParachainHostFunctions,
152
	moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
153
);
154
#[cfg(not(feature = "runtime-benchmarks"))]
155
pub type HostFunctions = (
156
	ParachainHostFunctions,
157
	moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
158
);
159

            
160
/// Block Import Pipeline used.
161
pub enum BlockImportPipeline<T, E> {
162
	/// Used in dev mode to import new blocks as best blocks.
163
	Dev(T),
164
	/// Used in parachain mode.
165
	Parachain(E),
166
}
167

            
168
/// A trait that must be implemented by all moon* runtimes executors.
169
///
170
/// This feature allows, for instance, to customize the client extensions according to the type
171
/// of network.
172
/// For the moment, this feature is only used to specify the first block compatible with
173
/// ed25519-zebra, but it could be used for other things in the future.
174
pub trait ClientCustomizations {
175
	/// The host function ed25519_verify has changed its behavior in the substrate history,
176
	/// because of the change from lib ed25519-dalek to lib ed25519-zebra.
177
	/// Some networks may have old blocks that are not compatible with ed25519-zebra,
178
	/// for these networks this function should return the 1st block compatible with the new lib.
179
	/// If this function returns None (default behavior), it implies that all blocks are compatible
180
	/// with the new lib (ed25519-zebra).
181
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
182
		None
183
	}
184
}
185

            
186
#[cfg(feature = "moonbeam-native")]
187
pub struct MoonbeamCustomizations;
188
#[cfg(feature = "moonbeam-native")]
189
impl ClientCustomizations for MoonbeamCustomizations {
190
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
191
		Some(2_000_000)
192
	}
193
}
194

            
195
#[cfg(feature = "moonriver-native")]
196
pub struct MoonriverCustomizations;
197
#[cfg(feature = "moonriver-native")]
198
impl ClientCustomizations for MoonriverCustomizations {
199
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
200
		Some(3_000_000)
201
	}
202
}
203

            
204
#[cfg(feature = "moonbase-native")]
205
pub struct MoonbaseCustomizations;
206
#[cfg(feature = "moonbase-native")]
207
impl ClientCustomizations for MoonbaseCustomizations {
208
936
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
209
936
		Some(3_000_000)
210
936
	}
211
}
212

            
213
/// Trivial enum representing runtime variant
214
#[derive(Clone)]
215
pub enum RuntimeVariant {
216
	#[cfg(feature = "moonbeam-native")]
217
	Moonbeam,
218
	#[cfg(feature = "moonriver-native")]
219
	Moonriver,
220
	#[cfg(feature = "moonbase-native")]
221
	Moonbase,
222
	Unrecognized,
223
}
224

            
225
impl RuntimeVariant {
226
	pub fn from_chain_spec(chain_spec: &Box<dyn ChainSpec>) -> Self {
227
		match chain_spec {
228
			#[cfg(feature = "moonbeam-native")]
229
			spec if spec.is_moonbeam() => Self::Moonbeam,
230
			#[cfg(feature = "moonriver-native")]
231
			spec if spec.is_moonriver() => Self::Moonriver,
232
			#[cfg(feature = "moonbase-native")]
233
			spec if spec.is_moonbase() => Self::Moonbase,
234
			_ => Self::Unrecognized,
235
		}
236
	}
237
}
238

            
239
/// Can be called for a `Configuration` to check if it is a configuration for
240
/// the `Moonbeam` network.
241
pub trait IdentifyVariant {
242
	/// Returns `true` if this is a configuration for the `Moonbase` network.
243
	fn is_moonbase(&self) -> bool;
244

            
245
	/// Returns `true` if this is a configuration for the `Moonbeam` network.
246
	fn is_moonbeam(&self) -> bool;
247

            
248
	/// Returns `true` if this is a configuration for the `Moonriver` network.
249
	fn is_moonriver(&self) -> bool;
250

            
251
	/// Returns `true` if this is a configuration for a dev network.
252
	fn is_dev(&self) -> bool;
253
}
254

            
255
impl IdentifyVariant for Box<dyn ChainSpec> {
256
	fn is_moonbase(&self) -> bool {
257
		self.id().starts_with("moonbase")
258
	}
259

            
260
936
	fn is_moonbeam(&self) -> bool {
261
936
		self.id().starts_with("moonbeam")
262
936
	}
263

            
264
936
	fn is_moonriver(&self) -> bool {
265
936
		self.id().starts_with("moonriver")
266
936
	}
267

            
268
934
	fn is_dev(&self) -> bool {
269
934
		self.chain_type() == sc_chain_spec::ChainType::Development
270
934
	}
271
}
272

            
273
936
pub fn frontier_database_dir(config: &Configuration, path: &str) -> std::path::PathBuf {
274
936
	config
275
936
		.base_path
276
936
		.config_dir(config.chain_spec.id())
277
936
		.join("frontier")
278
936
		.join(path)
279
936
}
280

            
281
// TODO This is copied from frontier. It should be imported instead after
282
// https://github.com/paritytech/frontier/issues/333 is solved
283
936
pub fn open_frontier_backend<C, BE>(
284
936
	client: Arc<C>,
285
936
	config: &Configuration,
286
936
	rpc_config: &RpcConfig,
287
936
) -> Result<fc_db::Backend<Block, C>, String>
288
936
where
289
936
	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
290
936
	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,
291
936
	C: Send + Sync + 'static,
292
936
	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
293
936
	BE: Backend<Block> + 'static,
294
936
	BE::State: StateBackend<BlakeTwo256>,
295
936
{
296
936
	let frontier_backend = match rpc_config.frontier_backend_config {
297
		FrontierBackendConfig::KeyValue => {
298
			fc_db::Backend::KeyValue(Arc::new(fc_db::kv::Backend::<Block, C>::new(
299
936
				client,
300
936
				&fc_db::kv::DatabaseSettings {
301
936
					source: match config.database {
302
936
						DatabaseSource::RocksDb { .. } => DatabaseSource::RocksDb {
303
936
							path: frontier_database_dir(config, "db"),
304
936
							cache_size: 0,
305
936
						},
306
						DatabaseSource::ParityDb { .. } => DatabaseSource::ParityDb {
307
							path: frontier_database_dir(config, "paritydb"),
308
						},
309
						DatabaseSource::Auto { .. } => DatabaseSource::Auto {
310
							rocksdb_path: frontier_database_dir(config, "db"),
311
							paritydb_path: frontier_database_dir(config, "paritydb"),
312
							cache_size: 0,
313
						},
314
						_ => {
315
							return Err(
316
								"Supported db sources: `rocksdb` | `paritydb` | `auto`".to_string()
317
							)
318
						}
319
					},
320
				},
321
			)?))
322
		}
323
		FrontierBackendConfig::Sql {
324
			pool_size,
325
			num_ops_timeout,
326
			thread_count,
327
			cache_size,
328
		} => {
329
			let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
330
			let sqlite_db_path = frontier_database_dir(config, "sql");
331
			std::fs::create_dir_all(&sqlite_db_path).expect("failed creating sql db directory");
332
			let backend = futures::executor::block_on(fc_db::sql::Backend::new(
333
				fc_db::sql::BackendConfig::Sqlite(fc_db::sql::SqliteBackendConfig {
334
					path: Path::new("sqlite:///")
335
						.join(sqlite_db_path)
336
						.join("frontier.db3")
337
						.to_str()
338
						.expect("frontier sql path error"),
339
					create_if_missing: true,
340
					thread_count: thread_count,
341
					cache_size: cache_size,
342
				}),
343
				pool_size,
344
				std::num::NonZeroU32::new(num_ops_timeout),
345
				overrides.clone(),
346
			))
347
			.unwrap_or_else(|err| panic!("failed creating sql backend: {:?}", err));
348
			fc_db::Backend::Sql(Arc::new(backend))
349
		}
350
	};
351

            
352
936
	Ok(frontier_backend)
353
936
}
354

            
355
use sp_runtime::{traits::BlakeTwo256, DigestItem, Percent};
356

            
357
pub const SOFT_DEADLINE_PERCENT: Percent = Percent::from_percent(100);
358

            
359
/// Builds a new object suitable for chain operations.
360
#[allow(clippy::type_complexity)]
361
pub fn new_chain_ops(
362
	config: &mut Configuration,
363
	rpc_config: &RpcConfig,
364
	legacy_block_import_strategy: bool,
365
) -> Result<
366
	(
367
		Arc<Client>,
368
		Arc<FullBackend>,
369
		sc_consensus::BasicQueue<Block>,
370
		TaskManager,
371
	),
372
	ServiceError,
373
> {
374
	match &config.chain_spec {
375
		#[cfg(feature = "moonriver-native")]
376
		spec if spec.is_moonriver() => new_chain_ops_inner::<
377
			moonriver_runtime::RuntimeApi,
378
			MoonriverCustomizations,
379
		>(config, rpc_config, legacy_block_import_strategy),
380
		#[cfg(feature = "moonbeam-native")]
381
		spec if spec.is_moonbeam() => new_chain_ops_inner::<
382
			moonbeam_runtime::RuntimeApi,
383
			MoonbeamCustomizations,
384
		>(config, rpc_config, legacy_block_import_strategy),
385
		#[cfg(feature = "moonbase-native")]
386
		_ => new_chain_ops_inner::<moonbase_runtime::RuntimeApi, MoonbaseCustomizations>(
387
			config,
388
			rpc_config,
389
			legacy_block_import_strategy,
390
		),
391
		#[cfg(not(feature = "moonbase-native"))]
392
		_ => panic!("invalid chain spec"),
393
	}
394
}
395

            
396
#[allow(clippy::type_complexity)]
397
fn new_chain_ops_inner<RuntimeApi, Customizations>(
398
	config: &mut Configuration,
399
	rpc_config: &RpcConfig,
400
	legacy_block_import_strategy: bool,
401
) -> Result<
402
	(
403
		Arc<Client>,
404
		Arc<FullBackend>,
405
		sc_consensus::BasicQueue<Block>,
406
		TaskManager,
407
	),
408
	ServiceError,
409
>
410
where
411
	Client: From<Arc<crate::FullClient<RuntimeApi>>>,
412
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
413
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
414
	Customizations: ClientCustomizations + 'static,
415
{
416
	config.keystore = sc_service::config::KeystoreConfig::InMemory;
417
	let PartialComponents {
418
		client,
419
		backend,
420
		import_queue,
421
		task_manager,
422
		..
423
	} = new_partial::<RuntimeApi, Customizations>(
424
		config,
425
		rpc_config,
426
		config.chain_spec.is_dev(),
427
		legacy_block_import_strategy,
428
	)?;
429
	Ok((
430
		Arc::new(Client::from(client)),
431
		backend,
432
		import_queue,
433
		task_manager,
434
	))
435
}
436

            
437
// If we're using prometheus, use a registry with a prefix of `moonbeam`.
438
936
fn set_prometheus_registry(
439
936
	config: &mut Configuration,
440
936
	skip_prefix: bool,
441
936
) -> Result<(), ServiceError> {
442
936
	if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
443
		let labels = hashmap! {
444
			"chain".into() => config.chain_spec.id().into(),
445
		};
446
		let prefix = if skip_prefix {
447
			None
448
		} else {
449
			Some("moonbeam".into())
450
		};
451

            
452
		*registry = Registry::new_custom(prefix, Some(labels))?;
453
936
	}
454

            
455
936
	Ok(())
456
936
}
457

            
458
/// Builds the PartialComponents for a parachain or development service
459
///
460
/// Use this function if you don't actually need the full service, but just the partial in order to
461
/// be able to perform chain operations.
462
#[allow(clippy::type_complexity)]
463
936
pub fn new_partial<RuntimeApi, Customizations>(
464
936
	config: &mut Configuration,
465
936
	rpc_config: &RpcConfig,
466
936
	dev_service: bool,
467
936
	legacy_block_import_strategy: bool,
468
936
) -> PartialComponentsResult<FullClient<RuntimeApi>, FullBackend>
469
936
where
470
936
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
471
936
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
472
936
	Customizations: ClientCustomizations + 'static,
473
936
{
474
936
	set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
475

            
476
	// Use ethereum style for subscription ids
477
936
	config.rpc.id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
478

            
479
936
	let telemetry = config
480
936
		.telemetry_endpoints
481
936
		.clone()
482
936
		.filter(|x| !x.is_empty())
483
936
		.map(|endpoints| -> Result<_, sc_telemetry::Error> {
484
			let worker = TelemetryWorker::new(16)?;
485
			let telemetry = worker.handle().new_telemetry(endpoints);
486
			Ok((worker, telemetry))
487
936
		})
488
936
		.transpose()?;
489

            
490
936
	let heap_pages = config
491
936
		.executor
492
936
		.default_heap_pages
493
936
		.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
494
			extra_pages: h as _,
495
936
		});
496
936
	let mut wasm_builder = WasmExecutor::builder()
497
936
		.with_execution_method(config.executor.wasm_method)
498
936
		.with_onchain_heap_alloc_strategy(heap_pages)
499
936
		.with_offchain_heap_alloc_strategy(heap_pages)
500
936
		.with_ignore_onchain_heap_pages(true)
501
936
		.with_max_runtime_instances(config.executor.max_runtime_instances)
502
936
		.with_runtime_cache_size(config.executor.runtime_cache_size);
503

            
504
936
	if let Some(ref wasmtime_precompiled_path) = config.executor.wasmtime_precompiled {
505
934
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
506
934
	}
507

            
508
936
	let executor = wasm_builder.build();
509

            
510
936
	let (client, backend, keystore_container, task_manager) =
511
936
		sc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
512
936
			config,
513
936
			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
514
936
			executor,
515
936
			true,
516
936
		)?;
517

            
518
936
	if let Some(block_number) = Customizations::first_block_number_compatible_with_ed25519_zebra() {
519
936
		client
520
936
			.execution_extensions()
521
936
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
522
936
			Block,
523
936
			sp_io::UseDalekExt,
524
936
		>::new(block_number));
525
936
	}
526

            
527
936
	let client = Arc::new(client);
528
936

            
529
936
	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
530
936

            
531
936
	let telemetry = telemetry.map(|(worker, telemetry)| {
532
		task_manager
533
			.spawn_handle()
534
			.spawn("telemetry", None, worker.run());
535
		telemetry
536
936
	});
537

            
538
936
	let maybe_select_chain = if dev_service {
539
934
		Some(sc_consensus::LongestChain::new(backend.clone()))
540
	} else {
541
2
		None
542
	};
543

            
544
936
	let transaction_pool = sc_transaction_pool::Builder::new(
545
936
		task_manager.spawn_essential_handle(),
546
936
		client.clone(),
547
936
		config.role.is_authority().into(),
548
936
	)
549
936
	.with_options(config.transaction_pool.clone())
550
936
	.with_prometheus(config.prometheus_registry())
551
936
	.build();
552
936

            
553
936
	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
554
936
	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
555

            
556
936
	let frontier_backend = Arc::new(open_frontier_backend(client.clone(), config, rpc_config)?);
557
936
	let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
558
936

            
559
936
	let create_inherent_data_providers = move |_, _| async move {
560
		let time = sp_timestamp::InherentDataProvider::from_system_time();
561
		Ok((time,))
562
	};
563

            
564
936
	let (import_queue, block_import) = if dev_service {
565
		(
566
934
			nimbus_consensus::import_queue(
567
934
				client.clone(),
568
934
				frontier_block_import.clone(),
569
934
				create_inherent_data_providers,
570
934
				&task_manager.spawn_essential_handle(),
571
934
				config.prometheus_registry(),
572
934
				legacy_block_import_strategy,
573
934
			)?,
574
934
			BlockImportPipeline::Dev(frontier_block_import),
575
		)
576
	} else {
577
2
		let parachain_block_import = if legacy_block_import_strategy {
578
			ParachainBlockImport::new_with_delayed_best_block(
579
				frontier_block_import,
580
				backend.clone(),
581
			)
582
		} else {
583
2
			ParachainBlockImport::new(frontier_block_import, backend.clone())
584
		};
585
		(
586
2
			nimbus_consensus::import_queue(
587
2
				client.clone(),
588
2
				parachain_block_import.clone(),
589
2
				create_inherent_data_providers,
590
2
				&task_manager.spawn_essential_handle(),
591
2
				config.prometheus_registry(),
592
2
				legacy_block_import_strategy,
593
2
			)?,
594
2
			BlockImportPipeline::Parachain(parachain_block_import),
595
		)
596
	};
597

            
598
936
	Ok(PartialComponents {
599
936
		backend,
600
936
		client,
601
936
		import_queue,
602
936
		keystore_container,
603
936
		task_manager,
604
936
		transaction_pool: transaction_pool.into(),
605
936
		select_chain: maybe_select_chain,
606
936
		other: (
607
936
			block_import,
608
936
			filter_pool,
609
936
			telemetry,
610
936
			telemetry_worker_handle,
611
936
			frontier_backend,
612
936
			fee_history_cache,
613
936
		),
614
936
	})
615
936
}
616

            
617
async fn build_relay_chain_interface(
618
	polkadot_config: Configuration,
619
	parachain_config: &Configuration,
620
	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
621
	task_manager: &mut TaskManager,
622
	collator_options: CollatorOptions,
623
	hwbench: Option<sc_sysinfo::HwBench>,
624
) -> RelayChainResult<(
625
	Arc<(dyn RelayChainInterface + 'static)>,
626
	Option<CollatorPair>,
627
)> {
628
	if let cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) =
629
		collator_options.relay_chain_mode
630
	{
631
		build_minimal_relay_chain_node_with_rpc(
632
			polkadot_config,
633
			parachain_config.prometheus_registry(),
634
			task_manager,
635
			rpc_target_urls,
636
		)
637
		.await
638
	} else {
639
		build_inprocess_relay_chain(
640
			polkadot_config,
641
			parachain_config,
642
			telemetry_worker_handle,
643
			task_manager,
644
			hwbench,
645
		)
646
	}
647
}
648

            
649
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
650
///
651
/// This is the actual implementation that is abstract over the executor and the runtime api.
652
#[sc_tracing::logging::prefix_logs_with("🌗")]
653
async fn start_node_impl<RuntimeApi, Customizations, Net>(
654
	parachain_config: Configuration,
655
	polkadot_config: Configuration,
656
	collator_options: CollatorOptions,
657
	para_id: ParaId,
658
	rpc_config: RpcConfig,
659
	async_backing: bool,
660
	block_authoring_duration: Duration,
661
	hwbench: Option<sc_sysinfo::HwBench>,
662
	legacy_block_import_strategy: bool,
663
	nimbus_full_pov: bool,
664
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi>>)>
665
where
666
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
667
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
668
	Customizations: ClientCustomizations + 'static,
669
	Net: NetworkBackend<Block, Hash>,
670
{
671
	let mut parachain_config = prepare_node_config(parachain_config);
672

            
673
	let params = new_partial::<RuntimeApi, Customizations>(
674
		&mut parachain_config,
675
		&rpc_config,
676
		false,
677
		legacy_block_import_strategy,
678
	)?;
679
	let (
680
		block_import,
681
		filter_pool,
682
		mut telemetry,
683
		telemetry_worker_handle,
684
		frontier_backend,
685
		fee_history_cache,
686
	) = params.other;
687

            
688
	let client = params.client.clone();
689
	let backend = params.backend.clone();
690
	let mut task_manager = params.task_manager;
691

            
692
	let (relay_chain_interface, collator_key) = build_relay_chain_interface(
693
		polkadot_config,
694
		&parachain_config,
695
		telemetry_worker_handle,
696
		&mut task_manager,
697
		collator_options.clone(),
698
		hwbench.clone(),
699
	)
700
	.await
701
	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
702

            
703
	let force_authoring = parachain_config.force_authoring;
704
	let collator = parachain_config.role.is_authority();
705
	let prometheus_registry = parachain_config.prometheus_registry().cloned();
706
	let transaction_pool = params.transaction_pool.clone();
707
	let import_queue_service = params.import_queue.service();
708
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(
709
		&parachain_config.network,
710
		prometheus_registry.clone(),
711
	);
712

            
713
	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
714
		cumulus_client_service::build_network(cumulus_client_service::BuildNetworkParams {
715
			parachain_config: &parachain_config,
716
			client: client.clone(),
717
			transaction_pool: transaction_pool.clone(),
718
			spawn_handle: task_manager.spawn_handle(),
719
			import_queue: params.import_queue,
720
			para_id,
721
			relay_chain_interface: relay_chain_interface.clone(),
722
			net_config,
723
			sybil_resistance_level: CollatorSybilResistance::Resistant,
724
		})
725
		.await?;
726

            
727
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
728
	let fee_history_limit = rpc_config.fee_history_limit;
729

            
730
	// Sinks for pubsub notifications.
731
	// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
732
	// The MappingSyncWorker sends through the channel on block import and the subscription emits a
733
	// notification to the subscriber on receiving a message through this channel.
734
	// This way we avoid race conditions when using native substrate block import notification
735
	// stream.
736
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
737
		fc_mapping_sync::EthereumBlockNotification<Block>,
738
	> = Default::default();
739
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
740

            
741
	rpc::spawn_essential_tasks(
742
		rpc::SpawnTasksParams {
743
			task_manager: &task_manager,
744
			client: client.clone(),
745
			substrate_backend: backend.clone(),
746
			frontier_backend: frontier_backend.clone(),
747
			filter_pool: filter_pool.clone(),
748
			overrides: overrides.clone(),
749
			fee_history_limit,
750
			fee_history_cache: fee_history_cache.clone(),
751
		},
752
		sync_service.clone(),
753
		pubsub_notification_sinks.clone(),
754
	);
755

            
756
	let ethapi_cmd = rpc_config.ethapi.clone();
757
	let tracing_requesters =
758
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
759
			rpc::tracing::spawn_tracing_tasks(
760
				&rpc_config,
761
				prometheus_registry.clone(),
762
				rpc::SpawnTasksParams {
763
					task_manager: &task_manager,
764
					client: client.clone(),
765
					substrate_backend: backend.clone(),
766
					frontier_backend: frontier_backend.clone(),
767
					filter_pool: filter_pool.clone(),
768
					overrides: overrides.clone(),
769
					fee_history_limit,
770
					fee_history_cache: fee_history_cache.clone(),
771
				},
772
			)
773
		} else {
774
			rpc::tracing::RpcRequesters {
775
				debug: None,
776
				trace: None,
777
			}
778
		};
779

            
780
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
781
		task_manager.spawn_handle(),
782
		overrides.clone(),
783
		rpc_config.eth_log_block_cache,
784
		rpc_config.eth_statuses_cache,
785
		prometheus_registry.clone(),
786
	));
787

            
788
	let rpc_builder = {
789
		let client = client.clone();
790
		let pool = transaction_pool.clone();
791
		let network = network.clone();
792
		let sync = sync_service.clone();
793
		let filter_pool = filter_pool.clone();
794
		let frontier_backend = frontier_backend.clone();
795
		let backend = backend.clone();
796
		let ethapi_cmd = ethapi_cmd.clone();
797
		let max_past_logs = rpc_config.max_past_logs;
798
		let max_block_range = rpc_config.max_block_range;
799
		let overrides = overrides.clone();
800
		let fee_history_cache = fee_history_cache.clone();
801
		let block_data_cache = block_data_cache.clone();
802
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
803

            
804
		let keystore = params.keystore_container.keystore();
805
		move |subscription_task_executor| {
806
			#[cfg(feature = "moonbase-native")]
807
			let forced_parent_hashes = {
808
				let mut forced_parent_hashes = BTreeMap::new();
809
				// Fixes for https://github.com/paritytech/frontier/pull/570
810
				// #1648995
811
				forced_parent_hashes.insert(
812
					H256::from_str(
813
						"0xa352fee3eef9c554a31ec0612af887796a920613358abf3353727760ea14207b",
814
					)
815
					.expect("must be valid hash"),
816
					H256::from_str(
817
						"0x0d0fd88778aec08b3a83ce36387dbf130f6f304fc91e9a44c9605eaf8a80ce5d",
818
					)
819
					.expect("must be valid hash"),
820
				);
821
				Some(forced_parent_hashes)
822
			};
823
			#[cfg(not(feature = "moonbase-native"))]
824
			let forced_parent_hashes = None;
825

            
826
			let deps = rpc::FullDeps {
827
				backend: backend.clone(),
828
				client: client.clone(),
829
				command_sink: None,
830
				ethapi_cmd: ethapi_cmd.clone(),
831
				filter_pool: filter_pool.clone(),
832
				frontier_backend: match &*frontier_backend {
833
					fc_db::Backend::KeyValue(b) => b.clone(),
834
					fc_db::Backend::Sql(b) => b.clone(),
835
				},
836
				graph: pool.clone(),
837
				pool: pool.clone(),
838
				is_authority: collator,
839
				max_past_logs,
840
				max_block_range,
841
				fee_history_limit,
842
				fee_history_cache: fee_history_cache.clone(),
843
				network: network.clone(),
844
				sync: sync.clone(),
845
				dev_rpc_data: None,
846
				block_data_cache: block_data_cache.clone(),
847
				overrides: overrides.clone(),
848
				forced_parent_hashes,
849
			};
850
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
851
				client.clone(),
852
				keystore.clone(),
853
			));
854
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
855
				rpc::create_full(
856
					deps,
857
					subscription_task_executor,
858
					Some(crate::rpc::TracingConfig {
859
						tracing_requesters: tracing_requesters.clone(),
860
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
861
					}),
862
					pubsub_notification_sinks.clone(),
863
					pending_consensus_data_provider,
864
				)
865
				.map_err(Into::into)
866
			} else {
867
				rpc::create_full(
868
					deps,
869
					subscription_task_executor,
870
					None,
871
					pubsub_notification_sinks.clone(),
872
					pending_consensus_data_provider,
873
				)
874
				.map_err(Into::into)
875
			}
876
		}
877
	};
878

            
879
	sc_service::spawn_tasks(sc_service::SpawnTasksParams {
880
		rpc_builder: Box::new(rpc_builder),
881
		client: client.clone(),
882
		transaction_pool: transaction_pool.clone(),
883
		task_manager: &mut task_manager,
884
		config: parachain_config,
885
		keystore: params.keystore_container.keystore(),
886
		backend: backend.clone(),
887
		network: network.clone(),
888
		sync_service: sync_service.clone(),
889
		system_rpc_tx,
890
		tx_handler_controller,
891
		telemetry: telemetry.as_mut(),
892
	})?;
893

            
894
	if let Some(hwbench) = hwbench {
895
		sc_sysinfo::print_hwbench(&hwbench);
896

            
897
		if let Some(ref mut telemetry) = telemetry {
898
			let telemetry_handle = telemetry.handle();
899
			task_manager.spawn_handle().spawn(
900
				"telemetry_hwbench",
901
				None,
902
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
903
			);
904
		}
905
	}
906

            
907
	let announce_block = {
908
		let sync_service = sync_service.clone();
909
		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
910
	};
911

            
912
	let relay_chain_slot_duration = Duration::from_secs(6);
913
	let overseer_handle = relay_chain_interface
914
		.overseer_handle()
915
		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
916

            
917
	start_relay_chain_tasks(StartRelayChainTasksParams {
918
		client: client.clone(),
919
		announce_block: announce_block.clone(),
920
		para_id,
921
		relay_chain_interface: relay_chain_interface.clone(),
922
		task_manager: &mut task_manager,
923
		da_recovery_profile: if collator {
924
			DARecoveryProfile::Collator
925
		} else {
926
			DARecoveryProfile::FullNode
927
		},
928
		import_queue: import_queue_service,
929
		relay_chain_slot_duration,
930
		recovery_handle: Box::new(overseer_handle.clone()),
931
		sync_service: sync_service.clone(),
932
	})?;
933

            
934
	let BlockImportPipeline::Parachain(block_import) = block_import else {
935
		return Err(sc_service::Error::Other(
936
			"Block import pipeline is not for parachain".into(),
937
		));
938
	};
939

            
940
	if collator {
941
		start_consensus::<RuntimeApi, _>(
942
			async_backing,
943
			backend.clone(),
944
			client.clone(),
945
			block_import,
946
			prometheus_registry.as_ref(),
947
			telemetry.as_ref().map(|t| t.handle()),
948
			&task_manager,
949
			relay_chain_interface.clone(),
950
			transaction_pool,
951
			params.keystore_container.keystore(),
952
			para_id,
953
			collator_key.expect("Command line arguments do not allow this. qed"),
954
			overseer_handle,
955
			announce_block,
956
			force_authoring,
957
			relay_chain_slot_duration,
958
			block_authoring_duration,
959
			sync_service.clone(),
960
			nimbus_full_pov,
961
		)?;
962
		/*let parachain_consensus = build_consensus(
963
			client.clone(),
964
			backend,
965
			block_import,
966
			prometheus_registry.as_ref(),
967
			telemetry.as_ref().map(|t| t.handle()),
968
			&task_manager,
969
			relay_chain_interface.clone(),
970
			transaction_pool,
971
			sync_service.clone(),
972
			params.keystore_container.keystore(),
973
			force_authoring,
974
		)?;
975

            
976
		let spawner = task_manager.spawn_handle();
977

            
978
		let params = StartCollatorParams {
979
			para_id,
980
			block_status: client.clone(),
981
			announce_block,
982
			client: client.clone(),
983
			task_manager: &mut task_manager,
984
			relay_chain_interface,
985
			spawner,
986
			parachain_consensus,
987
			import_queue: import_queue_service,
988
			recovery_handle: Box::new(overseer_handle),
989
			collator_key: collator_key.ok_or(sc_service::error::Error::Other(
990
				"Collator Key is None".to_string(),
991
			))?,
992
			relay_chain_slot_duration,
993
			sync_service,
994
		};
995

            
996
		#[allow(deprecated)]
997
		start_collator(params).await?;*/
998
	}
999

            
	start_network.start_network();
	Ok((task_manager, client))
}
fn start_consensus<RuntimeApi, SO>(
	async_backing: bool,
	backend: Arc<FullBackend>,
	client: Arc<FullClient<RuntimeApi>>,
	block_import: ParachainBlockImport<FullClient<RuntimeApi>, FullBackend>,
	prometheus_registry: Option<&Registry>,
	telemetry: Option<TelemetryHandle>,
	task_manager: &TaskManager,
	relay_chain_interface: Arc<dyn RelayChainInterface>,
	transaction_pool: Arc<
		sc_transaction_pool::TransactionPoolHandle<Block, FullClient<RuntimeApi>>,
	>,
	keystore: KeystorePtr,
	para_id: ParaId,
	collator_key: CollatorPair,
	overseer_handle: OverseerHandle,
	announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
	force_authoring: bool,
	relay_chain_slot_duration: Duration,
	block_authoring_duration: Duration,
	sync_oracle: SO,
	nimbus_full_pov: bool,
) -> Result<(), sc_service::Error>
where
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
	sc_client_api::StateBackendFor<FullBackend, Block>: sc_client_api::StateBackend<BlakeTwo256>,
	SO: SyncOracle + Send + Sync + Clone + 'static,
{
	let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording(
		task_manager.spawn_handle(),
		client.clone(),
		transaction_pool,
		prometheus_registry,
		telemetry.clone(),
	);
	let proposer = Proposer::new(proposer_factory);
	let collator_service = CollatorService::new(
		client.clone(),
		Arc::new(task_manager.spawn_handle()),
		announce_block,
		client.clone(),
	);
	let create_inherent_data_providers = |_, _| async move {
		let time = sp_timestamp::InherentDataProvider::from_system_time();
		let author = nimbus_primitives::InherentDataProvider;
		let randomness = session_keys_primitives::InherentDataProvider;
		Ok((time, author, randomness))
	};
	let client_clone = client.clone();
	let keystore_clone = keystore.clone();
	let maybe_provide_vrf_digest =
		move |nimbus_id: NimbusId, parent: Hash| -> Option<sp_runtime::generic::DigestItem> {
			moonbeam_vrf::vrf_pre_digest::<Block, FullClient<RuntimeApi>>(
				&client_clone,
				&keystore_clone,
				nimbus_id,
				parent,
			)
		};
	if async_backing {
		log::info!("Collator started with asynchronous backing.");
		let client_clone = client.clone();
		let code_hash_provider = move |block_hash| {
			client_clone
				.code_at(block_hash)
				.ok()
				.map(polkadot_primitives::ValidationCode)
				.map(|c| c.hash())
		};
		task_manager.spawn_essential_handle().spawn(
			"nimbus",
			None,
			nimbus_consensus::collators::lookahead::run::<
				Block,
				_,
				_,
				_,
				FullBackend,
				_,
				_,
				_,
				_,
				_,
				_,
			>(nimbus_consensus::collators::lookahead::Params {
				additional_digests_provider: maybe_provide_vrf_digest,
				additional_relay_keys: vec![
					moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
				],
				authoring_duration: block_authoring_duration,
				block_import,
				code_hash_provider,
				collator_key,
				collator_service,
				create_inherent_data_providers,
				force_authoring,
				keystore,
				overseer_handle,
				para_backend: backend,
				para_client: client,
				para_id,
				proposer,
				relay_chain_slot_duration,
				relay_client: relay_chain_interface,
				slot_duration: None,
				sync_oracle,
				reinitialize: false,
				full_pov_size: nimbus_full_pov,
			}),
		);
	} else {
		log::info!("Collator started without asynchronous backing.");
		task_manager.spawn_essential_handle().spawn(
			"nimbus",
			None,
			nimbus_consensus::collators::basic::run::<Block, _, _, FullBackend, _, _, _, _, _>(
				nimbus_consensus::collators::basic::Params {
					additional_digests_provider: maybe_provide_vrf_digest,
					additional_relay_keys: vec![
						moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
					],
					//authoring_duration: Duration::from_millis(500),
					block_import,
					collator_key,
					collator_service,
					create_inherent_data_providers,
					force_authoring,
					keystore,
					overseer_handle,
					para_id,
					para_client: client,
					proposer,
					relay_client: relay_chain_interface,
					full_pov_size: nimbus_full_pov,
				},
			),
		);
	};
	Ok(())
}
/// Start a normal parachain node.
// Rustfmt wants to format the closure with space identation.
#[rustfmt::skip]
pub async fn start_node<RuntimeApi, Customizations>(
	parachain_config: Configuration,
	polkadot_config: Configuration,
	collator_options: CollatorOptions,
	para_id: ParaId,
	rpc_config: RpcConfig,
	async_backing: bool,
	block_authoring_duration: Duration,
	hwbench: Option<sc_sysinfo::HwBench>,
	legacy_block_import_strategy: bool,
	nimbus_full_pov: bool,
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi>>)>
where
	RuntimeApi:
		ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
	RuntimeApi::RuntimeApi:
		RuntimeApiCollection,
	Customizations: ClientCustomizations + 'static,
{
	start_node_impl::<RuntimeApi, Customizations, sc_network::NetworkWorker<_, _>>(
		parachain_config,
		polkadot_config,
		collator_options,
		para_id,
		rpc_config,
		async_backing,
		block_authoring_duration,
		hwbench,
		legacy_block_import_strategy,
		nimbus_full_pov,
	)
	.await
}
/// Builds a new development service. This service uses manual seal, and mocks
/// the parachain inherent.
934
pub async fn new_dev<RuntimeApi, Customizations, Net>(
934
	mut config: Configuration,
934
	para_id: Option<u32>,
934
	_author_id: Option<NimbusId>,
934
	sealing: moonbeam_cli_opt::Sealing,
934
	rpc_config: RpcConfig,
934
	hwbench: Option<sc_sysinfo::HwBench>,
934
) -> Result<TaskManager, ServiceError>
934
where
934
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
934
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
934
	Customizations: ClientCustomizations + 'static,
934
	Net: NetworkBackend<Block, Hash>,
934
{
	use async_io::Timer;
	use futures::Stream;
	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};
	let sc_service::PartialComponents {
934
		client,
934
		backend,
934
		mut task_manager,
934
		import_queue,
934
		keystore_container,
934
		select_chain: maybe_select_chain,
934
		transaction_pool,
934
		other:
934
			(
934
				block_import_pipeline,
934
				filter_pool,
934
				mut telemetry,
934
				_telemetry_worker_handle,
934
				frontier_backend,
934
				fee_history_cache,
			),
934
	} = new_partial::<RuntimeApi, Customizations>(&mut config, &rpc_config, true, true)?;
934
	let block_import = if let BlockImportPipeline::Dev(block_import) = block_import_pipeline {
934
		block_import
	} else {
		return Err(ServiceError::Other(
			"Block import pipeline is not dev".to_string(),
		));
	};
934
	let prometheus_registry = config.prometheus_registry().cloned();
934
	let net_config =
934
		FullNetworkConfiguration::<_, _, Net>::new(&config.network, prometheus_registry.clone());
934

            
934
	let metrics = Net::register_notification_metrics(
934
		config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
934
	);
934
	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
934
		sc_service::build_network(sc_service::BuildNetworkParams {
934
			config: &config,
934
			client: client.clone(),
934
			transaction_pool: transaction_pool.clone(),
934
			spawn_handle: task_manager.spawn_handle(),
934
			import_queue,
934
			block_announce_validator_builder: None,
934
			warp_sync_config: None,
934
			net_config,
934
			block_relay: None,
934
			metrics,
934
		})?;
934
	if config.offchain_worker.enabled {
934
		task_manager.spawn_handle().spawn(
934
			"offchain-workers-runner",
934
			"offchain-work",
934
			sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
934
				runtime_api_provider: client.clone(),
934
				keystore: Some(keystore_container.keystore()),
934
				offchain_db: backend.offchain_storage(),
934
				transaction_pool: Some(OffchainTransactionPoolFactory::new(
934
					transaction_pool.clone(),
934
				)),
934
				network_provider: Arc::new(network.clone()),
934
				is_validator: config.role.is_authority(),
934
				enable_http_requests: true,
26882
				custom_extensions: move |_| vec![],
934
			})?
934
			.run(client.clone(), task_manager.spawn_handle())
934
			.boxed(),
		);
	}
934
	let prometheus_registry = config.prometheus_registry().cloned();
934
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
934
	let fee_history_limit = rpc_config.fee_history_limit;
934
	let mut command_sink = None;
934
	let mut dev_rpc_data = None;
934
	let collator = config.role.is_authority();
934

            
934
	if collator {
934
		let mut env = sc_basic_authorship::ProposerFactory::with_proof_recording(
934
			task_manager.spawn_handle(),
934
			client.clone(),
934
			transaction_pool.clone(),
934
			prometheus_registry.as_ref(),
934
			telemetry.as_ref().map(|x| x.handle()),
934
		);
934
		env.set_soft_deadline(SOFT_DEADLINE_PERCENT);
		// TODO: Need to cherry-pick
		//
		// https://github.com/moonbeam-foundation/substrate/commit/
		// d59476b362e38071d44d32c98c32fb35fd280930#diff-a1c022c97c7f9200cab161864c
		// 06d204f0c8b689955e42177731e232115e9a6f
		//
		// env.enable_ensure_proof_size_limit_after_each_extrinsic();
934
		let commands_stream: Box<dyn Stream<Item = EngineCommand<H256>> + Send + Sync + Unpin> =
934
			match sealing {
				moonbeam_cli_opt::Sealing::Instant => {
					Box::new(
						// This bit cribbed from the implementation of instant seal.
						transaction_pool.import_notification_stream().map(|_| {
							EngineCommand::SealNewBlock {
								create_empty: false,
								finalize: false,
								parent_hash: None,
								sender: None,
							}
						}),
					)
				}
				moonbeam_cli_opt::Sealing::Manual => {
934
					let (sink, stream) = futures::channel::mpsc::channel(1000);
934
					// Keep a reference to the other end of the channel. It goes to the RPC.
934
					command_sink = Some(sink);
934
					Box::new(stream)
				}
				moonbeam_cli_opt::Sealing::Interval(millis) => Box::new(StreamExt::map(
					Timer::interval(Duration::from_millis(millis)),
					|_| EngineCommand::SealNewBlock {
						create_empty: true,
						finalize: false,
						parent_hash: None,
						sender: None,
					},
				)),
			};
934
		let select_chain = maybe_select_chain.expect(
934
			"`new_partial` builds a `LongestChainRule` when building dev service.\
934
				We specified the dev service when calling `new_partial`.\
934
				Therefore, a `LongestChainRule` is present. qed.",
934
		);
934

            
934
		// Create channels for mocked XCM messages.
934
		let (downward_xcm_sender, downward_xcm_receiver) = flume::bounded::<Vec<u8>>(100);
934
		let (hrmp_xcm_sender, hrmp_xcm_receiver) = flume::bounded::<(ParaId, Vec<u8>)>(100);
934
		let additional_relay_offset = Arc::new(std::sync::atomic::AtomicU32::new(0));
934
		dev_rpc_data = Some((
934
			downward_xcm_sender,
934
			hrmp_xcm_sender,
934
			additional_relay_offset.clone(),
934
		));
934

            
934
		// Need to clone it and store here to avoid moving of `client`
934
		// variable in closure below.
934
		let client_vrf = client.clone();
934

            
934
		let keystore_clone = keystore_container.keystore().clone();
934
		let maybe_provide_vrf_digest =
26898
			move |nimbus_id: NimbusId, parent: Hash| -> Option<sp_runtime::generic::DigestItem> {
26898
				moonbeam_vrf::vrf_pre_digest::<Block, FullClient<RuntimeApi>>(
26898
					&client_vrf,
26898
					&keystore_clone,
26898
					nimbus_id,
26898
					parent,
26898
				)
26898
			};
934

            
934
		// Need to clone it and store here to avoid moving of `client`
934
		// variable in closure below.
934
		let client_for_cidp = client.clone();
934

            
934
		task_manager.spawn_essential_handle().spawn_blocking(
934
			"authorship_task",
934
			Some("block-authoring"),
934
			run_manual_seal(ManualSealParams {
934
				block_import,
934
				env,
934
				client: client.clone(),
934
				pool: transaction_pool.clone(),
934
				commands_stream,
934
				select_chain,
934
				consensus_data_provider: Some(Box::new(NimbusManualSealConsensusDataProvider {
934
					keystore: keystore_container.keystore(),
934
					client: client.clone(),
934
					additional_digests_provider: maybe_provide_vrf_digest,
934
					_phantom: Default::default(),
934
				})),
26898
				create_inherent_data_providers: move |block: H256, ()| {
26898
					let maybe_current_para_block = client_for_cidp.number(block);
26898
					let maybe_current_para_head = client_for_cidp.expect_header(block);
26898
					let downward_xcm_receiver = downward_xcm_receiver.clone();
26898
					let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
26898
					let additional_relay_offset = additional_relay_offset.clone();
26898
					let relay_slot_key = well_known_keys::CURRENT_SLOT.to_vec();
26898

            
26898
					// Need to clone it and store here to avoid moving of `client`
26898
					// variable in closure below.
26898
					let client_for_xcm = client_for_cidp.clone();
26898
					async move {
26898
						let time = MockTimestampInherentDataProvider;
26898
						let current_para_block = maybe_current_para_block?
26898
							.ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?;
26898
						let current_para_block_head = Some(polkadot_primitives::HeadData(
26898
							maybe_current_para_head?.encode(),
26898
						));
26898

            
26898
						// Get the mocked timestamp
26898
						let timestamp = TIMESTAMP.load(Ordering::SeqCst);
26898
						// Calculate mocked slot number (should be consecutively 1, 2, ...)
26898
						let slot = timestamp.saturating_div(RELAY_CHAIN_SLOT_DURATION_MILLIS);
26898

            
26898
						let additional_key_values = vec![
26898
							(
26898
								moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW
26898
									.to_vec(),
26898
								sp_timestamp::Timestamp::current().encode(),
26898
							),
26898
							(relay_slot_key, Slot::from(slot).encode()),
26898
							(
26898
								relay_chain::well_known_keys::ACTIVE_CONFIG.to_vec(),
26898
								AbridgedHostConfiguration {
26898
									max_code_size: 3_145_728,
26898
									max_head_data_size: 20_480,
26898
									max_upward_queue_count: 174_762,
26898
									max_upward_queue_size: 1_048_576,
26898
									max_upward_message_size: 65_531,
26898
									max_upward_message_num_per_candidate: 16,
26898
									hrmp_max_message_num_per_candidate: 10,
26898
									validation_upgrade_cooldown: 6,
26898
									validation_upgrade_delay: 6,
26898
									async_backing_params: AsyncBackingParams {
26898
										max_candidate_depth: 3,
26898
										allowed_ancestry_len: 2,
26898
									},
26898
								}
26898
								.encode(),
26898
							),
26898
						];
26898

            
26898
						let current_para_head = client_for_xcm
26898
							.header(block)
26898
							.expect("Header lookup should succeed")
26898
							.expect("Header passed in as parent should be present in backend.");
26898
						let should_send_go_ahead = match client_for_xcm
26898
							.runtime_api()
26898
							.collect_collation_info(block, &current_para_head)
						{
26898
							Ok(info) => info.new_validation_code.is_some(),
							Err(e) => {
								log::error!("Failed to collect collation info: {:?}", e);
								false
							}
						};
26898
						let mocked_parachain = MockValidationDataInherentDataProvider {
26898
							current_para_block,
26898
							para_id: para_id
26898
								.expect("para ID should be specified for dev service")
26898
								.into(),
26898
							upgrade_go_ahead: should_send_go_ahead.then(|| {
								log::info!(
									"Detected pending validation code, sending go-ahead signal."
								);
								UpgradeGoAhead::GoAhead
26898
							}),
26898
							current_para_block_head,
26898
							relay_offset: 1000
26898
								+ additional_relay_offset.load(std::sync::atomic::Ordering::SeqCst),
26898
							relay_blocks_per_para_block: 2,
26898
							// TODO: Recheck
26898
							para_blocks_per_relay_epoch: 10,
26898
							relay_randomness_config: (),
26898
							xcm_config: MockXcmConfig::new(
26898
								&*client_for_xcm,
26898
								block,
26898
								Default::default(),
26898
							),
26898
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
26898
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
26898
							additional_key_values: Some(additional_key_values),
26898
						};
26898

            
26898
						let randomness = session_keys_primitives::InherentDataProvider;
26898

            
26898
						Ok((time, mocked_parachain, randomness))
26898
					}
26898
				},
934
			}),
934
		);
934
	}
	// Sinks for pubsub notifications.
	// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
	// The MappingSyncWorker sends through the channel on block import and the subscription emits a
	// notification to the subscriber on receiving a message through this channel.
	// This way we avoid race conditions when using native substrate block import notification
	// stream.
934
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
934
		fc_mapping_sync::EthereumBlockNotification<Block>,
934
	> = Default::default();
934
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
934

            
934
	rpc::spawn_essential_tasks(
934
		rpc::SpawnTasksParams {
934
			task_manager: &task_manager,
934
			client: client.clone(),
934
			substrate_backend: backend.clone(),
934
			frontier_backend: frontier_backend.clone(),
934
			filter_pool: filter_pool.clone(),
934
			overrides: overrides.clone(),
934
			fee_history_limit,
934
			fee_history_cache: fee_history_cache.clone(),
934
		},
934
		sync_service.clone(),
934
		pubsub_notification_sinks.clone(),
934
	);
934
	let ethapi_cmd = rpc_config.ethapi.clone();
934
	let tracing_requesters =
934
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
			rpc::tracing::spawn_tracing_tasks(
				&rpc_config,
				prometheus_registry.clone(),
				rpc::SpawnTasksParams {
					task_manager: &task_manager,
					client: client.clone(),
					substrate_backend: backend.clone(),
					frontier_backend: frontier_backend.clone(),
					filter_pool: filter_pool.clone(),
					overrides: overrides.clone(),
					fee_history_limit,
					fee_history_cache: fee_history_cache.clone(),
				},
			)
		} else {
934
			rpc::tracing::RpcRequesters {
934
				debug: None,
934
				trace: None,
934
			}
		};
934
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
934
		task_manager.spawn_handle(),
934
		overrides.clone(),
934
		rpc_config.eth_log_block_cache,
934
		rpc_config.eth_statuses_cache,
934
		prometheus_registry,
934
	));
934

            
934
	let rpc_builder = {
934
		let client = client.clone();
934
		let pool = transaction_pool.clone();
934
		let backend = backend.clone();
934
		let network = network.clone();
934
		let sync = sync_service.clone();
934
		let ethapi_cmd = ethapi_cmd.clone();
934
		let max_past_logs = rpc_config.max_past_logs;
934
		let max_block_range = rpc_config.max_block_range;
934
		let overrides = overrides.clone();
934
		let fee_history_cache = fee_history_cache.clone();
934
		let block_data_cache = block_data_cache.clone();
934
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
934

            
934
		let keystore = keystore_container.keystore();
1868
		move |subscription_task_executor| {
1868
			let deps = rpc::FullDeps {
1868
				backend: backend.clone(),
1868
				client: client.clone(),
1868
				command_sink: command_sink.clone(),
1868
				ethapi_cmd: ethapi_cmd.clone(),
1868
				filter_pool: filter_pool.clone(),
1868
				frontier_backend: match &*frontier_backend {
1868
					fc_db::Backend::KeyValue(b) => b.clone(),
					fc_db::Backend::Sql(b) => b.clone(),
				},
1868
				graph: pool.clone(),
1868
				pool: pool.clone(),
1868
				is_authority: collator,
1868
				max_past_logs,
1868
				max_block_range,
1868
				fee_history_limit,
1868
				fee_history_cache: fee_history_cache.clone(),
1868
				network: network.clone(),
1868
				sync: sync.clone(),
1868
				dev_rpc_data: dev_rpc_data.clone(),
1868
				overrides: overrides.clone(),
1868
				block_data_cache: block_data_cache.clone(),
1868
				forced_parent_hashes: None,
1868
			};
1868

            
1868
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
1868
				client.clone(),
1868
				keystore.clone(),
1868
			));
1868
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
				rpc::create_full(
					deps,
					subscription_task_executor,
					Some(crate::rpc::TracingConfig {
						tracing_requesters: tracing_requesters.clone(),
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
					}),
					pubsub_notification_sinks.clone(),
					pending_consensus_data_provider,
				)
				.map_err(Into::into)
			} else {
1868
				rpc::create_full(
1868
					deps,
1868
					subscription_task_executor,
1868
					None,
1868
					pubsub_notification_sinks.clone(),
1868
					pending_consensus_data_provider,
1868
				)
1868
				.map_err(Into::into)
			}
1868
		}
	};
934
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
934
		network,
934
		client,
934
		keystore: keystore_container.keystore(),
934
		task_manager: &mut task_manager,
934
		transaction_pool,
934
		rpc_builder: Box::new(rpc_builder),
934
		backend,
934
		system_rpc_tx,
934
		sync_service: sync_service.clone(),
934
		config,
934
		tx_handler_controller,
934
		telemetry: None,
934
	})?;
934
	if let Some(hwbench) = hwbench {
		sc_sysinfo::print_hwbench(&hwbench);
		if let Some(ref mut telemetry) = telemetry {
			let telemetry_handle = telemetry.handle();
			task_manager.spawn_handle().spawn(
				"telemetry_hwbench",
				None,
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
			);
		}
934
	}
934
	log::info!("Development Service Ready");
934
	network_starter.start_network();
934
	Ok(task_manager)
934
}
#[cfg(test)]
mod tests {
	use crate::chain_spec::moonbase::ChainSpec;
	use crate::chain_spec::Extensions;
	use jsonrpsee::server::BatchRequestConfig;
	use moonbase_runtime::{currency::UNIT, AccountId};
	use prometheus::{proto::LabelPair, Counter};
	use sc_network::config::NetworkConfiguration;
	use sc_service::config::RpcConfiguration;
	use sc_service::ChainType;
	use sc_service::{
		config::{BasePath, DatabaseSource, KeystoreConfig},
		Configuration, Role,
	};
	use std::path::Path;
	use std::str::FromStr;
	use super::*;
	#[test]
	fn test_set_prometheus_registry_uses_moonbeam_prefix() {
		let counter_name = "my_counter";
		let expected_metric_name = "moonbeam_my_counter";
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config("test")
		};
		set_prometheus_registry(&mut config, false).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
		assert_eq!(actual_metric_name.as_str(), expected_metric_name);
	}
	#[test]
	fn test_set_prometheus_registry_skips_moonbeam_prefix() {
		let counter_name = "my_counter";
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config("test")
		};
		set_prometheus_registry(&mut config, true).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
		assert_eq!(actual_metric_name.as_str(), counter_name);
	}
	#[test]
	fn test_set_prometheus_registry_adds_chain_id_as_label() {
		let input_chain_id = "moonriver";
		let mut expected_label = LabelPair::default();
		expected_label.set_name("chain".to_owned());
		expected_label.set_value("moonriver".to_owned());
		let expected_chain_label = Some(expected_label);
		let counter = Box::new(Counter::new("foo", "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config(input_chain_id)
		};
		set_prometheus_registry(&mut config, false).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_chain_label = reg
			.gather()
			.first()
			.unwrap()
			.get_metric()
			.first()
			.unwrap()
			.get_label()
			.into_iter()
			.find(|x| x.get_name() == "chain")
			.cloned();
		assert_eq!(actual_chain_label, expected_chain_label);
	}
	#[test]
	fn dalek_does_not_panic() {
		use futures::executor::block_on;
		use sc_block_builder::BlockBuilderBuilder;
		use sc_client_db::{Backend, BlocksPruning, DatabaseSettings, DatabaseSource, PruningMode};
		use sp_api::ProvideRuntimeApi;
		use sp_consensus::BlockOrigin;
		use substrate_test_runtime::TestAPI;
		use substrate_test_runtime_client::runtime::Block;
		use substrate_test_runtime_client::{
			ClientBlockImportExt, TestClientBuilder, TestClientBuilderExt,
		};
		fn zero_ed_pub() -> sp_core::ed25519::Public {
			sp_core::ed25519::Public::default()
		}
		// This is an invalid signature
		// this breaks after ed25519 1.3. It makes the signature panic at creation
		// This test ensures we should never panic
		fn invalid_sig() -> sp_core::ed25519::Signature {
			let signature = hex_literal::hex!(
				"a25b94f9c64270fdfffa673f11cfe961633e3e4972e6940a3cf
		7351dd90b71447041a83583a52cee1cf21b36ba7fd1d0211dca58b48d997fc78d9bc82ab7a38e"
			);
			sp_core::ed25519::Signature::from_raw(signature[0..64].try_into().unwrap())
		}
		let tmp = tempfile::tempdir().unwrap();
		let backend = Arc::new(
			Backend::new(
				DatabaseSettings {
					trie_cache_maximum_size: Some(1 << 20),
					state_pruning: Some(PruningMode::ArchiveAll),
					blocks_pruning: BlocksPruning::KeepAll,
					source: DatabaseSource::RocksDb {
						path: tmp.path().into(),
						cache_size: 1024,
					},
				},
				u64::MAX,
			)
			.unwrap(),
		);
		let client = TestClientBuilder::with_backend(backend).build();
		client
			.execution_extensions()
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
			Block,
			sp_io::UseDalekExt,
		>::new(1));
		let a1 = BlockBuilderBuilder::new(&client)
			.on_parent_block(client.chain_info().genesis_hash)
			.with_parent_block_number(0)
			// Enable proof recording if required. This call is optional.
			.enable_proof_recording()
			.build()
			.unwrap()
			.build()
			.unwrap()
			.block;
		block_on(client.import(BlockOrigin::NetworkInitialSync, a1.clone())).unwrap();
		// On block zero it will use dalek
		// shouldnt panic on importing invalid sig
		assert!(!client
			.runtime_api()
			.verify_ed25519(
				client.chain_info().genesis_hash,
				invalid_sig(),
				zero_ed_pub(),
				vec![]
			)
			.unwrap());
	}
	fn test_config(chain_id: &str) -> Configuration {
		let network_config = NetworkConfiguration::new("", "", Default::default(), None);
		let runtime = tokio::runtime::Runtime::new().expect("failed creating tokio runtime");
		let spec = ChainSpec::builder(&[0u8], Extensions::default())
			.with_name("test")
			.with_id(chain_id)
			.with_chain_type(ChainType::Local)
			.with_genesis_config(moonbase_runtime::genesis_config_preset::testnet_genesis(
				AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(),
				vec![],
				vec![],
				vec![],
				vec![],
				vec![],
				1000 * UNIT,
				ParaId::new(0),
				0,
			))
			.build();
		Configuration {
			impl_name: String::from("test-impl"),
			impl_version: String::from("0.1"),
			role: Role::Full,
			tokio_handle: runtime.handle().clone(),
			transaction_pool: Default::default(),
			network: network_config,
			keystore: KeystoreConfig::Path {
				path: "key".into(),
				password: None,
			},
			database: DatabaseSource::RocksDb {
				path: "db".into(),
				cache_size: 128,
			},
			trie_cache_maximum_size: Some(16777216),
			state_pruning: Default::default(),
			blocks_pruning: sc_service::BlocksPruning::KeepAll,
			chain_spec: Box::new(spec),
			executor: Default::default(),
			wasm_runtime_overrides: Default::default(),
			rpc: RpcConfiguration {
				addr: None,
				max_connections: Default::default(),
				cors: None,
				methods: Default::default(),
				max_request_size: Default::default(),
				max_response_size: Default::default(),
				id_provider: None,
				max_subs_per_conn: Default::default(),
				port: Default::default(),
				message_buffer_capacity: Default::default(),
				batch_config: BatchRequestConfig::Unlimited,
				rate_limit: Default::default(),
				rate_limit_whitelisted_ips: vec![],
				rate_limit_trust_proxy_headers: false,
			},
			data_path: Default::default(),
			prometheus_config: None,
			telemetry_endpoints: None,
			offchain_worker: Default::default(),
			force_authoring: false,
			disable_grandpa: false,
			dev_key_seed: None,
			tracing_targets: None,
			tracing_receiver: Default::default(),
			announce_block: true,
			base_path: BasePath::new(Path::new("")),
		}
	}
}
struct PendingConsensusDataProvider<Client>
where
	Client: HeaderBackend<Block> + sp_api::ProvideRuntimeApi<Block> + Send + Sync,
	Client::Api: VrfApi<Block>,
{
	client: Arc<Client>,
	keystore: Arc<dyn Keystore>,
}
impl<Client> PendingConsensusDataProvider<Client>
where
	Client: HeaderBackend<Block> + sp_api::ProvideRuntimeApi<Block> + Send + Sync,
	Client::Api: VrfApi<Block>,
{
1868
	pub fn new(client: Arc<Client>, keystore: Arc<dyn Keystore>) -> Self {
1868
		Self { client, keystore }
1868
	}
}
impl<Client> fc_rpc::pending::ConsensusDataProvider<Block> for PendingConsensusDataProvider<Client>
where
	Client: HeaderBackend<Block> + sp_api::ProvideRuntimeApi<Block> + Send + Sync,
	Client::Api: VrfApi<Block>,
{
8
	fn create_digest(
8
		&self,
8
		parent: &Header,
8
		_data: &sp_inherents::InherentData,
8
	) -> Result<sp_runtime::Digest, sp_inherents::Error> {
8
		let hash = parent.hash();
		// Get the digest from the best block header.
8
		let mut digest = self
8
			.client
8
			.header(hash)
8
			.map_err(|e| sp_inherents::Error::Application(Box::new(e)))?
8
			.ok_or(sp_inherents::Error::Application(
8
				"Best block header should be present".into(),
8
			))?
			.digest;
		// Get the nimbus id from the digest.
8
		let nimbus_id = digest
8
			.logs
8
			.iter()
8
			.find_map(|x| {
8
				if let DigestItem::PreRuntime(nimbus_primitives::NIMBUS_ENGINE_ID, nimbus_id) = x {
8
					Some(NimbusId::from_slice(nimbus_id.as_slice()).map_err(|_| {
						sp_inherents::Error::Application(
							"Nimbus pre-runtime digest should be valid".into(),
						)
8
					}))
				} else {
					None
				}
8
			})
8
			.ok_or(sp_inherents::Error::Application(
8
				"Nimbus pre-runtime digest should be present".into(),
8
			))??;
		// Remove the old VRF digest.
16
		let pos = digest.logs.iter().position(|x| {
8
			matches!(
16
				x,
				DigestItem::PreRuntime(session_keys_primitives::VRF_ENGINE_ID, _)
			)
16
		});
8
		if let Some(pos) = pos {
8
			digest.logs.remove(pos);
8
		}
		// Create the VRF digest.
8
		let vrf_digest = VrfDigestsProvider::new(self.client.clone(), self.keystore.clone())
8
			.provide_digests(nimbus_id, hash);
8
		// Append the VRF digest to the digest.
8
		digest.logs.extend(vrf_digest);
8
		Ok(digest)
8
	}
}