reth_node_ethereum/
node.rs

1//! Ethereum Node types config.
2
3pub use crate::{payload::EthereumPayloadBuilder, EthereumEngineValidator};
4use crate::{EthEngineTypes, EthEvmConfig};
5use alloy_eips::{eip7840::BlobParams, merge::EPOCH_SLOTS};
6use alloy_network::Ethereum;
7use alloy_rpc_types_engine::ExecutionData;
8use reth_chainspec::{ChainSpec, EthChainSpec, EthereumHardforks, Hardforks};
9use reth_engine_local::LocalPayloadAttributesBuilder;
10use reth_engine_primitives::EngineTypes;
11use reth_ethereum_consensus::EthBeaconConsensus;
12use reth_ethereum_engine_primitives::{
13    EthBuiltPayload, EthPayloadAttributes, EthPayloadBuilderAttributes,
14};
15use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
16use reth_evm::{
17    eth::spec::EthExecutorSpec, ConfigureEvm, EvmFactory, EvmFactoryFor, NextBlockEnvAttributes,
18};
19use reth_network::{primitives::BasicNetworkPrimitives, NetworkHandle, PeersInfo};
20use reth_node_api::{
21    AddOnsContext, FullNodeComponents, HeaderTy, NodeAddOns, NodePrimitives,
22    PayloadAttributesBuilder, PrimitivesTy, TxTy,
23};
24use reth_node_builder::{
25    components::{
26        BasicPayloadServiceBuilder, ComponentsBuilder, ConsensusBuilder, ExecutorBuilder,
27        NetworkBuilder, PoolBuilder, TxPoolBuilder,
28    },
29    node::{FullNodeTypes, NodeTypes},
30    rpc::{
31        BasicEngineApiBuilder, BasicEngineValidatorBuilder, EngineApiBuilder, EngineValidatorAddOn,
32        EngineValidatorBuilder, EthApiBuilder, EthApiCtx, Identity, PayloadValidatorBuilder,
33        RethRpcAddOns, RpcAddOns, RpcHandle,
34    },
35    BuilderContext, DebugNode, Node, NodeAdapter, PayloadBuilderConfig,
36};
37use reth_payload_primitives::PayloadTypes;
38use reth_provider::{providers::ProviderFactoryBuilder, EthStorage};
39use reth_rpc::{
40    eth::core::{EthApiFor, EthRpcConverterFor},
41    ValidationApi,
42};
43use reth_rpc_api::servers::BlockSubmissionValidationApiServer;
44use reth_rpc_builder::{config::RethRpcServerConfig, middleware::RethRpcMiddleware};
45use reth_rpc_eth_api::{
46    helpers::{
47        config::{EthConfigApiServer, EthConfigHandler},
48        pending_block::BuildPendingEnv,
49    },
50    RpcConvert, RpcTypes, SignableTxRequest,
51};
52use reth_rpc_eth_types::{error::FromEvmError, EthApiError};
53use reth_rpc_server_types::RethRpcModule;
54use reth_tracing::tracing::{debug, info};
55use reth_transaction_pool::{
56    blobstore::DiskFileBlobStore, EthTransactionPool, PoolPooledTx, PoolTransaction,
57    TransactionPool, TransactionValidationTaskExecutor,
58};
59use revm::context::TxEnv;
60use std::{marker::PhantomData, sync::Arc, time::SystemTime};
61
62/// Type configuration for a regular Ethereum node.
63#[derive(Debug, Default, Clone, Copy)]
64#[non_exhaustive]
65pub struct EthereumNode;
66
67impl EthereumNode {
68    /// Returns a [`ComponentsBuilder`] configured for a regular Ethereum node.
69    pub fn components<Node>() -> ComponentsBuilder<
70        Node,
71        EthereumPoolBuilder,
72        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
73        EthereumNetworkBuilder,
74        EthereumExecutorBuilder,
75        EthereumConsensusBuilder,
76    >
77    where
78        Node: FullNodeTypes<
79            Types: NodeTypes<
80                ChainSpec: Hardforks + EthereumHardforks + EthExecutorSpec,
81                Primitives = EthPrimitives,
82            >,
83        >,
84        <Node::Types as NodeTypes>::Payload: PayloadTypes<
85            BuiltPayload = EthBuiltPayload,
86            PayloadAttributes = EthPayloadAttributes,
87            PayloadBuilderAttributes = EthPayloadBuilderAttributes,
88        >,
89    {
90        ComponentsBuilder::default()
91            .node_types::<Node>()
92            .pool(EthereumPoolBuilder::default())
93            .executor(EthereumExecutorBuilder::default())
94            .payload(BasicPayloadServiceBuilder::default())
95            .network(EthereumNetworkBuilder::default())
96            .consensus(EthereumConsensusBuilder::default())
97    }
98
99    /// Instantiates the [`ProviderFactoryBuilder`] for an ethereum node.
100    ///
101    /// # Open a Providerfactory in read-only mode from a datadir
102    ///
103    /// See also: [`ProviderFactoryBuilder`] and
104    /// [`ReadOnlyConfig`](reth_provider::providers::ReadOnlyConfig).
105    ///
106    /// ```no_run
107    /// use reth_chainspec::MAINNET;
108    /// use reth_node_ethereum::EthereumNode;
109    ///
110    /// let factory = EthereumNode::provider_factory_builder()
111    ///     .open_read_only(MAINNET.clone(), "datadir")
112    ///     .unwrap();
113    /// ```
114    ///
115    /// # Open a Providerfactory manually with all required components
116    ///
117    /// ```no_run
118    /// use reth_chainspec::ChainSpecBuilder;
119    /// use reth_db::open_db_read_only;
120    /// use reth_node_ethereum::EthereumNode;
121    /// use reth_provider::providers::StaticFileProvider;
122    /// use std::sync::Arc;
123    ///
124    /// let factory = EthereumNode::provider_factory_builder()
125    ///     .db(Arc::new(open_db_read_only("db", Default::default()).unwrap()))
126    ///     .chainspec(ChainSpecBuilder::mainnet().build().into())
127    ///     .static_file(StaticFileProvider::read_only("db/static_files", false).unwrap())
128    ///     .build_provider_factory();
129    /// ```
130    pub fn provider_factory_builder() -> ProviderFactoryBuilder<Self> {
131        ProviderFactoryBuilder::default()
132    }
133}
134
135impl NodeTypes for EthereumNode {
136    type Primitives = EthPrimitives;
137    type ChainSpec = ChainSpec;
138    type Storage = EthStorage;
139    type Payload = EthEngineTypes;
140}
141
142/// Builds [`EthApi`](reth_rpc::EthApi) for Ethereum.
143#[derive(Debug)]
144pub struct EthereumEthApiBuilder<NetworkT = Ethereum>(PhantomData<NetworkT>);
145
146impl<NetworkT> Default for EthereumEthApiBuilder<NetworkT> {
147    fn default() -> Self {
148        Self(Default::default())
149    }
150}
151
152impl<N, NetworkT> EthApiBuilder<N> for EthereumEthApiBuilder<NetworkT>
153where
154    N: FullNodeComponents<
155        Types: NodeTypes<ChainSpec: Hardforks + EthereumHardforks>,
156        Evm: ConfigureEvm<NextBlockEnvCtx: BuildPendingEnv<HeaderTy<N::Types>>>,
157    >,
158    NetworkT: RpcTypes<TransactionRequest: SignableTxRequest<TxTy<N::Types>>>,
159    EthRpcConverterFor<N, NetworkT>: RpcConvert<
160        Primitives = PrimitivesTy<N::Types>,
161        Error = EthApiError,
162        Network = NetworkT,
163        Evm = N::Evm,
164    >,
165    EthApiError: FromEvmError<N::Evm>,
166{
167    type EthApi = EthApiFor<N, NetworkT>;
168
169    async fn build_eth_api(self, ctx: EthApiCtx<'_, N>) -> eyre::Result<Self::EthApi> {
170        Ok(ctx.eth_api_builder().map_converter(|r| r.with_network()).build())
171    }
172}
173
174/// Add-ons w.r.t. l1 ethereum.
175#[derive(Debug)]
176pub struct EthereumAddOns<
177    N: FullNodeComponents,
178    EthB: EthApiBuilder<N>,
179    PVB,
180    EB = BasicEngineApiBuilder<PVB>,
181    EVB = BasicEngineValidatorBuilder<PVB>,
182    RpcMiddleware = Identity,
183> {
184    inner: RpcAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>,
185}
186
187impl<N, EthB, PVB, EB, EVB, RpcMiddleware> EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>
188where
189    N: FullNodeComponents,
190    EthB: EthApiBuilder<N>,
191{
192    /// Creates a new instance from the inner `RpcAddOns`.
193    pub const fn new(inner: RpcAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>) -> Self {
194        Self { inner }
195    }
196}
197
198impl<N> Default for EthereumAddOns<N, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>
199where
200    N: FullNodeComponents<
201        Types: NodeTypes<
202            ChainSpec: EthereumHardforks + Clone + 'static,
203            Payload: EngineTypes<ExecutionData = ExecutionData>
204                         + PayloadTypes<PayloadAttributes = EthPayloadAttributes>,
205            Primitives = EthPrimitives,
206        >,
207    >,
208    EthereumEthApiBuilder: EthApiBuilder<N>,
209{
210    fn default() -> Self {
211        Self::new(RpcAddOns::new(
212            EthereumEthApiBuilder::default(),
213            EthereumEngineValidatorBuilder::default(),
214            BasicEngineApiBuilder::default(),
215            BasicEngineValidatorBuilder::default(),
216            Default::default(),
217        ))
218    }
219}
220
221impl<N, EthB, PVB, EB, EVB, RpcMiddleware> EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>
222where
223    N: FullNodeComponents,
224    EthB: EthApiBuilder<N>,
225{
226    /// Replace the engine API builder.
227    pub fn with_engine_api<T>(
228        self,
229        engine_api_builder: T,
230    ) -> EthereumAddOns<N, EthB, PVB, T, EVB, RpcMiddleware>
231    where
232        T: Send,
233    {
234        let Self { inner } = self;
235        EthereumAddOns::new(inner.with_engine_api(engine_api_builder))
236    }
237
238    /// Replace the payload validator builder.
239    pub fn with_payload_validator<V, T>(
240        self,
241        payload_validator_builder: T,
242    ) -> EthereumAddOns<N, EthB, T, EB, EVB, RpcMiddleware> {
243        let Self { inner } = self;
244        EthereumAddOns::new(inner.with_payload_validator(payload_validator_builder))
245    }
246
247    /// Sets rpc middleware
248    pub fn with_rpc_middleware<T>(
249        self,
250        rpc_middleware: T,
251    ) -> EthereumAddOns<N, EthB, PVB, EB, EVB, T>
252    where
253        T: Send,
254    {
255        let Self { inner } = self;
256        EthereumAddOns::new(inner.with_rpc_middleware(rpc_middleware))
257    }
258
259    /// Sets the tokio runtime for the RPC servers.
260    ///
261    /// Caution: This runtime must not be created from within asynchronous context.
262    pub fn with_tokio_runtime(self, tokio_runtime: Option<tokio::runtime::Handle>) -> Self {
263        let Self { inner } = self;
264        Self { inner: inner.with_tokio_runtime(tokio_runtime) }
265    }
266}
267
268impl<N, EthB, PVB, EB, EVB, RpcMiddleware> NodeAddOns<N>
269    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>
270where
271    N: FullNodeComponents<
272        Types: NodeTypes<
273            ChainSpec: Hardforks + EthereumHardforks,
274            Primitives = EthPrimitives,
275            Payload: EngineTypes<ExecutionData = ExecutionData>,
276        >,
277        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
278    >,
279    EthB: EthApiBuilder<N>,
280    PVB: Send,
281    EB: EngineApiBuilder<N>,
282    EVB: EngineValidatorBuilder<N>,
283    EthApiError: FromEvmError<N::Evm>,
284    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
285    RpcMiddleware: RethRpcMiddleware,
286{
287    type Handle = RpcHandle<N, EthB::EthApi>;
288
289    async fn launch_add_ons(
290        self,
291        ctx: reth_node_api::AddOnsContext<'_, N>,
292    ) -> eyre::Result<Self::Handle> {
293        let validation_api = ValidationApi::<_, _, <N::Types as NodeTypes>::Payload>::new(
294            ctx.node.provider().clone(),
295            Arc::new(ctx.node.consensus().clone()),
296            ctx.node.evm_config().clone(),
297            ctx.config.rpc.flashbots_config(),
298            Box::new(ctx.node.task_executor().clone()),
299            Arc::new(EthereumEngineValidator::new(ctx.config.chain.clone())),
300        );
301
302        let eth_config =
303            EthConfigHandler::new(ctx.node.provider().clone(), ctx.node.evm_config().clone());
304
305        self.inner
306            .launch_add_ons_with(ctx, move |container| {
307                container.modules.merge_if_module_configured(
308                    RethRpcModule::Flashbots,
309                    validation_api.into_rpc(),
310                )?;
311
312                container
313                    .modules
314                    .merge_if_module_configured(RethRpcModule::Eth, eth_config.into_rpc())?;
315
316                Ok(())
317            })
318            .await
319    }
320}
321
322impl<N, EthB, PVB, EB, EVB> RethRpcAddOns<N> for EthereumAddOns<N, EthB, PVB, EB, EVB>
323where
324    N: FullNodeComponents<
325        Types: NodeTypes<
326            ChainSpec: Hardforks + EthereumHardforks,
327            Primitives = EthPrimitives,
328            Payload: EngineTypes<ExecutionData = ExecutionData>,
329        >,
330        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
331    >,
332    EthB: EthApiBuilder<N>,
333    PVB: PayloadValidatorBuilder<N>,
334    EB: EngineApiBuilder<N>,
335    EVB: EngineValidatorBuilder<N>,
336    EthApiError: FromEvmError<N::Evm>,
337    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
338{
339    type EthApi = EthB::EthApi;
340
341    fn hooks_mut(&mut self) -> &mut reth_node_builder::rpc::RpcHooks<N, Self::EthApi> {
342        self.inner.hooks_mut()
343    }
344}
345
346impl<N, EthB, PVB, EB, EVB, RpcMiddleware> EngineValidatorAddOn<N>
347    for EthereumAddOns<N, EthB, PVB, EB, EVB, RpcMiddleware>
348where
349    N: FullNodeComponents<
350        Types: NodeTypes<
351            ChainSpec: EthChainSpec + EthereumHardforks,
352            Primitives = EthPrimitives,
353            Payload: EngineTypes<ExecutionData = ExecutionData>,
354        >,
355        Evm: ConfigureEvm<NextBlockEnvCtx = NextBlockEnvAttributes>,
356    >,
357    EthB: EthApiBuilder<N>,
358    PVB: Send,
359    EB: EngineApiBuilder<N>,
360    EVB: EngineValidatorBuilder<N>,
361    EthApiError: FromEvmError<N::Evm>,
362    EvmFactoryFor<N::Evm>: EvmFactory<Tx = TxEnv>,
363    RpcMiddleware: Send,
364{
365    type ValidatorBuilder = EVB;
366
367    fn engine_validator_builder(&self) -> Self::ValidatorBuilder {
368        self.inner.engine_validator_builder()
369    }
370}
371
372impl<N> Node<N> for EthereumNode
373where
374    N: FullNodeTypes<Types = Self>,
375{
376    type ComponentsBuilder = ComponentsBuilder<
377        N,
378        EthereumPoolBuilder,
379        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
380        EthereumNetworkBuilder,
381        EthereumExecutorBuilder,
382        EthereumConsensusBuilder,
383    >;
384
385    type AddOns =
386        EthereumAddOns<NodeAdapter<N>, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>;
387
388    fn components_builder(&self) -> Self::ComponentsBuilder {
389        Self::components()
390    }
391
392    fn add_ons(&self) -> Self::AddOns {
393        EthereumAddOns::default()
394    }
395}
396
397impl<N: FullNodeComponents<Types = Self>> DebugNode<N> for EthereumNode {
398    type RpcBlock = alloy_rpc_types_eth::Block;
399
400    fn rpc_to_primitive_block(rpc_block: Self::RpcBlock) -> reth_ethereum_primitives::Block {
401        rpc_block.into_consensus().convert_transactions()
402    }
403
404    fn local_payload_attributes_builder(
405        chain_spec: &Self::ChainSpec,
406    ) -> impl PayloadAttributesBuilder<<Self::Payload as PayloadTypes>::PayloadAttributes> {
407        LocalPayloadAttributesBuilder::new(Arc::new(chain_spec.clone()))
408    }
409}
410
411/// A regular ethereum evm and executor builder.
412#[derive(Debug, Default, Clone, Copy)]
413#[non_exhaustive]
414pub struct EthereumExecutorBuilder;
415
416impl<Types, Node> ExecutorBuilder<Node> for EthereumExecutorBuilder
417where
418    Types: NodeTypes<
419        ChainSpec: Hardforks + EthExecutorSpec + EthereumHardforks,
420        Primitives = EthPrimitives,
421    >,
422    Node: FullNodeTypes<Types = Types>,
423{
424    type EVM = EthEvmConfig<Types::ChainSpec>;
425
426    async fn build_evm(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::EVM> {
427        let evm_config = EthEvmConfig::new(ctx.chain_spec())
428            .with_extra_data(ctx.payload_builder_config().extra_data_bytes());
429        Ok(evm_config)
430    }
431}
432
433/// A basic ethereum transaction pool.
434///
435/// This contains various settings that can be configured and take precedence over the node's
436/// config.
437#[derive(Debug, Default, Clone, Copy)]
438#[non_exhaustive]
439pub struct EthereumPoolBuilder {
440    // TODO add options for txpool args
441}
442
443impl<Types, Node> PoolBuilder<Node> for EthereumPoolBuilder
444where
445    Types: NodeTypes<
446        ChainSpec: EthereumHardforks,
447        Primitives: NodePrimitives<SignedTx = TransactionSigned>,
448    >,
449    Node: FullNodeTypes<Types = Types>,
450{
451    type Pool = EthTransactionPool<Node::Provider, DiskFileBlobStore>;
452
453    async fn build_pool(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::Pool> {
454        let pool_config = ctx.pool_config();
455
456        let blob_cache_size = if let Some(blob_cache_size) = pool_config.blob_cache_size {
457            Some(blob_cache_size)
458        } else {
459            // get the current blob params for the current timestamp, fallback to default Cancun
460            // params
461            let current_timestamp =
462                SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_secs();
463            let blob_params = ctx
464                .chain_spec()
465                .blob_params_at_timestamp(current_timestamp)
466                .unwrap_or_else(BlobParams::cancun);
467
468            // Derive the blob cache size from the target blob count, to auto scale it by
469            // multiplying it with the slot count for 2 epochs: 384 for pectra
470            Some((blob_params.target_blob_count * EPOCH_SLOTS * 2) as u32)
471        };
472
473        let blob_store =
474            reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?;
475
476        let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone())
477            .with_head_timestamp(ctx.head().timestamp)
478            .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes)
479            .kzg_settings(ctx.kzg_settings()?)
480            .with_local_transactions_config(pool_config.local_transactions_config.clone())
481            .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap)
482            .with_max_tx_gas_limit(ctx.config().txpool.max_tx_gas_limit)
483            .with_minimum_priority_fee(ctx.config().txpool.minimum_priority_fee)
484            .with_additional_tasks(ctx.config().txpool.additional_validation_tasks)
485            .build_with_tasks(ctx.task_executor().clone(), blob_store.clone());
486
487        if validator.validator().eip4844() {
488            // initializing the KZG settings can be expensive, this should be done upfront so that
489            // it doesn't impact the first block or the first gossiped blob transaction, so we
490            // initialize this in the background
491            let kzg_settings = validator.validator().kzg_settings().clone();
492            ctx.task_executor().spawn_blocking(async move {
493                let _ = kzg_settings.get();
494                debug!(target: "reth::cli", "Initialized KZG settings");
495            });
496        }
497
498        let transaction_pool = TxPoolBuilder::new(ctx)
499            .with_validator(validator)
500            .build_and_spawn_maintenance_task(blob_store, pool_config)?;
501
502        info!(target: "reth::cli", "Transaction pool initialized");
503        debug!(target: "reth::cli", "Spawned txpool maintenance task");
504
505        Ok(transaction_pool)
506    }
507}
508
509/// A basic ethereum payload service.
510#[derive(Debug, Default, Clone, Copy)]
511pub struct EthereumNetworkBuilder {
512    // TODO add closure to modify network
513}
514
515impl<Node, Pool> NetworkBuilder<Node, Pool> for EthereumNetworkBuilder
516where
517    Node: FullNodeTypes<Types: NodeTypes<ChainSpec: Hardforks>>,
518    Pool: TransactionPool<Transaction: PoolTransaction<Consensus = TxTy<Node::Types>>>
519        + Unpin
520        + 'static,
521{
522    type Network =
523        NetworkHandle<BasicNetworkPrimitives<PrimitivesTy<Node::Types>, PoolPooledTx<Pool>>>;
524
525    async fn build_network(
526        self,
527        ctx: &BuilderContext<Node>,
528        pool: Pool,
529    ) -> eyre::Result<Self::Network> {
530        let network = ctx.network_builder().await?;
531        let handle = ctx.start_network(network, pool);
532        info!(target: "reth::cli", enode=%handle.local_node_record(), "P2P networking initialized");
533        Ok(handle)
534    }
535}
536
537/// A basic ethereum consensus builder.
538#[derive(Debug, Default, Clone, Copy)]
539pub struct EthereumConsensusBuilder {
540    // TODO add closure to modify consensus
541}
542
543impl<Node> ConsensusBuilder<Node> for EthereumConsensusBuilder
544where
545    Node: FullNodeTypes<
546        Types: NodeTypes<ChainSpec: EthChainSpec + EthereumHardforks, Primitives = EthPrimitives>,
547    >,
548{
549    type Consensus = Arc<EthBeaconConsensus<<Node::Types as NodeTypes>::ChainSpec>>;
550
551    async fn build_consensus(self, ctx: &BuilderContext<Node>) -> eyre::Result<Self::Consensus> {
552        Ok(Arc::new(EthBeaconConsensus::new(ctx.chain_spec())))
553    }
554}
555
556/// Builder for [`EthereumEngineValidator`].
557#[derive(Debug, Default, Clone)]
558#[non_exhaustive]
559pub struct EthereumEngineValidatorBuilder;
560
561impl<Node, Types> PayloadValidatorBuilder<Node> for EthereumEngineValidatorBuilder
562where
563    Types: NodeTypes<
564        ChainSpec: Hardforks + EthereumHardforks + Clone + 'static,
565        Payload: EngineTypes<ExecutionData = ExecutionData>
566                     + PayloadTypes<PayloadAttributes = EthPayloadAttributes>,
567        Primitives = EthPrimitives,
568    >,
569    Node: FullNodeComponents<Types = Types>,
570{
571    type Validator = EthereumEngineValidator<Types::ChainSpec>;
572
573    async fn build(self, ctx: &AddOnsContext<'_, Node>) -> eyre::Result<Self::Validator> {
574        Ok(EthereumEngineValidator::new(ctx.config.chain.clone()))
575    }
576}