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
23300
	) -> Result<(), sp_inherents::Error> {
131
23300
		TIMESTAMP.fetch_add(RELAY_CHAIN_SLOT_DURATION_MILLIS, Ordering::SeqCst);
132
23300
		inherent_data.put_data(
133
23300
			sp_timestamp::INHERENT_IDENTIFIER,
134
23300
			&TIMESTAMP.load(Ordering::SeqCst),
135
23300
		)
136
46600
	}
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
898
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
209
898
		Some(3_000_000)
210
898
	}
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
898
	fn is_moonbeam(&self) -> bool {
261
898
		self.id().starts_with("moonbeam")
262
898
	}
263

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

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

            
273
898
pub fn frontier_database_dir(config: &Configuration, path: &str) -> std::path::PathBuf {
274
898
	config
275
898
		.base_path
276
898
		.config_dir(config.chain_spec.id())
277
898
		.join("frontier")
278
898
		.join(path)
279
898
}
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
898
pub fn open_frontier_backend<C, BE>(
284
898
	client: Arc<C>,
285
898
	config: &Configuration,
286
898
	rpc_config: &RpcConfig,
287
898
) -> Result<fc_db::Backend<Block, C>, String>
288
898
where
289
898
	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
290
898
	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError>,
291
898
	C: Send + Sync + 'static,
292
898
	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,
293
898
	BE: Backend<Block> + 'static,
294
898
	BE::State: StateBackend<BlakeTwo256>,
295
898
{
296
898
	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
898
				client,
300
898
				&fc_db::kv::DatabaseSettings {
301
898
					source: match config.database {
302
898
						DatabaseSource::RocksDb { .. } => DatabaseSource::RocksDb {
303
898
							path: frontier_database_dir(config, "db"),
304
898
							cache_size: 0,
305
898
						},
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
898
	Ok(frontier_backend)
353
898
}
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
901
fn set_prometheus_registry(
430
901
	config: &mut Configuration,
431
901
	skip_prefix: bool,
432
901
) -> Result<(), ServiceError> {
433
901
	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
898
	}
445

            
446
901
	Ok(())
447
901
}
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
898
pub fn new_partial<RuntimeApi, Customizations>(
455
898
	config: &mut Configuration,
456
898
	rpc_config: &RpcConfig,
457
898
	dev_service: bool,
458
898
) -> PartialComponentsResult<FullClient<RuntimeApi>, FullBackend>
459
898
where
460
898
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
461
898
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
462
898
	Customizations: ClientCustomizations + 'static,
463
898
{
464
898
	set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
465

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

            
469
898
	let telemetry = config
470
898
		.telemetry_endpoints
471
898
		.clone()
472
898
		.filter(|x| !x.is_empty())
473
898
		.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
898
		})
478
898
		.transpose()?;
479

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

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

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

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

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

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

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

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

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

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

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

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

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

            
552
898
	let (import_queue, block_import) = if dev_service {
553
		(
554
896
			nimbus_consensus::import_queue(
555
896
				client.clone(),
556
896
				frontier_block_import.clone(),
557
896
				create_inherent_data_providers,
558
896
				&task_manager.spawn_essential_handle(),
559
896
				config.prometheus_registry(),
560
896
				!dev_service,
561
896
			)?,
562
896
			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
898
	Ok(PartialComponents {
583
898
		backend,
584
898
		client,
585
898
		import_queue,
586
898
		keystore_container,
587
898
		task_manager,
588
898
		transaction_pool,
589
898
		select_chain: maybe_select_chain,
590
898
		other: (
591
898
			block_import,
592
898
			filter_pool,
593
898
			telemetry,
594
898
			telemetry_worker_handle,
595
898
			frontier_backend,
596
898
			fee_history_cache,
597
898
		),
598
898
	})
599
898
}
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.
896
pub async fn new_dev<RuntimeApi, Customizations, Net>(
896
	mut config: Configuration,
896
	para_id: Option<u32>,
896
	_author_id: Option<NimbusId>,
896
	sealing: moonbeam_cli_opt::Sealing,
896
	rpc_config: RpcConfig,
896
	hwbench: Option<sc_sysinfo::HwBench>,
896
) -> Result<TaskManager, ServiceError>
896
where
896
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
896
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
896
	Customizations: ClientCustomizations + 'static,
896
	Net: NetworkBackend<Block, Hash>,
896
{
	use async_io::Timer;
	use futures::Stream;
	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};
	let sc_service::PartialComponents {
896
		client,
896
		backend,
896
		mut task_manager,
896
		import_queue,
896
		keystore_container,
896
		select_chain: maybe_select_chain,
896
		transaction_pool,
896
		other:
896
			(
896
				block_import_pipeline,
896
				filter_pool,
896
				mut telemetry,
896
				_telemetry_worker_handle,
896
				frontier_backend,
896
				fee_history_cache,
			),
896
	} = new_partial::<RuntimeApi, Customizations>(&mut config, &rpc_config, true)?;
896
	let block_import = if let BlockImportPipeline::Dev(block_import) = block_import_pipeline {
896
		block_import
	} else {
		return Err(ServiceError::Other(
			"Block import pipeline is not dev".to_string(),
		));
	};
896
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(&config.network);
896

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

            
896
	if collator {
896
		let mut env = sc_basic_authorship::ProposerFactory::with_proof_recording(
896
			task_manager.spawn_handle(),
896
			client.clone(),
896
			transaction_pool.clone(),
896
			prometheus_registry.as_ref(),
896
			telemetry.as_ref().map(|x| x.handle()),
896
		);
896
		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();
896
		let commands_stream: Box<dyn Stream<Item = EngineCommand<H256>> + Send + Sync + Unpin> =
896
			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 => {
896
					let (sink, stream) = futures::channel::mpsc::channel(1000);
896
					// Keep a reference to the other end of the channel. It goes to the RPC.
896
					command_sink = Some(sink);
896
					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,
					},
				)),
			};
896
		let select_chain = maybe_select_chain.expect(
896
			"`new_partial` builds a `LongestChainRule` when building dev service.\
896
				We specified the dev service when calling `new_partial`.\
896
				Therefore, a `LongestChainRule` is present. qed.",
896
		);
896

            
896
		let client_set_aside_for_cidp = client.clone();
896

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

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

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

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

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

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

            
23300
						let randomness = session_keys_primitives::InherentDataProvider;
23300

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

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

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

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

            
1792
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
1792
				client.clone(),
1792
				keystore.clone(),
1792
			));
1792
			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 {
1792
				rpc::create_full(
1792
					deps,
1792
					subscription_task_executor,
1792
					None,
1792
					pubsub_notification_sinks.clone(),
1792
					pending_consensus_data_provider,
1792
				)
1792
				.map_err(Into::into)
			}
1792
		}
	};
896
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
896
		network,
896
		client,
896
		keystore: keystore_container.keystore(),
896
		task_manager: &mut task_manager,
896
		transaction_pool,
896
		rpc_builder: Box::new(rpc_builder),
896
		backend,
896
		system_rpc_tx,
896
		sync_service: sync_service.clone(),
896
		config,
896
		tx_handler_controller,
896
		telemetry: None,
896
	})?;
896
	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),
			);
		}
896
	}
896
	log::info!("Development Service Ready");
896
	network_starter.start_network();
896
	Ok(task_manager)
896
}
#[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>,
{
1792
	pub fn new(client: Arc<Client>, keystore: Arc<dyn Keystore>) -> Self {
1792
		Self { client, keystore }
1792
	}
}
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
	}
}