1
// Copyright 2019-2022 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::{well_known_keys, CollatorPair},
38
	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::Slot;
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;
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::FullPool<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
23398
	) -> Result<(), sp_inherents::Error> {
131
23398
		TIMESTAMP.fetch_add(RELAY_CHAIN_SLOT_DURATION_MILLIS, Ordering::SeqCst);
132
23398
		inherent_data.put_data(
133
23398
			sp_timestamp::INHERENT_IDENTIFIER,
134
23398
			&TIMESTAMP.load(Ordering::SeqCst),
135
23398
		)
136
46796
	}
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
896
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
209
896
		Some(3_000_000)
210
896
	}
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
896
	fn is_moonbeam(&self) -> bool {
261
896
		self.id().starts_with("moonbeam")
262
896
	}
263

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

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

            
273
896
pub fn frontier_database_dir(config: &Configuration, path: &str) -> std::path::PathBuf {
274
896
	config
275
896
		.base_path
276
896
		.config_dir(config.chain_spec.id())
277
896
		.join("frontier")
278
896
		.join(path)
279
896
}
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
896
pub fn open_frontier_backend<C, BE>(
284
896
	client: Arc<C>,
285
896
	config: &Configuration,
286
896
	rpc_config: &RpcConfig,
287
896
) -> Result<fc_db::Backend<Block, C>, String>
288
896
where
289
896
	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
290
896
	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,
291
896
	C: Send + Sync + 'static,
292
896
	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
293
896
	BE: Backend<Block> + 'static,
294
896
	BE::State: StateBackend<BlakeTwo256>,
295
896
{
296
896
	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
896
				client,
300
896
				&fc_db::kv::DatabaseSettings {
301
896
					source: match config.database {
302
896
						DatabaseSource::RocksDb { .. } => DatabaseSource::RocksDb {
303
896
							path: frontier_database_dir(config, "db"),
304
896
							cache_size: 0,
305
896
						},
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
896
	Ok(frontier_backend)
353
896
}
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
) -> Result<
365
	(
366
		Arc<Client>,
367
		Arc<FullBackend>,
368
		sc_consensus::BasicQueue<Block>,
369
		TaskManager,
370
	),
371
	ServiceError,
372
> {
373
	match &config.chain_spec {
374
		#[cfg(feature = "moonriver-native")]
375
		spec if spec.is_moonriver() => new_chain_ops_inner::<
376
			moonriver_runtime::RuntimeApi,
377
			MoonriverCustomizations,
378
		>(config, rpc_config),
379
		#[cfg(feature = "moonbeam-native")]
380
		spec if spec.is_moonbeam() => new_chain_ops_inner::<
381
			moonbeam_runtime::RuntimeApi,
382
			MoonbeamCustomizations,
383
		>(config, rpc_config),
384
		#[cfg(feature = "moonbase-native")]
385
		_ => new_chain_ops_inner::<moonbase_runtime::RuntimeApi, MoonbaseCustomizations>(
386
			config, rpc_config,
387
		),
388
		#[cfg(not(feature = "moonbase-native"))]
389
		_ => panic!("invalid chain spec"),
390
	}
391
}
392

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

            
428
// If we're using prometheus, use a registry with a prefix of `moonbeam`.
429
899
fn set_prometheus_registry(
430
899
	config: &mut Configuration,
431
899
	skip_prefix: bool,
432
899
) -> Result<(), ServiceError> {
433
899
	if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
434
3
		let labels = hashmap! {
435
3
			"chain".into() => config.chain_spec.id().into(),
436
3
		};
437
3
		let prefix = if skip_prefix {
438
1
			None
439
		} else {
440
2
			Some("moonbeam".into())
441
		};
442

            
443
3
		*registry = Registry::new_custom(prefix, Some(labels))?;
444
896
	}
445

            
446
899
	Ok(())
447
899
}
448

            
449
/// Builds the PartialComponents for a parachain or development service
450
///
451
/// Use this function if you don't actually need the full service, but just the partial in order to
452
/// be able to perform chain operations.
453
#[allow(clippy::type_complexity)]
454
896
pub fn new_partial<RuntimeApi, Customizations>(
455
896
	config: &mut Configuration,
456
896
	rpc_config: &RpcConfig,
457
896
	dev_service: bool,
458
896
) -> PartialComponentsResult<FullClient<RuntimeApi>, FullBackend>
459
896
where
460
896
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
461
896
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
462
896
	Customizations: ClientCustomizations + 'static,
463
896
{
464
896
	set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
465

            
466
	// Use ethereum style for subscription ids
467
896
	config.rpc_id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
468

            
469
896
	let telemetry = config
470
896
		.telemetry_endpoints
471
896
		.clone()
472
896
		.filter(|x| !x.is_empty())
473
896
		.map(|endpoints| -> Result<_, sc_telemetry::Error> {
474
			let worker = TelemetryWorker::new(16)?;
475
			let telemetry = worker.handle().new_telemetry(endpoints);
476
			Ok((worker, telemetry))
477
896
		})
478
896
		.transpose()?;
479

            
480
896
	let heap_pages = config
481
896
		.default_heap_pages
482
896
		.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
483
			extra_pages: h as _,
484
896
		});
485
896
	let mut wasm_builder = WasmExecutor::builder()
486
896
		.with_execution_method(config.wasm_method)
487
896
		.with_onchain_heap_alloc_strategy(heap_pages)
488
896
		.with_offchain_heap_alloc_strategy(heap_pages)
489
896
		.with_ignore_onchain_heap_pages(true)
490
896
		.with_max_runtime_instances(config.max_runtime_instances)
491
896
		.with_runtime_cache_size(config.runtime_cache_size);
492

            
493
896
	if let Some(ref wasmtime_precompiled_path) = config.wasmtime_precompiled {
494
894
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
495
894
	}
496

            
497
896
	let executor = wasm_builder.build();
498

            
499
896
	let (client, backend, keystore_container, task_manager) =
500
896
		sc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
501
896
			config,
502
896
			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
503
896
			executor,
504
896
			true,
505
896
		)?;
506

            
507
896
	if let Some(block_number) = Customizations::first_block_number_compatible_with_ed25519_zebra() {
508
896
		client
509
896
			.execution_extensions()
510
896
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
511
896
			Block,
512
896
			sp_io::UseDalekExt,
513
896
		>::new(block_number));
514
896
	}
515

            
516
896
	let client = Arc::new(client);
517
896

            
518
896
	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
519
896

            
520
896
	let telemetry = telemetry.map(|(worker, telemetry)| {
521
		task_manager
522
			.spawn_handle()
523
			.spawn("telemetry", None, worker.run());
524
		telemetry
525
896
	});
526

            
527
896
	let maybe_select_chain = if dev_service {
528
894
		Some(sc_consensus::LongestChain::new(backend.clone()))
529
	} else {
530
2
		None
531
	};
532

            
533
896
	let transaction_pool = sc_transaction_pool::BasicPool::new_full(
534
896
		config.transaction_pool.clone(),
535
896
		config.role.is_authority().into(),
536
896
		config.prometheus_registry(),
537
896
		task_manager.spawn_essential_handle(),
538
896
		client.clone(),
539
896
	);
540
896

            
541
896
	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
542
896
	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
543

            
544
896
	let frontier_backend = Arc::new(open_frontier_backend(client.clone(), config, rpc_config)?);
545
896
	let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
546
896

            
547
896
	let create_inherent_data_providers = move |_, _| async move {
548
		let time = sp_timestamp::InherentDataProvider::from_system_time();
549
		Ok((time,))
550
	};
551

            
552
896
	let (import_queue, block_import) = if dev_service {
553
		(
554
894
			nimbus_consensus::import_queue(
555
894
				client.clone(),
556
894
				frontier_block_import.clone(),
557
894
				create_inherent_data_providers,
558
894
				&task_manager.spawn_essential_handle(),
559
894
				config.prometheus_registry(),
560
894
				!dev_service,
561
894
			)?,
562
894
			BlockImportPipeline::Dev(frontier_block_import),
563
		)
564
	} else {
565
2
		let parachain_block_import = ParachainBlockImport::new_with_delayed_best_block(
566
2
			frontier_block_import,
567
2
			backend.clone(),
568
2
		);
569
2
		(
570
2
			nimbus_consensus::import_queue(
571
2
				client.clone(),
572
2
				parachain_block_import.clone(),
573
2
				create_inherent_data_providers,
574
2
				&task_manager.spawn_essential_handle(),
575
2
				config.prometheus_registry(),
576
2
				!dev_service,
577
2
			)?,
578
2
			BlockImportPipeline::Parachain(parachain_block_import),
579
		)
580
	};
581

            
582
896
	Ok(PartialComponents {
583
896
		backend,
584
896
		client,
585
896
		import_queue,
586
896
		keystore_container,
587
896
		task_manager,
588
896
		transaction_pool,
589
896
		select_chain: maybe_select_chain,
590
896
		other: (
591
896
			block_import,
592
896
			filter_pool,
593
896
			telemetry,
594
896
			telemetry_worker_handle,
595
896
			frontier_backend,
596
896
			fee_history_cache,
597
896
		),
598
896
	})
599
896
}
600

            
601
async fn build_relay_chain_interface(
602
	polkadot_config: Configuration,
603
	parachain_config: &Configuration,
604
	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
605
	task_manager: &mut TaskManager,
606
	collator_options: CollatorOptions,
607
	hwbench: Option<sc_sysinfo::HwBench>,
608
) -> RelayChainResult<(
609
	Arc<(dyn RelayChainInterface + 'static)>,
610
	Option<CollatorPair>,
611
)> {
612
	if let cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) =
613
		collator_options.relay_chain_mode
614
	{
615
		build_minimal_relay_chain_node_with_rpc(polkadot_config, task_manager, rpc_target_urls)
616
			.await
617
	} else {
618
		build_inprocess_relay_chain(
619
			polkadot_config,
620
			parachain_config,
621
			telemetry_worker_handle,
622
			task_manager,
623
			hwbench,
624
		)
625
	}
626
}
627

            
628
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
629
///
630
/// This is the actual implementation that is abstract over the executor and the runtime api.
631
#[sc_tracing::logging::prefix_logs_with("🌗")]
632
async fn start_node_impl<RuntimeApi, Customizations, Net>(
633
	parachain_config: Configuration,
634
	polkadot_config: Configuration,
635
	collator_options: CollatorOptions,
636
	para_id: ParaId,
637
	rpc_config: RpcConfig,
638
	async_backing: bool,
639
	block_authoring_duration: Duration,
640
	hwbench: Option<sc_sysinfo::HwBench>,
641
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi>>)>
642
where
643
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
644
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
645
	Customizations: ClientCustomizations + 'static,
646
	Net: NetworkBackend<Block, Hash>,
647
{
648
	let mut parachain_config = prepare_node_config(parachain_config);
649

            
650
	let params =
651
		new_partial::<RuntimeApi, Customizations>(&mut parachain_config, &rpc_config, false)?;
652
	let (
653
		block_import,
654
		filter_pool,
655
		mut telemetry,
656
		telemetry_worker_handle,
657
		frontier_backend,
658
		fee_history_cache,
659
	) = params.other;
660

            
661
	let client = params.client.clone();
662
	let backend = params.backend.clone();
663
	let mut task_manager = params.task_manager;
664

            
665
	let (relay_chain_interface, collator_key) = build_relay_chain_interface(
666
		polkadot_config,
667
		&parachain_config,
668
		telemetry_worker_handle,
669
		&mut task_manager,
670
		collator_options.clone(),
671
		hwbench.clone(),
672
	)
673
	.await
674
	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
675

            
676
	let force_authoring = parachain_config.force_authoring;
677
	let collator = parachain_config.role.is_authority();
678
	let prometheus_registry = parachain_config.prometheus_registry().cloned();
679
	let transaction_pool = params.transaction_pool.clone();
680
	let import_queue_service = params.import_queue.service();
681
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(&parachain_config.network);
682

            
683
	let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) =
684
		cumulus_client_service::build_network(cumulus_client_service::BuildNetworkParams {
685
			parachain_config: &parachain_config,
686
			client: client.clone(),
687
			transaction_pool: transaction_pool.clone(),
688
			spawn_handle: task_manager.spawn_handle(),
689
			import_queue: params.import_queue,
690
			para_id,
691
			relay_chain_interface: relay_chain_interface.clone(),
692
			net_config,
693
			sybil_resistance_level: CollatorSybilResistance::Resistant,
694
		})
695
		.await?;
696

            
697
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
698
	let fee_history_limit = rpc_config.fee_history_limit;
699

            
700
	// Sinks for pubsub notifications.
701
	// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
702
	// The MappingSyncWorker sends through the channel on block import and the subscription emits a
703
	// notification to the subscriber on receiving a message through this channel.
704
	// This way we avoid race conditions when using native substrate block import notification
705
	// stream.
706
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
707
		fc_mapping_sync::EthereumBlockNotification<Block>,
708
	> = Default::default();
709
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
710

            
711
	rpc::spawn_essential_tasks(
712
		rpc::SpawnTasksParams {
713
			task_manager: &task_manager,
714
			client: client.clone(),
715
			substrate_backend: backend.clone(),
716
			frontier_backend: frontier_backend.clone(),
717
			filter_pool: filter_pool.clone(),
718
			overrides: overrides.clone(),
719
			fee_history_limit,
720
			fee_history_cache: fee_history_cache.clone(),
721
		},
722
		sync_service.clone(),
723
		pubsub_notification_sinks.clone(),
724
	);
725

            
726
	let ethapi_cmd = rpc_config.ethapi.clone();
727
	let tracing_requesters =
728
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
729
			rpc::tracing::spawn_tracing_tasks(
730
				&rpc_config,
731
				prometheus_registry.clone(),
732
				rpc::SpawnTasksParams {
733
					task_manager: &task_manager,
734
					client: client.clone(),
735
					substrate_backend: backend.clone(),
736
					frontier_backend: frontier_backend.clone(),
737
					filter_pool: filter_pool.clone(),
738
					overrides: overrides.clone(),
739
					fee_history_limit,
740
					fee_history_cache: fee_history_cache.clone(),
741
				},
742
			)
743
		} else {
744
			rpc::tracing::RpcRequesters {
745
				debug: None,
746
				trace: None,
747
			}
748
		};
749

            
750
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
751
		task_manager.spawn_handle(),
752
		overrides.clone(),
753
		rpc_config.eth_log_block_cache,
754
		rpc_config.eth_statuses_cache,
755
		prometheus_registry.clone(),
756
	));
757

            
758
	let rpc_builder = {
759
		let client = client.clone();
760
		let pool = transaction_pool.clone();
761
		let network = network.clone();
762
		let sync = sync_service.clone();
763
		let filter_pool = filter_pool.clone();
764
		let frontier_backend = frontier_backend.clone();
765
		let backend = backend.clone();
766
		let ethapi_cmd = ethapi_cmd.clone();
767
		let max_past_logs = rpc_config.max_past_logs;
768
		let overrides = overrides.clone();
769
		let fee_history_cache = fee_history_cache.clone();
770
		let block_data_cache = block_data_cache.clone();
771
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
772

            
773
		let keystore = params.keystore_container.keystore();
774
		move |deny_unsafe, subscription_task_executor| {
775
			#[cfg(feature = "moonbase-native")]
776
			let forced_parent_hashes = {
777
				let mut forced_parent_hashes = BTreeMap::new();
778
				// Fixes for https://github.com/paritytech/frontier/pull/570
779
				// #1648995
780
				forced_parent_hashes.insert(
781
					H256::from_str(
782
						"0xa352fee3eef9c554a31ec0612af887796a920613358abf3353727760ea14207b",
783
					)
784
					.expect("must be valid hash"),
785
					H256::from_str(
786
						"0x0d0fd88778aec08b3a83ce36387dbf130f6f304fc91e9a44c9605eaf8a80ce5d",
787
					)
788
					.expect("must be valid hash"),
789
				);
790
				Some(forced_parent_hashes)
791
			};
792
			#[cfg(not(feature = "moonbase-native"))]
793
			let forced_parent_hashes = None;
794

            
795
			let deps = rpc::FullDeps {
796
				backend: backend.clone(),
797
				client: client.clone(),
798
				command_sink: None,
799
				deny_unsafe,
800
				ethapi_cmd: ethapi_cmd.clone(),
801
				filter_pool: filter_pool.clone(),
802
				frontier_backend: match &*frontier_backend {
803
					fc_db::Backend::KeyValue(b) => b.clone(),
804
					fc_db::Backend::Sql(b) => b.clone(),
805
				},
806
				graph: pool.pool().clone(),
807
				pool: pool.clone(),
808
				is_authority: collator,
809
				max_past_logs,
810
				fee_history_limit,
811
				fee_history_cache: fee_history_cache.clone(),
812
				network: network.clone(),
813
				sync: sync.clone(),
814
				dev_rpc_data: None,
815
				block_data_cache: block_data_cache.clone(),
816
				overrides: overrides.clone(),
817
				forced_parent_hashes,
818
			};
819
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
820
				client.clone(),
821
				keystore.clone(),
822
			));
823
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
824
				rpc::create_full(
825
					deps,
826
					subscription_task_executor,
827
					Some(crate::rpc::TracingConfig {
828
						tracing_requesters: tracing_requesters.clone(),
829
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
830
					}),
831
					pubsub_notification_sinks.clone(),
832
					pending_consensus_data_provider,
833
				)
834
				.map_err(Into::into)
835
			} else {
836
				rpc::create_full(
837
					deps,
838
					subscription_task_executor,
839
					None,
840
					pubsub_notification_sinks.clone(),
841
					pending_consensus_data_provider,
842
				)
843
				.map_err(Into::into)
844
			}
845
		}
846
	};
847

            
848
	sc_service::spawn_tasks(sc_service::SpawnTasksParams {
849
		rpc_builder: Box::new(rpc_builder),
850
		client: client.clone(),
851
		transaction_pool: transaction_pool.clone(),
852
		task_manager: &mut task_manager,
853
		config: parachain_config,
854
		keystore: params.keystore_container.keystore(),
855
		backend: backend.clone(),
856
		network: network.clone(),
857
		sync_service: sync_service.clone(),
858
		system_rpc_tx,
859
		tx_handler_controller,
860
		telemetry: telemetry.as_mut(),
861
	})?;
862

            
863
	if let Some(hwbench) = hwbench {
864
		sc_sysinfo::print_hwbench(&hwbench);
865

            
866
		if let Some(ref mut telemetry) = telemetry {
867
			let telemetry_handle = telemetry.handle();
868
			task_manager.spawn_handle().spawn(
869
				"telemetry_hwbench",
870
				None,
871
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
872
			);
873
		}
874
	}
875

            
876
	let announce_block = {
877
		let sync_service = sync_service.clone();
878
		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
879
	};
880

            
881
	let relay_chain_slot_duration = Duration::from_secs(6);
882
	let overseer_handle = relay_chain_interface
883
		.overseer_handle()
884
		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
885

            
886
	start_relay_chain_tasks(StartRelayChainTasksParams {
887
		client: client.clone(),
888
		announce_block: announce_block.clone(),
889
		para_id,
890
		relay_chain_interface: relay_chain_interface.clone(),
891
		task_manager: &mut task_manager,
892
		da_recovery_profile: if collator {
893
			DARecoveryProfile::Collator
894
		} else {
895
			DARecoveryProfile::FullNode
896
		},
897
		import_queue: import_queue_service,
898
		relay_chain_slot_duration,
899
		recovery_handle: Box::new(overseer_handle.clone()),
900
		sync_service: sync_service.clone(),
901
	})?;
902

            
903
	let BlockImportPipeline::Parachain(block_import) = block_import else {
904
		return Err(sc_service::Error::Other(
905
			"Block import pipeline is not for parachain".into(),
906
		));
907
	};
908

            
909
	if collator {
910
		start_consensus::<RuntimeApi, _>(
911
			async_backing,
912
			backend.clone(),
913
			client.clone(),
914
			block_import,
915
			prometheus_registry.as_ref(),
916
			telemetry.as_ref().map(|t| t.handle()),
917
			&task_manager,
918
			relay_chain_interface.clone(),
919
			transaction_pool,
920
			params.keystore_container.keystore(),
921
			para_id,
922
			collator_key.expect("Command line arguments do not allow this. qed"),
923
			overseer_handle,
924
			announce_block,
925
			force_authoring,
926
			relay_chain_slot_duration,
927
			block_authoring_duration,
928
			sync_service.clone(),
929
		)?;
930
		/*let parachain_consensus = build_consensus(
931
			client.clone(),
932
			backend,
933
			block_import,
934
			prometheus_registry.as_ref(),
935
			telemetry.as_ref().map(|t| t.handle()),
936
			&task_manager,
937
			relay_chain_interface.clone(),
938
			transaction_pool,
939
			sync_service.clone(),
940
			params.keystore_container.keystore(),
941
			force_authoring,
942
		)?;
943

            
944
		let spawner = task_manager.spawn_handle();
945

            
946
		let params = StartCollatorParams {
947
			para_id,
948
			block_status: client.clone(),
949
			announce_block,
950
			client: client.clone(),
951
			task_manager: &mut task_manager,
952
			relay_chain_interface,
953
			spawner,
954
			parachain_consensus,
955
			import_queue: import_queue_service,
956
			recovery_handle: Box::new(overseer_handle),
957
			collator_key: collator_key.ok_or(sc_service::error::Error::Other(
958
				"Collator Key is None".to_string(),
959
			))?,
960
			relay_chain_slot_duration,
961
			sync_service,
962
		};
963

            
964
		#[allow(deprecated)]
965
		start_collator(params).await?;*/
966
	}
967

            
968
	start_network.start_network();
969

            
970
	Ok((task_manager, client))
971
}
972

            
973
fn start_consensus<RuntimeApi, SO>(
974
	async_backing: bool,
975
	backend: Arc<FullBackend>,
976
	client: Arc<FullClient<RuntimeApi>>,
977
	block_import: ParachainBlockImport<FullClient<RuntimeApi>, FullBackend>,
978
	prometheus_registry: Option<&Registry>,
979
	telemetry: Option<TelemetryHandle>,
980
	task_manager: &TaskManager,
981
	relay_chain_interface: Arc<dyn RelayChainInterface>,
982
	transaction_pool: Arc<sc_transaction_pool::FullPool<Block, FullClient<RuntimeApi>>>,
983
	keystore: KeystorePtr,
984
	para_id: ParaId,
985
	collator_key: CollatorPair,
986
	overseer_handle: OverseerHandle,
987
	announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
988
	force_authoring: bool,
989
	relay_chain_slot_duration: Duration,
990
	block_authoring_duration: Duration,
991
	sync_oracle: SO,
992
) -> Result<(), sc_service::Error>
993
where
994
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
995
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
996
	sc_client_api::StateBackendFor<FullBackend, Block>: sc_client_api::StateBackend<BlakeTwo256>,
997
	SO: SyncOracle + Send + Sync + Clone + 'static,
998
{
999
	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,
			}),
		);
	} 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,
				},
			),
		);
	};
	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>,
) -> 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,
	)
	.await
}
/// Builds a new development service. This service uses manual seal, and mocks
/// the parachain inherent.
894
pub async fn new_dev<RuntimeApi, Customizations, Net>(
894
	mut config: Configuration,
894
	para_id: Option<u32>,
894
	_author_id: Option<NimbusId>,
894
	sealing: moonbeam_cli_opt::Sealing,
894
	rpc_config: RpcConfig,
894
	hwbench: Option<sc_sysinfo::HwBench>,
894
) -> Result<TaskManager, ServiceError>
894
where
894
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
894
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
894
	Customizations: ClientCustomizations + 'static,
894
	Net: NetworkBackend<Block, Hash>,
894
{
	use async_io::Timer;
	use futures::Stream;
	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};
	let sc_service::PartialComponents {
894
		client,
894
		backend,
894
		mut task_manager,
894
		import_queue,
894
		keystore_container,
894
		select_chain: maybe_select_chain,
894
		transaction_pool,
894
		other:
894
			(
894
				block_import_pipeline,
894
				filter_pool,
894
				mut telemetry,
894
				_telemetry_worker_handle,
894
				frontier_backend,
894
				fee_history_cache,
			),
894
	} = new_partial::<RuntimeApi, Customizations>(&mut config, &rpc_config, true)?;
894
	let block_import = if let BlockImportPipeline::Dev(block_import) = block_import_pipeline {
894
		block_import
	} else {
		return Err(ServiceError::Other(
			"Block import pipeline is not dev".to_string(),
		));
	};
894
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(&config.network);
894

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

            
894
	if collator {
894
		let mut env = sc_basic_authorship::ProposerFactory::with_proof_recording(
894
			task_manager.spawn_handle(),
894
			client.clone(),
894
			transaction_pool.clone(),
894
			prometheus_registry.as_ref(),
894
			telemetry.as_ref().map(|x| x.handle()),
894
		);
894
		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();
894
		let commands_stream: Box<dyn Stream<Item = EngineCommand<H256>> + Send + Sync + Unpin> =
894
			match sealing {
				moonbeam_cli_opt::Sealing::Instant => {
					Box::new(
						// This bit cribbed from the implementation of instant seal.
						transaction_pool
							.pool()
							.validated_pool()
							.import_notification_stream()
							.map(|_| EngineCommand::SealNewBlock {
								create_empty: false,
								finalize: false,
								parent_hash: None,
								sender: None,
							}),
					)
				}
				moonbeam_cli_opt::Sealing::Manual => {
894
					let (sink, stream) = futures::channel::mpsc::channel(1000);
894
					// Keep a reference to the other end of the channel. It goes to the RPC.
894
					command_sink = Some(sink);
894
					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,
					},
				)),
			};
894
		let select_chain = maybe_select_chain.expect(
894
			"`new_partial` builds a `LongestChainRule` when building dev service.\
894
				We specified the dev service when calling `new_partial`.\
894
				Therefore, a `LongestChainRule` is present. qed.",
894
		);
894

            
894
		let client_set_aside_for_cidp = client.clone();
894

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

            
894
		let client_clone = client.clone();
894
		let keystore_clone = keystore_container.keystore().clone();
894
		let maybe_provide_vrf_digest =
23398
			move |nimbus_id: NimbusId, parent: Hash| -> Option<sp_runtime::generic::DigestItem> {
23398
				moonbeam_vrf::vrf_pre_digest::<Block, FullClient<RuntimeApi>>(
23398
					&client_clone,
23398
					&keystore_clone,
23398
					nimbus_id,
23398
					parent,
23398
				)
23398
			};
894
		task_manager.spawn_essential_handle().spawn_blocking(
894
			"authorship_task",
894
			Some("block-authoring"),
894
			run_manual_seal(ManualSealParams {
894
				block_import,
894
				env,
894
				client: client.clone(),
894
				pool: transaction_pool.clone(),
894
				commands_stream,
894
				select_chain,
894
				consensus_data_provider: Some(Box::new(NimbusManualSealConsensusDataProvider {
894
					keystore: keystore_container.keystore(),
894
					client: client.clone(),
894
					additional_digests_provider: maybe_provide_vrf_digest,
894
					_phantom: Default::default(),
894
				})),
23398
				create_inherent_data_providers: move |block: H256, ()| {
23398
					let maybe_current_para_block = client_set_aside_for_cidp.number(block);
23398
					let maybe_current_para_head = client_set_aside_for_cidp.expect_header(block);
23398
					let downward_xcm_receiver = downward_xcm_receiver.clone();
23398
					let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
23398
					let additional_relay_offset = additional_relay_offset.clone();
23398
					let relay_slot_key = well_known_keys::CURRENT_SLOT.to_vec();
23398

            
23398
					let client_for_xcm = client_set_aside_for_cidp.clone();
23398
					async move {
23398
						let time = MockTimestampInherentDataProvider;
23398
						let current_para_block = maybe_current_para_block?
23398
							.ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?;
23398
						let current_para_block_head = Some(polkadot_primitives::HeadData(
23398
							maybe_current_para_head?.encode(),
23398
						));
23398

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

            
23398
						let additional_key_values = Some(vec![
23398
							(
23398
								moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW
23398
									.to_vec(),
23398
								sp_timestamp::Timestamp::current().encode(),
23398
							),
23398
							(relay_slot_key, Slot::from(slot).encode()),
23398
						]);
23398

            
23398
						let mocked_parachain = MockValidationDataInherentDataProvider {
23398
							current_para_block,
23398
							para_id: para_id.unwrap().into(),
23398
							current_para_block_head,
23398
							relay_offset: 1000
23398
								+ additional_relay_offset.load(std::sync::atomic::Ordering::SeqCst),
23398
							relay_blocks_per_para_block: 2,
23398
							// TODO: Recheck
23398
							para_blocks_per_relay_epoch: 10,
23398
							relay_randomness_config: (),
23398
							xcm_config: MockXcmConfig::new(
23398
								&*client_for_xcm,
23398
								block,
23398
								Default::default(),
23398
							),
23398
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
23398
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
23398
							additional_key_values,
23398
						};
23398

            
23398
						let randomness = session_keys_primitives::InherentDataProvider;
23398

            
23398
						Ok((time, mocked_parachain, randomness))
23398
					}
23398
				},
894
			}),
894
		);
	}
	// 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.
894
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
894
		fc_mapping_sync::EthereumBlockNotification<Block>,
894
	> = Default::default();
894
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
894

            
894
	rpc::spawn_essential_tasks(
894
		rpc::SpawnTasksParams {
894
			task_manager: &task_manager,
894
			client: client.clone(),
894
			substrate_backend: backend.clone(),
894
			frontier_backend: frontier_backend.clone(),
894
			filter_pool: filter_pool.clone(),
894
			overrides: overrides.clone(),
894
			fee_history_limit,
894
			fee_history_cache: fee_history_cache.clone(),
894
		},
894
		sync_service.clone(),
894
		pubsub_notification_sinks.clone(),
894
	);
894
	let ethapi_cmd = rpc_config.ethapi.clone();
894
	let tracing_requesters =
894
		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 {
894
			rpc::tracing::RpcRequesters {
894
				debug: None,
894
				trace: None,
894
			}
		};
894
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
894
		task_manager.spawn_handle(),
894
		overrides.clone(),
894
		rpc_config.eth_log_block_cache,
894
		rpc_config.eth_statuses_cache,
894
		prometheus_registry,
894
	));
894

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

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

            
1788
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
1788
				client.clone(),
1788
				keystore.clone(),
1788
			));
1788
			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 {
1788
				rpc::create_full(
1788
					deps,
1788
					subscription_task_executor,
1788
					None,
1788
					pubsub_notification_sinks.clone(),
1788
					pending_consensus_data_provider,
1788
				)
1788
				.map_err(Into::into)
			}
1788
		}
	};
894
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
894
		network,
894
		client,
894
		keystore: keystore_container.keystore(),
894
		task_manager: &mut task_manager,
894
		transaction_pool,
894
		rpc_builder: Box::new(rpc_builder),
894
		backend,
894
		system_rpc_tx,
894
		sync_service: sync_service.clone(),
894
		config,
894
		tx_handler_controller,
894
		telemetry: None,
894
	})?;
894
	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),
			);
		}
894
	}
894
	log::info!("Development Service Ready");
894
	network_starter.start_network();
894
	Ok(task_manager)
894
}
#[cfg(test)]
mod tests {
	use jsonrpsee::server::BatchRequestConfig;
	use moonbase_runtime::{currency::UNIT, AccountId};
	use prometheus::{proto::LabelPair, Counter};
	use sc_network::config::NetworkConfiguration;
	use sc_service::ChainType;
	use sc_service::{
		config::{BasePath, DatabaseSource, KeystoreConfig},
		Configuration, Role,
	};
	use std::path::Path;
	use std::str::FromStr;
	use crate::chain_spec::moonbase::{testnet_genesis, ChainSpec};
	use crate::chain_spec::Extensions;
	use super::*;
	#[test]
1
	fn test_set_prometheus_registry_uses_moonbeam_prefix() {
1
		let counter_name = "my_counter";
1
		let expected_metric_name = "moonbeam_my_counter";
1
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
1
		let mut config = Configuration {
1
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
1
				"0.0.0.0:8080".parse().unwrap(),
1
				"".into(),
1
			)),
1
			..test_config("test")
1
		};
1

            
1
		set_prometheus_registry(&mut config, false).unwrap();
1
		// generate metric
1
		let reg = config.prometheus_registry().unwrap();
1
		reg.register(counter.clone()).unwrap();
1
		counter.inc();
1

            
1
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
1
		assert_eq!(actual_metric_name.as_str(), expected_metric_name);
1
	}
	#[test]
1
	fn test_set_prometheus_registry_skips_moonbeam_prefix() {
1
		let counter_name = "my_counter";
1
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
1
		let mut config = Configuration {
1
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
1
				"0.0.0.0:8080".parse().unwrap(),
1
				"".into(),
1
			)),
1
			..test_config("test")
1
		};
1

            
1
		set_prometheus_registry(&mut config, true).unwrap();
1
		// generate metric
1
		let reg = config.prometheus_registry().unwrap();
1
		reg.register(counter.clone()).unwrap();
1
		counter.inc();
1

            
1
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
1
		assert_eq!(actual_metric_name.as_str(), counter_name);
1
	}
	#[test]
1
	fn test_set_prometheus_registry_adds_chain_id_as_label() {
1
		let input_chain_id = "moonriver";
1

            
1
		let mut expected_label = LabelPair::default();
1
		expected_label.set_name("chain".to_owned());
1
		expected_label.set_value("moonriver".to_owned());
1
		let expected_chain_label = Some(expected_label);
1

            
1
		let counter = Box::new(Counter::new("foo", "foobar").unwrap());
1
		let mut config = Configuration {
1
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
1
				"0.0.0.0:8080".parse().unwrap(),
1
				"".into(),
1
			)),
1
			..test_config(input_chain_id)
1
		};
1

            
1
		set_prometheus_registry(&mut config, false).unwrap();
1
		// generate metric
1
		let reg = config.prometheus_registry().unwrap();
1
		reg.register(counter.clone()).unwrap();
1
		counter.inc();
1

            
1
		let actual_chain_label = reg
1
			.gather()
1
			.first()
1
			.unwrap()
1
			.get_metric()
1
			.first()
1
			.unwrap()
1
			.get_label()
1
			.into_iter()
1
			.find(|x| x.get_name() == "chain")
1
			.cloned();
1

            
1
		assert_eq!(actual_chain_label, expected_chain_label);
1
	}
	#[test]
1
	fn dalek_does_not_panic() {
1
		use futures::executor::block_on;
1
		use sc_block_builder::BlockBuilderBuilder;
1
		use sc_client_db::{Backend, BlocksPruning, DatabaseSettings, DatabaseSource, PruningMode};
1
		use sp_api::ProvideRuntimeApi;
1
		use sp_consensus::BlockOrigin;
1
		use substrate_test_runtime::TestAPI;
1
		use substrate_test_runtime_client::runtime::Block;
1
		use substrate_test_runtime_client::{
1
			ClientBlockImportExt, TestClientBuilder, TestClientBuilderExt,
1
		};
1

            
1
		fn zero_ed_pub() -> sp_core::ed25519::Public {
1
			sp_core::ed25519::Public::default()
1
		}
1

            
1
		// This is an invalid signature
1
		// this breaks after ed25519 1.3. It makes the signature panic at creation
1
		// This test ensures we should never panic
1
		fn invalid_sig() -> sp_core::ed25519::Signature {
1
			let signature = hex_literal::hex!(
1
				"a25b94f9c64270fdfffa673f11cfe961633e3e4972e6940a3cf
1
		7351dd90b71447041a83583a52cee1cf21b36ba7fd1d0211dca58b48d997fc78d9bc82ab7a38e"
1
			);
1
			sp_core::ed25519::Signature::from_raw(signature[0..64].try_into().unwrap())
1
		}
1

            
1
		let tmp = tempfile::tempdir().unwrap();
1
		let backend = Arc::new(
1
			Backend::new(
1
				DatabaseSettings {
1
					trie_cache_maximum_size: Some(1 << 20),
1
					state_pruning: Some(PruningMode::ArchiveAll),
1
					blocks_pruning: BlocksPruning::KeepAll,
1
					source: DatabaseSource::RocksDb {
1
						path: tmp.path().into(),
1
						cache_size: 1024,
1
					},
1
				},
1
				u64::MAX,
1
			)
1
			.unwrap(),
1
		);
1
		let mut client = TestClientBuilder::with_backend(backend).build();
1

            
1
		client
1
			.execution_extensions()
1
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
1
			Block,
1
			sp_io::UseDalekExt,
1
		>::new(1));
1

            
1
		let a1 = BlockBuilderBuilder::new(&client)
1
			.on_parent_block(client.chain_info().genesis_hash)
1
			.with_parent_block_number(0)
1
			// Enable proof recording if required. This call is optional.
1
			.enable_proof_recording()
1
			.build()
1
			.unwrap()
1
			.build()
1
			.unwrap()
1
			.block;
1

            
1
		block_on(client.import(BlockOrigin::NetworkInitialSync, a1.clone())).unwrap();
1

            
1
		// On block zero it will use dalek
1
		// shouldnt panic on importing invalid sig
1
		assert!(!client
1
			.runtime_api()
1
			.verify_ed25519(
1
				client.chain_info().genesis_hash,
1
				invalid_sig(),
1
				zero_ed_pub(),
1
				vec![]
1
			)
1
			.unwrap());
1
	}
3
	fn test_config(chain_id: &str) -> Configuration {
3
		let network_config = NetworkConfiguration::new("", "", Default::default(), None);
3
		let runtime = tokio::runtime::Runtime::new().expect("failed creating tokio runtime");
3
		let spec = ChainSpec::builder(&[0u8], Extensions::default())
3
			.with_name("test")
3
			.with_id(chain_id)
3
			.with_chain_type(ChainType::Local)
3
			.with_genesis_config(testnet_genesis(
3
				AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(),
3
				vec![],
3
				vec![],
3
				vec![],
3
				vec![],
3
				vec![],
3
				1000 * UNIT,
3
				ParaId::new(0),
3
				0,
3
			))
3
			.build();
3

            
3
		Configuration {
3
			impl_name: String::from("test-impl"),
3
			impl_version: String::from("0.1"),
3
			role: Role::Full,
3
			tokio_handle: runtime.handle().clone(),
3
			transaction_pool: Default::default(),
3
			network: network_config,
3
			keystore: KeystoreConfig::Path {
3
				path: "key".into(),
3
				password: None,
3
			},
3
			database: DatabaseSource::RocksDb {
3
				path: "db".into(),
3
				cache_size: 128,
3
			},
3
			trie_cache_maximum_size: Some(16777216),
3
			state_pruning: Default::default(),
3
			blocks_pruning: sc_service::BlocksPruning::KeepAll,
3
			chain_spec: Box::new(spec),
3
			wasm_method: Default::default(),
3
			wasm_runtime_overrides: Default::default(),
3
			rpc_id_provider: None,
3
			rpc_max_connections: Default::default(),
3
			rpc_cors: None,
3
			rpc_methods: Default::default(),
3
			rpc_max_request_size: Default::default(),
3
			rpc_max_response_size: Default::default(),
3
			rpc_max_subs_per_conn: Default::default(),
3
			rpc_addr: None,
3
			rpc_port: Default::default(),
3
			rpc_message_buffer_capacity: Default::default(),
3
			data_path: Default::default(),
3
			prometheus_config: None,
3
			telemetry_endpoints: None,
3
			default_heap_pages: None,
3
			offchain_worker: Default::default(),
3
			force_authoring: false,
3
			disable_grandpa: false,
3
			dev_key_seed: None,
3
			tracing_targets: None,
3
			tracing_receiver: Default::default(),
3
			max_runtime_instances: 8,
3
			announce_block: true,
3
			base_path: BasePath::new(Path::new("")),
3
			informant_output_format: Default::default(),
3
			wasmtime_precompiled: None,
3
			runtime_cache_size: 2,
3
			rpc_rate_limit: Default::default(),
3
			rpc_rate_limit_whitelisted_ips: vec![],
3
			rpc_batch_config: BatchRequestConfig::Unlimited,
3
			rpc_rate_limit_trust_proxy_headers: false,
3
		}
3
	}
}
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>,
{
1788
	pub fn new(client: Arc<Client>, keystore: Arc<dyn Keystore>) -> Self {
1788
		Self { client, keystore }
1788
	}
}
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
	}
}