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

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

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

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

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

            
25
pub mod rpc;
26

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

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

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

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

            
119
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6_000;
120

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
353
932
	Ok(frontier_backend)
354
932
}
355

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

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

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

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

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

            
453
3
		*registry = Registry::new_custom(prefix, Some(labels))?;
454
932
	}
455

            
456
935
	Ok(())
457
935
}
458

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

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

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

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

            
505
932
	if let Some(ref wasmtime_precompiled_path) = config.executor.wasmtime_precompiled {
506
930
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
507
930
	}
508

            
509
932
	let executor = wasm_builder.build();
510

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

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

            
528
932
	let client = Arc::new(client);
529
932

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

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

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

            
545
932
	let transaction_pool = sc_transaction_pool::BasicPool::new_full(
546
932
		config.transaction_pool.clone(),
547
932
		config.role.is_authority().into(),
548
932
		config.prometheus_registry(),
549
932
		task_manager.spawn_essential_handle(),
550
932
		client.clone(),
551
932
	);
552
932

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

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

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

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

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

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

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

            
668
	let params = new_partial::<RuntimeApi, Customizations>(
669
		&mut parachain_config,
670
		&rpc_config,
671
		false,
672
		legacy_block_import_strategy,
673
	)?;
674
	let (
675
		block_import,
676
		filter_pool,
677
		mut telemetry,
678
		telemetry_worker_handle,
679
		frontier_backend,
680
		fee_history_cache,
681
	) = params.other;
682

            
683
	let client = params.client.clone();
684
	let backend = params.backend.clone();
685
	let mut task_manager = params.task_manager;
686

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

            
698
	let force_authoring = parachain_config.force_authoring;
699
	let collator = parachain_config.role.is_authority();
700
	let prometheus_registry = parachain_config.prometheus_registry().cloned();
701
	let transaction_pool = params.transaction_pool.clone();
702
	let import_queue_service = params.import_queue.service();
703
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(
704
		&parachain_config.network,
705
		prometheus_registry.clone(),
706
	);
707

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

            
722
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
723
	let fee_history_limit = rpc_config.fee_history_limit;
724

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

            
736
	rpc::spawn_essential_tasks(
737
		rpc::SpawnTasksParams {
738
			task_manager: &task_manager,
739
			client: client.clone(),
740
			substrate_backend: backend.clone(),
741
			frontier_backend: frontier_backend.clone(),
742
			filter_pool: filter_pool.clone(),
743
			overrides: overrides.clone(),
744
			fee_history_limit,
745
			fee_history_cache: fee_history_cache.clone(),
746
		},
747
		sync_service.clone(),
748
		pubsub_notification_sinks.clone(),
749
	);
750

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

            
775
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
776
		task_manager.spawn_handle(),
777
		overrides.clone(),
778
		rpc_config.eth_log_block_cache,
779
		rpc_config.eth_statuses_cache,
780
		prometheus_registry.clone(),
781
	));
782

            
783
	let rpc_builder = {
784
		let client = client.clone();
785
		let pool = transaction_pool.clone();
786
		let network = network.clone();
787
		let sync = sync_service.clone();
788
		let filter_pool = filter_pool.clone();
789
		let frontier_backend = frontier_backend.clone();
790
		let backend = backend.clone();
791
		let ethapi_cmd = ethapi_cmd.clone();
792
		let max_past_logs = rpc_config.max_past_logs;
793
		let overrides = overrides.clone();
794
		let fee_history_cache = fee_history_cache.clone();
795
		let block_data_cache = block_data_cache.clone();
796
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
797

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

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

            
872
	sc_service::spawn_tasks(sc_service::SpawnTasksParams {
873
		rpc_builder: Box::new(rpc_builder),
874
		client: client.clone(),
875
		transaction_pool: transaction_pool.clone(),
876
		task_manager: &mut task_manager,
877
		config: parachain_config,
878
		keystore: params.keystore_container.keystore(),
879
		backend: backend.clone(),
880
		network: network.clone(),
881
		sync_service: sync_service.clone(),
882
		system_rpc_tx,
883
		tx_handler_controller,
884
		telemetry: telemetry.as_mut(),
885
	})?;
886

            
887
	if let Some(hwbench) = hwbench {
888
		sc_sysinfo::print_hwbench(&hwbench);
889

            
890
		if let Some(ref mut telemetry) = telemetry {
891
			let telemetry_handle = telemetry.handle();
892
			task_manager.spawn_handle().spawn(
893
				"telemetry_hwbench",
894
				None,
895
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
896
			);
897
		}
898
	}
899

            
900
	let announce_block = {
901
		let sync_service = sync_service.clone();
902
		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
903
	};
904

            
905
	let relay_chain_slot_duration = Duration::from_secs(6);
906
	let overseer_handle = relay_chain_interface
907
		.overseer_handle()
908
		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
909

            
910
	start_relay_chain_tasks(StartRelayChainTasksParams {
911
		client: client.clone(),
912
		announce_block: announce_block.clone(),
913
		para_id,
914
		relay_chain_interface: relay_chain_interface.clone(),
915
		task_manager: &mut task_manager,
916
		da_recovery_profile: if collator {
917
			DARecoveryProfile::Collator
918
		} else {
919
			DARecoveryProfile::FullNode
920
		},
921
		import_queue: import_queue_service,
922
		relay_chain_slot_duration,
923
		recovery_handle: Box::new(overseer_handle.clone()),
924
		sync_service: sync_service.clone(),
925
	})?;
926

            
927
	let BlockImportPipeline::Parachain(block_import) = block_import else {
928
		return Err(sc_service::Error::Other(
929
			"Block import pipeline is not for parachain".into(),
930
		));
931
	};
932

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

            
969
		let spawner = task_manager.spawn_handle();
970

            
971
		let params = StartCollatorParams {
972
			para_id,
973
			block_status: client.clone(),
974
			announce_block,
975
			client: client.clone(),
976
			task_manager: &mut task_manager,
977
			relay_chain_interface,
978
			spawner,
979
			parachain_consensus,
980
			import_queue: import_queue_service,
981
			recovery_handle: Box::new(overseer_handle),
982
			collator_key: collator_key.ok_or(sc_service::error::Error::Other(
983
				"Collator Key is None".to_string(),
984
			))?,
985
			relay_chain_slot_duration,
986
			sync_service,
987
		};
988

            
989
		#[allow(deprecated)]
990
		start_collator(params).await?;*/
991
	}
992

            
993
	start_network.start_network();
994

            
995
	Ok((task_manager, client))
996
}
997

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

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

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

            
930
		let client_set_aside_for_cidp = client.clone();
930

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

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

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

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

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

            
26832
						let storage_key = [
26832
							twox_128(b"ParachainSystem"),
26832
							twox_128(b"PendingValidationCode"),
26832
						]
26832
						.concat();
26832
						let has_pending_upgrade = client_for_xcm
26832
							.storage(block, &sp_storage::StorageKey(storage_key))
26832
							.map_or(false, |ok| ok.map_or(false, |some| !some.0.is_empty()));
26832
						if has_pending_upgrade {
							additional_key_values.push((
								relay_chain::well_known_keys::upgrade_go_ahead_signal(ParaId::new(
									para_id.unwrap(),
								)),
								Some(relay_chain::UpgradeGoAhead::GoAhead).encode(),
							));
26832
						}
26832
						let mocked_parachain = MockValidationDataInherentDataProvider {
26832
							current_para_block,
26832
							para_id: para_id.unwrap().into(),
26832
							current_para_block_head,
26832
							relay_offset: 1000
26832
								+ additional_relay_offset.load(std::sync::atomic::Ordering::SeqCst),
26832
							relay_blocks_per_para_block: 2,
26832
							// TODO: Recheck
26832
							para_blocks_per_relay_epoch: 10,
26832
							relay_randomness_config: (),
26832
							xcm_config: MockXcmConfig::new(
26832
								&*client_for_xcm,
26832
								block,
26832
								Default::default(),
26832
							),
26832
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
26832
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
26832
							additional_key_values: Some(additional_key_values),
26832
						};
26832

            
26832
						let randomness = session_keys_primitives::InherentDataProvider;
26832

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

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

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

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

            
1860
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
1860
				client.clone(),
1860
				keystore.clone(),
1860
			));
1860
			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 {
1860
				rpc::create_full(
1860
					deps,
1860
					subscription_task_executor,
1860
					None,
1860
					pubsub_notification_sinks.clone(),
1860
					pending_consensus_data_provider,
1860
				)
1860
				.map_err(Into::into)
			}
1860
		}
	};
930
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
930
		network,
930
		client,
930
		keystore: keystore_container.keystore(),
930
		task_manager: &mut task_manager,
930
		transaction_pool,
930
		rpc_builder: Box::new(rpc_builder),
930
		backend,
930
		system_rpc_tx,
930
		sync_service: sync_service.clone(),
930
		config,
930
		tx_handler_controller,
930
		telemetry: None,
930
	})?;
930
	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),
			);
		}
930
	}
930
	log::info!("Development Service Ready");
930
	network_starter.start_network();
930
	Ok(task_manager)
930
}
#[cfg(test)]
mod tests {
	use crate::chain_spec::moonbase::ChainSpec;
	use crate::chain_spec::Extensions;
	use jsonrpsee::server::BatchRequestConfig;
	use moonbase_runtime::{currency::UNIT, AccountId};
	use prometheus::{proto::LabelPair, Counter};
	use sc_network::config::NetworkConfiguration;
	use sc_service::config::RpcConfiguration;
	use sc_service::ChainType;
	use sc_service::{
		config::{BasePath, DatabaseSource, KeystoreConfig},
		Configuration, Role,
	};
	use std::path::Path;
	use std::str::FromStr;
	use super::*;
	#[test]
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 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(moonbase_runtime::genesis_config_preset::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
			executor: Default::default(),
3
			wasm_runtime_overrides: Default::default(),
3
			rpc: RpcConfiguration {
3
				addr: None,
3
				max_connections: Default::default(),
3
				cors: None,
3
				methods: Default::default(),
3
				max_request_size: Default::default(),
3
				max_response_size: Default::default(),
3
				id_provider: None,
3
				max_subs_per_conn: Default::default(),
3
				port: Default::default(),
3
				message_buffer_capacity: Default::default(),
3
				batch_config: BatchRequestConfig::Unlimited,
3
				rate_limit: Default::default(),
3
				rate_limit_whitelisted_ips: vec![],
3
				rate_limit_trust_proxy_headers: false,
3
			},
3
			data_path: Default::default(),
3
			prometheus_config: None,
3
			telemetry_endpoints: 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
			announce_block: true,
3
			base_path: BasePath::new(Path::new("")),
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>,
{
1860
	pub fn new(client: Arc<Client>, keystore: Arc<dyn Keystore>) -> Self {
1860
		Self { client, keystore }
1860
	}
}
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
	}
}