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 maintenance tasks without a complete node (eg import/export blocks, purge)
22
//! Full Service: A complete parachain node including the pool, rpc, network, embedded relay chain
23
//! Dev Service: A leaner service without the relay chain backing.
24

            
25
pub mod rpc;
26

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

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

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

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

            
118
const RELAY_CHAIN_SLOT_DURATION_MILLIS: u64 = 6_000;
119

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

            
122
/// Provide a mock duration starting at 0 in millisecond for timestamp inherent.
123
/// Each call will increment timestamp by slot_duration making Aura think time has passed.
124
struct MockTimestampInherentDataProvider;
125

            
126
impl MockTimestampInherentDataProvider {
127
27438
	fn advance_timestamp(slot_duration: u64) {
128
27438
		if TIMESTAMP.load(Ordering::SeqCst) == 0 {
129
890
			// Initialize timestamp inherent provider
130
890
			TIMESTAMP.store(
131
890
				sp_timestamp::Timestamp::current().as_millis(),
132
890
				Ordering::SeqCst,
133
890
			);
134
26548
		} else {
135
26548
			TIMESTAMP.fetch_add(slot_duration, Ordering::SeqCst);
136
26548
		}
137
27438
	}
138
}
139

            
140
#[async_trait::async_trait]
141
impl sp_inherents::InherentDataProvider for MockTimestampInherentDataProvider {
142
	async fn provide_inherent_data(
143
		&self,
144
		inherent_data: &mut sp_inherents::InherentData,
145
27438
	) -> Result<(), sp_inherents::Error> {
146
27438
		inherent_data.put_data(
147
27438
			sp_timestamp::INHERENT_IDENTIFIER,
148
27438
			&TIMESTAMP.load(Ordering::SeqCst),
149
27438
		)
150
54876
	}
151

            
152
	async fn try_handle_error(
153
		&self,
154
		_identifier: &sp_inherents::InherentIdentifier,
155
		_error: &[u8],
156
	) -> Option<Result<(), sp_inherents::Error>> {
157
		// The pallet never reports error.
158
		None
159
	}
160
}
161

            
162
#[cfg(feature = "runtime-benchmarks")]
163
pub type HostFunctions = (
164
	frame_benchmarking::benchmarking::HostFunctions,
165
	ParachainHostFunctions,
166
	moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
167
);
168
#[cfg(not(feature = "runtime-benchmarks"))]
169
pub type HostFunctions = (
170
	ParachainHostFunctions,
171
	moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
172
);
173

            
174
/// Block Import Pipeline used.
175
pub enum BlockImportPipeline<T, E> {
176
	/// Used in dev mode to import new blocks as best blocks.
177
	Dev(T),
178
	/// Used in parachain mode.
179
	Parachain(E),
180
}
181

            
182
/// A trait that must be implemented by all moon* runtimes executors.
183
///
184
/// This feature allows, for instance, to customize the client extensions according to the type
185
/// of network.
186
/// For the moment, this feature is only used to specify the first block compatible with
187
/// ed25519-zebra, but it could be used for other things in the future.
188
pub trait ClientCustomizations {
189
	/// The host function ed25519_verify has changed its behavior in the substrate history,
190
	/// because of the change from lib ed25519-dalek to lib ed25519-zebra.
191
	/// Some networks may have old blocks that are not compatible with ed25519-zebra,
192
	/// for these networks this function should return the 1st block compatible with the new lib.
193
	/// If this function returns None (default behavior), it implies that all blocks are compatible
194
	/// with the new lib (ed25519-zebra).
195
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
196
		None
197
	}
198
}
199

            
200
#[cfg(feature = "moonbeam-native")]
201
pub struct MoonbeamCustomizations;
202
#[cfg(feature = "moonbeam-native")]
203
impl ClientCustomizations for MoonbeamCustomizations {
204
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
205
		Some(2_000_000)
206
	}
207
}
208

            
209
#[cfg(feature = "moonriver-native")]
210
pub struct MoonriverCustomizations;
211
#[cfg(feature = "moonriver-native")]
212
impl ClientCustomizations for MoonriverCustomizations {
213
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
214
		Some(3_000_000)
215
	}
216
}
217

            
218
#[cfg(feature = "moonbase-native")]
219
pub struct MoonbaseCustomizations;
220
#[cfg(feature = "moonbase-native")]
221
impl ClientCustomizations for MoonbaseCustomizations {
222
942
	fn first_block_number_compatible_with_ed25519_zebra() -> Option<u32> {
223
942
		Some(3_000_000)
224
942
	}
225
}
226

            
227
/// Trivial enum representing runtime variant
228
#[derive(Clone)]
229
pub enum RuntimeVariant {
230
	#[cfg(feature = "moonbeam-native")]
231
	Moonbeam,
232
	#[cfg(feature = "moonriver-native")]
233
	Moonriver,
234
	#[cfg(feature = "moonbase-native")]
235
	Moonbase,
236
	Unrecognized,
237
}
238

            
239
impl RuntimeVariant {
240
	pub fn from_chain_spec(chain_spec: &Box<dyn ChainSpec>) -> Self {
241
		match chain_spec {
242
			#[cfg(feature = "moonbeam-native")]
243
			spec if spec.is_moonbeam() => Self::Moonbeam,
244
			#[cfg(feature = "moonriver-native")]
245
			spec if spec.is_moonriver() => Self::Moonriver,
246
			#[cfg(feature = "moonbase-native")]
247
			spec if spec.is_moonbase() => Self::Moonbase,
248
			_ => Self::Unrecognized,
249
		}
250
	}
251
}
252

            
253
/// Can be called for a `Configuration` to check if it is a configuration for
254
/// the `Moonbeam` network.
255
pub trait IdentifyVariant {
256
	/// Returns `true` if this is a configuration for the `Moonbase` network.
257
	fn is_moonbase(&self) -> bool;
258

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

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

            
265
	/// Returns `true` if this is a configuration for a dev network.
266
	fn is_dev(&self) -> bool;
267
}
268

            
269
impl IdentifyVariant for Box<dyn ChainSpec> {
270
	fn is_moonbase(&self) -> bool {
271
		self.id().starts_with("moonbase")
272
	}
273

            
274
942
	fn is_moonbeam(&self) -> bool {
275
942
		self.id().starts_with("moonbeam")
276
942
	}
277

            
278
942
	fn is_moonriver(&self) -> bool {
279
942
		self.id().starts_with("moonriver")
280
942
	}
281

            
282
940
	fn is_dev(&self) -> bool {
283
940
		self.chain_type() == sc_chain_spec::ChainType::Development
284
940
	}
285
}
286

            
287
942
pub fn frontier_database_dir(config: &Configuration, path: &str) -> std::path::PathBuf {
288
942
	config
289
942
		.base_path
290
942
		.config_dir(config.chain_spec.id())
291
942
		.join("frontier")
292
942
		.join(path)
293
942
}
294

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

            
366
942
	Ok(frontier_backend)
367
942
}
368

            
369
use sp_runtime::{traits::BlakeTwo256, DigestItem, Percent};
370

            
371
pub const SOFT_DEADLINE_PERCENT: Percent = Percent::from_percent(100);
372

            
373
/// Builds a new object suitable for chain operations.
374
#[allow(clippy::type_complexity)]
375
pub fn new_chain_ops(
376
	config: &mut Configuration,
377
	rpc_config: &RpcConfig,
378
	legacy_block_import_strategy: bool,
379
) -> Result<
380
	(
381
		Arc<Client>,
382
		Arc<FullBackend>,
383
		sc_consensus::BasicQueue<Block>,
384
		TaskManager,
385
	),
386
	ServiceError,
387
> {
388
	match &config.chain_spec {
389
		#[cfg(feature = "moonriver-native")]
390
		spec if spec.is_moonriver() => new_chain_ops_inner::<
391
			moonriver_runtime::RuntimeApi,
392
			MoonriverCustomizations,
393
		>(config, rpc_config, legacy_block_import_strategy),
394
		#[cfg(feature = "moonbeam-native")]
395
		spec if spec.is_moonbeam() => new_chain_ops_inner::<
396
			moonbeam_runtime::RuntimeApi,
397
			MoonbeamCustomizations,
398
		>(config, rpc_config, legacy_block_import_strategy),
399
		#[cfg(feature = "moonbase-native")]
400
		_ => new_chain_ops_inner::<moonbase_runtime::RuntimeApi, MoonbaseCustomizations>(
401
			config,
402
			rpc_config,
403
			legacy_block_import_strategy,
404
		),
405
		#[cfg(not(feature = "moonbase-native"))]
406
		_ => panic!("invalid chain spec"),
407
	}
408
}
409

            
410
#[allow(clippy::type_complexity)]
411
fn new_chain_ops_inner<RuntimeApi, Customizations>(
412
	config: &mut Configuration,
413
	rpc_config: &RpcConfig,
414
	legacy_block_import_strategy: bool,
415
) -> Result<
416
	(
417
		Arc<Client>,
418
		Arc<FullBackend>,
419
		sc_consensus::BasicQueue<Block>,
420
		TaskManager,
421
	),
422
	ServiceError,
423
>
424
where
425
	Client: From<Arc<crate::FullClient<RuntimeApi>>>,
426
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
427
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
428
	Customizations: ClientCustomizations + 'static,
429
{
430
	config.keystore = sc_service::config::KeystoreConfig::InMemory;
431
	let PartialComponents {
432
		client,
433
		backend,
434
		import_queue,
435
		task_manager,
436
		..
437
	} = new_partial::<RuntimeApi, Customizations>(
438
		config,
439
		rpc_config,
440
		config.chain_spec.is_dev(),
441
		legacy_block_import_strategy,
442
	)?;
443
	Ok((
444
		Arc::new(Client::from(client)),
445
		backend,
446
		import_queue,
447
		task_manager,
448
	))
449
}
450

            
451
// If we're using prometheus, use a registry with a prefix of `moonbeam`.
452
942
fn set_prometheus_registry(
453
942
	config: &mut Configuration,
454
942
	skip_prefix: bool,
455
942
) -> Result<(), ServiceError> {
456
942
	if let Some(PrometheusConfig { registry, .. }) = config.prometheus_config.as_mut() {
457
		let labels = hashmap! {
458
			"chain".into() => config.chain_spec.id().into(),
459
		};
460
		let prefix = if skip_prefix {
461
			None
462
		} else {
463
			Some("moonbeam".into())
464
		};
465

            
466
		*registry = Registry::new_custom(prefix, Some(labels))?;
467
942
	}
468

            
469
942
	Ok(())
470
942
}
471

            
472
/// Builds the PartialComponents for a parachain or development service
473
///
474
/// Use this function if you don't actually need the full service, but just the partial in order to
475
/// be able to perform chain operations.
476
#[allow(clippy::type_complexity)]
477
942
pub fn new_partial<RuntimeApi, Customizations>(
478
942
	config: &mut Configuration,
479
942
	rpc_config: &RpcConfig,
480
942
	dev_service: bool,
481
942
	legacy_block_import_strategy: bool,
482
942
) -> PartialComponentsResult<FullClient<RuntimeApi>, FullBackend>
483
942
where
484
942
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
485
942
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
486
942
	Customizations: ClientCustomizations + 'static,
487
942
{
488
942
	set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
489

            
490
	// Use ethereum style for subscription ids
491
942
	config.rpc.id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
492

            
493
942
	let telemetry = config
494
942
		.telemetry_endpoints
495
942
		.clone()
496
942
		.filter(|x| !x.is_empty())
497
942
		.map(|endpoints| -> Result<_, sc_telemetry::Error> {
498
			let worker = TelemetryWorker::new(16)?;
499
			let telemetry = worker.handle().new_telemetry(endpoints);
500
			Ok((worker, telemetry))
501
942
		})
502
942
		.transpose()?;
503

            
504
942
	let heap_pages = config
505
942
		.executor
506
942
		.default_heap_pages
507
942
		.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
508
			extra_pages: h as _,
509
942
		});
510
942
	let mut wasm_builder = WasmExecutor::builder()
511
942
		.with_execution_method(config.executor.wasm_method)
512
942
		.with_onchain_heap_alloc_strategy(heap_pages)
513
942
		.with_offchain_heap_alloc_strategy(heap_pages)
514
942
		.with_ignore_onchain_heap_pages(true)
515
942
		.with_max_runtime_instances(config.executor.max_runtime_instances)
516
942
		.with_runtime_cache_size(config.executor.runtime_cache_size);
517

            
518
942
	if let Some(ref wasmtime_precompiled_path) = config.executor.wasmtime_precompiled {
519
940
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
520
940
	}
521

            
522
942
	let executor = wasm_builder.build();
523

            
524
942
	let (client, backend, keystore_container, task_manager) =
525
942
		sc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
526
942
			config,
527
942
			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
528
942
			executor,
529
942
			true,
530
942
		)?;
531

            
532
942
	if let Some(block_number) = Customizations::first_block_number_compatible_with_ed25519_zebra() {
533
942
		client
534
942
			.execution_extensions()
535
942
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
536
942
			Block,
537
942
			sp_io::UseDalekExt,
538
942
		>::new(block_number));
539
942
	}
540

            
541
942
	let client = Arc::new(client);
542
942

            
543
942
	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
544
942

            
545
942
	let telemetry = telemetry.map(|(worker, telemetry)| {
546
		task_manager
547
			.spawn_handle()
548
			.spawn("telemetry", None, worker.run());
549
		telemetry
550
942
	});
551

            
552
942
	let maybe_select_chain = if dev_service {
553
940
		Some(sc_consensus::LongestChain::new(backend.clone()))
554
	} else {
555
2
		None
556
	};
557

            
558
942
	let transaction_pool = sc_transaction_pool::Builder::new(
559
942
		task_manager.spawn_essential_handle(),
560
942
		client.clone(),
561
942
		config.role.is_authority().into(),
562
942
	)
563
942
	.with_options(config.transaction_pool.clone())
564
942
	.with_prometheus(config.prometheus_registry())
565
942
	.build();
566
942

            
567
942
	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
568
942
	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
569

            
570
942
	let frontier_backend = Arc::new(open_frontier_backend(client.clone(), config, rpc_config)?);
571
942
	let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
572
942

            
573
942
	let create_inherent_data_providers = move |_, _| async move {
574
		let time = sp_timestamp::InherentDataProvider::from_system_time();
575
		Ok((time,))
576
	};
577

            
578
942
	let (import_queue, block_import) = if dev_service {
579
		(
580
940
			nimbus_consensus::import_queue(
581
940
				client.clone(),
582
940
				frontier_block_import.clone(),
583
940
				create_inherent_data_providers,
584
940
				&task_manager.spawn_essential_handle(),
585
940
				config.prometheus_registry(),
586
940
				legacy_block_import_strategy,
587
940
				false,
588
940
			)?,
589
940
			BlockImportPipeline::Dev(frontier_block_import),
590
		)
591
	} else {
592
2
		let parachain_block_import = if legacy_block_import_strategy {
593
			ParachainBlockImport::new_with_delayed_best_block(
594
				frontier_block_import,
595
				backend.clone(),
596
			)
597
		} else {
598
2
			ParachainBlockImport::new(frontier_block_import, backend.clone())
599
		};
600
		(
601
2
			nimbus_consensus::import_queue(
602
2
				client.clone(),
603
2
				parachain_block_import.clone(),
604
2
				create_inherent_data_providers,
605
2
				&task_manager.spawn_essential_handle(),
606
2
				config.prometheus_registry(),
607
2
				legacy_block_import_strategy,
608
2
				false,
609
2
			)?,
610
2
			BlockImportPipeline::Parachain(parachain_block_import),
611
		)
612
	};
613

            
614
942
	Ok(PartialComponents {
615
942
		backend,
616
942
		client,
617
942
		import_queue,
618
942
		keystore_container,
619
942
		task_manager,
620
942
		transaction_pool: transaction_pool.into(),
621
942
		select_chain: maybe_select_chain,
622
942
		other: (
623
942
			block_import,
624
942
			filter_pool,
625
942
			telemetry,
626
942
			telemetry_worker_handle,
627
942
			frontier_backend,
628
942
			fee_history_cache,
629
942
		),
630
942
	})
631
942
}
632

            
633
async fn build_relay_chain_interface(
634
	polkadot_config: Configuration,
635
	parachain_config: &Configuration,
636
	telemetry_worker_handle: Option<TelemetryWorkerHandle>,
637
	task_manager: &mut TaskManager,
638
	collator_options: CollatorOptions,
639
	hwbench: Option<sc_sysinfo::HwBench>,
640
) -> RelayChainResult<(
641
	Arc<(dyn RelayChainInterface + 'static)>,
642
	Option<CollatorPair>,
643
)> {
644
	if let cumulus_client_cli::RelayChainMode::ExternalRpc(rpc_target_urls) =
645
		collator_options.relay_chain_mode
646
	{
647
		build_minimal_relay_chain_node_with_rpc(
648
			polkadot_config,
649
			parachain_config.prometheus_registry(),
650
			task_manager,
651
			rpc_target_urls,
652
		)
653
		.await
654
	} else {
655
		build_inprocess_relay_chain(
656
			polkadot_config,
657
			parachain_config,
658
			telemetry_worker_handle,
659
			task_manager,
660
			hwbench,
661
		)
662
	}
663
}
664

            
665
/// Start a node with the given parachain `Configuration` and relay chain `Configuration`.
666
///
667
/// This is the actual implementation that is abstract over the executor and the runtime api.
668
#[sc_tracing::logging::prefix_logs_with("🌗")]
669
async fn start_node_impl<RuntimeApi, Customizations, Net>(
670
	parachain_config: Configuration,
671
	polkadot_config: Configuration,
672
	collator_options: CollatorOptions,
673
	para_id: ParaId,
674
	rpc_config: RpcConfig,
675
	block_authoring_duration: Duration,
676
	hwbench: Option<sc_sysinfo::HwBench>,
677
	legacy_block_import_strategy: bool,
678
	max_pov_percentage: u8,
679
) -> sc_service::error::Result<(TaskManager, Arc<FullClient<RuntimeApi>>)>
680
where
681
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
682
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
683
	Customizations: ClientCustomizations + 'static,
684
	Net: NetworkBackend<Block, Hash>,
685
{
686
	let mut parachain_config = prepare_node_config(parachain_config);
687

            
688
	let params = new_partial::<RuntimeApi, Customizations>(
689
		&mut parachain_config,
690
		&rpc_config,
691
		false,
692
		legacy_block_import_strategy,
693
	)?;
694
	let (
695
		block_import,
696
		filter_pool,
697
		mut telemetry,
698
		telemetry_worker_handle,
699
		frontier_backend,
700
		fee_history_cache,
701
	) = params.other;
702

            
703
	let client = params.client.clone();
704
	let backend = params.backend.clone();
705
	let mut task_manager = params.task_manager;
706

            
707
	let (relay_chain_interface, collator_key) = build_relay_chain_interface(
708
		polkadot_config,
709
		&parachain_config,
710
		telemetry_worker_handle,
711
		&mut task_manager,
712
		collator_options.clone(),
713
		hwbench.clone(),
714
	)
715
	.await
716
	.map_err(|e| sc_service::Error::Application(Box::new(e) as Box<_>))?;
717

            
718
	let force_authoring = parachain_config.force_authoring;
719
	let collator = parachain_config.role.is_authority();
720
	let prometheus_registry = parachain_config.prometheus_registry().cloned();
721
	let transaction_pool = params.transaction_pool.clone();
722
	let import_queue_service = params.import_queue.service();
723
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(
724
		&parachain_config.network,
725
		prometheus_registry.clone(),
726
	);
727

            
728
	let (network, system_rpc_tx, tx_handler_controller, sync_service) =
729
		cumulus_client_service::build_network(cumulus_client_service::BuildNetworkParams {
730
			parachain_config: &parachain_config,
731
			client: client.clone(),
732
			transaction_pool: transaction_pool.clone(),
733
			spawn_handle: task_manager.spawn_handle(),
734
			import_queue: params.import_queue,
735
			para_id: para_id.clone(),
736
			relay_chain_interface: relay_chain_interface.clone(),
737
			net_config,
738
			sybil_resistance_level: CollatorSybilResistance::Resistant,
739
		})
740
		.await?;
741

            
742
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
743
	let fee_history_limit = rpc_config.fee_history_limit;
744

            
745
	// Sinks for pubsub notifications.
746
	// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
747
	// The MappingSyncWorker sends through the channel on block import and the subscription emits a
748
	// notification to the subscriber on receiving a message through this channel.
749
	// This way we avoid race conditions when using native substrate block import notification
750
	// stream.
751
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
752
		fc_mapping_sync::EthereumBlockNotification<Block>,
753
	> = Default::default();
754
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
755

            
756
	rpc::spawn_essential_tasks(
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
		sync_service.clone(),
768
		pubsub_notification_sinks.clone(),
769
	);
770

            
771
	let ethapi_cmd = rpc_config.ethapi.clone();
772
	let tracing_requesters =
773
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
774
			rpc::tracing::spawn_tracing_tasks(
775
				&rpc_config,
776
				prometheus_registry.clone(),
777
				rpc::SpawnTasksParams {
778
					task_manager: &task_manager,
779
					client: client.clone(),
780
					substrate_backend: backend.clone(),
781
					frontier_backend: frontier_backend.clone(),
782
					filter_pool: filter_pool.clone(),
783
					overrides: overrides.clone(),
784
					fee_history_limit,
785
					fee_history_cache: fee_history_cache.clone(),
786
				},
787
			)
788
		} else {
789
			rpc::tracing::RpcRequesters {
790
				debug: None,
791
				trace: None,
792
			}
793
		};
794

            
795
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
796
		task_manager.spawn_handle(),
797
		overrides.clone(),
798
		rpc_config.eth_log_block_cache,
799
		rpc_config.eth_statuses_cache,
800
		prometheus_registry.clone(),
801
	));
802

            
803
	let rpc_builder = {
804
		let client = client.clone();
805
		let pool = transaction_pool.clone();
806
		let network = network.clone();
807
		let sync = sync_service.clone();
808
		let filter_pool = filter_pool.clone();
809
		let frontier_backend = frontier_backend.clone();
810
		let backend = backend.clone();
811
		let ethapi_cmd = ethapi_cmd.clone();
812
		let max_past_logs = rpc_config.max_past_logs;
813
		let max_block_range = rpc_config.max_block_range;
814
		let overrides = overrides.clone();
815
		let fee_history_cache = fee_history_cache.clone();
816
		let block_data_cache = block_data_cache.clone();
817
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
818

            
819
		let keystore = params.keystore_container.keystore();
820
		move |subscription_task_executor| {
821
			#[cfg(feature = "moonbase-native")]
822
			let forced_parent_hashes = {
823
				let mut forced_parent_hashes = BTreeMap::new();
824
				// Fixes for https://github.com/paritytech/frontier/pull/570
825
				// #1648995
826
				forced_parent_hashes.insert(
827
					H256::from_str(
828
						"0xa352fee3eef9c554a31ec0612af887796a920613358abf3353727760ea14207b",
829
					)
830
					.expect("must be valid hash"),
831
					H256::from_str(
832
						"0x0d0fd88778aec08b3a83ce36387dbf130f6f304fc91e9a44c9605eaf8a80ce5d",
833
					)
834
					.expect("must be valid hash"),
835
				);
836
				Some(forced_parent_hashes)
837
			};
838
			#[cfg(not(feature = "moonbase-native"))]
839
			let forced_parent_hashes = None;
840

            
841
			let deps = rpc::FullDeps {
842
				backend: backend.clone(),
843
				client: client.clone(),
844
				command_sink: None,
845
				ethapi_cmd: ethapi_cmd.clone(),
846
				filter_pool: filter_pool.clone(),
847
				frontier_backend: match &*frontier_backend {
848
					fc_db::Backend::KeyValue(b) => b.clone(),
849
					fc_db::Backend::Sql(b) => b.clone(),
850
				},
851
				graph: pool.clone(),
852
				pool: pool.clone(),
853
				is_authority: collator,
854
				max_past_logs,
855
				max_block_range,
856
				fee_history_limit,
857
				fee_history_cache: fee_history_cache.clone(),
858
				network: network.clone(),
859
				sync: sync.clone(),
860
				dev_rpc_data: None,
861
				block_data_cache: block_data_cache.clone(),
862
				overrides: overrides.clone(),
863
				forced_parent_hashes,
864
			};
865
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
866
				client.clone(),
867
				keystore.clone(),
868
			));
869
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
870
				rpc::create_full(
871
					deps,
872
					subscription_task_executor,
873
					Some(crate::rpc::TracingConfig {
874
						tracing_requesters: tracing_requesters.clone(),
875
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
876
					}),
877
					pubsub_notification_sinks.clone(),
878
					pending_consensus_data_provider,
879
					para_id,
880
				)
881
				.map_err(Into::into)
882
			} else {
883
				rpc::create_full(
884
					deps,
885
					subscription_task_executor,
886
					None,
887
					pubsub_notification_sinks.clone(),
888
					pending_consensus_data_provider,
889
					para_id,
890
				)
891
				.map_err(Into::into)
892
			}
893
		}
894
	};
895

            
896
	sc_service::spawn_tasks(sc_service::SpawnTasksParams {
897
		rpc_builder: Box::new(rpc_builder),
898
		client: client.clone(),
899
		transaction_pool: transaction_pool.clone(),
900
		task_manager: &mut task_manager,
901
		config: parachain_config,
902
		keystore: params.keystore_container.keystore(),
903
		backend: backend.clone(),
904
		network: network.clone(),
905
		sync_service: sync_service.clone(),
906
		system_rpc_tx,
907
		tx_handler_controller,
908
		telemetry: telemetry.as_mut(),
909
	})?;
910

            
911
	if let Some(hwbench) = hwbench {
912
		sc_sysinfo::print_hwbench(&hwbench);
913

            
914
		if let Some(ref mut telemetry) = telemetry {
915
			let telemetry_handle = telemetry.handle();
916
			task_manager.spawn_handle().spawn(
917
				"telemetry_hwbench",
918
				None,
919
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
920
			);
921
		}
922
	}
923

            
924
	let announce_block = {
925
		let sync_service = sync_service.clone();
926
		Arc::new(move |hash, data| sync_service.announce_block(hash, data))
927
	};
928

            
929
	let relay_chain_slot_duration = Duration::from_secs(6);
930
	let overseer_handle = relay_chain_interface
931
		.overseer_handle()
932
		.map_err(|e| sc_service::Error::Application(Box::new(e)))?;
933

            
934
	start_relay_chain_tasks(StartRelayChainTasksParams {
935
		client: client.clone(),
936
		announce_block: announce_block.clone(),
937
		para_id,
938
		relay_chain_interface: relay_chain_interface.clone(),
939
		task_manager: &mut task_manager,
940
		da_recovery_profile: if collator {
941
			DARecoveryProfile::Collator
942
		} else {
943
			DARecoveryProfile::FullNode
944
		},
945
		import_queue: import_queue_service,
946
		relay_chain_slot_duration,
947
		recovery_handle: Box::new(overseer_handle.clone()),
948
		sync_service: sync_service.clone(),
949
	})?;
950

            
951
	let BlockImportPipeline::Parachain(block_import) = block_import else {
952
		return Err(sc_service::Error::Other(
953
			"Block import pipeline is not for parachain".into(),
954
		));
955
	};
956

            
957
	if collator {
958
		start_consensus::<RuntimeApi, _>(
959
			backend.clone(),
960
			client.clone(),
961
			block_import,
962
			prometheus_registry.as_ref(),
963
			telemetry.as_ref().map(|t| t.handle()),
964
			&task_manager,
965
			relay_chain_interface.clone(),
966
			transaction_pool,
967
			params.keystore_container.keystore(),
968
			para_id,
969
			collator_key.expect("Command line arguments do not allow this. qed"),
970
			overseer_handle,
971
			announce_block,
972
			force_authoring,
973
			relay_chain_slot_duration,
974
			block_authoring_duration,
975
			sync_service.clone(),
976
			max_pov_percentage,
977
		)?;
978
	}
979

            
980
	Ok((task_manager, client))
981
}
982

            
983
fn start_consensus<RuntimeApi, SO>(
984
	backend: Arc<FullBackend>,
985
	client: Arc<FullClient<RuntimeApi>>,
986
	block_import: ParachainBlockImport<FullClient<RuntimeApi>, FullBackend>,
987
	prometheus_registry: Option<&Registry>,
988
	telemetry: Option<TelemetryHandle>,
989
	task_manager: &TaskManager,
990
	relay_chain_interface: Arc<dyn RelayChainInterface>,
991
	transaction_pool: Arc<
992
		sc_transaction_pool::TransactionPoolHandle<Block, FullClient<RuntimeApi>>,
993
	>,
994
	keystore: KeystorePtr,
995
	para_id: ParaId,
996
	collator_key: CollatorPair,
997
	overseer_handle: OverseerHandle,
998
	announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
999
	force_authoring: bool,
	relay_chain_slot_duration: Duration,
	block_authoring_duration: Duration,
	sync_oracle: SO,
	max_pov_percentage: u8,
) -> 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 author = nimbus_primitives::InherentDataProvider;
		let randomness = session_keys_primitives::InherentDataProvider;
		Ok((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,
			)
		};
	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![
					// TODO: Can be removed after runtime 4000
					#[allow(deprecated)]
					moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
					relay_chain::well_known_keys::EPOCH_INDEX.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,
				max_pov_percentage,
			},
		),
	);
	Ok(())
}
/// Start a normal parachain node.
// Rustfmt wants to format the closure with space indentation.
#[rustfmt::skip]
pub async fn start_node<RuntimeApi, Customizations>(
	parachain_config: Configuration,
	polkadot_config: Configuration,
	collator_options: CollatorOptions,
	para_id: ParaId,
	rpc_config: RpcConfig,
	block_authoring_duration: Duration,
	hwbench: Option<sc_sysinfo::HwBench>,
	legacy_block_import_strategy: bool,
	max_pov_percentage: u8,
) -> 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,
		block_authoring_duration,
		hwbench,
		legacy_block_import_strategy,
		max_pov_percentage,
	)
	.await
}
/// Builds a new development service. This service uses manual seal, and mocks
/// the parachain inherent.
940
pub async fn new_dev<RuntimeApi, Customizations, Net>(
940
	mut config: Configuration,
940
	para_id: Option<u32>,
940
	_author_id: Option<NimbusId>,
940
	sealing: moonbeam_cli_opt::Sealing,
940
	rpc_config: RpcConfig,
940
	hwbench: Option<sc_sysinfo::HwBench>,
940
) -> Result<TaskManager, ServiceError>
940
where
940
	RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi>> + Send + Sync + 'static,
940
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
940
	Customizations: ClientCustomizations + 'static,
940
	Net: NetworkBackend<Block, Hash>,
940
{
	use async_io::Timer;
	use futures::Stream;
	use sc_consensus_manual_seal::{run_manual_seal, EngineCommand, ManualSealParams};
	let sc_service::PartialComponents {
940
		client,
940
		backend,
940
		mut task_manager,
940
		import_queue,
940
		keystore_container,
940
		select_chain: maybe_select_chain,
940
		transaction_pool,
940
		other:
940
			(
940
				block_import_pipeline,
940
				filter_pool,
940
				mut telemetry,
940
				_telemetry_worker_handle,
940
				frontier_backend,
940
				fee_history_cache,
			),
940
	} = new_partial::<RuntimeApi, Customizations>(&mut config, &rpc_config, true, true)?;
940
	let block_import = if let BlockImportPipeline::Dev(block_import) = block_import_pipeline {
940
		block_import
	} else {
		return Err(ServiceError::Other(
			"Block import pipeline is not dev".to_string(),
		));
	};
940
	let prometheus_registry = config.prometheus_registry().cloned();
940
	let net_config =
940
		FullNetworkConfiguration::<_, _, Net>::new(&config.network, prometheus_registry.clone());
940

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

            
940
	let parachain_id: ParaId = para_id
940
		.expect("para ID should be specified for dev service")
940
		.into();
940

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

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

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

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

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

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

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

            
27438
						// Get the mocked timestamp
27438
						let timestamp = TIMESTAMP.load(Ordering::SeqCst);
27438
						// Calculate mocked slot number
27438
						let slot = timestamp.saturating_div(RELAY_CHAIN_SLOT_DURATION_MILLIS);
27438

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

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

            
27438
						let randomness = session_keys_primitives::InherentDataProvider;
27438

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

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

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

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

            
1880
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
1880
				client.clone(),
1880
				keystore.clone(),
1880
			));
1880
			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,
					parachain_id,
				)
				.map_err(Into::into)
			} else {
1880
				rpc::create_full(
1880
					deps,
1880
					subscription_task_executor,
1880
					None,
1880
					pubsub_notification_sinks.clone(),
1880
					pending_consensus_data_provider,
1880
					parachain_id,
1880
				)
1880
				.map_err(Into::into)
			}
1880
		}
	};
940
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
940
		network,
940
		client,
940
		keystore: keystore_container.keystore(),
940
		task_manager: &mut task_manager,
940
		transaction_pool,
940
		rpc_builder: Box::new(rpc_builder),
940
		backend,
940
		system_rpc_tx,
940
		sync_service: sync_service.clone(),
940
		config,
940
		tx_handler_controller,
940
		telemetry: None,
940
	})?;
940
	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),
			);
		}
940
	}
940
	log::info!("Development Service Ready");
940
	Ok(task_manager)
940
}
#[cfg(test)]
mod tests {
	use crate::chain_spec::moonbase::ChainSpec;
	use crate::chain_spec::Extensions;
	use jsonrpsee::server::BatchRequestConfig;
	use moonbase_runtime::{currency::UNIT, AccountId};
	use prometheus::{proto::LabelPair, Counter};
	use sc_network::config::NetworkConfiguration;
	use sc_service::config::RpcConfiguration;
	use sc_service::ChainType;
	use sc_service::{
		config::{BasePath, DatabaseSource, KeystoreConfig},
		Configuration, Role,
	};
	use std::path::Path;
	use std::str::FromStr;
	use super::*;
	#[test]
	fn test_set_prometheus_registry_uses_moonbeam_prefix() {
		let counter_name = "my_counter";
		let expected_metric_name = "moonbeam_my_counter";
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config("test")
		};
		set_prometheus_registry(&mut config, false).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
		assert_eq!(actual_metric_name.as_str(), expected_metric_name);
	}
	#[test]
	fn test_set_prometheus_registry_skips_moonbeam_prefix() {
		let counter_name = "my_counter";
		let counter = Box::new(Counter::new(counter_name, "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config("test")
		};
		set_prometheus_registry(&mut config, true).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_metric_name = reg.gather().first().unwrap().get_name().to_string();
		assert_eq!(actual_metric_name.as_str(), counter_name);
	}
	#[test]
	fn test_set_prometheus_registry_adds_chain_id_as_label() {
		let input_chain_id = "moonriver";
		let mut expected_label = LabelPair::default();
		expected_label.set_name("chain".to_owned());
		expected_label.set_value("moonriver".to_owned());
		let expected_chain_label = Some(expected_label);
		let counter = Box::new(Counter::new("foo", "foobar").unwrap());
		let mut config = Configuration {
			prometheus_config: Some(PrometheusConfig::new_with_default_registry(
				"0.0.0.0:8080".parse().unwrap(),
				"".into(),
			)),
			..test_config(input_chain_id)
		};
		set_prometheus_registry(&mut config, false).unwrap();
		// generate metric
		let reg = config.prometheus_registry().unwrap();
		reg.register(counter.clone()).unwrap();
		counter.inc();
		let actual_chain_label = reg
			.gather()
			.first()
			.unwrap()
			.get_metric()
			.first()
			.unwrap()
			.get_label()
			.into_iter()
			.find(|x| x.get_name() == "chain")
			.cloned();
		assert_eq!(actual_chain_label, expected_chain_label);
	}
	#[test]
	fn dalek_does_not_panic() {
		use futures::executor::block_on;
		use sc_block_builder::BlockBuilderBuilder;
		use sc_client_db::{Backend, BlocksPruning, DatabaseSettings, DatabaseSource, PruningMode};
		use sp_api::ProvideRuntimeApi;
		use sp_consensus::BlockOrigin;
		use substrate_test_runtime::TestAPI;
		use substrate_test_runtime_client::runtime::Block;
		use substrate_test_runtime_client::{
			ClientBlockImportExt, TestClientBuilder, TestClientBuilderExt,
		};
		fn zero_ed_pub() -> sp_core::ed25519::Public {
			sp_core::ed25519::Public::default()
		}
		// This is an invalid signature
		// this breaks after ed25519 1.3. It makes the signature panic at creation
		// This test ensures we should never panic
		fn invalid_sig() -> sp_core::ed25519::Signature {
			let signature = hex_literal::hex!(
				"a25b94f9c64270fdfffa673f11cfe961633e3e4972e6940a3cf
		7351dd90b71447041a83583a52cee1cf21b36ba7fd1d0211dca58b48d997fc78d9bc82ab7a38e"
			);
			sp_core::ed25519::Signature::from_raw(signature[0..64].try_into().unwrap())
		}
		let tmp = tempfile::tempdir().unwrap();
		let backend = Arc::new(
			Backend::new(
				DatabaseSettings {
					trie_cache_maximum_size: Some(1 << 20),
					state_pruning: Some(PruningMode::ArchiveAll),
					blocks_pruning: BlocksPruning::KeepAll,
					source: DatabaseSource::RocksDb {
						path: tmp.path().into(),
						cache_size: 1024,
					},
				},
				u64::MAX,
			)
			.unwrap(),
		);
		let client = TestClientBuilder::with_backend(backend).build();
		client
			.execution_extensions()
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
			Block,
			sp_io::UseDalekExt,
		>::new(1));
		let a1 = BlockBuilderBuilder::new(&client)
			.on_parent_block(client.chain_info().genesis_hash)
			.with_parent_block_number(0)
			// Enable proof recording if required. This call is optional.
			.enable_proof_recording()
			.build()
			.unwrap()
			.build()
			.unwrap()
			.block;
		block_on(client.import(BlockOrigin::NetworkInitialSync, a1.clone())).unwrap();
		// On block zero it will use dalek
		// shouldnt panic on importing invalid sig
		assert!(!client
			.runtime_api()
			.verify_ed25519(
				client.chain_info().genesis_hash,
				invalid_sig(),
				zero_ed_pub(),
				vec![]
			)
			.unwrap());
	}
	fn test_config(chain_id: &str) -> Configuration {
		let network_config = NetworkConfiguration::new("", "", Default::default(), None);
		let runtime = tokio::runtime::Runtime::new().expect("failed creating tokio runtime");
		let spec = ChainSpec::builder(&[0u8], Extensions::default())
			.with_name("test")
			.with_id(chain_id)
			.with_chain_type(ChainType::Local)
			.with_genesis_config(moonbase_runtime::genesis_config_preset::testnet_genesis(
				AccountId::from_str("6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b").unwrap(),
				vec![],
				vec![],
				vec![],
				vec![],
				vec![],
				1000 * UNIT,
				ParaId::new(0),
				0,
			))
			.build();
		Configuration {
			impl_name: String::from("test-impl"),
			impl_version: String::from("0.1"),
			role: Role::Full,
			tokio_handle: runtime.handle().clone(),
			transaction_pool: Default::default(),
			network: network_config,
			keystore: KeystoreConfig::Path {
				path: "key".into(),
				password: None,
			},
			database: DatabaseSource::RocksDb {
				path: "db".into(),
				cache_size: 128,
			},
			trie_cache_maximum_size: Some(16777216),
			state_pruning: Default::default(),
			blocks_pruning: sc_service::BlocksPruning::KeepAll,
			chain_spec: Box::new(spec),
			executor: Default::default(),
			wasm_runtime_overrides: Default::default(),
			rpc: RpcConfiguration {
				addr: None,
				max_connections: Default::default(),
				cors: None,
				methods: Default::default(),
				max_request_size: Default::default(),
				max_response_size: Default::default(),
				id_provider: None,
				max_subs_per_conn: Default::default(),
				port: Default::default(),
				message_buffer_capacity: Default::default(),
				batch_config: BatchRequestConfig::Unlimited,
				rate_limit: Default::default(),
				rate_limit_whitelisted_ips: vec![],
				rate_limit_trust_proxy_headers: false,
			},
			data_path: Default::default(),
			prometheus_config: None,
			telemetry_endpoints: None,
			offchain_worker: Default::default(),
			force_authoring: false,
			disable_grandpa: false,
			dev_key_seed: None,
			tracing_targets: None,
			tracing_receiver: Default::default(),
			announce_block: true,
			base_path: BasePath::new(Path::new("")),
		}
	}
}
struct PendingConsensusDataProvider<Client>
where
	Client: HeaderBackend<Block> + sp_api::ProvideRuntimeApi<Block> + Send + Sync,
	Client::Api: VrfApi<Block>,
{
	client: Arc<Client>,
	keystore: Arc<dyn Keystore>,
}
impl<Client> PendingConsensusDataProvider<Client>
where
	Client: HeaderBackend<Block> + sp_api::ProvideRuntimeApi<Block> + Send + Sync,
	Client::Api: VrfApi<Block>,
{
1880
	pub fn new(client: Arc<Client>, keystore: Arc<dyn Keystore>) -> Self {
1880
		Self { client, keystore }
1880
	}
}
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
	}
}