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            ctx.sender_recovery_cache.clone(),
346        );
347
348        let eth_config =
349            EthConfigHandler::new(ctx.node.provider().clone(), ctx.node.evm_config().clone());
350
351        let testing_skip_invalid_transactions = ctx.config.rpc.testing_skip_invalid_transactions;
352        let testing_gas_limit_override = ctx.config.rpc.testing_gas_limit;
353        let testing_desired_gas_limit = ctx.config.builder.gas_limit_for(ctx.config.chain.chain());
354        let testing_engine_handle = ctx.beacon_engine_handle.clone();
355
356        let (ssz_proxy_layer, ssz_proxy_handle) = EngineSszProxyLayer::new();
357        ssz_proxy_handle.set_witness_handler_sync(Arc::new(EngineSszWitnessGenerator::new(
358            ctx.node.provider().clone(),
359            ctx.node.evm_config().clone(),
360            ctx.node.task_executor().clone(),
361        )));
362
363        self.inner
364            .map_engine_api(|engine_api_builder| {
365                EngineApiExt::new(engine_api_builder, move |engine_api| {
366                    ssz_proxy_handle.set_engine_api_sync(engine_api);
367                })
368            })
369            .map_auth_http_middleware(|middleware| Stack::new(ssz_proxy_layer, middleware))
370            .launch_add_ons_with(ctx, move |container| {
371                container.modules.merge_if_module_configured(
372                    RethRpcModule::Flashbots,
373                    validation_api.into_rpc(),
374                )?;
375
376                container
377                    .modules
378                    .merge_if_module_configured(RethRpcModule::Eth, eth_config.into_rpc())?;
379
380                // testing_buildBlockV1: only wire when the hidden testing module is explicitly
381                // requested on any transport. Default stays disabled to honor security guidance.
382                let mut testing_api = TestingApi::new(
383                    container.registry.eth_api().clone(),
384                    container.registry.evm_config().clone(),
385                    testing_desired_gas_limit,
386                    testing_engine_handle,
387                );
388                if testing_skip_invalid_transactions {
389                    testing_api = testing_api.with_skip_invalid_transactions();
390                }
391                if let Some(gas_limit) = testing_gas_limit_override {
392                    testing_api = testing_api.with_gas_limit_override(gas_limit);
393                }
394                container
395                    .modules
396                    .merge_if_module_configured(RethRpcModule::Testing, testing_api.into_rpc())?;
397
398                Ok(())
399            })
400            .await
401    }
402}
403
404impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware> RethRpcAddOns<N>
405    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
406where
407    N: FullNodeComponents<
408        Types: NodeTypes<
409            ChainSpec: Hardforks + EthereumHardforks,
410            Primitives = EthPrimitives,
411            Payload: EngineTypes<ExecutionData = ExecutionData>,
412        >,
413        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
414    >,
415    EthB: EthApiBuilder<N>,
416    PVB: PayloadValidatorBuilder<N>,
417    EB: EngineApiBuilder<N>,
418    EB::EngineApi: EngineSszApi,
419    EVB: EngineValidatorBuilder<N>,
420    EthApiError: FromEvmError<N::Evm>,
421    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
422    RpcMiddleware: RethRpcMiddleware,
423    AuthHttpMiddleware: RethAuthHttpMiddleware<Identity>,
424    Stack<EngineSszProxyLayer<EB::EngineApi>, AuthHttpMiddleware>: RethAuthHttpMiddleware<Identity>,
425{
426    type EthApi = EthB::EthApi;
427
428    fn hooks_mut(&mut self) -> &mut reth_node_builder::rpc::RpcHooks<N, Self::EthApi> {
429        self.inner.hooks_mut()
430    }
431}
432
433impl<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware> EngineValidatorAddOn<N>
434    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware, AuthHttpMiddleware>
435where
436    N: FullNodeComponents<
437        Types: NodeTypes<
438            ChainSpec: EthChainSpec + EthereumHardforks,
439            Primitives = EthPrimitives,
440            Payload: EngineTypes<ExecutionData = ExecutionData>,
441        >,
442        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
443    >,
444    EthB: EthApiBuilder<N>,
445    PVB: Send,
446    EB: EngineApiBuilder<N>,
447    EVB: EngineValidatorBuilder<N>,
448    EthApiError: FromEvmError<N::Evm>,
449    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
450    RpcMiddleware: Send,
451    AuthHttpMiddleware: Send,
452{
453    type ValidatorBuilder = EVB;
454
455    fn engine_validator_builder(&self) -> Self::ValidatorBuilder {
456        self.inner.engine_validator_builder()
457    }
458}
459
460impl<N> Node<N> for EthereumNode
461where
462    N: FullNodeTypes<Types = Self>,
463{
464    type ComponentsBuilder = ComponentsBuilder<
465        N,
466        EthereumPoolBuilder,
467        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
468        EthereumNetworkBuilder,
469        EthereumExecutorBuilder,
470        EthereumConsensusBuilder,
471    >;
472
473    type AddOns =
474        EthereumAddOns<NodeAdapter<N>, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>;
475
476    fn components_builder(&self) -> Self::ComponentsBuilder {
477        Self::components()
478    }
479
480    fn add_ons(&self) -> Self::AddOns {
481        EthereumAddOns::default()
482    }
483}
484
485impl<N: FullNodeComponents<Types = Self>> DebugNode<N> for EthereumNode {
486    type RpcBlock = alloy_rpc_types_eth::Block;
487
488    fn rpc_to_primitive_block(rpc_block: Self::RpcBlock) -> reth_ethereum_primitives::Block {
489        rpc_block.into_consensus().convert_transactions()
490    }
491
492    fn local_payload_attributes_builder(
493        chain_spec: &Self::ChainSpec,
494    ) -> impl PayloadAttributesBuilder<<Self::Payload as PayloadTypes>::PayloadAttributes> {
495        LocalPayloadAttributesBuilder::new(Arc::new(chain_spec.clone()))
496    }
497}
498
499/// Builds a [`RuntimeConfig`] from CLI [`JitArgs`].
500#[cfg(feature = "jit")]
501fn jit_runtime_config(jit: &JitArgs) -> RuntimeConfig {
502    let default_tuning = RuntimeTuning::default();
503    let tuning = RuntimeTuning {
504        channel_capacity: jit.channel_capacity,
505        jit_hot_threshold: jit.hot_threshold,
506        jit_max_bytecode_len: jit.max_bytecode_len,
507        jit_max_pending_jobs: jit.max_pending_jobs,
508        jit_worker_count: jit.worker_count.unwrap_or(default_tuning.jit_worker_count),
509        jit_timeout: default_tuning.jit_timeout,
510        jit_helper_memory_limit_bytes: default_tuning.jit_helper_memory_limit_bytes,
511        jit_helper_cpu_count: default_tuning.jit_helper_cpu_count,
512        resident_code_cache_bytes: jit.code_cache_bytes,
513        idle_evict_duration: Some(jit.idle_evict_duration),
514
515        max_events_per_drain: default_tuning.max_events_per_drain,
516        event_drain_interval: default_tuning.event_drain_interval,
517        shutdown_timeout: default_tuning.shutdown_timeout,
518        jit_worker_queue_capacity: default_tuning.jit_worker_queue_capacity,
519        jit_opt_level: default_tuning.jit_opt_level,
520        aot_opt_level: default_tuning.aot_opt_level,
521        eviction_sweep_interval: default_tuning.eviction_sweep_interval,
522        compiler_recycle_threshold: default_tuning.compiler_recycle_threshold,
523    };
524
525    let default_config = RuntimeConfig::default();
526    RuntimeConfig {
527        enabled: jit.enabled,
528        thread_name: default_config.thread_name,
529        store: default_config.store,
530        tuning,
531        dump_dir: default_config.dump_dir,
532        debug_assertions: jit.debug,
533        blocking: jit.blocking,
534        single_error: default_config.single_error,
535        no_dedup: default_config.no_dedup,
536        no_dse: default_config.no_dse,
537        gas_params: default_config.gas_params,
538        aot: default_config.aot,
539        jit_mode: JitMode::OutOfProcess,
540        jit_helper_path: default_config.jit_helper_path,
541        on_compilation: default_config.on_compilation,
542    }
543}
544
545/// Builds an [`EthEvmConfig`] with revmc JIT from CLI [`JitArgs`].
546///
547/// This is the shared setup used by both [`EthereumExecutorBuilder`] and `reth re-execute`.
548///
549/// Returns the evm config and metrics recorder if JIT starts enabled.
550#[cfg(feature = "jit")]
551#[allow(clippy::type_complexity)]
552pub fn build_evm_config<C: EthereumHardforks>(
553    chain_spec: Arc<C>,
554    jit: &JitArgs,
555    dump_dir: Option<std::path::PathBuf>,
556) -> eyre::Result<(EthEvmConfig<C, RethEvmFactory>, Option<Arc<RevmcMetrics>>)> {
557    if !jit.enabled {
558        let factory = RethEvmFactory::disabled();
559        return Ok((EthEvmConfig::new_with_evm_factory(chain_spec, factory), None));
560    }
561
562    let mut config = jit_runtime_config(jit);
563    config.dump_dir = dump_dir;
564
565    let revmc_metrics = Arc::new(RevmcMetrics::default());
566    let compilation_metrics = revmc_metrics.clone();
567    config.on_compilation = Some(Arc::new(move |event| {
568        compilation_metrics.record_compilation(&event);
569    }));
570
571    let tuning = config.tuning;
572    let jit_mode = config.jit_mode;
573    let backend = JitBackend::new(config)?;
574
575    reth_tracing::tracing::warn!(target: "reth::cli",
576        hot_threshold = tuning.jit_hot_threshold,
577        workers = tuning.jit_worker_count,
578        mode = ?jit_mode,
579        blocking = jit.blocking,
580        "Started experimental revmc JIT backend; this may cause instability",
581    );
582
583    let factory = RethEvmFactory::new_with_metrics(backend, revmc_metrics.as_ref().clone());
584    let evm_config = EthEvmConfig::new_with_evm_factory(chain_spec, factory);
585
586    Ok((evm_config, Some(revmc_metrics)))
587}
588
589/// Builds an [`EthEvmConfig`] from CLI [`JitArgs`].
590///
591/// This is the shared setup used by both [`EthereumExecutorBuilder`] and `reth re-execute`.
592///
593/// Compiled without the `jit` feature: errors if JIT was requested via [`JitArgs`] and otherwise
594/// returns a plain interpreter-backed config.
595#[cfg(not(feature = "jit"))]
596#[allow(clippy::type_complexity)]
597pub fn build_evm_config<C: EthereumHardforks>(
598    chain_spec: Arc<C>,
599    jit: &JitArgs,
600    _dump_dir: Option<std::path::PathBuf>,
601) -> eyre::Result<(EthEvmConfig<C, RethEvmFactory>, Option<()>)> {
602    if jit.enabled {
603        eyre::bail!(
604            "JIT compilation was requested but this binary was compiled without the `jit` feature"
605        );
606    }
607    let factory = RethEvmFactory::default();
608    Ok((EthEvmConfig::new_with_evm_factory(chain_spec, factory), None))
609}
610
611/// A regular ethereum evm and executor builder.
612///
613/// Uses [`RethEvmFactory`].
614#[derive(Debug, Default, Clone, Copy)]
615#[non_exhaustive]
616pub struct EthereumExecutorBuilder;
617
618impl<Types, Node> ExecutorBuilder<Node> for EthereumExecutorBuilder
619where
620    Types: NodeTypes<
621        ChainSpec: Hardforks + EthExecutorSpec + EthereumHardforks,
622        Primitives = EthPrimitives,
623    >,
624    Node: FullNodeTypes<Types = Types>,
625{
626    type EVM = EthEvmConfig<Types::ChainSpec, RethEvmFactory>;
627
628    async fn build_evm(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::EVM> {
629        let jit = &ctx.config().jit;
630        let dump_dir = jit.debug.then(|| ctx.config().datadir().data_dir().join("jit"));
631
632        let (mut evm_config, revmc_metrics) = build_evm_config(ctx.chain_spec(), jit, dump_dir)?;
633        if let Some(cache) = ctx.sender_recovery_cache() {
634            evm_config = evm_config.with_sender_recovery_cache(cache.clone());
635        }
636
637        #[cfg(not(feature = "jit"))]
638        let _ = revmc_metrics;
639
640        #[cfg(feature = "jit")]
641        if let Some(revmc_metrics) = revmc_metrics {
642            let metrics_backend = evm_config.executor_factory.evm_factory().backend().clone();
643            ctx.task_executor().spawn_with_graceful_shutdown_signal(|shutdown| async move {
644                let mut shutdown = std::pin::pin!(shutdown);
645                loop {
646                    tokio::select! {
647                        _ = tokio::time::sleep(std::time::Duration::from_secs(5)) => {
648                            revmc_metrics.record(&metrics_backend.stats());
649                        }
650                        _ = &mut shutdown => break,
651                    }
652                }
653            });
654        }
655
656        Ok(evm_config)
657    }
658}
659
660/// A basic ethereum transaction pool.
661///
662/// This contains various settings that can be configured and take precedence over the node's
663/// config.
664#[derive(Debug, Clone, Copy)]
665#[non_exhaustive]
666pub struct EthereumPoolBuilder {
667    init_kzg_settings: bool,
668}
669
670impl EthereumPoolBuilder {
671    /// Creates a new [`EthereumPoolBuilder`].
672    pub const fn new() -> Self {
673        Self { init_kzg_settings: false }
674    }
675
676    /// Sets whether to initialize KZG settings even if EIP-4844 support is disabled in the pool.
677    pub const fn with_init_kzg_settings(mut self, init_kzg_settings: bool) -> Self {
678        self.init_kzg_settings = init_kzg_settings;
679        self
680    }
681}
682
683impl Default for EthereumPoolBuilder {
684    fn default() -> Self {
685        Self::new()
686    }
687}
688
689impl<Types, Node, Evm> PoolBuilder<Node, Evm> for EthereumPoolBuilder
690where
691    Types: NodeTypes<
692        ChainSpec: EthereumHardforks,
693        Primitives: NodePrimitives<SignedTx = TransactionSigned>,
694    >,
695    Node: FullNodeTypes<Types = Types>,
696    Evm: ConfigureEvm<Primitives = PrimitivesTy<Types>> + Clone + 'static,
697{
698    type Pool = EthTransactionPool<Node::Provider, DiskFileBlobStore, Evm>;
699
700    async fn build_pool(
701        self,
702        ctx: &BuilderContext<Node>,
703        evm_config: Evm,
704    ) -> eyre::Result<Self::Pool> {
705        let pool_config = ctx.pool_config();
706
707        let blobs_disabled = ctx.config().txpool.disable_blobs_support ||
708            ctx.config().txpool.blobpool_max_count == 0;
709
710        let blob_cache_size = if let Some(blob_cache_size) = pool_config.blob_cache_size {
711            Some(blob_cache_size)
712        } else {
713            // get the current blob params for the current timestamp, fallback to default Cancun
714            // params
715            let current_timestamp =
716                SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_secs();
717            let blob_params = ctx
718                .chain_spec()
719                .blob_params_at_timestamp(current_timestamp)
720                .unwrap_or_else(BlobParams::cancun);
721
722            // Derive the blob cache size from the target blob count, to auto scale it by
723            // multiplying it with the slot count for 2 epochs: 384 for pectra
724            Some((blob_params.target_blob_count * EPOCH_SLOTS * 2) as u32)
725        };
726
727        let blob_store =
728            reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?;
729
730        let validator =
731            TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), evm_config)
732                .set_eip4844(!blobs_disabled)
733                .kzg_settings(ctx.kzg_settings()?)
734                .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes)
735                .with_local_transactions_config(pool_config.local_transactions_config.clone())
736                .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap)
737                .with_max_tx_gas_limit(ctx.config().txpool.max_tx_gas_limit)
738                .with_minimum_priority_fee(ctx.config().txpool.minimum_priority_fee)
739                .with_additional_tasks(ctx.config().txpool.additional_validation_tasks)
740                .build_with_tasks(ctx.task_executor().clone(), blob_store.clone());
741
742        if validator.validator().eip4844() || self.init_kzg_settings {
743            // initializing the KZG settings can be expensive, this should be done upfront so that
744            // it doesn't impact the first block or the first gossiped blob transaction, so we
745            // initialize this in the background
746            let kzg_settings = validator.validator().kzg_settings().clone();
747            ctx.task_executor().spawn_blocking_task(async move {
748                let _ = kzg_settings.get();
749                debug!(target: "reth::cli", "Initialized KZG settings");
750            });
751        }
752
753        let transaction_pool = TxPoolBuilder::new(ctx)
754            .with_validator(validator)
755            .build_and_spawn_maintenance_task(blob_store, pool_config)?;
756
757        info!(target: "reth::cli", "Transaction pool initialized");
758        debug!(target: "reth::cli", "Spawned txpool maintenance task");
759
760        Ok(transaction_pool)
761    }
762}
763
764/// A basic ethereum payload service.
765#[derive(Debug, Default, Clone, Copy)]
766pub struct EthereumNetworkBuilder {
767    // TODO add closure to modify network
768}
769
770impl<Node, Pool> NetworkBuilder<Node, Pool> for EthereumNetworkBuilder
771where
772    Node: FullNodeTypes<Types: NodeTypes<ChainSpec: Hardforks>>,
773    Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TxTy<Node::Types>>>
774        + Unpin
775        + 'static,
776{
777    type Network =
778        NetworkHandle<BasicNetworkPrimitives<PrimitivesTy<Node::Types>, PoolPooledTx<Pool>>>;
779
780    async fn build_network(
781        self,
782        ctx: &BuilderContext<Node>,
783        pool: Pool,
784    ) -> eyre::Result<Self::Network> {
785        let network = ctx.network_builder().await?;
786        let handle = ctx.start_network(network, pool);
787        info!(target: "reth::cli", enode=%handle.local_node_record(), "P2P networking initialized");
788        Ok(handle)
789    }
790}
791
792/// A basic ethereum consensus builder.
793#[derive(Debug, Default, Clone, Copy)]
794pub struct EthereumConsensusBuilder {
795    // TODO add closure to modify consensus
796}
797
798impl<Node> ConsensusBuilder<Node> for EthereumConsensusBuilder
799where
800    Node: FullNodeTypes<
801        Types: NodeTypes<ChainSpec: EthChainSpec + EthereumHardforks, Primitives = EthPrimitives>,
802    >,
803{
804    type Consensus = Arc<EthBeaconConsensus<<Node::Types as NodeTypes>::ChainSpec>>;
805
806    async fn build_consensus(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::Consensus> {
807        Ok(Arc::new(EthBeaconConsensus::new(ctx.chain_spec())))
808    }
809}
810
811/// Builder for [`EthereumEngineValidator`].
812#[derive(Debug, Default, Clone)]
813#[non_exhaustive]
814pub struct EthereumEngineValidatorBuilder;
815
816impl<Node, Types> PayloadValidatorBuilder<Node> for EthereumEngineValidatorBuilder
817where
818    Types: NodeTypes<
819        ChainSpec: Hardforks + EthereumHardforks + Clone + 'static,
820        Payload: EngineTypes<ExecutionData = ExecutionData>
821                     + PayloadTypes<PayloadAttributes = EthPayloadAttributes>,
822        Primitives = EthPrimitives,
823    >,
824    Node: FullNodeComponents<Types = Types>,
825{
826    type Validator = EthereumEngineValidator<Types::ChainSpec>;
827
828    async fn build(self, ctx: &AddOnsContext<'_, Node>) -> eyre::Result<Self::Validator> {
829        Ok(EthereumEngineValidator::new(ctx.config.chain.clone()))
830    }
831}
832
833#[cfg(test)]
834mod tests {
835    use super::EthereumPoolBuilder;
836
837    #[test]
838    fn configures_kzg_settings_initialization() {
839        assert!(!EthereumPoolBuilder::new().init_kzg_settings);
840        assert!(EthereumPoolBuilder::new().with_init_kzg_settings(true).init_kzg_settings);
841    }
842}