1
// Copyright 2024 Moonbeam foundation
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
use crate::{
18
	lazy_loading, open_frontier_backend, rpc, set_prometheus_registry, BlockImportPipeline,
19
	ClientCustomizations, FrontierBlockImport, HostFunctions, PartialComponentsResult,
20
	PendingConsensusDataProvider, RuntimeApiCollection, SOFT_DEADLINE_PERCENT,
21
};
22
use cumulus_client_parachain_inherent::{MockValidationDataInherentDataProvider, MockXcmConfig};
23
use cumulus_primitives_core::{relay_chain, BlockT, ParaId};
24
use cumulus_primitives_parachain_inherent::ParachainInherentData;
25
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
26
use fc_rpc::StorageOverrideHandler;
27
use fc_rpc_core::types::{FeeHistoryCache, FilterPool};
28
use futures::{FutureExt, StreamExt};
29
use moonbeam_cli_opt::{EthApi as EthApiCmd, LazyLoadingConfig, RpcConfig};
30
use moonbeam_core_primitives::{Block, Hash};
31
use nimbus_consensus::NimbusManualSealConsensusDataProvider;
32
use nimbus_primitives::NimbusId;
33
use parity_scale_codec::Encode;
34
use polkadot_primitives::{
35
	AbridgedHostConfiguration, AsyncBackingParams, PersistedValidationData, Slot, UpgradeGoAhead,
36
	UpgradeRestriction,
37
};
38
use sc_chain_spec::{get_extension, BuildGenesisBlock, GenesisBlockBuilder};
39
use sc_client_api::{Backend, BadBlocks, ExecutorProvider, ForkBlocks, StorageProvider};
40
use sc_executor::{HeapAllocStrategy, RuntimeVersionOf, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
41
use sc_network::config::FullNetworkConfiguration;
42
use sc_network::NetworkBackend;
43
use sc_network_common::sync::SyncMode;
44
use sc_service::{
45
	error::Error as ServiceError, ClientConfig, Configuration, Error, KeystoreContainer,
46
	LocalCallExecutor, PartialComponents, TaskManager,
47
};
48
use sc_telemetry::{TelemetryHandle, TelemetryWorker};
49
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
50
use sp_api::ConstructRuntimeApi;
51
use sp_blockchain::HeaderBackend;
52
use sp_core::traits::CodeExecutor;
53
use sp_core::{twox_128, H256};
54
use sp_runtime::traits::NumberFor;
55
use sp_storage::StorageKey;
56
use std::collections::BTreeMap;
57
use std::str::FromStr;
58
use std::sync::{Arc, Mutex};
59
use std::time::Duration;
60

            
61
pub mod backend;
62
pub mod call_executor;
63
mod client;
64
mod helpers;
65
mod lock;
66
mod manual_sealing;
67
mod state_overrides;
68

            
69
pub const LAZY_LOADING_LOG_TARGET: &'static str = "lazy-loading";
70

            
71
/// Lazy loading client type.
72
pub type TLazyLoadingClient<TBl, TRtApi, TExec> = sc_service::client::Client<
73
	TLazyLoadingBackend<TBl>,
74
	TLazyLoadingCallExecutor<TBl, TExec>,
75
	TBl,
76
	TRtApi,
77
>;
78

            
79
/// Lazy loading client backend type.
80
pub type TLazyLoadingBackend<TBl> = backend::Backend<TBl>;
81

            
82
/// Lazy loading client call executor type.
83
pub type TLazyLoadingCallExecutor<TBl, TExec> = call_executor::LazyLoadingCallExecutor<
84
	TBl,
85
	LocalCallExecutor<TBl, TLazyLoadingBackend<TBl>, TExec>,
86
>;
87

            
88
/// Lazy loading parts type.
89
pub type TLazyLoadingParts<TBl, TRtApi, TExec> = (
90
	TLazyLoadingClient<TBl, TRtApi, TExec>,
91
	Arc<TLazyLoadingBackend<TBl>>,
92
	KeystoreContainer,
93
	TaskManager,
94
);
95

            
96
type LazyLoadingClient<RuntimeApi> =
97
	TLazyLoadingClient<Block, RuntimeApi, WasmExecutor<HostFunctions>>;
98
type LazyLoadingBackend = TLazyLoadingBackend<Block>;
99

            
100
/// Create the initial parts of a lazy loading node.
101
pub fn new_lazy_loading_parts<TBl, TRtApi, TExec>(
102
	config: &mut Configuration,
103
	lazy_loading_config: &LazyLoadingConfig,
104
	telemetry: Option<TelemetryHandle>,
105
	executor: TExec,
106
) -> Result<TLazyLoadingParts<TBl, TRtApi, TExec>, Error>
107
where
108
	TBl: BlockT + sp_runtime::DeserializeOwned,
109
	TBl::Hash: From<H256>,
110
	TExec: CodeExecutor + RuntimeVersionOf + Clone,
111
{
112
	let backend = backend::new_lazy_loading_backend(config, &lazy_loading_config)?;
113

            
114
	let genesis_block_builder = GenesisBlockBuilder::new(
115
		config.chain_spec.as_storage_builder(),
116
		!config.no_genesis(),
117
		backend.clone(),
118
		executor.clone(),
119
	)?;
120

            
121
	new_lazy_loading_parts_with_genesis_builder(
122
		config,
123
		telemetry,
124
		executor,
125
		backend,
126
		genesis_block_builder,
127
	)
128
}
129

            
130
/// Create the initial parts of a lazy loading node.
131
pub fn new_lazy_loading_parts_with_genesis_builder<TBl, TRtApi, TExec, TBuildGenesisBlock>(
132
	config: &Configuration,
133
	telemetry: Option<TelemetryHandle>,
134
	executor: TExec,
135
	backend: Arc<TLazyLoadingBackend<TBl>>,
136
	genesis_block_builder: TBuildGenesisBlock,
137
) -> Result<TLazyLoadingParts<TBl, TRtApi, TExec>, Error>
138
where
139
	TBl: BlockT + sp_runtime::DeserializeOwned,
140
	TBl::Hash: From<H256>,
141
	TExec: CodeExecutor + RuntimeVersionOf + Clone,
142
	TBuildGenesisBlock:
143
		BuildGenesisBlock<
144
			TBl,
145
			BlockImportOperation = <TLazyLoadingBackend<TBl> as sc_client_api::backend::Backend<
146
				TBl,
147
			>>::BlockImportOperation,
148
		>,
149
{
150
	let keystore_container = KeystoreContainer::new(&config.keystore)?;
151

            
152
	let task_manager = {
153
		let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry);
154
		TaskManager::new(config.tokio_handle.clone(), registry)?
155
	};
156

            
157
	let chain_spec = &config.chain_spec;
158
	let fork_blocks = get_extension::<ForkBlocks<TBl>>(chain_spec.extensions())
159
		.cloned()
160
		.unwrap_or_default();
161

            
162
	let bad_blocks = get_extension::<BadBlocks<TBl>>(chain_spec.extensions())
163
		.cloned()
164
		.unwrap_or_default();
165

            
166
	let client = {
167
		let extensions = sc_client_api::execution_extensions::ExecutionExtensions::new(
168
			None,
169
			Arc::new(executor.clone()),
170
		);
171

            
172
		let wasm_runtime_substitutes = config
173
			.chain_spec
174
			.code_substitutes()
175
			.into_iter()
176
			.map(|(n, c)| {
177
				let number = NumberFor::<TBl>::from_str(&n).map_err(|_| {
178
					Error::Application(Box::from(format!(
179
						"Failed to parse `{}` as block number for code substitutes. \
180
						 In an old version the key for code substitute was a block hash. \
181
						 Please update the chain spec to a version that is compatible with your node.",
182
						n
183
					)))
184
				})?;
185
				Ok((number, c))
186
			})
187
			.collect::<Result<std::collections::HashMap<_, _>, Error>>()?;
188

            
189
		let client = client::new_client(
190
			backend.clone(),
191
			executor,
192
			genesis_block_builder,
193
			fork_blocks,
194
			bad_blocks,
195
			extensions,
196
			Box::new(task_manager.spawn_handle()),
197
			config
198
				.prometheus_config
199
				.as_ref()
200
				.map(|config| config.registry.clone()),
201
			telemetry,
202
			ClientConfig {
203
				offchain_worker_enabled: config.offchain_worker.enabled,
204
				offchain_indexing_api: config.offchain_worker.indexing_enabled,
205
				wasmtime_precompiled: config.executor.wasmtime_precompiled.clone(),
206
				wasm_runtime_overrides: config.wasm_runtime_overrides.clone(),
207
				no_genesis: matches!(
208
					config.network.sync_mode,
209
					SyncMode::LightState { .. } | SyncMode::Warp { .. }
210
				),
211
				wasm_runtime_substitutes,
212
				enable_import_proof_recording: false,
213
			},
214
		)?;
215

            
216
		client
217
	};
218

            
219
	Ok((client, backend, keystore_container, task_manager))
220
}
221

            
222
/// Builds the PartialComponents for a lazy loading node.
223
#[allow(clippy::type_complexity)]
224
pub fn new_lazy_loading_partial<RuntimeApi, Customizations>(
225
	config: &mut Configuration,
226
	rpc_config: &RpcConfig,
227
	lazy_loading_config: &LazyLoadingConfig,
228
) -> PartialComponentsResult<LazyLoadingClient<RuntimeApi>, LazyLoadingBackend>
229
where
230
	RuntimeApi: ConstructRuntimeApi<Block, LazyLoadingClient<RuntimeApi>> + Send + Sync + 'static,
231
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
232
	Customizations: ClientCustomizations + 'static,
233
{
234
	set_prometheus_registry(config, rpc_config.no_prometheus_prefix)?;
235

            
236
	// Use ethereum style for subscription ids
237
	config.rpc.id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
238

            
239
	let telemetry = config
240
		.telemetry_endpoints
241
		.clone()
242
		.filter(|x| !x.is_empty())
243
		.map(|endpoints| -> Result<_, sc_telemetry::Error> {
244
			let worker = TelemetryWorker::new(16)?;
245
			let telemetry = worker.handle().new_telemetry(endpoints);
246
			Ok((worker, telemetry))
247
		})
248
		.transpose()?;
249

            
250
	let heap_pages = config
251
		.executor
252
		.default_heap_pages
253
		.map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static {
254
			extra_pages: h as _,
255
		});
256
	let mut wasm_builder = WasmExecutor::builder()
257
		.with_execution_method(config.executor.wasm_method)
258
		.with_onchain_heap_alloc_strategy(heap_pages)
259
		.with_offchain_heap_alloc_strategy(heap_pages)
260
		.with_ignore_onchain_heap_pages(true)
261
		.with_max_runtime_instances(config.executor.max_runtime_instances)
262
		.with_runtime_cache_size(config.executor.runtime_cache_size);
263

            
264
	if let Some(ref wasmtime_precompiled_path) = config.executor.wasmtime_precompiled {
265
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
266
	}
267

            
268
	let executor = wasm_builder.build();
269

            
270
	let (client, backend, keystore_container, task_manager) =
271
		new_lazy_loading_parts::<Block, RuntimeApi, _>(
272
			config,
273
			lazy_loading_config,
274
			telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
275
			executor,
276
		)?;
277

            
278
	if let Some(block_number) = Customizations::first_block_number_compatible_with_ed25519_zebra() {
279
		client
280
			.execution_extensions()
281
			.set_extensions_factory(sc_client_api::execution_extensions::ExtensionBeforeBlock::<
282
			Block,
283
			sp_io::UseDalekExt,
284
		>::new(block_number));
285
	}
286

            
287
	let client = Arc::new(client);
288

            
289
	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
290

            
291
	let telemetry = telemetry.map(|(worker, telemetry)| {
292
		task_manager
293
			.spawn_handle()
294
			.spawn("telemetry", None, worker.run());
295
		telemetry
296
	});
297

            
298
	let maybe_select_chain = Some(sc_consensus::LongestChain::new(backend.clone()));
299

            
300
	let transaction_pool = sc_transaction_pool::BasicPool::new_full(
301
		config.transaction_pool.clone(),
302
		config.role.is_authority().into(),
303
		config.prometheus_registry(),
304
		task_manager.spawn_essential_handle(),
305
		client.clone(),
306
	);
307

            
308
	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
309
	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
310

            
311
	let frontier_backend = Arc::new(open_frontier_backend(client.clone(), config, rpc_config)?);
312
	let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
313

            
314
	let create_inherent_data_providers = move |_, _| async move {
315
		let time = sp_timestamp::InherentDataProvider::from_system_time();
316
		// Create a dummy parachain inherent data provider which is required to pass
317
		// the checks by the para chain system. We use dummy values because in the 'pending context'
318
		// neither do we have access to the real values nor do we need them.
319
		let (relay_parent_storage_root, relay_chain_state) =
320
			RelayStateSproofBuilder::default().into_state_root_and_proof();
321
		let vfp = PersistedValidationData {
322
			// This is a hack to make `cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases`
323
			// happy. Relay parent number can't be bigger than u32::MAX.
324
			relay_parent_number: u32::MAX,
325
			relay_parent_storage_root,
326
			..Default::default()
327
		};
328
		let parachain_inherent_data = ParachainInherentData {
329
			validation_data: vfp,
330
			relay_chain_state,
331
			downward_messages: Default::default(),
332
			horizontal_messages: Default::default(),
333
		};
334
		Ok((time, parachain_inherent_data))
335
	};
336

            
337
	let import_queue = nimbus_consensus::import_queue(
338
		client.clone(),
339
		frontier_block_import.clone(),
340
		create_inherent_data_providers,
341
		&task_manager.spawn_essential_handle(),
342
		config.prometheus_registry(),
343
		false,
344
	)?;
345
	let block_import = BlockImportPipeline::Dev(frontier_block_import);
346

            
347
	Ok(PartialComponents {
348
		backend,
349
		client,
350
		import_queue,
351
		keystore_container,
352
		task_manager,
353
		transaction_pool,
354
		select_chain: maybe_select_chain,
355
		other: (
356
			block_import,
357
			filter_pool,
358
			telemetry,
359
			telemetry_worker_handle,
360
			frontier_backend,
361
			fee_history_cache,
362
		),
363
	})
364
}
365

            
366
/// Builds a new lazy loading service. This service uses manual seal, and mocks
367
/// the parachain inherent.
368
#[sc_tracing::logging::prefix_logs_with("Lazy loading 🌗")]
369
pub async fn new_lazy_loading_service<RuntimeApi, Customizations, Net>(
370
	mut config: Configuration,
371
	_author_id: Option<NimbusId>,
372
	sealing: moonbeam_cli_opt::Sealing,
373
	rpc_config: RpcConfig,
374
	lazy_loading_config: LazyLoadingConfig,
375
	hwbench: Option<sc_sysinfo::HwBench>,
376
) -> Result<TaskManager, ServiceError>
377
where
378
	RuntimeApi: ConstructRuntimeApi<Block, LazyLoadingClient<RuntimeApi>> + Send + Sync + 'static,
379
	RuntimeApi::RuntimeApi: RuntimeApiCollection,
380
	Customizations: ClientCustomizations + 'static,
381
	Net: NetworkBackend<Block, Hash>,
382
{
383
	use async_io::Timer;
384
	use futures::Stream;
385
	use sc_consensus_manual_seal::{EngineCommand, ManualSealParams};
386

            
387
	let sc_service::PartialComponents {
388
		client,
389
		backend,
390
		mut task_manager,
391
		import_queue,
392
		keystore_container,
393
		select_chain: maybe_select_chain,
394
		transaction_pool,
395
		other:
396
			(
397
				block_import_pipeline,
398
				filter_pool,
399
				mut telemetry,
400
				_telemetry_worker_handle,
401
				frontier_backend,
402
				fee_history_cache,
403
			),
404
	} = lazy_loading::new_lazy_loading_partial::<RuntimeApi, Customizations>(
405
		&mut config,
406
		&rpc_config,
407
		&lazy_loading_config,
408
	)?;
409

            
410
	let start_delay = 10;
411
	let lazy_loading_startup_disclaimer = format!(
412
		r#"
413

            
414
		You are now running the Moonbeam client in lazy loading mode, where data is retrieved
415
		from a live RPC node on demand.
416

            
417
		Using remote state from: {rpc}
418
		Forking from block: {fork_block}
419

            
420
		To ensure the client works properly, please note the following:
421

            
422
		    1. *Avoid Throttling*: Ensure that the backing RPC node is not limiting the number of
423
		    requests, as this can prevent the lazy loading client from functioning correctly;
424

            
425
		    2. *Be Patient*: As the client may take approximately 20 times longer than normal to
426
		    retrieve and process the necessary data for the requested operation.
427

            
428

            
429
		The service will start in {start_delay} seconds...
430

            
431
		"#,
432
		rpc = lazy_loading_config.state_rpc,
433
		fork_block = backend.fork_checkpoint.number
434
	);
435

            
436
	log::warn!(
437
		"{}",
438
		ansi_term::Colour::Yellow.paint(lazy_loading_startup_disclaimer)
439
	);
440
	tokio::time::sleep(Duration::from_secs(start_delay)).await;
441

            
442
	let block_import = if let BlockImportPipeline::Dev(block_import) = block_import_pipeline {
443
		block_import
444
	} else {
445
		return Err(ServiceError::Other(
446
			"Block import pipeline is not dev".to_string(),
447
		));
448
	};
449

            
450
	let prometheus_registry = config.prometheus_registry().cloned();
451
	let net_config =
452
		FullNetworkConfiguration::<_, _, Net>::new(&config.network, prometheus_registry.clone());
453

            
454
	let metrics = Net::register_notification_metrics(
455
		config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
456
	);
457

            
458
	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
459
		sc_service::build_network(sc_service::BuildNetworkParams {
460
			config: &config,
461
			client: client.clone(),
462
			transaction_pool: transaction_pool.clone(),
463
			spawn_handle: task_manager.spawn_handle(),
464
			import_queue,
465
			block_announce_validator_builder: None,
466
			warp_sync_config: None,
467
			net_config,
468
			block_relay: None,
469
			metrics,
470
		})?;
471

            
472
	if config.offchain_worker.enabled {
473
		task_manager.spawn_handle().spawn(
474
			"offchain-workers-runner",
475
			"offchain-work",
476
			sc_offchain::OffchainWorkers::new(sc_offchain::OffchainWorkerOptions {
477
				runtime_api_provider: client.clone(),
478
				keystore: Some(keystore_container.keystore()),
479
				offchain_db: backend.offchain_storage(),
480
				transaction_pool: Some(OffchainTransactionPoolFactory::new(
481
					transaction_pool.clone(),
482
				)),
483
				network_provider: Arc::new(network.clone()),
484
				is_validator: config.role.is_authority(),
485
				enable_http_requests: true,
486
				custom_extensions: move |_| vec![],
487
			})
488
			.run(client.clone(), task_manager.spawn_handle())
489
			.boxed(),
490
		);
491
	}
492

            
493
	let prometheus_registry = config.prometheus_registry().cloned();
494
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
495
	let fee_history_limit = rpc_config.fee_history_limit;
496
	let mut command_sink = None;
497
	let mut dev_rpc_data = None;
498
	let collator = config.role.is_authority();
499

            
500
	if collator {
501
		let mut env = sc_basic_authorship::ProposerFactory::with_proof_recording(
502
			task_manager.spawn_handle(),
503
			client.clone(),
504
			transaction_pool.clone(),
505
			prometheus_registry.as_ref(),
506
			telemetry.as_ref().map(|x| x.handle()),
507
		);
508
		env.set_soft_deadline(SOFT_DEADLINE_PERCENT);
509

            
510
		let commands_stream: Box<dyn Stream<Item = EngineCommand<H256>> + Send + Sync + Unpin> =
511
			match sealing {
512
				moonbeam_cli_opt::Sealing::Instant => {
513
					Box::new(
514
						// This bit cribbed from the implementation of instant seal.
515
						transaction_pool
516
							.pool()
517
							.validated_pool()
518
							.import_notification_stream()
519
							.map(|_| EngineCommand::SealNewBlock {
520
								create_empty: false,
521
								finalize: false,
522
								parent_hash: None,
523
								sender: None,
524
							}),
525
					)
526
				}
527
				moonbeam_cli_opt::Sealing::Manual => {
528
					let (sink, stream) = futures::channel::mpsc::channel(1000);
529
					// Keep a reference to the other end of the channel. It goes to the RPC.
530
					command_sink = Some(sink);
531
					Box::new(stream)
532
				}
533
				moonbeam_cli_opt::Sealing::Interval(millis) => Box::new(StreamExt::map(
534
					Timer::interval(Duration::from_millis(millis)),
535
					|_| EngineCommand::SealNewBlock {
536
						create_empty: true,
537
						finalize: false,
538
						parent_hash: None,
539
						sender: None,
540
					},
541
				)),
542
			};
543

            
544
		let select_chain = maybe_select_chain.expect(
545
			"`new_lazy_loading_partial` builds a `LongestChainRule` when building dev service.\
546
				We specified the dev service when calling `new_partial`.\
547
				Therefore, a `LongestChainRule` is present. qed.",
548
		);
549

            
550
		let client_set_aside_for_cidp = client.clone();
551

            
552
		// Create channels for mocked XCM messages.
553
		let (downward_xcm_sender, downward_xcm_receiver) = flume::bounded::<Vec<u8>>(100);
554
		let (hrmp_xcm_sender, hrmp_xcm_receiver) = flume::bounded::<(ParaId, Vec<u8>)>(100);
555
		let additional_relay_offset = Arc::new(std::sync::atomic::AtomicU32::new(0));
556
		dev_rpc_data = Some((
557
			downward_xcm_sender,
558
			hrmp_xcm_sender,
559
			additional_relay_offset,
560
		));
561

            
562
		let client_clone = client.clone();
563
		let keystore_clone = keystore_container.keystore().clone();
564
		let maybe_provide_vrf_digest =
565
			move |nimbus_id: NimbusId, parent: Hash| -> Option<sp_runtime::generic::DigestItem> {
566
				moonbeam_vrf::vrf_pre_digest::<Block, LazyLoadingClient<RuntimeApi>>(
567
					&client_clone,
568
					&keystore_clone,
569
					nimbus_id,
570
					parent,
571
				)
572
			};
573

            
574
		let parachain_id = helpers::get_parachain_id(backend.rpc_client.clone())
575
			.unwrap_or_else(|| panic!("Could not get parachain identifier for lazy loading mode."));
576

            
577
		task_manager.spawn_essential_handle().spawn_blocking(
578
			"authorship_task",
579
			Some("block-authoring"),
580
			manual_sealing::run_manual_seal(ManualSealParams {
581
				block_import,
582
				env,
583
				client: client.clone(),
584
				pool: transaction_pool.clone(),
585
				commands_stream,
586
				select_chain,
587
				consensus_data_provider: Some(Box::new(NimbusManualSealConsensusDataProvider {
588
					keystore: keystore_container.keystore(),
589
					client: client.clone(),
590
					additional_digests_provider: maybe_provide_vrf_digest,
591
					_phantom: Default::default(),
592
				})),
593
				create_inherent_data_providers: move |block: H256, ()| {
594
					let maybe_current_para_block = client_set_aside_for_cidp.number(block);
595
					let maybe_current_para_head = client_set_aside_for_cidp.expect_header(block);
596
					let downward_xcm_receiver = downward_xcm_receiver.clone();
597
					let hrmp_xcm_receiver = hrmp_xcm_receiver.clone();
598

            
599
					let client_for_cidp = client_set_aside_for_cidp.clone();
600
					async move {
601
						let time = sp_timestamp::InherentDataProvider::from_system_time();
602

            
603
						let current_para_block = maybe_current_para_block?
604
							.ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?;
605

            
606
						let current_para_block_head = Some(polkadot_primitives::HeadData(
607
							maybe_current_para_head?.encode(),
608
						));
609

            
610
						let mut additional_key_values = vec![
611
							(
612
								moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW
613
									.to_vec(),
614
								sp_timestamp::Timestamp::current().encode(),
615
							),
616
							(
617
								relay_chain::well_known_keys::ACTIVE_CONFIG.to_vec(),
618
								AbridgedHostConfiguration {
619
									max_code_size: 3_145_728,
620
									max_head_data_size: 20_480,
621
									max_upward_queue_count: 174_762,
622
									max_upward_queue_size: 1_048_576,
623
									max_upward_message_size: 65_531,
624
									max_upward_message_num_per_candidate: 16,
625
									hrmp_max_message_num_per_candidate: 10,
626
									validation_upgrade_cooldown: 14_400,
627
									validation_upgrade_delay: 600,
628
									async_backing_params: AsyncBackingParams {
629
										max_candidate_depth: 3,
630
										allowed_ancestry_len: 2,
631
									},
632
								}
633
								.encode(),
634
							),
635
							// Override current slot number
636
							(
637
								relay_chain::well_known_keys::CURRENT_SLOT.to_vec(),
638
								Slot::from(u64::from(current_para_block)).encode(),
639
							),
640
						];
641

            
642
						// If there is a pending upgrade, lets mimic a GoAhead
643
						// signal from the relay
644

            
645
						let storage_key = [
646
							twox_128(b"ParachainSystem"),
647
							twox_128(b"PendingValidationCode"),
648
						]
649
						.concat();
650
						let has_pending_upgrade = client_for_cidp
651
							.storage(block, &StorageKey(storage_key))
652
							.map_or(false, |ok| ok.map_or(false, |some| !some.0.is_empty()));
653
						if has_pending_upgrade {
654
							additional_key_values.push((
655
								relay_chain::well_known_keys::upgrade_go_ahead_signal(ParaId::new(
656
									parachain_id,
657
								)),
658
								Some(UpgradeGoAhead::GoAhead).encode(),
659
							));
660
							additional_key_values.push((
661
								relay_chain::well_known_keys::upgrade_restriction_signal(
662
									ParaId::new(parachain_id),
663
								),
664
								None::<UpgradeRestriction>.encode(),
665
							));
666
						}
667

            
668
						let mocked_parachain = MockValidationDataInherentDataProvider {
669
							current_para_block,
670
							para_id: ParaId::new(parachain_id),
671
							current_para_block_head,
672
							relay_offset: 1000,
673
							relay_blocks_per_para_block: 2,
674
							// TODO: Recheck
675
							para_blocks_per_relay_epoch: 10,
676
							relay_randomness_config: (),
677
							xcm_config: MockXcmConfig::new(
678
								&*client_for_cidp,
679
								block,
680
								Default::default(),
681
							),
682
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
683
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
684
							additional_key_values: Some(additional_key_values),
685
						};
686

            
687
						let randomness = session_keys_primitives::InherentDataProvider;
688

            
689
						Ok((time, mocked_parachain, randomness))
690
					}
691
				},
692
			}),
693
		);
694
	}
695

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

            
707
	/* TODO: only enable this when frontier backend is compatible with lazy-loading
708
	rpc::spawn_essential_tasks(
709
		rpc::SpawnTasksParams {
710
			task_manager: &task_manager,
711
			client: client.clone(),
712
			substrate_backend: backend.clone(),
713
			frontier_backend: frontier_backend.clone(),
714
			filter_pool: filter_pool.clone(),
715
			overrides: overrides.clone(),
716
			fee_history_limit,
717
			fee_history_cache: fee_history_cache.clone(),
718
		},
719
		sync_service.clone(),
720
		pubsub_notification_sinks.clone(),
721
	);
722
	*/
723

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

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

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

            
770
		let keystore = keystore_container.keystore();
771
		let command_sink_for_task = command_sink.clone();
772
		move |subscription_task_executor| {
773
			let deps = rpc::FullDeps {
774
				backend: backend.clone(),
775
				client: client.clone(),
776
				command_sink: command_sink_for_task.clone(),
777
				ethapi_cmd: ethapi_cmd.clone(),
778
				filter_pool: filter_pool.clone(),
779
				frontier_backend: match *frontier_backend {
780
					fc_db::Backend::KeyValue(ref b) => b.clone(),
781
					fc_db::Backend::Sql(ref b) => b.clone(),
782
				},
783
				graph: pool.pool().clone(),
784
				pool: pool.clone(),
785
				is_authority: collator,
786
				max_past_logs,
787
				max_block_range,
788
				fee_history_limit,
789
				fee_history_cache: fee_history_cache.clone(),
790
				network: network.clone(),
791
				sync: sync.clone(),
792
				dev_rpc_data: dev_rpc_data.clone(),
793
				overrides: overrides.clone(),
794
				block_data_cache: block_data_cache.clone(),
795
				forced_parent_hashes: None,
796
			};
797

            
798
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
799
				client.clone(),
800
				keystore.clone(),
801
			));
802
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
803
				rpc::create_full(
804
					deps,
805
					subscription_task_executor,
806
					Some(crate::rpc::TracingConfig {
807
						tracing_requesters: tracing_requesters.clone(),
808
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
809
					}),
810
					pubsub_notification_sinks.clone(),
811
					pending_consensus_data_provider,
812
				)
813
				.map_err(Into::into)
814
			} else {
815
				rpc::create_full(
816
					deps,
817
					subscription_task_executor,
818
					None,
819
					pubsub_notification_sinks.clone(),
820
					pending_consensus_data_provider,
821
				)
822
				.map_err(Into::into)
823
			}
824
		}
825
	};
826

            
827
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
828
		network,
829
		client,
830
		keystore: keystore_container.keystore(),
831
		task_manager: &mut task_manager,
832
		transaction_pool,
833
		rpc_builder: Box::new(rpc_builder),
834
		backend,
835
		system_rpc_tx,
836
		sync_service: sync_service.clone(),
837
		config,
838
		tx_handler_controller,
839
		telemetry: None,
840
	})?;
841

            
842
	if let Some(hwbench) = hwbench {
843
		sc_sysinfo::print_hwbench(&hwbench);
844

            
845
		if let Some(ref mut telemetry) = telemetry {
846
			let telemetry_handle = telemetry.handle();
847
			task_manager.spawn_handle().spawn(
848
				"telemetry_hwbench",
849
				None,
850
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
851
			);
852
		}
853
	}
854

            
855
	network_starter.start_network();
856

            
857
	log::info!("Service Ready");
858

            
859
	Ok(task_manager)
860
}