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

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

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

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

            
17
//! A collection of node-specific RPC extensions and related background tasks.
18

            
19
pub mod tracing;
20

            
21
use std::{sync::Arc, time::Duration};
22

            
23
use fp_rpc::EthereumRuntimeRPCApi;
24
use sp_block_builder::BlockBuilder;
25

            
26
use crate::client::RuntimeApiCollection;
27
use crate::RELAY_CHAIN_SLOT_DURATION_MILLIS;
28
use cumulus_primitives_core::{ParaId, PersistedValidationData};
29
use cumulus_primitives_parachain_inherent::ParachainInherentData;
30
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
31
use fc_mapping_sync::{kv::MappingSyncWorker, SyncStrategy};
32
use fc_rpc::{pending::ConsensusDataProvider, EthBlockDataCacheTask, EthTask, StorageOverride};
33
use fc_rpc_core::types::{FeeHistoryCache, FilterPool, TransactionRequest};
34
use futures::StreamExt;
35
use jsonrpsee::RpcModule;
36
use moonbeam_cli_opt::EthApi as EthApiCmd;
37
use moonbeam_core_primitives::{Block, Hash};
38
use parity_scale_codec::Encode;
39
use sc_client_api::{
40
	backend::{AuxStore, Backend, StateBackend, StorageProvider},
41
	client::BlockchainEvents,
42
	BlockOf,
43
};
44
use sc_client_db::PruningMode;
45
use sc_consensus_manual_seal::rpc::{EngineCommand, ManualSeal, ManualSealApiServer};
46
use sc_network::service::traits::NetworkService;
47
use sc_network_sync::SyncingService;
48
use sc_rpc::SubscriptionTaskExecutor;
49
use sc_service::TaskManager;
50
use sc_transaction_pool_api::TransactionPool;
51
use sp_api::{CallApiAt, ProvideRuntimeApi};
52
use sp_blockchain::{
53
	Backend as BlockchainBackend, Error as BlockChainError, HeaderBackend, HeaderMetadata,
54
};
55
use sp_core::H256;
56
use sp_runtime::traits::{BlakeTwo256, Block as BlockT, Header as HeaderT};
57
use sp_timestamp::Timestamp;
58
use std::collections::BTreeMap;
59

            
60
pub struct MoonbeamEGA;
61

            
62
impl fc_rpc::EstimateGasAdapter for MoonbeamEGA {
63
8488
	fn adapt_request(mut request: TransactionRequest) -> TransactionRequest {
64
		// Redirect any call to batch precompile:
65
		// force usage of batchAll method for estimation
66
		use sp_core::H160;
67
		const BATCH_PRECOMPILE_ADDRESS: H160 = H160(hex_literal::hex!(
68
			"0000000000000000000000000000000000000808"
69
		));
70
		const BATCH_PRECOMPILE_BATCH_ALL_SELECTOR: [u8; 4] = hex_literal::hex!("96e292b8");
71
8488
		if request.to == Some(BATCH_PRECOMPILE_ADDRESS) {
72
18
			match (&mut request.data.input, &mut request.data.data) {
73
				(Some(ref mut input), _) => {
74
					if input.0.len() >= 4 {
75
						input.0[..4].copy_from_slice(&BATCH_PRECOMPILE_BATCH_ALL_SELECTOR);
76
					}
77
				}
78
18
				(None, Some(ref mut data)) => {
79
18
					if data.0.len() >= 4 {
80
18
						data.0[..4].copy_from_slice(&BATCH_PRECOMPILE_BATCH_ALL_SELECTOR);
81
18
					}
82
				}
83
				(_, _) => {}
84
			};
85
8470
		}
86
8488
		request
87
8488
	}
88
}
89

            
90
pub struct MoonbeamEthConfig<C, BE>(std::marker::PhantomData<(C, BE)>);
91

            
92
impl<C, BE> fc_rpc::EthConfig<Block, C> for MoonbeamEthConfig<C, BE>
93
where
94
	C: sc_client_api::StorageProvider<Block, BE> + Sync + Send + 'static,
95
	BE: Backend<Block> + 'static,
96
{
97
	type EstimateGasAdapter = MoonbeamEGA;
98
	type RuntimeStorageOverride =
99
		fc_rpc::frontier_backend_client::SystemAccountId20StorageOverride<Block, C, BE>;
100
}
101

            
102
/// Full client dependencies.
103
pub struct FullDeps<C, P, BE> {
104
	/// The client instance to use.
105
	pub client: Arc<C>,
106
	/// Transaction pool instance.
107
	pub pool: Arc<P>,
108
	/// Graph pool instance.
109
	pub graph: Arc<P>,
110
	/// The Node authority flag
111
	pub is_authority: bool,
112
	/// Network service
113
	pub network: Arc<dyn NetworkService>,
114
	/// Chain syncing service
115
	pub sync: Arc<SyncingService<Block>>,
116
	/// EthFilterApi pool.
117
	pub filter_pool: Option<FilterPool>,
118
	/// The list of optional RPC extensions.
119
	pub ethapi_cmd: Vec<EthApiCmd>,
120
	/// Frontier Backend.
121
	pub frontier_backend: Arc<dyn fc_api::Backend<Block>>,
122
	/// Backend.
123
	pub backend: Arc<BE>,
124
	/// Manual seal command sink
125
	pub command_sink: Option<futures::channel::mpsc::Sender<EngineCommand<Hash>>>,
126
	/// Maximum number of logs in a query.
127
	pub max_past_logs: u32,
128
	/// Maximum block range in a query.
129
	pub max_block_range: u32,
130
	/// Maximum fee history cache size.
131
	pub fee_history_limit: u64,
132
	/// Fee history cache.
133
	pub fee_history_cache: FeeHistoryCache,
134
	/// Channels for manual xcm messages (downward, hrmp)
135
	pub dev_rpc_data: Option<(
136
		flume::Sender<Vec<u8>>,
137
		flume::Sender<(ParaId, Vec<u8>)>,
138
		Arc<std::sync::atomic::AtomicU32>,
139
	)>,
140
	/// Ethereum data access overrides.
141
	pub overrides: Arc<dyn StorageOverride<Block>>,
142
	/// Cache for Ethereum block data.
143
	pub block_data_cache: Arc<EthBlockDataCacheTask<Block>>,
144
	/// Mandated parent hashes for a given block hash.
145
	pub forced_parent_hashes: Option<BTreeMap<H256, H256>>,
146
}
147

            
148
pub struct TracingConfig {
149
	pub tracing_requesters: crate::rpc::tracing::RpcRequesters,
150
	pub trace_filter_max_count: u32,
151
	pub max_block_range: u32,
152
}
153

            
154
/// Instantiate all Full RPC extensions.
155
1856
pub fn create_full<C, P, BE>(
156
1856
	deps: FullDeps<C, P, BE>,
157
1856
	subscription_task_executor: SubscriptionTaskExecutor,
158
1856
	maybe_tracing_config: Option<TracingConfig>,
159
1856
	pubsub_notification_sinks: Arc<
160
1856
		fc_mapping_sync::EthereumBlockNotificationSinks<
161
1856
			fc_mapping_sync::EthereumBlockNotification<Block>,
162
1856
		>,
163
1856
	>,
164
1856
	pending_consenus_data_provider: Box<dyn ConsensusDataProvider<Block>>,
165
1856
	para_id: ParaId,
166
1856
) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>>
167
1856
where
168
1856
	BE: Backend<Block> + 'static,
169
1856
	BE::State: StateBackend<BlakeTwo256>,
170
1856
	BE::Blockchain: BlockchainBackend<Block>,
171
1856
	C: ProvideRuntimeApi<Block> + StorageProvider<Block, BE> + AuxStore,
172
1856
	C: BlockchainEvents<Block>,
173
1856
	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,
174
1856
	C: CallApiAt<Block>,
175
1856
	C: Send + Sync + 'static,
176
1856
	C::Api: RuntimeApiCollection,
177
1856
	P: TransactionPool<Block = Block, Hash = <Block as BlockT>::Hash> + 'static,
178
{
179
	use fc_rpc::{
180
		Eth, EthApiServer, EthFilter, EthFilterApiServer, EthPubSub, EthPubSubApiServer, Net,
181
		NetApiServer, TxPool, TxPoolApiServer, Web3, Web3ApiServer,
182
	};
183
	use moonbeam_dev_rpc::{DevApiServer, DevRpc};
184
	use moonbeam_finality_rpc::{MoonbeamFinality, MoonbeamFinalityApiServer};
185
	use moonbeam_rpc_debug::{Debug, DebugServer};
186
	use moonbeam_rpc_trace::{Trace, TraceServer};
187
	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
188
	use substrate_frame_rpc_system::{System, SystemApiServer};
189

            
190
1856
	let mut io = RpcModule::new(());
191
	let FullDeps {
192
1856
		client,
193
1856
		pool,
194
1856
		graph,
195
1856
		is_authority,
196
1856
		network,
197
1856
		sync,
198
1856
		filter_pool,
199
1856
		ethapi_cmd,
200
1856
		command_sink,
201
1856
		frontier_backend,
202
		backend: _,
203
1856
		max_past_logs,
204
1856
		max_block_range,
205
1856
		fee_history_limit,
206
1856
		fee_history_cache,
207
1856
		dev_rpc_data,
208
1856
		overrides,
209
1856
		block_data_cache,
210
1856
		forced_parent_hashes,
211
1856
	} = deps;
212

            
213
1856
	io.merge(System::new(Arc::clone(&client), Arc::clone(&pool)).into_rpc())?;
214
1856
	io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;
215

            
216
	// TODO: are we supporting signing?
217
1856
	let signers = Vec::new();
218

            
219
	enum Never {}
220
	impl<T> fp_rpc::ConvertTransaction<T> for Never {
221
		fn convert_transaction(&self, _transaction: pallet_ethereum::Transaction) -> T {
222
			// The Never type is not instantiable, but this method requires the type to be
223
			// instantiated to be called (`&self` parameter), so if the code compiles we have the
224
			// guarantee that this function will never be called.
225
			unreachable!()
226
		}
227
	}
228
1856
	let convert_transaction: Option<Never> = None;
229

            
230
	// Need to clone it to avoid moving of `client` variable in closure below.
231
1856
	let client_for_cidp = client.clone();
232

            
233
1856
	let pending_create_inherent_data_providers = move |block, _| {
234
		// Use timestamp in the future
235
8
		let timestamp = sp_timestamp::InherentDataProvider::new(
236
8
			Timestamp::current()
237
8
				.saturating_add(RELAY_CHAIN_SLOT_DURATION_MILLIS.saturating_mul(100))
238
8
				.into(),
239
		);
240

            
241
8
		let maybe_current_para_head = client_for_cidp.expect_header(block);
242
8
		async move {
243
8
			let current_para_block_head = Some(polkadot_primitives::HeadData(
244
8
				maybe_current_para_head?.encode(),
245
			));
246

            
247
8
			let builder = RelayStateSproofBuilder {
248
8
				para_id,
249
8
				// Use a future relay slot (We derive one from the timestamp)
250
8
				current_slot: polkadot_primitives::Slot::from(
251
8
					timestamp
252
8
						.timestamp()
253
8
						.as_millis()
254
8
						.saturating_div(RELAY_CHAIN_SLOT_DURATION_MILLIS),
255
8
				),
256
8
				included_para_head: current_para_block_head,
257
8
				..Default::default()
258
8
			};
259

            
260
			// Create a dummy parachain inherent data provider which is required to pass
261
			// the checks by the para chain system. We use dummy values because in the 'pending context'
262
			// neither do we have access to the real values nor do we need them.
263
8
			let (relay_parent_storage_root, relay_chain_state) =
264
8
				builder.into_state_root_and_proof();
265

            
266
8
			let vfp = PersistedValidationData {
267
8
				// This is a hack to make `cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases`
268
8
				// happy. Relay parent number can't be bigger than u32::MAX.
269
8
				relay_parent_number: u32::MAX,
270
8
				relay_parent_storage_root,
271
8
				..Default::default()
272
8
			};
273
8
			let parachain_inherent_data = ParachainInherentData {
274
8
				validation_data: vfp,
275
8
				relay_chain_state,
276
8
				downward_messages: Default::default(),
277
8
				horizontal_messages: Default::default(),
278
8
				relay_parent_descendants: Default::default(),
279
8
				collator_peer_id: None,
280
8
			};
281

            
282
8
			Ok((timestamp, parachain_inherent_data))
283
8
		}
284
8
	};
285

            
286
1856
	io.merge(
287
1856
		Eth::<_, _, _, _, _, _, MoonbeamEthConfig<_, _>>::new(
288
1856
			Arc::clone(&client.clone()),
289
1856
			Arc::clone(&pool),
290
1856
			convert_transaction,
291
1856
			Arc::clone(&sync),
292
1856
			signers,
293
1856
			Arc::clone(&overrides),
294
1856
			Arc::clone(&frontier_backend),
295
1856
			is_authority,
296
1856
			Arc::clone(&block_data_cache),
297
1856
			fee_history_cache,
298
1856
			fee_history_limit,
299
1856
			10,
300
1856
			false,
301
1856
			forced_parent_hashes,
302
1856
			pending_create_inherent_data_providers,
303
1856
			Some(pending_consenus_data_provider),
304
1856
		)
305
1856
		.replace_config::<MoonbeamEthConfig<C, BE>>()
306
1856
		.into_rpc(),
307
1856
	)?;
308

            
309
1856
	if let Some(filter_pool) = filter_pool {
310
1856
		io.merge(
311
1856
			EthFilter::new(
312
1856
				client.clone(),
313
1856
				frontier_backend.clone(),
314
1856
				graph.clone(),
315
1856
				filter_pool,
316
1856
				500_usize, // max stored filters
317
1856
				max_past_logs,
318
1856
				max_block_range,
319
1856
				block_data_cache,
320
1856
			)
321
1856
			.into_rpc(),
322
1856
		)?;
323
	}
324

            
325
1856
	io.merge(
326
1856
		Net::new(
327
1856
			Arc::clone(&client),
328
1856
			network.clone(),
329
1856
			// Whether to format the `peer_count` response as Hex (default) or not.
330
1856
			true,
331
1856
		)
332
1856
		.into_rpc(),
333
1856
	)?;
334

            
335
1856
	io.merge(Web3::new(Arc::clone(&client)).into_rpc())?;
336
1856
	io.merge(
337
1856
		EthPubSub::new(
338
1856
			pool,
339
1856
			Arc::clone(&client),
340
1856
			sync.clone(),
341
1856
			subscription_task_executor,
342
1856
			overrides,
343
1856
			pubsub_notification_sinks.clone(),
344
1856
		)
345
1856
		.into_rpc(),
346
1856
	)?;
347

            
348
1856
	if ethapi_cmd.contains(&EthApiCmd::Txpool) {
349
1856
		io.merge(TxPool::new(Arc::clone(&client), graph).into_rpc())?;
350
	}
351

            
352
1856
	io.merge(MoonbeamFinality::new(client.clone(), frontier_backend.clone()).into_rpc())?;
353

            
354
1856
	if let Some(command_sink) = command_sink {
355
1856
		io.merge(
356
1856
			// We provide the rpc handler with the sending end of the channel to allow the rpc
357
1856
			// send EngineCommands to the background block authorship task.
358
1856
			ManualSeal::new(command_sink).into_rpc(),
359
1856
		)?;
360
	};
361

            
362
1856
	if let Some((downward_message_channel, hrmp_message_channel, additional_relay_offset)) =
363
1856
		dev_rpc_data
364
	{
365
1856
		io.merge(
366
1856
			DevRpc {
367
1856
				downward_message_channel,
368
1856
				hrmp_message_channel,
369
1856
				additional_relay_offset,
370
1856
			}
371
1856
			.into_rpc(),
372
1856
		)?;
373
	}
374

            
375
1856
	if let Some(tracing_config) = maybe_tracing_config {
376
		if let Some(trace_filter_requester) = tracing_config.tracing_requesters.trace {
377
			io.merge(
378
				Trace::new(
379
					client,
380
					trace_filter_requester,
381
					tracing_config.trace_filter_max_count,
382
					tracing_config.max_block_range,
383
				)
384
				.into_rpc(),
385
			)?;
386
		}
387

            
388
		if let Some(debug_requester) = tracing_config.tracing_requesters.debug {
389
			io.merge(Debug::new(debug_requester).into_rpc())?;
390
		}
391
1856
	}
392

            
393
1856
	Ok(io)
394
1856
}
395

            
396
pub struct SpawnTasksParams<'a, B: BlockT, C, BE> {
397
	pub task_manager: &'a TaskManager,
398
	pub client: Arc<C>,
399
	pub substrate_backend: Arc<BE>,
400
	pub frontier_backend: Arc<fc_db::Backend<B, C>>,
401
	pub filter_pool: Option<FilterPool>,
402
	pub overrides: Arc<dyn StorageOverride<B>>,
403
	pub fee_history_limit: u64,
404
	pub fee_history_cache: FeeHistoryCache,
405
	pub state_pruning: Option<PruningMode>,
406
}
407

            
408
/// Spawn the tasks that are required to run Moonbeam.
409
928
pub fn spawn_essential_tasks<B, C, BE>(
410
928
	params: SpawnTasksParams<B, C, BE>,
411
928
	sync: Arc<SyncingService<B>>,
412
928
	pubsub_notification_sinks: Arc<
413
928
		fc_mapping_sync::EthereumBlockNotificationSinks<
414
928
			fc_mapping_sync::EthereumBlockNotification<B>,
415
928
		>,
416
928
	>,
417
928
) where
418
928
	C: ProvideRuntimeApi<B> + BlockOf,
419
928
	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,
420
928
	C: BlockchainEvents<B> + StorageProvider<B, BE>,
421
928
	C: Send + Sync + 'static,
422
928
	C::Api: EthereumRuntimeRPCApi<B>,
423
928
	C::Api: BlockBuilder<B>,
424
928
	B: BlockT<Hash = H256> + Send + Sync + 'static,
425
928
	B::Header: HeaderT<Number = u32>,
426
928
	BE: Backend<B> + 'static,
427
928
	BE::State: StateBackend<BlakeTwo256>,
428
{
429
	// Frontier offchain DB task. Essential.
430
	// Maps emulated ethereum data to substrate native data.
431
928
	match *params.frontier_backend {
432
928
		fc_db::Backend::KeyValue(ref b) => {
433
928
			params.task_manager.spawn_essential_handle().spawn(
434
				"frontier-mapping-sync-worker",
435
928
				Some("frontier"),
436
928
				MappingSyncWorker::new(
437
928
					params.client.import_notification_stream(),
438
928
					Duration::new(6, 0),
439
928
					params.client.clone(),
440
928
					params.substrate_backend.clone(),
441
928
					params.overrides.clone(),
442
928
					b.clone(),
443
					3,
444
					0,
445
928
					params.state_pruning.and_then(|mode| {
446
						if let PruningMode::Constrained(c) = mode {
447
							c.max_blocks.map(u64::from)
448
						} else {
449
							None
450
						}
451
					}),
452
928
					SyncStrategy::Parachain,
453
928
					sync.clone(),
454
928
					pubsub_notification_sinks.clone(),
455
				)
456
59914
				.for_each(|()| futures::future::ready(())),
457
			);
458
		}
459
		fc_db::Backend::Sql(ref b) => {
460
			params.task_manager.spawn_essential_handle().spawn_blocking(
461
				"frontier-mapping-sync-worker",
462
				Some("frontier"),
463
				fc_mapping_sync::sql::SyncWorker::run(
464
					params.client.clone(),
465
					params.substrate_backend.clone(),
466
					b.clone(),
467
					params.client.import_notification_stream(),
468
					fc_mapping_sync::sql::SyncWorkerConfig {
469
						read_notification_timeout: Duration::from_secs(10),
470
						check_indexed_blocks_interval: Duration::from_secs(60),
471
					},
472
					fc_mapping_sync::SyncStrategy::Parachain,
473
					sync.clone(),
474
					pubsub_notification_sinks.clone(),
475
				),
476
			);
477
		}
478
	}
479

            
480
	// Frontier `EthFilterApi` maintenance.
481
	// Manages the pool of user-created Filters.
482
928
	if let Some(filter_pool) = params.filter_pool {
483
		// Each filter is allowed to stay in the pool for 100 blocks.
484
		const FILTER_RETAIN_THRESHOLD: u64 = 100;
485
928
		params.task_manager.spawn_essential_handle().spawn(
486
			"frontier-filter-pool",
487
928
			Some("frontier"),
488
928
			EthTask::filter_pool_task(
489
928
				Arc::clone(&params.client),
490
928
				filter_pool,
491
				FILTER_RETAIN_THRESHOLD,
492
			),
493
		);
494
	}
495

            
496
	// Spawn Frontier FeeHistory cache maintenance task.
497
928
	params.task_manager.spawn_essential_handle().spawn(
498
		"frontier-fee-history",
499
928
		Some("frontier"),
500
928
		EthTask::fee_history_task(
501
928
			Arc::clone(&params.client),
502
928
			Arc::clone(&params.overrides),
503
928
			params.fee_history_cache,
504
928
			params.fee_history_limit,
505
		),
506
	);
507
928
}