Skip to main content

reth_engine_primitives/
lib.rs

1//! Traits, validation methods, and helper types used to abstract over engine types.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10#![cfg_attr(not(feature = "std"), no_std)]
11
12extern crate alloc;
13
14use alloc::sync::Arc;
15use alloy_consensus::BlockHeader;
16use reth_payload_primitives::{
17    EngineApiMessageVersion, EngineObjectValidationError, InvalidPayloadAttributesError,
18    NewPayloadError, PayloadAttributes, PayloadOrAttributes, PayloadTypes,
19};
20use reth_primitives_traits::{Block, RecoveredBlock, SealedBlock, SealedHeader};
21use reth_storage_api::{errors::ProviderResult, StateProviderBox};
22use reth_trie_common::HashedPostState;
23use serde::{de::DeserializeOwned, Serialize};
24
25// Re-export [`ExecutionPayload`] moved to `reth_payload_primitives`
26#[cfg(feature = "std")]
27pub use reth_evm::{ConfigureEngineEvm, ConvertTx, ExecutableTxIterator, ExecutableTxTuple};
28pub use reth_payload_primitives::ExecutionPayload;
29
30mod error;
31pub use error::*;
32
33mod forkchoice;
34pub use forkchoice::{ForkchoiceStateHash, ForkchoiceStateTracker, ForkchoiceStatus};
35
36#[cfg(feature = "std")]
37mod message;
38#[cfg(feature = "std")]
39pub use message::*;
40
41mod event;
42pub use event::*;
43
44mod invalid_block_hook;
45pub use invalid_block_hook::{InvalidBlockHook, InvalidBlockHooks, NoopInvalidBlockHook};
46
47pub mod config;
48pub use config::*;
49
50/// This type defines the versioned types of the engine API based on the [ethereum engine API](https://github.com/ethereum/execution-apis/tree/main/src/engine).
51///
52/// This includes the execution payload types and payload attributes that are used to trigger a
53/// payload job. Hence this trait is also [`PayloadTypes`].
54///
55/// Implementations of this type are intended to be stateless and just define the types as
56/// associated types.
57/// This type is intended for non-ethereum chains that closely mirror the ethereum engine API spec,
58/// but may have different payload, for example opstack, but structurally equivalent otherwise (same
59/// engine API RPC endpoints for example).
60pub trait EngineTypes:
61    PayloadTypes<
62        BuiltPayload: TryInto<Self::ExecutionPayloadEnvelopeV1>
63                          + TryInto<Self::ExecutionPayloadEnvelopeV2>
64                          + TryInto<Self::ExecutionPayloadEnvelopeV3>
65                          + TryInto<Self::ExecutionPayloadEnvelopeV4>
66                          + TryInto<Self::ExecutionPayloadEnvelopeV5>
67                          + TryInto<Self::ExecutionPayloadEnvelopeV6>,
68    > + DeserializeOwned
69    + Serialize
70{
71    /// Execution Payload V1 envelope type.
72    type ExecutionPayloadEnvelopeV1: DeserializeOwned
73        + Serialize
74        + Clone
75        + Unpin
76        + Send
77        + Sync
78        + 'static;
79    /// Execution Payload V2  envelope type.
80    type ExecutionPayloadEnvelopeV2: DeserializeOwned
81        + Serialize
82        + Clone
83        + Unpin
84        + Send
85        + Sync
86        + 'static;
87    /// Execution Payload V3 envelope type.
88    type ExecutionPayloadEnvelopeV3: DeserializeOwned
89        + Serialize
90        + Clone
91        + Unpin
92        + Send
93        + Sync
94        + 'static;
95    /// Execution Payload V4 envelope type.
96    type ExecutionPayloadEnvelopeV4: DeserializeOwned
97        + Serialize
98        + Clone
99        + Unpin
100        + Send
101        + Sync
102        + 'static;
103    /// Execution Payload V5 envelope type.
104    type ExecutionPayloadEnvelopeV5: DeserializeOwned
105        + Serialize
106        + Clone
107        + Unpin
108        + Send
109        + Sync
110        + 'static;
111    /// Execution Payload V6 envelope type.
112    type ExecutionPayloadEnvelopeV6: DeserializeOwned
113        + Serialize
114        + Clone
115        + Unpin
116        + Send
117        + Sync
118        + 'static;
119}
120
121/// Validates engine API requests at the RPC layer, before payloads and attributes
122/// are forwarded to the engine for processing.
123///
124/// - [`validate_version_specific_fields`](Self::validate_version_specific_fields): Enforced in each
125///   `engine_newPayloadVN` RPC handler to verify the payload contains the correct fields for the
126///   engine API version (e.g., blob fields in V3+, requests in V4+).
127///
128/// - [`ensure_well_formed_attributes`](Self::ensure_well_formed_attributes): Enforced in
129///   `engine_forkchoiceUpdatedVN` RPC handlers to validate payload attributes are well-formed for
130///   the given version before forwarding to the engine.
131///
132/// After this validation passes, the engine performs the full consensus validation
133/// pipeline (header, pre-execution, execution, post-execution).
134pub trait EngineApiValidator<Types: PayloadTypes>: Send + Sync + Unpin + 'static {
135    /// Validates the presence or exclusion of fork-specific fields based on the payload attributes
136    /// and the message version.
137    fn validate_version_specific_fields(
138        &self,
139        version: EngineApiMessageVersion,
140        payload_or_attrs: PayloadOrAttributes<'_, Types::ExecutionData, Types::PayloadAttributes>,
141    ) -> Result<(), EngineObjectValidationError>;
142
143    /// Ensures that the payload attributes are valid for the given [`EngineApiMessageVersion`].
144    fn ensure_well_formed_attributes(
145        &self,
146        version: EngineApiMessageVersion,
147        attributes: &Types::PayloadAttributes,
148    ) -> Result<(), EngineObjectValidationError>;
149}
150
151/// Type that validates an [`ExecutionPayload`].
152///
153/// This trait handles validation at the engine API boundary — converting payloads
154/// into blocks and validating payload attributes for block building.
155///
156/// # Methods and when they're used
157///
158/// - [`convert_payload_to_block`](Self::convert_payload_to_block): Used during `engine_newPayload`
159///   processing to decode the payload into a [`SealedBlock`]. Also used to validate payload
160///   structure during backfill buffering. In the engine tree, this runs concurrently with state
161///   setup on a background thread.
162///
163/// - [`ensure_well_formed_payload`](Self::ensure_well_formed_payload): Converts payload and
164///   recovers transaction signatures. Used when recovered senders are needed immediately.
165///
166/// - [`validate_payload_attributes_against_header`](Self::validate_payload_attributes_against_header):
167///   Enforced as part of the engine's `forkchoiceUpdated` handling when payload attributes
168///   are provided. Gates whether a payload build job is started.
169///
170/// - [`validate_block_post_execution_with_hashed_state`](Self::validate_block_post_execution_with_hashed_state):
171///   Called after block execution in the engine's payload validation pipeline.
172///   No-op on L1, used by L2s (e.g., OP Stack) for additional post-execution checks.
173///
174/// # Relationship to consensus traits
175///
176/// This trait does NOT replace the consensus traits (`Consensus`, `FullConsensus` from
177/// `reth-consensus`). Those handle the actual consensus rule
178/// validation (header checks, pre/post-execution). This trait handles engine API-specific
179/// concerns: payload encoding/decoding and attribute validation.
180#[auto_impl::auto_impl(&, Arc)]
181pub trait PayloadValidator<Types: PayloadTypes>: Send + Sync + Unpin + 'static {
182    /// The block type used by the engine.
183    type Block: Block;
184
185    /// Converts the given payload into a sealed block without recovering signatures.
186    ///
187    /// This function validates the payload and converts it into a [`SealedBlock`] which contains
188    /// the block hash but does not perform signature recovery on transactions.
189    ///
190    /// Returns an [`Arc`] so a payload that already shares its block can hand it over uncloned.
191    ///
192    /// This is more efficient than [`Self::ensure_well_formed_payload`] when signature recovery
193    /// is not needed immediately or will be performed later.
194    ///
195    /// Implementers should ensure that the checks are done in the order that conforms with the
196    /// engine-API specification.
197    fn convert_payload_to_block(
198        &self,
199        payload: Types::ExecutionData,
200    ) -> Result<Arc<SealedBlock<Self::Block>>, NewPayloadError>;
201
202    /// Ensures that the given payload does not violate any consensus rules that concern the block's
203    /// layout.
204    ///
205    /// This function must convert the payload into the executable block and pre-validate its
206    /// fields.
207    ///
208    /// Implementers should ensure that the checks are done in the order that conforms with the
209    /// engine-API specification. Callers that recover senders separately use
210    /// [`Self::convert_payload_to_block`] directly, so required payload checks belong there.
211    fn ensure_well_formed_payload(
212        &self,
213        payload: Types::ExecutionData,
214    ) -> Result<RecoveredBlock<Self::Block>, NewPayloadError> {
215        let sealed_block = Arc::unwrap_or_clone(self.convert_payload_to_block(payload)?);
216        sealed_block.try_recover().map_err(|e| NewPayloadError::Other(e.into()))
217    }
218
219    /// Verifies payload post-execution w.r.t. hashed state updates.
220    ///
221    /// `state_updates` lazily yields the block's hashed post-state; call it only if the
222    /// implementation needs the executed state changes (the L1 default does not).
223    ///
224    /// `parent_header` is the parent header the engine resolved for the block.
225    ///
226    /// `parent_state` lazily builds the overlay-aware provider for the block's parent that the
227    /// engine used for execution — resolving even a not-yet-canonical in-memory parent. It is only
228    /// built if the implementation needs it (the L1 default does not).
229    fn validate_block_post_execution_with_hashed_state<'a>(
230        &self,
231        _state_updates: impl FnOnce() -> &'a HashedPostState,
232        _block: &RecoveredBlock<Self::Block>,
233        _parent_header: &SealedHeader<<Self::Block as Block>::Header>,
234        _parent_state: impl FnOnce() -> ProviderResult<StateProviderBox>,
235    ) -> Result<(), InsertBlockErrorKind>
236    where
237        Self: Sized,
238    {
239        // method not used by l1
240        Ok(())
241    }
242
243    /// Validates the payload attributes with respect to the header.
244    ///
245    /// By default, this enforces that the payload attributes timestamp is greater than the
246    /// timestamp according to:
247    ///   > 7. Client software MUST ensure that payloadAttributes.timestamp is greater than
248    ///   > timestamp
249    ///   > of a block referenced by forkchoiceState.headBlockHash.
250    ///
251    /// See also: <https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md#specification-1>
252    ///
253    /// Enforced as part of the engine's `forkchoiceUpdated` handling when the consensus layer
254    /// provides payload attributes. If this returns an error, the forkchoice state update itself
255    /// is NOT rolled back, but no payload build job is started — the response includes
256    /// `INVALID_PAYLOAD_ATTRIBUTES`.
257    fn validate_payload_attributes_against_header(
258        &self,
259        attr: &Types::PayloadAttributes,
260        header: &<Self::Block as Block>::Header,
261    ) -> Result<(), InvalidPayloadAttributesError> {
262        if attr.timestamp() <= header.timestamp() {
263            return Err(InvalidPayloadAttributesError::InvalidTimestamp);
264        }
265        Ok(())
266    }
267}