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

            
57
pub struct MoonbeamEGA;
58

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

            
87
pub struct MoonbeamEthConfig<C, BE>(std::marker::PhantomData<(C, BE)>);
88

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

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

            
145
pub struct TracingConfig {
146
	pub tracing_requesters: crate::rpc::tracing::RpcRequesters,
147
	pub trace_filter_max_count: u32,
148
}
149

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

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

            
209
1872
	io.merge(System::new(Arc::clone(&client), Arc::clone(&pool)).into_rpc())?;
210
1872
	io.merge(TransactionPayment::new(Arc::clone(&client)).into_rpc())?;
211

            
212
	// TODO: are we supporting signing?
213
1872
	let signers = Vec::new();
214
1872

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

            
226
1872
	let pending_create_inherent_data_providers = move |_, _| async move {
227
8
		let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
228
8
		// Create a dummy parachain inherent data provider which is required to pass
229
8
		// the checks by the para chain system. We use dummy values because in the 'pending context'
230
8
		// neither do we have access to the real values nor do we need them.
231
8
		let (relay_parent_storage_root, relay_chain_state) =
232
8
			RelayStateSproofBuilder::default().into_state_root_and_proof();
233
8
		let vfp = PersistedValidationData {
234
8
			// This is a hack to make `cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases`
235
8
			// happy. Relay parent number can't be bigger than u32::MAX.
236
8
			relay_parent_number: u32::MAX,
237
8
			relay_parent_storage_root,
238
8
			..Default::default()
239
8
		};
240
8
		let parachain_inherent_data = ParachainInherentData {
241
8
			validation_data: vfp,
242
8
			relay_chain_state,
243
8
			downward_messages: Default::default(),
244
8
			horizontal_messages: Default::default(),
245
8
		};
246
8
		Ok((timestamp, parachain_inherent_data))
247
8
	};
248

            
249
1872
	io.merge(
250
1872
		Eth::<_, _, _, _, _, _, _, MoonbeamEthConfig<_, _>>::new(
251
1872
			Arc::clone(&client),
252
1872
			Arc::clone(&pool),
253
1872
			graph.clone(),
254
1872
			convert_transaction,
255
1872
			Arc::clone(&sync),
256
1872
			signers,
257
1872
			Arc::clone(&overrides),
258
1872
			Arc::clone(&frontier_backend),
259
1872
			is_authority,
260
1872
			Arc::clone(&block_data_cache),
261
1872
			fee_history_cache,
262
1872
			fee_history_limit,
263
1872
			10,
264
1872
			forced_parent_hashes,
265
1872
			pending_create_inherent_data_providers,
266
1872
			Some(pending_consenus_data_provider),
267
1872
		)
268
1872
		.replace_config::<MoonbeamEthConfig<C, BE>>()
269
1872
		.into_rpc(),
270
1872
	)?;
271

            
272
1872
	if let Some(filter_pool) = filter_pool {
273
1872
		io.merge(
274
1872
			EthFilter::new(
275
1872
				client.clone(),
276
1872
				frontier_backend.clone(),
277
1872
				graph.clone(),
278
1872
				filter_pool,
279
1872
				500_usize, // max stored filters
280
1872
				max_past_logs,
281
1872
				max_block_range,
282
1872
				block_data_cache,
283
1872
			)
284
1872
			.into_rpc(),
285
1872
		)?;
286
	}
287

            
288
1872
	io.merge(
289
1872
		Net::new(
290
1872
			Arc::clone(&client),
291
1872
			network.clone(),
292
1872
			// Whether to format the `peer_count` response as Hex (default) or not.
293
1872
			true,
294
1872
		)
295
1872
		.into_rpc(),
296
1872
	)?;
297

            
298
1872
	io.merge(Web3::new(Arc::clone(&client)).into_rpc())?;
299
1872
	io.merge(
300
1872
		EthPubSub::new(
301
1872
			pool,
302
1872
			Arc::clone(&client),
303
1872
			sync.clone(),
304
1872
			subscription_task_executor,
305
1872
			overrides,
306
1872
			pubsub_notification_sinks.clone(),
307
1872
		)
308
1872
		.into_rpc(),
309
1872
	)?;
310

            
311
1872
	if ethapi_cmd.contains(&EthApiCmd::Txpool) {
312
1872
		io.merge(TxPool::new(Arc::clone(&client), graph).into_rpc())?;
313
	}
314

            
315
1872
	io.merge(MoonbeamFinality::new(client.clone(), frontier_backend.clone()).into_rpc())?;
316

            
317
1872
	if let Some(command_sink) = command_sink {
318
1872
		io.merge(
319
1872
			// We provide the rpc handler with the sending end of the channel to allow the rpc
320
1872
			// send EngineCommands to the background block authorship task.
321
1872
			ManualSeal::new(command_sink).into_rpc(),
322
1872
		)?;
323
	};
324

            
325
1872
	if let Some((downward_message_channel, hrmp_message_channel, additional_relay_offset)) =
326
1872
		dev_rpc_data
327
	{
328
1872
		io.merge(
329
1872
			DevRpc {
330
1872
				downward_message_channel,
331
1872
				hrmp_message_channel,
332
1872
				additional_relay_offset,
333
1872
			}
334
1872
			.into_rpc(),
335
1872
		)?;
336
	}
337

            
338
1872
	if let Some(tracing_config) = maybe_tracing_config {
339
		if let Some(trace_filter_requester) = tracing_config.tracing_requesters.trace {
340
			io.merge(
341
				Trace::new(
342
					client,
343
					trace_filter_requester,
344
					tracing_config.trace_filter_max_count,
345
				)
346
				.into_rpc(),
347
			)?;
348
		}
349

            
350
		if let Some(debug_requester) = tracing_config.tracing_requesters.debug {
351
			io.merge(Debug::new(debug_requester).into_rpc())?;
352
		}
353
1872
	}
354

            
355
1872
	Ok(io)
356
1872
}
357

            
358
pub struct SpawnTasksParams<'a, B: BlockT, C, BE> {
359
	pub task_manager: &'a TaskManager,
360
	pub client: Arc<C>,
361
	pub substrate_backend: Arc<BE>,
362
	pub frontier_backend: Arc<fc_db::Backend<B, C>>,
363
	pub filter_pool: Option<FilterPool>,
364
	pub overrides: Arc<dyn StorageOverride<B>>,
365
	pub fee_history_limit: u64,
366
	pub fee_history_cache: FeeHistoryCache,
367
}
368

            
369
/// Spawn the tasks that are required to run Moonbeam.
370
936
pub fn spawn_essential_tasks<B, C, BE>(
371
936
	params: SpawnTasksParams<B, C, BE>,
372
936
	sync: Arc<SyncingService<B>>,
373
936
	pubsub_notification_sinks: Arc<
374
936
		fc_mapping_sync::EthereumBlockNotificationSinks<
375
936
			fc_mapping_sync::EthereumBlockNotification<B>,
376
936
		>,
377
936
	>,
378
936
) where
379
936
	C: ProvideRuntimeApi<B> + BlockOf,
380
936
	C: HeaderBackend<B> + HeaderMetadata<B, Error = BlockChainError> + 'static,
381
936
	C: BlockchainEvents<B> + StorageProvider<B, BE>,
382
936
	C: Send + Sync + 'static,
383
936
	C::Api: EthereumRuntimeRPCApi<B>,
384
936
	C::Api: BlockBuilder<B>,
385
936
	B: BlockT<Hash = H256> + Send + Sync + 'static,
386
936
	B::Header: HeaderT<Number = u32>,
387
936
	BE: Backend<B> + 'static,
388
936
	BE::State: StateBackend<BlakeTwo256>,
389
936
{
390
936
	// Frontier offchain DB task. Essential.
391
936
	// Maps emulated ethereum data to substrate native data.
392
936
	match *params.frontier_backend {
393
936
		fc_db::Backend::KeyValue(ref b) => {
394
936
			params.task_manager.spawn_essential_handle().spawn(
395
936
				"frontier-mapping-sync-worker",
396
936
				Some("frontier"),
397
936
				MappingSyncWorker::new(
398
936
					params.client.import_notification_stream(),
399
936
					Duration::new(6, 0),
400
936
					params.client.clone(),
401
936
					params.substrate_backend.clone(),
402
936
					params.overrides.clone(),
403
936
					b.clone(),
404
936
					3,
405
936
					0,
406
936
					SyncStrategy::Parachain,
407
936
					sync.clone(),
408
936
					pubsub_notification_sinks.clone(),
409
936
				)
410
55470
				.for_each(|()| futures::future::ready(())),
411
936
			);
412
936
		}
413
		fc_db::Backend::Sql(ref b) => {
414
			params.task_manager.spawn_essential_handle().spawn_blocking(
415
				"frontier-mapping-sync-worker",
416
				Some("frontier"),
417
				fc_mapping_sync::sql::SyncWorker::run(
418
					params.client.clone(),
419
					params.substrate_backend.clone(),
420
					b.clone(),
421
					params.client.import_notification_stream(),
422
					fc_mapping_sync::sql::SyncWorkerConfig {
423
						read_notification_timeout: Duration::from_secs(10),
424
						check_indexed_blocks_interval: Duration::from_secs(60),
425
					},
426
					fc_mapping_sync::SyncStrategy::Parachain,
427
					sync.clone(),
428
					pubsub_notification_sinks.clone(),
429
				),
430
			);
431
		}
432
	}
433

            
434
	// Frontier `EthFilterApi` maintenance.
435
	// Manages the pool of user-created Filters.
436
936
	if let Some(filter_pool) = params.filter_pool {
437
936
		// Each filter is allowed to stay in the pool for 100 blocks.
438
936
		const FILTER_RETAIN_THRESHOLD: u64 = 100;
439
936
		params.task_manager.spawn_essential_handle().spawn(
440
936
			"frontier-filter-pool",
441
936
			Some("frontier"),
442
936
			EthTask::filter_pool_task(
443
936
				Arc::clone(&params.client),
444
936
				filter_pool,
445
936
				FILTER_RETAIN_THRESHOLD,
446
936
			),
447
936
		);
448
936
	}
449

            
450
	// Spawn Frontier FeeHistory cache maintenance task.
451
936
	params.task_manager.spawn_essential_handle().spawn(
452
936
		"frontier-fee-history",
453
936
		Some("frontier"),
454
936
		EthTask::fee_history_task(
455
936
			Arc::clone(&params.client),
456
936
			Arc::clone(&params.overrides),
457
936
			params.fee_history_cache,
458
936
			params.fee_history_limit,
459
936
		),
460
936
	);
461
936
}