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
};
37
use sc_chain_spec::{get_extension, BuildGenesisBlock, GenesisBlockBuilder};
38
use sc_client_api::{Backend, BadBlocks, ExecutorProvider, ForkBlocks, StorageProvider};
39
use sc_executor::{HeapAllocStrategy, RuntimeVersionOf, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
40
use sc_network::config::FullNetworkConfiguration;
41
use sc_network::NetworkBackend;
42
use sc_network_common::sync::SyncMode;
43
use sc_service::{
44
	error::Error as ServiceError, ClientConfig, Configuration, Error, KeystoreContainer,
45
	LocalCallExecutor, PartialComponents, TaskManager,
46
};
47
use sc_telemetry::{TelemetryHandle, TelemetryWorker};
48
use sc_transaction_pool_api::OffchainTransactionPoolFactory;
49
use sp_api::ConstructRuntimeApi;
50
use sp_blockchain::HeaderBackend;
51
use sp_core::traits::CodeExecutor;
52
use sp_core::{twox_128, H256};
53
use sp_runtime::traits::NumberFor;
54
use sp_storage::StorageKey;
55
use std::collections::BTreeMap;
56
use std::str::FromStr;
57
use std::sync::{Arc, Mutex};
58
use std::time::Duration;
59

            
60
pub mod backend;
61
pub mod call_executor;
62
mod client;
63
mod helpers;
64
mod lock;
65
mod state_overrides;
66

            
67
pub const LAZY_LOADING_LOG_TARGET: &'static str = "lazy-loading";
68

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
214
		client
215
	};
216

            
217
	Ok((client, backend, keystore_container, task_manager))
218
}
219

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

            
234
	// Use ethereum style for subscription ids
235
	config.rpc_id_provider = Some(Box::new(fc_rpc::EthereumSubIdProvider));
236

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

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

            
261
	if let Some(ref wasmtime_precompiled_path) = config.wasmtime_precompiled {
262
		wasm_builder = wasm_builder.with_wasmtime_precompiled_path(wasmtime_precompiled_path);
263
	}
264

            
265
	let executor = wasm_builder.build();
266

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

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

            
284
	let client = Arc::new(client);
285

            
286
	let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());
287

            
288
	let telemetry = telemetry.map(|(worker, telemetry)| {
289
		task_manager
290
			.spawn_handle()
291
			.spawn("telemetry", None, worker.run());
292
		telemetry
293
	});
294

            
295
	let maybe_select_chain = Some(sc_consensus::LongestChain::new(backend.clone()));
296

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

            
305
	let filter_pool: Option<FilterPool> = Some(Arc::new(Mutex::new(BTreeMap::new())));
306
	let fee_history_cache: FeeHistoryCache = Arc::new(Mutex::new(BTreeMap::new()));
307

            
308
	let frontier_backend = Arc::new(open_frontier_backend(client.clone(), config, rpc_config)?);
309
	let frontier_block_import = FrontierBlockImport::new(client.clone(), client.clone());
310

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

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

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

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

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

            
407
	let start_delay = 10;
408
	let lazy_loading_startup_disclaimer = format!(
409
		r#"
410

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

            
414
		Using remote state from: {rpc}
415
		Forking from block: {fork_block}
416

            
417
		To ensure the client works properly, please note the following:
418

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

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

            
425

            
426
		The service will start in {start_delay} seconds...
427

            
428
		"#,
429
		rpc = lazy_loading_config.state_rpc,
430
		fork_block = backend.fork_checkpoint.number
431
	);
432

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

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

            
447
	let net_config = FullNetworkConfiguration::<_, _, Net>::new(&config.network);
448

            
449
	let metrics = Net::register_notification_metrics(
450
		config.prometheus_config.as_ref().map(|cfg| &cfg.registry),
451
	);
452

            
453
	let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) =
454
		sc_service::build_network(sc_service::BuildNetworkParams {
455
			config: &config,
456
			client: client.clone(),
457
			transaction_pool: transaction_pool.clone(),
458
			spawn_handle: task_manager.spawn_handle(),
459
			import_queue,
460
			block_announce_validator_builder: None,
461
			warp_sync_params: None,
462
			net_config,
463
			block_relay: None,
464
			metrics,
465
		})?;
466

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

            
488
	let prometheus_registry = config.prometheus_registry().cloned();
489
	let overrides = Arc::new(StorageOverrideHandler::new(client.clone()));
490
	let fee_history_limit = rpc_config.fee_history_limit;
491
	let mut command_sink = None;
492
	let mut dev_rpc_data = None;
493
	let collator = config.role.is_authority();
494

            
495
	if collator {
496
		let mut env = sc_basic_authorship::ProposerFactory::with_proof_recording(
497
			task_manager.spawn_handle(),
498
			client.clone(),
499
			transaction_pool.clone(),
500
			prometheus_registry.as_ref(),
501
			telemetry.as_ref().map(|x| x.handle()),
502
		);
503
		env.set_soft_deadline(SOFT_DEADLINE_PERCENT);
504

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

            
539
		let select_chain = maybe_select_chain.expect(
540
			"`new_lazy_loading_partial` builds a `LongestChainRule` when building dev service.\
541
				We specified the dev service when calling `new_partial`.\
542
				Therefore, a `LongestChainRule` is present. qed.",
543
		);
544

            
545
		let client_set_aside_for_cidp = client.clone();
546

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

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

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

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

            
594
					let client_for_cidp = client_set_aside_for_cidp.clone();
595
					async move {
596
						let time = sp_timestamp::InherentDataProvider::from_system_time();
597

            
598
						let current_para_block = maybe_current_para_block?
599
							.ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?;
600

            
601
						let current_para_block_head = Some(polkadot_primitives::HeadData(
602
							maybe_current_para_head?.encode(),
603
						));
604

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

            
637
						// If there is a pending upgrade, lets mimic a GoAhead
638
						// signal from the relay
639

            
640
						let storage_key = [
641
							twox_128(b"ParachainSystem"),
642
							twox_128(b"PendingValidationCode"),
643
						]
644
						.concat();
645
						let has_pending_upgrade = client_for_cidp
646
							.storage(block, &StorageKey(storage_key))
647
							.map_or(false, |ok| ok.map_or(false, |some| !some.0.is_empty()));
648
						if has_pending_upgrade {
649
							additional_key_values.push((
650
								relay_chain::well_known_keys::upgrade_go_ahead_signal(ParaId::new(
651
									parachain_id,
652
								)),
653
								Some(UpgradeGoAhead::GoAhead).encode(),
654
							));
655
						}
656

            
657
						let mocked_parachain = MockValidationDataInherentDataProvider {
658
							current_para_block,
659
							para_id: ParaId::new(parachain_id),
660
							current_para_block_head,
661
							relay_offset: 1000,
662
							relay_blocks_per_para_block: 2,
663
							// TODO: Recheck
664
							para_blocks_per_relay_epoch: 10,
665
							relay_randomness_config: (),
666
							xcm_config: MockXcmConfig::new(
667
								&*client_for_cidp,
668
								block,
669
								Default::default(),
670
							),
671
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
672
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
673
							additional_key_values: Some(additional_key_values),
674
						};
675

            
676
						let randomness = session_keys_primitives::InherentDataProvider;
677

            
678
						Ok((time, mocked_parachain, randomness))
679
					}
680
				},
681
			}),
682
		);
683
	}
684

            
685
	// Sinks for pubsub notifications.
686
	// Everytime a new subscription is created, a new mpsc channel is added to the sink pool.
687
	// The MappingSyncWorker sends through the channel on block import and the subscription emits a
688
	// notification to the subscriber on receiving a message through this channel.
689
	// This way we avoid race conditions when using native substrate block import notification
690
	// stream.
691
	let pubsub_notification_sinks: fc_mapping_sync::EthereumBlockNotificationSinks<
692
		fc_mapping_sync::EthereumBlockNotification<Block>,
693
	> = Default::default();
694
	let pubsub_notification_sinks = Arc::new(pubsub_notification_sinks);
695

            
696
	rpc::spawn_essential_tasks(
697
		rpc::SpawnTasksParams {
698
			task_manager: &task_manager,
699
			client: client.clone(),
700
			substrate_backend: backend.clone(),
701
			frontier_backend: frontier_backend.clone(),
702
			filter_pool: filter_pool.clone(),
703
			overrides: overrides.clone(),
704
			fee_history_limit,
705
			fee_history_cache: fee_history_cache.clone(),
706
		},
707
		sync_service.clone(),
708
		pubsub_notification_sinks.clone(),
709
	);
710
	let ethapi_cmd = rpc_config.ethapi.clone();
711
	let tracing_requesters =
712
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
713
			rpc::tracing::spawn_tracing_tasks(
714
				&rpc_config,
715
				prometheus_registry.clone(),
716
				rpc::SpawnTasksParams {
717
					task_manager: &task_manager,
718
					client: client.clone(),
719
					substrate_backend: backend.clone(),
720
					frontier_backend: frontier_backend.clone(),
721
					filter_pool: filter_pool.clone(),
722
					overrides: overrides.clone(),
723
					fee_history_limit,
724
					fee_history_cache: fee_history_cache.clone(),
725
				},
726
			)
727
		} else {
728
			rpc::tracing::RpcRequesters {
729
				debug: None,
730
				trace: None,
731
			}
732
		};
733

            
734
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
735
		task_manager.spawn_handle(),
736
		overrides.clone(),
737
		rpc_config.eth_log_block_cache,
738
		rpc_config.eth_statuses_cache,
739
		prometheus_registry,
740
	));
741

            
742
	let rpc_builder = {
743
		let client = client.clone();
744
		let pool = transaction_pool.clone();
745
		let backend = backend.clone();
746
		let network = network.clone();
747
		let sync = sync_service.clone();
748
		let ethapi_cmd = ethapi_cmd.clone();
749
		let max_past_logs = rpc_config.max_past_logs;
750
		let overrides = overrides.clone();
751
		let fee_history_cache = fee_history_cache.clone();
752
		let block_data_cache = block_data_cache.clone();
753
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
754

            
755
		let keystore = keystore_container.keystore();
756
		let command_sink_for_task = command_sink.clone();
757
		move |deny_unsafe, subscription_task_executor| {
758
			let deps = rpc::FullDeps {
759
				backend: backend.clone(),
760
				client: client.clone(),
761
				command_sink: command_sink_for_task.clone(),
762
				deny_unsafe,
763
				ethapi_cmd: ethapi_cmd.clone(),
764
				filter_pool: filter_pool.clone(),
765
				frontier_backend: match *frontier_backend {
766
					fc_db::Backend::KeyValue(ref b) => b.clone(),
767
					fc_db::Backend::Sql(ref b) => b.clone(),
768
				},
769
				graph: pool.pool().clone(),
770
				pool: pool.clone(),
771
				is_authority: collator,
772
				max_past_logs,
773
				fee_history_limit,
774
				fee_history_cache: fee_history_cache.clone(),
775
				network: network.clone(),
776
				sync: sync.clone(),
777
				dev_rpc_data: dev_rpc_data.clone(),
778
				overrides: overrides.clone(),
779
				block_data_cache: block_data_cache.clone(),
780
				forced_parent_hashes: None,
781
			};
782

            
783
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
784
				client.clone(),
785
				keystore.clone(),
786
			));
787
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
788
				rpc::create_full(
789
					deps,
790
					subscription_task_executor,
791
					Some(crate::rpc::TracingConfig {
792
						tracing_requesters: tracing_requesters.clone(),
793
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
794
					}),
795
					pubsub_notification_sinks.clone(),
796
					pending_consensus_data_provider,
797
				)
798
				.map_err(Into::into)
799
			} else {
800
				rpc::create_full(
801
					deps,
802
					subscription_task_executor,
803
					None,
804
					pubsub_notification_sinks.clone(),
805
					pending_consensus_data_provider,
806
				)
807
				.map_err(Into::into)
808
			}
809
		}
810
	};
811

            
812
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
813
		network,
814
		client,
815
		keystore: keystore_container.keystore(),
816
		task_manager: &mut task_manager,
817
		transaction_pool,
818
		rpc_builder: Box::new(rpc_builder),
819
		backend,
820
		system_rpc_tx,
821
		sync_service: sync_service.clone(),
822
		config,
823
		tx_handler_controller,
824
		telemetry: None,
825
	})?;
826

            
827
	if let Some(hwbench) = hwbench {
828
		sc_sysinfo::print_hwbench(&hwbench);
829

            
830
		if let Some(ref mut telemetry) = telemetry {
831
			let telemetry_handle = telemetry.handle();
832
			task_manager.spawn_handle().spawn(
833
				"telemetry_hwbench",
834
				None,
835
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
836
			);
837
		}
838
	}
839

            
840
	network_starter.start_network();
841

            
842
	log::info!("Service Ready");
843

            
844
	Ok(task_manager)
845
}