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, CollectCollationInfo, 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};
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, TransactionPool};
50
use sp_api::{ConstructRuntimeApi, ProvideRuntimeApi};
51
use sp_blockchain::HeaderBackend;
52
use sp_core::traits::CodeExecutor;
53
use sp_core::H256;
54
use sp_runtime::traits::NumberFor;
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 manual_sealing;
66
mod state_overrides;
67

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
215
		client
216
	};
217

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

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

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

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

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

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

            
267
	let executor = wasm_builder.build();
268

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

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

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

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

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

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

            
299
	let transaction_pool = sc_transaction_pool::Builder::new(
300
		task_manager.spawn_essential_handle(),
301
		client.clone(),
302
		config.role.is_authority().into(),
303
	)
304
	.with_options(config.transaction_pool.clone())
305
	.with_prometheus(config.prometheus_registry())
306
	.build();
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: transaction_pool.into(),
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.import_notification_stream().map(|_| {
516
							EngineCommand::SealNewBlock {
517
								create_empty: false,
518
								finalize: false,
519
								parent_hash: None,
520
								sender: None,
521
							}
522
						}),
523
					)
524
				}
525
				moonbeam_cli_opt::Sealing::Manual => {
526
					let (sink, stream) = futures::channel::mpsc::channel(1000);
527
					// Keep a reference to the other end of the channel. It goes to the RPC.
528
					command_sink = Some(sink);
529
					Box::new(stream)
530
				}
531
				moonbeam_cli_opt::Sealing::Interval(millis) => Box::new(StreamExt::map(
532
					Timer::interval(Duration::from_millis(millis)),
533
					|_| EngineCommand::SealNewBlock {
534
						create_empty: true,
535
						finalize: false,
536
						parent_hash: None,
537
						sender: None,
538
					},
539
				)),
540
			};
541

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

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

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

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

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

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

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

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

            
606
					async move {
607
						let time = sp_timestamp::InherentDataProvider::from_system_time();
608

            
609
						let current_para_block = maybe_current_para_block?
610
							.ok_or(sp_blockchain::Error::UnknownBlock(block.to_string()))?;
611

            
612
						let current_para_block_head = Some(polkadot_primitives::HeadData(
613
							maybe_current_para_head?.encode(),
614
						));
615

            
616
						let additional_key_values = vec![
617
							(
618
								moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW
619
									.to_vec(),
620
								sp_timestamp::Timestamp::current().encode(),
621
							),
622
							(
623
								relay_chain::well_known_keys::ACTIVE_CONFIG.to_vec(),
624
								AbridgedHostConfiguration {
625
									max_code_size: 3_145_728,
626
									max_head_data_size: 20_480,
627
									max_upward_queue_count: 174_762,
628
									max_upward_queue_size: 1_048_576,
629
									max_upward_message_size: 65_531,
630
									max_upward_message_num_per_candidate: 16,
631
									hrmp_max_message_num_per_candidate: 10,
632
									validation_upgrade_cooldown: 14_400,
633
									validation_upgrade_delay: 600,
634
									async_backing_params: AsyncBackingParams {
635
										max_candidate_depth: 3,
636
										allowed_ancestry_len: 2,
637
									},
638
								}
639
								.encode(),
640
							),
641
							// Override current slot number
642
							(
643
								relay_chain::well_known_keys::CURRENT_SLOT.to_vec(),
644
								Slot::from(u64::from(current_para_block)).encode(),
645
							),
646
							(
647
								relay_chain::well_known_keys::upgrade_restriction_signal(
648
									ParaId::new(parachain_id),
649
								),
650
								None::<UpgradeRestriction>.encode(),
651
							),
652
						];
653

            
654
						let current_para_head = client_for_xcm
655
							.header(block)
656
							.expect("Header lookup should succeed")
657
							.expect("Header passed in as parent should be present in backend.");
658

            
659
						let should_send_go_ahead = match client_for_xcm
660
							.runtime_api()
661
							.collect_collation_info(block, &current_para_head)
662
						{
663
							Ok(info) => info.new_validation_code.is_some(),
664
							Err(e) => {
665
								log::error!("Failed to collect collation info: {:?}", e);
666
								false
667
							}
668
						};
669

            
670
						let mocked_parachain = MockValidationDataInherentDataProvider {
671
							current_para_block,
672
							para_id: ParaId::new(parachain_id),
673
							upgrade_go_ahead: should_send_go_ahead.then(|| {
674
								log::info!(
675
									"Detected pending validation code, sending go-ahead signal."
676
								);
677
								UpgradeGoAhead::GoAhead
678
							}),
679
							current_para_block_head,
680
							relay_offset: 1000,
681
							relay_blocks_per_para_block: 2,
682
							// TODO: Recheck
683
							para_blocks_per_relay_epoch: 10,
684
							relay_randomness_config: (),
685
							xcm_config: MockXcmConfig::new(
686
								&*client_for_xcm,
687
								block,
688
								Default::default(),
689
							),
690
							raw_downward_messages: downward_xcm_receiver.drain().collect(),
691
							raw_horizontal_messages: hrmp_xcm_receiver.drain().collect(),
692
							additional_key_values: Some(additional_key_values),
693
						};
694

            
695
						let randomness = session_keys_primitives::InherentDataProvider;
696

            
697
						Ok((time, mocked_parachain, randomness))
698
					}
699
				},
700
			}),
701
		);
702
	}
703

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

            
715
	/* TODO: only enable this when frontier backend is compatible with lazy-loading
716
	rpc::spawn_essential_tasks(
717
		rpc::SpawnTasksParams {
718
			task_manager: &task_manager,
719
			client: client.clone(),
720
			substrate_backend: backend.clone(),
721
			frontier_backend: frontier_backend.clone(),
722
			filter_pool: filter_pool.clone(),
723
			overrides: overrides.clone(),
724
			fee_history_limit,
725
			fee_history_cache: fee_history_cache.clone(),
726
		},
727
		sync_service.clone(),
728
		pubsub_notification_sinks.clone(),
729
	);
730
	*/
731

            
732
	let ethapi_cmd = rpc_config.ethapi.clone();
733
	let tracing_requesters =
734
		if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
735
			rpc::tracing::spawn_tracing_tasks(
736
				&rpc_config,
737
				prometheus_registry.clone(),
738
				rpc::SpawnTasksParams {
739
					task_manager: &task_manager,
740
					client: client.clone(),
741
					substrate_backend: backend.clone(),
742
					frontier_backend: frontier_backend.clone(),
743
					filter_pool: filter_pool.clone(),
744
					overrides: overrides.clone(),
745
					fee_history_limit,
746
					fee_history_cache: fee_history_cache.clone(),
747
				},
748
			)
749
		} else {
750
			rpc::tracing::RpcRequesters {
751
				debug: None,
752
				trace: None,
753
			}
754
		};
755

            
756
	let block_data_cache = Arc::new(fc_rpc::EthBlockDataCacheTask::new(
757
		task_manager.spawn_handle(),
758
		overrides.clone(),
759
		rpc_config.eth_log_block_cache,
760
		rpc_config.eth_statuses_cache,
761
		prometheus_registry,
762
	));
763

            
764
	let rpc_builder = {
765
		let client = client.clone();
766
		let pool = transaction_pool.clone();
767
		let backend = backend.clone();
768
		let network = network.clone();
769
		let sync = sync_service.clone();
770
		let ethapi_cmd = ethapi_cmd.clone();
771
		let max_past_logs = rpc_config.max_past_logs;
772
		let max_block_range = rpc_config.max_block_range;
773
		let overrides = overrides.clone();
774
		let fee_history_cache = fee_history_cache.clone();
775
		let block_data_cache = block_data_cache.clone();
776
		let pubsub_notification_sinks = pubsub_notification_sinks.clone();
777

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

            
806
			let pending_consensus_data_provider = Box::new(PendingConsensusDataProvider::new(
807
				client.clone(),
808
				keystore.clone(),
809
			));
810
			if ethapi_cmd.contains(&EthApiCmd::Debug) || ethapi_cmd.contains(&EthApiCmd::Trace) {
811
				rpc::create_full(
812
					deps,
813
					subscription_task_executor,
814
					Some(crate::rpc::TracingConfig {
815
						tracing_requesters: tracing_requesters.clone(),
816
						trace_filter_max_count: rpc_config.ethapi_trace_max_count,
817
					}),
818
					pubsub_notification_sinks.clone(),
819
					pending_consensus_data_provider,
820
				)
821
				.map_err(Into::into)
822
			} else {
823
				rpc::create_full(
824
					deps,
825
					subscription_task_executor,
826
					None,
827
					pubsub_notification_sinks.clone(),
828
					pending_consensus_data_provider,
829
				)
830
				.map_err(Into::into)
831
			}
832
		}
833
	};
834

            
835
	let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams {
836
		network,
837
		client,
838
		keystore: keystore_container.keystore(),
839
		task_manager: &mut task_manager,
840
		transaction_pool,
841
		rpc_builder: Box::new(rpc_builder),
842
		backend,
843
		system_rpc_tx,
844
		sync_service: sync_service.clone(),
845
		config,
846
		tx_handler_controller,
847
		telemetry: None,
848
	})?;
849

            
850
	if let Some(hwbench) = hwbench {
851
		sc_sysinfo::print_hwbench(&hwbench);
852

            
853
		if let Some(ref mut telemetry) = telemetry {
854
			let telemetry_handle = telemetry.handle();
855
			task_manager.spawn_handle().spawn(
856
				"telemetry_hwbench",
857
				None,
858
				sc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
859
			);
860
		}
861
	}
862

            
863
	network_starter.start_network();
864

            
865
	log::info!("Service Ready");
866

            
867
	Ok(task_manager)
868
}