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_consensus_manual_seal::rpc::{EngineCommand, ManualSeal, ManualSealApiServer};
45
use sc_network::service::traits::NetworkService;
46
use sc_network_sync::SyncingService;
47
use sc_rpc::SubscriptionTaskExecutor;
48
use sc_service::TaskManager;
49
use sc_transaction_pool_api::TransactionPool;
50
use sp_api::{CallApiAt, ProvideRuntimeApi};
51
use sp_blockchain::{
52
	Backend as BlockchainBackend, Error as BlockChainError, HeaderBackend, HeaderMetadata,
53
};
54
use sp_core::H256;
55
use sp_runtime::traits::{BlakeTwo256, Block as BlockT, Header as HeaderT};
56
use sp_timestamp::Timestamp;
57
use std::collections::BTreeMap;
58

            
59
pub struct MoonbeamEGA;
60

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
392
1852
	Ok(io)
393
1852
}
394

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

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

            
471
	// Frontier `EthFilterApi` maintenance.
472
	// Manages the pool of user-created Filters.
473
926
	if let Some(filter_pool) = params.filter_pool {
474
		// Each filter is allowed to stay in the pool for 100 blocks.
475
		const FILTER_RETAIN_THRESHOLD: u64 = 100;
476
926
		params.task_manager.spawn_essential_handle().spawn(
477
			"frontier-filter-pool",
478
926
			Some("frontier"),
479
926
			EthTask::filter_pool_task(
480
926
				Arc::clone(&params.client),
481
926
				filter_pool,
482
				FILTER_RETAIN_THRESHOLD,
483
			),
484
		);
485
	}
486

            
487
	// Spawn Frontier FeeHistory cache maintenance task.
488
926
	params.task_manager.spawn_essential_handle().spawn(
489
		"frontier-fee-history",
490
926
		Some("frontier"),
491
926
		EthTask::fee_history_task(
492
926
			Arc::clone(&params.client),
493
926
			Arc::clone(&params.overrides),
494
926
			params.fee_history_cache,
495
926
			params.fee_history_limit,
496
		),
497
	);
498
926
}