Skip to main content

reth_node_ethereum/
node.rs

1//! Ethereum Node types config.
2
3use crate::{
4    engine_ssz_proxy::{EngineSszApi, EngineSszProxyLayer},
5    engine_ssz_witness::EngineSszWitnessGenerator,
6    EthEngineTypes, EthEvmConfig,
7};
8use alloy_eips::{eip7840::BlobParams, merge::EPOCH_SLOTS};
9use alloy_network::Ethereum;
10use alloy_rpc_types_engine::ExecutionData;
11use reth_chainspec::{ChainSpec, EthChainSpec, EthereumHardforks, Hardforks};
12use reth_engine_local::LocalPayloadAttributesBuilder;
13use reth_engine_primitives::EngineTypes;
14use reth_ethereum_consensus::EthBeaconConsensus;
15use reth_ethereum_engine_primitives::{EthBuiltPayload, EthPayloadAttributes};
16use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
17use reth_evm::{
18    eth::spec::EthExecutorSpec, ConfigureEvm, EvmFactory, EvmFactoryFor, NextBlockEnvAttributes,
19};
20use reth_evm_ethereum::factory::RethEvmFactory;
21#[cfg(feature = "jit")]
22use reth_evm_ethereum::factory::{JitBackend, JitMode, RevmcMetrics, RuntimeConfig, RuntimeTuning};
23use reth_network::{primitives::BasicNetworkPrimitives, NetworkHandle, PeersInfo};
24use reth_node_api::{
25    AddOnsContext, FullNodeComponents, HeaderTy, NodeAddOns, NodePrimitives,
26    PayloadAttributesBuilder, PrimitivesTy, TxTy,
27};
28use reth_node_builder::{
29    components::{
30        BasicPayloadServiceBuilder, ComponentsBuilder, ConsensusBuilder, ExecutorBuilder,
31        NetworkBuilder, PoolBuilder, TxPoolBuilder,
32    },
33    node::{FullNodeTypes, NodeTypes},
34    rpc::{
35        BasicEngineApiBuilder, BasicEngineValidatorBuilder, Either, EngineApiBuilder,
36        EngineValidatorAddOn, EngineValidatorBuilder, EthApiBuilder, EthApiCtx, Identity,
37        PayloadValidatorBuilder, RethAuthHttpMiddleware, RethRpcAddOns, RethRpcMiddleware,
38        RpcAddOns, RpcHandle, Stack,
39    },
40    BuilderContext, DebugNode, EngineApiExt, Node, NodeAdapter, PayloadBuilderConfig,
41};
42use reth_node_core::args::JitArgs;
43use reth_payload_primitives::PayloadTypes;
44use reth_provider::{providers::ProviderFactoryBuilder, EthStorage};
45use reth_rpc::{
46    eth::core::{EthApiFor, EthRpcConverterFor},
47    TestingApi, ValidationApi,
48};
49use reth_rpc_api::servers::{BlockSubmissionValidationApiServer, TestingApiServer};
50use reth_rpc_builder::config::RethRpcServerConfig;
51use reth_rpc_eth_api::{
52    helpers::{
53        config::{EthConfigApiServer, EthConfigHandler},
54        pending_block::BuildPendingEnv,
55    },
56    RpcConvert, RpcTypes, SignableTxRequest,
57};
58use reth_rpc_eth_types::{error::FromEvmError, EthApiError};
59use reth_rpc_server_types::RethRpcModule;
60use reth_tracing::tracing::{debug, info};
61use reth_transaction_pool::{
62    blobstore::DiskFileBlobStore, EthTransactionPool, PoolPooledTx, PoolTransaction,
63    TransactionPool, TransactionValidationTaskExecutor,
64};
65use revm::context::TxEnv;
66use std::{marker::PhantomData, sync::Arc, time::SystemTime};
67
68pub use crate::{payload::EthereumPayloadBuilder, EthereumEngineValidator};
69#[cfg(feature = "jit")]
70pub use reth_evm_ethereum::factory::maybe_run_jit_helper;
71
72/// Type configuration for a regular Ethereum node.
73#[derive(Debug, Default, Clone, Copy)]
74#[non_exhaustive]
75pub struct EthereumNode;
76
77impl EthereumNode {
78    /// Returns a [`ComponentsBuilder`] configured for a regular Ethereum node.
79    pub fn components<Node>() -> ComponentsBuilder<
80        Node,
81        EthereumPoolBuilder,
82        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
83        EthereumNetworkBuilder,
84        EthereumExecutorBuilder,
85        EthereumConsensusBuilder,
86    >
87    where
88        Node: FullNodeTypes<
89            Types: NodeTypes<
90                ChainSpec: Hardforks + EthereumHardforks + EthExecutorSpec,
91                Primitives = EthPrimitives,
92            >,
93        >,
94        <Node::Types as NodeTypes>::Payload:
95            PayloadTypes<BuiltPayload = EthBuiltPayload, PayloadAttributes = EthPayloadAttributes>,
96    {
97        ComponentsBuilder::default()
98            .node_types::<Node>()
99            .pool(EthereumPoolBuilder::default())
100            .executor(EthereumExecutorBuilder::default())
101            .payload(BasicPayloadServiceBuilder::default())
102            .network(EthereumNetworkBuilder::default())
103            .consensus(EthereumConsensusBuilder::default())
104    }
105
106    /// Instantiates the [`ProviderFactoryBuilder`] for an ethereum node.
107    ///
108    /// # Open a Providerfactory in read-only mode from a datadir
109    ///
110    /// See also: [`ProviderFactoryBuilder`] and
111    /// [`ReadOnlyConfig`](reth_provider::providers::ReadOnlyConfig).
112    ///
113    /// ```no_run
114    /// use reth_chainspec::MAINNET;
115    /// use reth_node_ethereum::EthereumNode;
116    ///
117    /// fn demo(runtime: reth_tasks::Runtime) {
118    ///     let factory = EthereumNode::provider_factory_builder()
119    ///         .open_read_only(MAINNET.clone(), "datadir", runtime)
120    ///         .unwrap();
121    /// }
122    /// ```
123    ///
124    /// See also [`ProviderFactory::new`](reth_provider::ProviderFactory::new) for constructing
125    /// a [`ProviderFactory`](reth_provider::ProviderFactory) manually with all required
126    /// components.
127    pub fn provider_factory_builder() -> ProviderFactoryBuilder<Self> {
128        ProviderFactoryBuilder::default()
129    }
130}
131
132impl NodeTypes for EthereumNode {
133    type Primitives = EthPrimitives;
134    type ChainSpec = ChainSpec;
135    type Storage = EthStorage;
136    type Payload = EthEngineTypes;
137}
138
139/// Builds [`EthApi`](reth_rpc::EthApi) for Ethereum.
140#[derive(Debug)]
141pub struct EthereumEthApiBuilder<NetworkT = Ethereum>(PhantomData<NetworkT>);
142
143impl<NetworkT> Default for EthereumEthApiBuilder<NetworkT> {
144    fn default() -> Self {
145        Self(Default::default())
146    }
147}
148
149impl<N, NetworkT> EthApiBuilder<N> for EthereumEthApiBuilder<NetworkT>
150where
151    N: FullNodeComponents<
152        Types: NodeTypes<ChainSpec: Hardforks + EthereumHardforks>,
153        Evm: ConfigureEvm<NextBlockEnvCtx: BuildPendingEnv<HeaderTy<N::Types>>>,
154    >,
155    NetworkT: RpcTypes<TransactionRequest: SignableTxRequest<TxTy<N::Types>>>,
156    EthRpcConverterFor<N, NetworkT>: RpcConvert<
157        Primitives = PrimitivesTy<N::Types>,
158        Error = EthApiError,
159        Network = NetworkT,
160        Evm = N::Evm,
161    >,
162    EthApiError: FromEvmError<N::Evm>,
163{
164    type EthApi = EthApiFor<N, NetworkT>;
165
166    async fn build_eth_api(self, ctx: EthApiCtx<'_, N>) -> eyre::Result<Self::EthApi> {
167        Ok(ctx.eth_api_builder().map_converter(|r| r.with_network()).build())
168    }
169}
170
171/// Add-ons w.r.t. l1 ethereum.
172#[derive(Debug)]
173pub struct EthereumAddOns<
174    N: FullNodeComponents,
175    EthB: EthApiBuilder<N>,
176    PVB,
177    EB = BasicEngineApiBuilder<PVB>,
178    EVB = BasicEngineValidatorBuilder<PVB>,
179    RpcMiddleware = Identity,
180    AuthHttpMiddleware = Identity,
181> {
182    inner: RpcAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>,
183}
184
185impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
186    EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
187where
188    N: FullNodeComponents,
189    EthB: EthApiBuilder<N>,
190{
191    /// Creates a new instance from the inner `RpcAddOns`.
192    pub const fn new(
193        inner: RpcAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>,
194    ) -> Self {
195        Self { inner }
196    }
197}
198
199impl<N> Default for EthereumAddOns<N, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>
200where
201    N: FullNodeComponents<
202        Types: NodeTypes<
203            ChainSpec: EthereumHardforks + Clone + 'static,
204            Payload: EngineTypes<ExecutionData = ExecutionData>
205                         + PayloadTypes<PayloadAttributes = EthPayloadAttributes>,
206            Primitives = EthPrimitives,
207        >,
208    >,
209    EthereumEthApiBuilder: EthApiBuilder<N>,
210{
211    fn default() -> Self {
212        Self::new(RpcAddOns::new(
213            EthereumEthApiBuilder::default(),
214            EthereumEngineValidatorBuilder::default(),
215            BasicEngineApiBuilder::default(),
216            BasicEngineValidatorBuilder::default(),
217            Default::default(),
218            Identity::new(),
219        ))
220    }
221}
222
223impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
224    EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
225where
226    N: FullNodeComponents,
227    EthB: EthApiBuilder<N>,
228{
229    /// Replace the engine API builder.
230    pub fn with_engine_api<T>(
231        self,
232        engine_api_builder: T,
233    ) -> EthereumAddOns<N, EthB, PVB, T, EVB, RpcMiddleware, AuthHttpMiddleware>
234    where
235        T: Send,
236    {
237        let Self { inner } = self;
238        EthereumAddOns::new(inner.with_engine_api(engine_api_builder))
239    }
240
241    /// Replace the payload validator builder.
242    pub fn with_payload_validator<V, T>(
243        self,
244        payload_validator_builder: T,
245    ) -> EthereumAddOns<N, EthB, T, EB, EVB, RpcMiddleware, AuthHttpMiddleware> {
246        let Self { inner } = self;
247        EthereumAddOns::new(inner.with_payload_validator(payload_validator_builder))
248    }
249
250    /// Sets rpc middleware
251    pub fn with_rpc_middleware<T>(
252        self,
253        rpc_middleware: T,
254    ) -> EthereumAddOns<N, EthB, PVB, EB, EVB, T, AuthHttpMiddleware>
255    where
256        T: Send,
257    {
258        let Self { inner } = self;
259        EthereumAddOns::new(inner.with_rpc_middleware(rpc_middleware))
260    }
261
262    /// Configures the HTTP transport middleware for the auth / Engine API server.
263    pub fn with_auth_http_middleware<T>(
264        self,
265        auth_http_middleware: T,
266    ) -> EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, T>
267    where
268        T: Send,
269    {
270        let Self { inner } = self;
271        EthereumAddOns::new(inner.with_auth_http_middleware(auth_http_middleware))
272    }
273
274    /// Stacks an additional HTTP transport middleware layer for the auth / Engine API server.
275    pub fn layer_auth_http_middleware<T>(
276        self,
277        layer: T,
278    ) -> EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, Stack<AuthHttpMiddleware, T>> {
279        let Self { inner } = self;
280        EthereumAddOns::new(inner.layer_auth_http_middleware(layer))
281    }
282
283    /// Conditionally stacks an HTTP transport middleware layer for the auth / Engine API server.
284    #[expect(clippy::type_complexity)]
285    pub fn option_layer_auth_http_middleware<T>(
286        self,
287        layer: Option<T>,
288    ) -> EthereumAddOns<
289        N,
290        EthB,
291        PVB,
292        EB,
293        EVB,
294        RpcMiddleware,
295        Stack<AuthHttpMiddleware, Either<T, Identity>>,
296    > {
297        let Self { inner } = self;
298        EthereumAddOns::new(inner.option_layer_auth_http_middleware(layer))
299    }
300
301    /// Sets the tokio runtime for the RPC servers.
302    ///
303    /// Caution: This runtime must not be created from within asynchronous context.
304    pub fn with_tokio_runtime(self, tokio_runtime: Option<tokio::runtime::Handle>) -> Self {
305        let Self { inner } = self;
306        Self { inner: inner.with_tokio_runtime(tokio_runtime) }
307    }
308}
309
310impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware> NodeAddOns<N>
311    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
312where
313    N: FullNodeComponents<
314        Types: NodeTypes<
315            ChainSpec: EthChainSpec + Hardforks + EthereumHardforks,
316            Primitives = EthPrimitives,
317            Payload: EngineTypes<ExecutionData = ExecutionData>,
318        >,
319        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
320    >,
321    EthB: EthApiBuilder<N>,
322    PVB: Send,
323    EB: EngineApiBuilder<N>,
324    EB::EngineApi: EngineSszApi,
325    EVB: EngineValidatorBuilder<N>,
326    EthApiError: FromEvmError<N::Evm>,
327    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
328    RpcMiddleware: RethRpcMiddleware,
329    AuthHttpMiddleware: RethAuthHttpMiddleware<Identity>,
330    Stack<EngineSszProxyLayer<EB::EngineApi>, AuthHttpMiddleware>: RethAuthHttpMiddleware<Identity>,
331{
332    type Handle = RpcHandle<N, EthB::EthApi>;
333
334    async fn launch_add_ons(
335        self,
336        ctx: reth_node_api::AddOnsContext<'_, N>,
337    ) -> eyre::Result<Self::Handle> {
338        let validation_api = ValidationApi::<_, _, <N::Types as NodeTypes>::Payload>::new(
339            ctx.node.provider().clone(),
340            Arc::new(ctx.node.consensus().clone()),
341            ctx.node.evm_config().clone(),
342            ctx.config.rpc.flashbots_config(),
343            ctx.node.task_executor().clone(),
344            Arc::new(EthereumEngineValidator::new(ctx.config.chain.clone())),
345        );
346
347        let eth_config =
348            EthConfigHandler::new(ctx.node.provider().clone(), ctx.node.evm_config().clone());
349
350        let testing_skip_invalid_transactions = ctx.config.rpc.testing_skip_invalid_transactions;
351        let testing_gas_limit_override = ctx.config.rpc.testing_gas_limit;
352        let testing_desired_gas_limit = ctx.config.builder.gas_limit_for(ctx.config.chain.chain());
353        let testing_engine_handle = ctx.beacon_engine_handle.clone();
354
355        let (ssz_proxy_layer, ssz_proxy_handle) = EngineSszProxyLayer::new();
356        ssz_proxy_handle.set_witness_handler_sync(Arc::new(EngineSszWitnessGenerator::new(
357            ctx.node.provider().clone(),
358            ctx.node.evm_config().clone(),
359            ctx.node.task_executor().clone(),
360        )));
361
362        self.inner
363            .map_engine_api(|engine_api_builder| {
364                EngineApiExt::new(engine_api_builder, move |engine_api| {
365                    ssz_proxy_handle.set_engine_api_sync(engine_api);
366                })
367            })
368            .map_auth_http_middleware(|middleware| Stack::new(ssz_proxy_layer, middleware))
369            .launch_add_ons_with(ctx, move |container| {
370                container.modules.merge_if_module_configured(
371                    RethRpcModule::Flashbots,
372                    validation_api.into_rpc(),
373                )?;
374
375                container
376                    .modules
377                    .merge_if_module_configured(RethRpcModule::Eth, eth_config.into_rpc())?;
378
379                // testing_buildBlockV1: only wire when the hidden testing module is explicitly
380                // requested on any transport. Default stays disabled to honor security guidance.
381                let mut testing_api = TestingApi::new(
382                    container.registry.eth_api().clone(),
383                    container.registry.evm_config().clone(),
384                    testing_desired_gas_limit,
385                    testing_engine_handle,
386                );
387                if testing_skip_invalid_transactions {
388                    testing_api = testing_api.with_skip_invalid_transactions();
389                }
390                if let Some(gas_limit) = testing_gas_limit_override {
391                    testing_api = testing_api.with_gas_limit_override(gas_limit);
392                }
393                container
394                    .modules
395                    .merge_if_module_configured(RethRpcModule::Testing, testing_api.into_rpc())?;
396
397                Ok(())
398            })
399            .await
400    }
401}
402
403impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware> RethRpcAddOns<N>
404    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
405where
406    N: FullNodeComponents<
407        Types: NodeTypes<
408            ChainSpec: Hardforks + EthereumHardforks,
409            Primitives = EthPrimitives,
410            Payload: EngineTypes<ExecutionData = ExecutionData>,
411        >,
412        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
413    >,
414    EthB: EthApiBuilder<N>,
415    PVB: PayloadValidatorBuilder<N>,
416    EB: EngineApiBuilder<N>,
417    EB::EngineApi: EngineSszApi,
418    EVB: EngineValidatorBuilder<N>,
419    EthApiError: FromEvmError<N::Evm>,
420    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
421    RpcMiddleware: RethRpcMiddleware,
422    AuthHttpMiddleware: RethAuthHttpMiddleware<Identity>,
423    Stack<EngineSszProxyLayer<EB::EngineApi>, AuthHttpMiddleware>: RethAuthHttpMiddleware<Identity>,
424{
425    type EthApi = EthB::EthApi;
426
427    fn hooks_mut(&mut self) -> &mut reth_node_builder::rpc::RpcHooks<N, Self::EthApi> {
428        self.inner.hooks_mut()
429    }
430}
431
432impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware> EngineValidatorAddOn<N>
433    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
434where
435    N: FullNodeComponents<
436        Types: NodeTypes<
437            ChainSpec: EthChainSpec + EthereumHardforks,
438            Primitives = EthPrimitives,
439            Payload: EngineTypes<ExecutionData = ExecutionData>,
440        >,
441        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
442    >,
443    EthB: EthApiBuilder<N>,
444    PVB: Send,
445    EB: EngineApiBuilder<N>,
446    EVB: EngineValidatorBuilder<N>,
447    EthApiError: FromEvmError<N::Evm>,
448    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
449    RpcMiddleware: Send,
450    AuthHttpMiddleware: Send,
451{
452    type ValidatorBuilder = EVB;
453
454    fn engine_validator_builder(&self) -> Self::ValidatorBuilder {
455        self.inner.engine_validator_builder()
456    }
457}
458
459impl<N> Node<N> for EthereumNode
460where
461    N: FullNodeTypes<Types = Self>,
462{
463    type ComponentsBuilder = ComponentsBuilder<
464        N,
465        EthereumPoolBuilder,
466        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
467        EthereumNetworkBuilder,
468        EthereumExecutorBuilder,
469        EthereumConsensusBuilder,
470    >;
471
472    type AddOns =
473        EthereumAddOns<NodeAdapter<N>, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>;
474
475    fn components_builder(&self) -> Self::ComponentsBuilder {
476        Self::components()
477    }
478
479    fn add_ons(&self) -> Self::AddOns {
480        EthereumAddOns::default()
481    }
482}
483
484impl<N: FullNodeComponents<Types = Self>> DebugNode<N> for EthereumNode {
485    type RpcBlock = alloy_rpc_types_eth::Block;
486
487    fn rpc_to_primitive_block(rpc_block: Self::RpcBlock) -> reth_ethereum_primitives::Block {
488        rpc_block.into_consensus().convert_transactions()
489    }
490
491    fn local_payload_attributes_builder(
492        chain_spec: &Self::ChainSpec,
493    ) -> impl PayloadAttributesBuilder<<Self::Payload as PayloadTypes>::PayloadAttributes> {
494        LocalPayloadAttributesBuilder::new(Arc::new(chain_spec.clone()))
495    }
496}
497
498/// Builds a [`RuntimeConfig`] from CLI [`JitArgs`].
499#[cfg(feature = "jit")]
500fn jit_runtime_config(jit: &JitArgs) -> RuntimeConfig {
501    let default_tuning = RuntimeTuning::default();
502    let tuning = RuntimeTuning {
503        channel_capacity: jit.channel_capacity,
504        jit_hot_threshold: jit.hot_threshold,
505        jit_max_bytecode_len: jit.max_bytecode_len,
506        jit_max_pending_jobs: jit.max_pending_jobs,
507        jit_worker_count: jit.worker_count.unwrap_or(default_tuning.jit_worker_count),
508        jit_timeout: default_tuning.jit_timeout,
509        jit_helper_memory_limit_bytes: default_tuning.jit_helper_memory_limit_bytes,
510        jit_helper_cpu_count: default_tuning.jit_helper_cpu_count,
511        resident_code_cache_bytes: jit.code_cache_bytes,
512        idle_evict_duration: Some(jit.idle_evict_duration),
513
514        max_events_per_drain: default_tuning.max_events_per_drain,
515        event_drain_interval: default_tuning.event_drain_interval,
516        shutdown_timeout: default_tuning.shutdown_timeout,
517        jit_worker_queue_capacity: default_tuning.jit_worker_queue_capacity,
518        jit_opt_level: default_tuning.jit_opt_level,
519        aot_opt_level: default_tuning.aot_opt_level,
520        eviction_sweep_interval: default_tuning.eviction_sweep_interval,
521        compiler_recycle_threshold: default_tuning.compiler_recycle_threshold,
522    };
523
524    let default_config = RuntimeConfig::default();
525    RuntimeConfig {
526        enabled: jit.enabled,
527        thread_name: default_config.thread_name,
528        store: default_config.store,
529        tuning,
530        dump_dir: default_config.dump_dir,
531        debug_assertions: jit.debug,
532        blocking: jit.blocking,
533        single_error: default_config.single_error,
534        no_dedup: default_config.no_dedup,
535        no_dse: default_config.no_dse,
536        gas_params: default_config.gas_params,
537        aot: default_config.aot,
538        jit_mode: JitMode::OutOfProcess,
539        jit_helper_path: default_config.jit_helper_path,
540        on_compilation: default_config.on_compilation,
541    }
542}
543
544/// Builds an [`EthEvmConfig`] with revmc JIT from CLI [`JitArgs`].
545///
546/// This is the shared setup used by both [`EthereumExecutorBuilder`] and `reth re-execute`.
547///
548/// Returns the evm config and metrics recorder if JIT starts enabled.
549#[cfg(feature = "jit")]
550#[allow(clippy::type_complexity)]
551pub fn build_evm_config<C: EthereumHardforks>(
552    chain_spec: Arc<C>,
553    jit: &JitArgs,
554    dump_dir: Option<std::path::PathBuf>,
555) -> eyre::Result<(EthEvmConfig<C, RethEvmFactory>, Option<Arc<RevmcMetrics>>)> {
556    if !jit.enabled {
557        let factory = RethEvmFactory::disabled();
558        return Ok((EthEvmConfig::new_with_evm_factory(chain_spec, factory), None));
559    }
560
561    let mut config = jit_runtime_config(jit);
562    config.dump_dir = dump_dir;
563
564    let revmc_metrics = Arc::new(RevmcMetrics::default());
565    let compilation_metrics = revmc_metrics.clone();
566    config.on_compilation = Some(Arc::new(move |event| {
567        compilation_metrics.record_compilation(&event);
568    }));
569
570    let tuning = config.tuning;
571    let jit_mode = config.jit_mode;
572    let backend = JitBackend::new(config)?;
573
574    reth_tracing::tracing::warn!(target: "reth::cli",
575        hot_threshold = tuning.jit_hot_threshold,
576        workers = tuning.jit_worker_count,
577        mode = ?jit_mode,
578        blocking = jit.blocking,
579        "Started experimental revmc JIT backend; this may cause instability",
580    );
581
582    let factory = RethEvmFactory::new_with_metrics(backend, revmc_metrics.as_ref().clone());
583    let evm_config = EthEvmConfig::new_with_evm_factory(chain_spec, factory);
584
585    Ok((evm_config, Some(revmc_metrics)))
586}
587
588/// Builds an [`EthEvmConfig`] from CLI [`JitArgs`].
589///
590/// This is the shared setup used by both [`EthereumExecutorBuilder`] and `reth re-execute`.
591///
592/// Compiled without the `jit` feature: errors if JIT was requested via [`JitArgs`] and otherwise
593/// returns a plain interpreter-backed config.
594#[cfg(not(feature = "jit"))]
595#[allow(clippy::type_complexity)]
596pub fn build_evm_config<C: EthereumHardforks>(
597    chain_spec: Arc<C>,
598    jit: &JitArgs,
599    _dump_dir: Option<std::path::PathBuf>,
600) -> eyre::Result<(EthEvmConfig<C, RethEvmFactory>, Option<()>)> {
601    if jit.enabled {
602        eyre::bail!(
603            "JIT compilation was requested but this binary was compiled without the `jit` feature"
604        );
605    }
606    let factory = RethEvmFactory::default();
607    Ok((EthEvmConfig::new_with_evm_factory(chain_spec, factory), None))
608}
609
610/// A regular ethereum evm and executor builder.
611///
612/// Uses [`RethEvmFactory`].
613#[derive(Debug, Default, Clone, Copy)]
614#[non_exhaustive]
615pub struct EthereumExecutorBuilder;
616
617impl<Types, Node> ExecutorBuilder<Node> for EthereumExecutorBuilder
618where
619    Types: NodeTypes<
620        ChainSpec: Hardforks + EthExecutorSpec + EthereumHardforks,
621        Primitives = EthPrimitives,
622    >,
623    Node: FullNodeTypes<Types = Types>,
624{
625    type EVM = EthEvmConfig<Types::ChainSpec, RethEvmFactory>;
626
627    async fn build_evm(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::EVM> {
628        let jit = &ctx.config().jit;
629        let dump_dir = jit.debug.then(|| ctx.config().datadir().data_dir().join("jit"));
630
631        let (mut evm_config, revmc_metrics) = build_evm_config(ctx.chain_spec(), jit, dump_dir)?;
632        if let Some(cache) = ctx.sender_recovery_cache() {
633            evm_config = evm_config.with_sender_recovery_cache(cache.clone());
634        }
635
636        #[cfg(not(feature = "jit"))]
637        let _ = revmc_metrics;
638
639        #[cfg(feature = "jit")]
640        if let Some(revmc_metrics) = revmc_metrics {
641            let metrics_backend = evm_config.executor_factory.evm_factory().backend().clone();
642            ctx.task_executor().spawn_with_graceful_shutdown_signal(|shutdown| async move {
643                let mut shutdown = std::pin::pin!(shutdown);
644                loop {
645                    tokio::select! {
646                        _ = tokio::time::sleep(std::time::Duration::from_secs(5)) => {
647                            revmc_metrics.record(&metrics_backend.stats());
648                        }
649                        _ = &mut shutdown => break,
650                    }
651                }
652            });
653        }
654
655        Ok(evm_config)
656    }
657}
658
659/// A basic ethereum transaction pool.
660///
661/// This contains various settings that can be configured and take precedence over the node's
662/// config.
663#[derive(Debug, Clone, Copy)]
664#[non_exhaustive]
665pub struct EthereumPoolBuilder {
666    init_kzg_settings: bool,
667}
668
669impl EthereumPoolBuilder {
670    /// Creates a new [`EthereumPoolBuilder`].
671    pub const fn new() -> Self {
672        Self { init_kzg_settings: false }
673    }
674
675    /// Sets whether to initialize KZG settings even if EIP-4844 support is disabled in the pool.
676    pub const fn with_init_kzg_settings(mut self, init_kzg_settings: bool) -> Self {
677        self.init_kzg_settings = init_kzg_settings;
678        self
679    }
680}
681
682impl Default for EthereumPoolBuilder {
683    fn default() -> Self {
684        Self::new()
685    }
686}
687
688impl<Types, Node, Evm> PoolBuilder<Node, Evm> for EthereumPoolBuilder
689where
690    Types: NodeTypes<
691        ChainSpec: EthereumHardforks,
692        Primitives: NodePrimitives<SignedTx = TransactionSigned>,
693    >,
694    Node: FullNodeTypes<Types = Types>,
695    Evm: ConfigureEvm<Primitives = PrimitivesTy<Types>> + Clone + 'static,
696{
697    type Pool = EthTransactionPool<Node::Provider, DiskFileBlobStore, Evm>;
698
699    async fn build_pool(
700        self,
701        ctx: &BuilderContext<Node>,
702        evm_config: Evm,
703    ) -> eyre::Result<Self::Pool> {
704        let pool_config = ctx.pool_config();
705
706        let blobs_disabled = ctx.config().txpool.disable_blobs_support ||
707            ctx.config().txpool.blobpool_max_count == 0;
708
709        let blob_cache_size = if let Some(blob_cache_size) = pool_config.blob_cache_size {
710            Some(blob_cache_size)
711        } else {
712            // get the current blob params for the current timestamp, fallback to default Cancun
713            // params
714            let current_timestamp =
715                SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_secs();
716            let blob_params = ctx
717                .chain_spec()
718                .blob_params_at_timestamp(current_timestamp)
719                .unwrap_or_else(BlobParams::cancun);
720
721            // Derive the blob cache size from the target blob count, to auto scale it by
722            // multiplying it with the slot count for 2 epochs: 384 for pectra
723            Some((blob_params.target_blob_count * EPOCH_SLOTS * 2) as u32)
724        };
725
726        let blob_store =
727            reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?;
728
729        let validator =
730            TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), evm_config)
731                .set_eip4844(!blobs_disabled)
732                .kzg_settings(ctx.kzg_settings()?)
733                .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes)
734                .with_local_transactions_config(pool_config.local_transactions_config.clone())
735                .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap)
736                .with_max_tx_gas_limit(ctx.config().txpool.max_tx_gas_limit)
737                .with_minimum_priority_fee(ctx.config().txpool.minimum_priority_fee)
738                .with_additional_tasks(ctx.config().txpool.additional_validation_tasks)
739                .build_with_tasks(ctx.task_executor().clone(), blob_store.clone());
740
741        if validator.validator().eip4844() || self.init_kzg_settings {
742            // initializing the KZG settings can be expensive, this should be done upfront so that
743            // it doesn't impact the first block or the first gossiped blob transaction, so we
744            // initialize this in the background
745            let kzg_settings = validator.validator().kzg_settings().clone();
746            ctx.task_executor().spawn_blocking_task(async move {
747                let _ = kzg_settings.get();
748                debug!(target: "reth::cli", "Initialized KZG settings");
749            });
750        }
751
752        let transaction_pool = TxPoolBuilder::new(ctx)
753            .with_validator(validator)
754            .build_and_spawn_maintenance_task(blob_store, pool_config)?;
755
756        info!(target: "reth::cli", "Transaction pool initialized");
757        debug!(target: "reth::cli", "Spawned txpool maintenance task");
758
759        Ok(transaction_pool)
760    }
761}
762
763/// A basic ethereum payload service.
764#[derive(Debug, Default, Clone, Copy)]
765pub struct EthereumNetworkBuilder {
766    // TODO add closure to modify network
767}
768
769impl<Node, Pool> NetworkBuilder<Node, Pool> for EthereumNetworkBuilder
770where
771    Node: FullNodeTypes<Types: NodeTypes<ChainSpec: Hardforks>>,
772    Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TxTy<Node::Types>>>
773        + Unpin
774        + 'static,
775{
776    type Network =
777        NetworkHandle<BasicNetworkPrimitives<PrimitivesTy<Node::Types>, PoolPooledTx<Pool>>>;
778
779    async fn build_network(
780        self,
781        ctx: &BuilderContext<Node>,
782        pool: Pool,
783    ) -> eyre::Result<Self::Network> {
784        let network = ctx.network_builder().await?;
785        let handle = ctx.start_network(network, pool);
786        info!(target: "reth::cli", enode=%handle.local_node_record(), "P2P networking initialized");
787        Ok(handle)
788    }
789}
790
791/// A basic ethereum consensus builder.
792#[derive(Debug, Default, Clone, Copy)]
793pub struct EthereumConsensusBuilder {
794    // TODO add closure to modify consensus
795}
796
797impl<Node> ConsensusBuilder<Node> for EthereumConsensusBuilder
798where
799    Node: FullNodeTypes<
800        Types: NodeTypes<ChainSpec: EthChainSpec + EthereumHardforks, Primitives = EthPrimitives>,
801    >,
802{
803    type Consensus = Arc<EthBeaconConsensus<<Node::Types as NodeTypes>::ChainSpec>>;
804
805    async fn build_consensus(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::Consensus> {
806        Ok(Arc::new(EthBeaconConsensus::new(ctx.chain_spec())))
807    }
808}
809
810/// Builder for [`EthereumEngineValidator`].
811#[derive(Debug, Default, Clone)]
812#[non_exhaustive]
813pub struct EthereumEngineValidatorBuilder;
814
815impl<Node, Types> PayloadValidatorBuilder<Node> for EthereumEngineValidatorBuilder
816where
817    Types: NodeTypes<
818        ChainSpec: Hardforks + EthereumHardforks + Clone + 'static,
819        Payload: EngineTypes<ExecutionData = ExecutionData>
820                     + PayloadTypes<PayloadAttributes = EthPayloadAttributes>,
821        Primitives = EthPrimitives,
822    >,
823    Node: FullNodeComponents<Types = Types>,
824{
825    type Validator = EthereumEngineValidator<Types::ChainSpec>;
826
827    async fn build(self, ctx: &AddOnsContext<'_, Node>) -> eyre::Result<Self::Validator> {
828        Ok(EthereumEngineValidator::new(ctx.config.chain.clone()))
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::EthereumPoolBuilder;
835
836    #[test]
837    fn configures_kzg_settings_initialization() {
838        assert!(!EthereumPoolBuilder::new().init_kzg_settings);
839        assert!(EthereumPoolBuilder::new().with_init_kzg_settings(true).init_kzg_settings);
840    }
841}