Skip to main content

reth_payload_primitives/
lib.rs

1//! Abstractions for working with execution payloads.
2//!
3//! This crate provides types and traits for execution and building payloads.
4
5#![doc(
6    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
7    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
8    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
9)]
10#![cfg_attr(not(test), warn(unused_crate_dependencies))]
11#![cfg_attr(docsrs, feature(doc_cfg))]
12#![cfg_attr(not(feature = "std"), no_std)]
13
14extern crate alloc;
15
16use alloy_primitives::Bytes;
17use reth_chainspec::EthereumHardforks;
18use reth_primitives_traits::{NodePrimitives, SealedBlock};
19
20mod error;
21pub use error::{
22    EngineObjectValidationError, InvalidPayloadAttributesError, NewPayloadError,
23    PayloadBuilderError, VersionSpecificValidationError,
24};
25
26mod traits;
27pub use traits::{
28    payload_id, BuildNextEnv, BuiltPayload, BuiltPayloadExecutedBlock, PayloadAttributes,
29    PayloadAttributesBuilder,
30};
31
32mod payload;
33pub use payload::{ExecutionPayload, PayloadOrAttributes};
34
35/// Core trait that defines the associated types for working with execution payloads.
36pub trait PayloadTypes: Send + Sync + Unpin + core::fmt::Debug + Clone + 'static {
37    /// The format for execution payload data that can be processed and validated.
38    ///
39    /// This type represents the canonical format for block data that includes
40    /// all necessary information for execution and validation.
41    type ExecutionData: ExecutionPayload + From<Self::BuiltPayload>;
42    /// The type representing a successfully built payload/block.
43    type BuiltPayload: BuiltPayload + Clone + Unpin;
44
45    /// Attributes that specify how a payload should be constructed.
46    ///
47    /// These attributes typically come from external sources (e.g., consensus layer over RPC such
48    /// as the Engine API) and contain parameters like timestamp, fee recipient, and randomness.
49    type PayloadAttributes: PayloadAttributes + Unpin;
50
51    /// Converts a sealed block into the execution payload format.
52    fn block_to_payload(
53        block: SealedBlock<
54            <<Self::BuiltPayload as BuiltPayload>::Primitives as NodePrimitives>::Block,
55        >,
56        bal: Option<Bytes>,
57    ) -> Self::ExecutionData;
58}
59
60/// Validates the timestamp depending on the version called:
61///
62/// * If V2, this ensures that the payload timestamp is pre-Cancun.
63/// * If V3, this ensures that the payload timestamp is within the Cancun timestamp.
64/// * If V4, this ensures that the payload timestamp is within the Prague timestamp, and within the
65///   Amsterdam timestamp for `engine_forkchoiceUpdatedV4` payload attributes.
66/// * If V5, this ensures that the payload timestamp is within the Osaka timestamp, within the
67///   Amsterdam timestamp for `engine_newPayloadV5` payloads, and within the Bogota timestamp for
68///   `engine_forkchoiceUpdatedV5` payload attributes.
69/// * If V6, this ensures that the payload timestamp is within the Amsterdam timestamp, and within
70///   the Bogota timestamp for `engine_newPayloadV6` payloads.
71///
72/// Additionally, it ensures that `engine_getPayloadV4` is not used for an Osaka payload and that
73/// staggered endpoint upgrades reject the next fork once a newer method version is required.
74///
75/// Otherwise, this will return [`EngineObjectValidationError::UnsupportedFork`].
76pub fn validate_payload_timestamp(
77    chain_spec: impl EthereumHardforks,
78    version: EngineApiMessageVersion,
79    timestamp: u64,
80    kind: MessageValidationKind,
81) -> Result<(), EngineObjectValidationError> {
82    let is_cancun = chain_spec.is_cancun_active_at_timestamp(timestamp);
83    if version.is_v2() && is_cancun {
84        // From the Engine API spec:
85        //
86        // ### Update the methods of previous forks
87        //
88        // This document defines how Cancun payload should be handled by the [`Shanghai
89        // API`](https://github.com/ethereum/execution-apis/blob/ff43500e653abde45aec0f545564abfb648317af/src/engine/shanghai.md).
90        //
91        // For the following methods:
92        //
93        // - [`engine_forkchoiceUpdatedV2`](https://github.com/ethereum/execution-apis/blob/ff43500e653abde45aec0f545564abfb648317af/src/engine/shanghai.md#engine_forkchoiceupdatedv2)
94        // - [`engine_newPayloadV2`](https://github.com/ethereum/execution-apis/blob/ff43500e653abde45aec0f545564abfb648317af/src/engine/shanghai.md#engine_newpayloadV2)
95        // - [`engine_getPayloadV2`](https://github.com/ethereum/execution-apis/blob/ff43500e653abde45aec0f545564abfb648317af/src/engine/shanghai.md#engine_getpayloadv2)
96        //
97        // a validation **MUST** be added:
98        //
99        // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
100        //    payload or payloadAttributes is greater or equal to the Cancun activation timestamp.
101        return Err(EngineObjectValidationError::UnsupportedFork)
102    }
103
104    if version.is_v3() && !is_cancun {
105        // From the Engine API spec:
106        // <https://github.com/ethereum/execution-apis/blob/ff43500e653abde45aec0f545564abfb648317af/src/engine/cancun.md#specification-2>
107        //
108        // For `engine_getPayloadV3`:
109        //
110        // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
111        //    the built payload does not fall within the time frame of the Cancun fork.
112        //
113        // For `engine_forkchoiceUpdatedV3`:
114        //
115        // 2. Client software **MUST** return `-38005: Unsupported fork` error if the
116        //    `payloadAttributes` is set and the `payloadAttributes.timestamp` does not fall within
117        //    the time frame of the Cancun fork.
118        //
119        // For `engine_newPayloadV3`:
120        //
121        // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
122        //    the payload does not fall within the time frame of the Cancun fork.
123        return Err(EngineObjectValidationError::UnsupportedFork)
124    }
125
126    let is_prague = chain_spec.is_prague_active_at_timestamp(timestamp);
127    if version.is_v3() && is_prague && kind != MessageValidationKind::PayloadAttributes {
128        // From the Engine API spec:
129        // <https://github.com/ethereum/execution-apis/blob/32fae20be73cdecc8881559682f533ec371e17d3/src/engine/prague.md#update-the-methods-of-previous-forks>
130        //
131        // For `engine_newPayloadV3` and `engine_getPayloadV3`:
132        //
133        // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
134        //    payload is greater than or equal to the Prague activation timestamp.
135        //
136        // `engine_forkchoiceUpdatedV3` takes Prague payload attributes, so it is not subject to
137        // this rule.
138        return Err(EngineObjectValidationError::UnsupportedFork)
139    }
140
141    if version.is_v4() && !is_prague {
142        // From the Engine API spec:
143        // <https://github.com/ethereum/execution-apis/blob/7907424db935b93c2fe6a3c0faab943adebe8557/src/engine/prague.md#specification-1>
144        //
145        // For `engine_getPayloadV4`:
146        //
147        // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
148        //    the built payload does not fall within the time frame of the Prague fork.
149        //
150        // For `engine_forkchoiceUpdatedV4`:
151        //
152        // 2. Client software **MUST** return `-38005: Unsupported fork` error if the
153        //    `payloadAttributes` is set and the `payloadAttributes.timestamp` does not fall within
154        //    the time frame of the Prague fork.
155        //
156        // For `engine_newPayloadV4`:
157        //
158        // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of
159        //    the payload does not fall within the time frame of the Prague fork.
160        return Err(EngineObjectValidationError::UnsupportedFork)
161    }
162
163    let is_osaka = chain_spec.is_osaka_active_at_timestamp(timestamp);
164    if version.is_v5() && !is_osaka {
165        // From the Engine API spec:
166        // <https://github.com/ethereum/execution-apis/blob/15399c2e2f16a5f800bf3f285640357e2c245ad9/src/engine/osaka.md#specification>
167        //
168        // For `engine_getPayloadV5`
169        //
170        // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the
171        //    built payload does not fall within the time frame of the Osaka fork.
172        return Err(EngineObjectValidationError::UnsupportedFork)
173    }
174
175    let is_amsterdam = chain_spec.is_amsterdam_active_at_timestamp(timestamp);
176
177    if !is_amsterdam &&
178        matches!(
179            (version, kind),
180            (EngineApiMessageVersion::V4, MessageValidationKind::PayloadAttributes) |
181                (EngineApiMessageVersion::V5, MessageValidationKind::Payload)
182        )
183    {
184        // From the Engine API spec:
185        // <https://github.com/ethereum/execution-apis/blob/main/src/engine/amsterdam.md>
186        //
187        // For `engine_newPayloadV5`:
188        //
189        // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the
190        //    payload does not fall within the time frame of the Amsterdam fork.
191        //
192        // For `engine_forkchoiceUpdatedV4`:
193        //
194        // 2. payloadAttributes.timestamp does not fall within the time frame of the Amsterdam fork,
195        //    return -38005: Unsupported fork on failure.
196        //
197        // `engine_getPayloadV5` is the Osaka method and is not subject to this rule.
198        return Err(EngineObjectValidationError::UnsupportedFork)
199    }
200
201    // Staggered endpoint upgrades must reject Amsterdam payloads until the Amsterdam-specific
202    // method version is used.
203    if is_amsterdam &&
204        matches!(
205            (version, kind),
206            (EngineApiMessageVersion::V3, MessageValidationKind::PayloadAttributes) |
207                (EngineApiMessageVersion::V4, MessageValidationKind::Payload) |
208                (EngineApiMessageVersion::V5, MessageValidationKind::GetPayload)
209        )
210    {
211        return Err(EngineObjectValidationError::UnsupportedFork)
212    }
213
214    // `engine_getPayloadV4` MUST reject payloads with a timestamp >= Osaka.
215    if version.is_v4() && kind == MessageValidationKind::GetPayload && is_osaka {
216        return Err(EngineObjectValidationError::UnsupportedFork)
217    }
218
219    if version.is_v6() && !is_amsterdam {
220        // From the Engine API spec:
221        // <https://github.com/ethereum/execution-apis/blob/15399c2e2f16a5f800bf3f285640357e2c245ad9/src/engine/osaka.md#specification>
222        //
223        // For `engine_getPayloadV6`
224        //
225        // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the
226        //    built payload does not fall within the time frame of the Amsterdam fork.
227
228        return Err(EngineObjectValidationError::UnsupportedFork)
229    }
230
231    let is_bogota = chain_spec.is_bogota_active_at_timestamp(timestamp);
232
233    // Staggered endpoint upgrades must reject Bogota payloads until the Bogota-specific method
234    // version is used.
235    //
236    // From the Engine API spec:
237    // <https://github.com/ethereum/execution-apis/blob/main/src/engine/bogota.md#update-the-methods-of-previous-forks>
238    //
239    // For `engine_newPayloadV5` and `engine_forkchoiceUpdatedV4`:
240    //
241    // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of payload is
242    //    greater than or equal to the Bogota activation timestamp.
243    if is_bogota &&
244        matches!(
245            (version, kind),
246            (EngineApiMessageVersion::V4, MessageValidationKind::PayloadAttributes) |
247                (EngineApiMessageVersion::V5, MessageValidationKind::Payload)
248        )
249    {
250        return Err(EngineObjectValidationError::UnsupportedFork)
251    }
252
253    if !is_bogota &&
254        matches!(
255            (version, kind),
256            (EngineApiMessageVersion::V5, MessageValidationKind::PayloadAttributes) |
257                (EngineApiMessageVersion::V6, MessageValidationKind::Payload)
258        )
259    {
260        // From the Engine API spec:
261        // <https://github.com/ethereum/execution-apis/blob/main/src/engine/bogota.md>
262        //
263        // For `engine_newPayloadV6`:
264        //
265        // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the
266        //    payload does not fall within the time frame of the Bogota fork.
267        //
268        // For `engine_forkchoiceUpdatedV5`:
269        //
270        // 2. Client software MUST return -38005: Unsupported fork error if the payloadAttributes is
271        //    set and the payloadAttributes.timestamp does not fall within the time frame of the
272        //    Bogota fork.
273        return Err(EngineObjectValidationError::UnsupportedFork)
274    }
275
276    Ok(())
277}
278
279/// Validates the presence of the `block access list` field for the engine method version.
280///
281/// `engine_newPayloadV5` and `engine_newPayloadV6` take an `ExecutionPayloadV4`, so the field must
282/// be [Some]; every other method must leave it [None]. Presence does not depend on the payload
283/// timestamp, so a well-formed payload outside the method's fork reaches the fork check in
284/// [`validate_payload_timestamp`] and fails with `-38005: Unsupported fork`.
285pub fn validate_block_access_list_presence(
286    version: EngineApiMessageVersion,
287    message_validation_kind: MessageValidationKind,
288    has_block_access_list: bool,
289) -> Result<(), EngineObjectValidationError> {
290    match version {
291        EngineApiMessageVersion::V1 |
292        EngineApiMessageVersion::V2 |
293        EngineApiMessageVersion::V3 |
294        EngineApiMessageVersion::V4 => {
295            if has_block_access_list {
296                return Err(message_validation_kind
297                    .to_error(VersionSpecificValidationError::BlockAccessListNotSupported))
298            }
299        }
300
301        EngineApiMessageVersion::V5 => {
302            if message_validation_kind == MessageValidationKind::Payload {
303                if !has_block_access_list {
304                    return Err(message_validation_kind
305                        .to_error(VersionSpecificValidationError::NoBlockAccessListPostAmsterdam))
306                }
307            } else if has_block_access_list {
308                return Err(message_validation_kind
309                    .to_error(VersionSpecificValidationError::BlockAccessListNotSupported))
310            }
311        }
312
313        EngineApiMessageVersion::V6 => {
314            if !has_block_access_list {
315                return Err(message_validation_kind
316                    .to_error(VersionSpecificValidationError::NoBlockAccessListPostAmsterdam))
317            }
318        }
319    };
320
321    Ok(())
322}
323
324/// Validates the presence of the `slot number` field for the engine method version.
325///
326/// `engine_newPayloadV5`, `engine_newPayloadV6`, `engine_forkchoiceUpdatedV4` and
327/// `engine_forkchoiceUpdatedV5` carry the field, so it must be [Some] for them; every other method
328/// must leave it [None]. Presence does not depend on the payload timestamp, so a well-formed
329/// request outside the method's fork reaches the fork check in [`validate_payload_timestamp`] and
330/// fails with `-38005: Unsupported fork`.
331pub fn validate_slot_number_presence(
332    version: EngineApiMessageVersion,
333    message_validation_kind: MessageValidationKind,
334    has_slot_number: bool,
335) -> Result<(), EngineObjectValidationError> {
336    match version {
337        EngineApiMessageVersion::V1 | EngineApiMessageVersion::V2 | EngineApiMessageVersion::V3 => {
338            if has_slot_number {
339                return Err(message_validation_kind
340                    .to_error(VersionSpecificValidationError::SlotNumberNotSupported))
341            }
342        }
343
344        EngineApiMessageVersion::V4 => {
345            if message_validation_kind == MessageValidationKind::PayloadAttributes {
346                if !has_slot_number {
347                    return Err(message_validation_kind
348                        .to_error(VersionSpecificValidationError::NoSlotNumberPostAmsterdam))
349                }
350            } else if has_slot_number {
351                return Err(message_validation_kind
352                    .to_error(VersionSpecificValidationError::SlotNumberNotSupported))
353            }
354        }
355
356        EngineApiMessageVersion::V5 => {
357            if matches!(
358                message_validation_kind,
359                MessageValidationKind::Payload | MessageValidationKind::PayloadAttributes
360            ) {
361                if !has_slot_number {
362                    return Err(message_validation_kind
363                        .to_error(VersionSpecificValidationError::NoSlotNumberPostAmsterdam))
364                }
365            } else if has_slot_number {
366                return Err(message_validation_kind
367                    .to_error(VersionSpecificValidationError::SlotNumberNotSupported))
368            }
369        }
370
371        EngineApiMessageVersion::V6 => {
372            if !has_slot_number {
373                return Err(message_validation_kind
374                    .to_error(VersionSpecificValidationError::NoSlotNumberPostAmsterdam))
375            }
376        }
377    };
378
379    Ok(())
380}
381
382/// Validates the presence of the `target gas limit` field in payload attributes.
383///
384/// The attributes of `engine_forkchoiceUpdatedV4` and `engine_forkchoiceUpdatedV5` include the
385/// field, so it must be [Some] for them. A missing field is a structural error and fails with
386/// `-38003: Invalid payload attributes`.
387pub fn validate_target_gas_limit_presence(
388    version: EngineApiMessageVersion,
389    message_validation_kind: MessageValidationKind,
390    has_target_gas_limit: bool,
391) -> Result<(), EngineObjectValidationError> {
392    if message_validation_kind == MessageValidationKind::PayloadAttributes &&
393        matches!(version, EngineApiMessageVersion::V4 | EngineApiMessageVersion::V5) &&
394        !has_target_gas_limit
395    {
396        return Err(message_validation_kind
397            .to_error(VersionSpecificValidationError::NoTargetGasLimitPostAmsterdam))
398    }
399
400    Ok(())
401}
402
403/// Validates the presence of `withdrawals` for the engine method version.
404///
405/// V1 forbids withdrawals. V2 supports both Paris and Shanghai payloads, so withdrawals must be
406/// present exactly when Shanghai is active. V3 and later require withdrawals regardless of the
407/// timestamp, allowing complete requests outside the method's fork to reach the timeframe check.
408pub fn validate_withdrawals_presence<T: EthereumHardforks>(
409    chain_spec: &T,
410    version: EngineApiMessageVersion,
411    message_validation_kind: MessageValidationKind,
412    timestamp: u64,
413    has_withdrawals: bool,
414) -> Result<(), EngineObjectValidationError> {
415    match version {
416        EngineApiMessageVersion::V1 => {
417            if has_withdrawals {
418                return Err(message_validation_kind
419                    .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1))
420            }
421        }
422        EngineApiMessageVersion::V2 => {
423            let is_shanghai_active = chain_spec.is_shanghai_active_at_timestamp(timestamp);
424            if is_shanghai_active && !has_withdrawals {
425                return Err(message_validation_kind
426                    .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai))
427            }
428            if !is_shanghai_active && has_withdrawals {
429                return Err(message_validation_kind
430                    .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai))
431            }
432        }
433        EngineApiMessageVersion::V3 |
434        EngineApiMessageVersion::V4 |
435        EngineApiMessageVersion::V5 |
436        EngineApiMessageVersion::V6 => {
437            if !has_withdrawals {
438                return Err(message_validation_kind
439                    .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai))
440            }
441        }
442    };
443
444    Ok(())
445}
446
447/// Validate the presence of the `parentBeaconBlockRoot` field according to the given timestamp.
448/// This method is meant to be used with either a `payloadAttributes` field or a full payload, with
449/// the `engine_forkchoiceUpdated` and `engine_newPayload` methods respectively.
450///
451/// After Cancun, the `parentBeaconBlockRoot` field must be [Some].
452/// Before Cancun, the `parentBeaconBlockRoot` field must be [None].
453///
454/// If the engine API message version is V1 or V2, and the timestamp is post-Cancun, then this will
455/// return [`EngineObjectValidationError::UnsupportedFork`].
456///
457/// If the timestamp is before the Cancun fork and the engine API message version is V3, then this
458/// will return [`EngineObjectValidationError::UnsupportedFork`].
459///
460/// If the engine API message version is V3, but the `parentBeaconBlockRoot` is [None], then
461/// this will return [`VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun`].
462///
463/// This implements the following Engine API spec rules:
464///
465/// 1. Client software **MUST** check that provided set of parameters and their fields strictly
466///    matches the expected one and return `-32602: Invalid params` error if this check fails. Any
467///    field having `null` value **MUST** be considered as not provided.
468///
469/// For `engine_forkchoiceUpdatedV3`:
470///
471/// 1. Client software **MUST** check that provided set of parameters and their fields strictly
472///    matches the expected one and return `-32602: Invalid params` error if this check fails. Any
473///    field having `null` value **MUST** be considered as not provided.
474///
475/// 2. Extend point (7) of the `engine_forkchoiceUpdatedV1` specification by defining the following
476///    sequence of checks that **MUST** be run over `payloadAttributes`:
477///     1. `payloadAttributes` matches the `PayloadAttributesV3` structure, return `-38003: Invalid
478///        payload attributes` on failure.
479///     2. `payloadAttributes.timestamp` falls within the time frame of the Cancun fork, return
480///        `-38005: Unsupported fork` on failure.
481///     3. `payloadAttributes.timestamp` is greater than `timestamp` of a block referenced by
482///        `forkchoiceState.headBlockHash`, return `-38003: Invalid payload attributes` on failure.
483///     4. If any of the above checks fails, the `forkchoiceState` update **MUST NOT** be rolled
484///        back.
485///
486/// For `engine_newPayloadV3`:
487///
488/// 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of the
489///    payload does not fall within the time frame of the Cancun fork.
490///
491/// For `engine_newPayloadV4`:
492///
493/// 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of the
494///    payload does not fall within the time frame of the Prague fork.
495///
496/// Returning the right error code (ie, if the client should return `-38003: Invalid payload
497/// attributes` is handled by the `message_validation_kind` parameter. If the parameter is
498/// `MessageValidationKind::Payload`, then the error code will be `-32602: Invalid params`. If the
499/// parameter is `MessageValidationKind::PayloadAttributes`, then the error code will be `-38003:
500/// Invalid payload attributes`.
501pub fn validate_parent_beacon_block_root_presence<T: EthereumHardforks>(
502    chain_spec: &T,
503    version: EngineApiMessageVersion,
504    validation_kind: MessageValidationKind,
505    timestamp: u64,
506    has_parent_beacon_block_root: bool,
507) -> Result<(), EngineObjectValidationError> {
508    // 1. Client software **MUST** check that provided set of parameters and their fields strictly
509    //    matches the expected one and return `-32602: Invalid params` error if this check fails.
510    //    Any field having `null` value **MUST** be considered as not provided.
511    //
512    // For `engine_forkchoiceUpdatedV3`:
513    //
514    // 2. Extend point (7) of the `engine_forkchoiceUpdatedV1` specification by defining the
515    //    following sequence of checks that **MUST** be run over `payloadAttributes`:
516    //     1. `payloadAttributes` matches the `PayloadAttributesV3` structure, return `-38003:
517    //        Invalid payload attributes` on failure.
518    //     2. `payloadAttributes.timestamp` falls within the time frame of the Cancun fork, return
519    //        `-38005: Unsupported fork` on failure.
520    //     3. `payloadAttributes.timestamp` is greater than `timestamp` of a block referenced by
521    //        `forkchoiceState.headBlockHash`, return `-38003: Invalid payload attributes` on
522    //        failure.
523    //     4. If any of the above checks fails, the `forkchoiceState` update **MUST NOT** be rolled
524    //        back.
525    match version {
526        EngineApiMessageVersion::V1 | EngineApiMessageVersion::V2 => {
527            if has_parent_beacon_block_root {
528                return Err(validation_kind.to_error(
529                    VersionSpecificValidationError::ParentBeaconBlockRootNotSupportedBeforeV3,
530                ))
531            }
532        }
533        EngineApiMessageVersion::V3 |
534        EngineApiMessageVersion::V4 |
535        EngineApiMessageVersion::V5 |
536        EngineApiMessageVersion::V6 => {
537            if !has_parent_beacon_block_root {
538                return Err(validation_kind
539                    .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun))
540            }
541        }
542    };
543
544    // For `engine_forkchoiceUpdatedV3`:
545    //
546    // 2. Client software **MUST** return `-38005: Unsupported fork` error if the
547    //    `payloadAttributes` is set and the `payloadAttributes.timestamp` does not fall within the
548    //    time frame of the Cancun fork.
549    //
550    // For `engine_newPayloadV3`:
551    //
552    // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of the
553    //    payload does not fall within the time frame of the Cancun fork.
554    validate_payload_timestamp(chain_spec, version, timestamp, validation_kind)?;
555
556    Ok(())
557}
558
559/// A type that represents whether or not we are validating a payload or payload attributes.
560///
561/// This is used to ensure that the correct error code is returned when validating the payload or
562/// payload attributes.
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564pub enum MessageValidationKind {
565    /// We are validating fields of a payload attributes.
566    /// This corresponds to `engine_forkchoiceUpdated`.
567    PayloadAttributes,
568    /// We are validating fields of a payload.
569    /// This corresponds to `engine_newPayload`.
570    Payload,
571    /// We are validating a built payload.
572    /// This corresponds to `engine_getPayload`.
573    GetPayload,
574}
575
576impl MessageValidationKind {
577    /// Returns an `EngineObjectValidationError` based on the given
578    /// `VersionSpecificValidationError` and the current validation kind.
579    pub const fn to_error(
580        self,
581        error: VersionSpecificValidationError,
582    ) -> EngineObjectValidationError {
583        match self {
584            // Both NewPayload and GetPayload errors are treated as generic Payload validation
585            // errors
586            Self::Payload | Self::GetPayload => EngineObjectValidationError::Payload(error),
587            Self::PayloadAttributes => EngineObjectValidationError::PayloadAttributes(error),
588        }
589    }
590}
591
592/// Validates the presence or exclusion of fork-specific fields based on the ethereum execution
593/// payload, or payload attributes, and the message version.
594///
595/// The object being validated is provided by the [`PayloadOrAttributes`] argument, which can be
596/// either an execution payload, or payload attributes.
597///
598/// The version is provided by the [`EngineApiMessageVersion`] argument.
599pub fn validate_version_specific_fields<Payload, Type, T>(
600    chain_spec: &T,
601    version: EngineApiMessageVersion,
602    payload_or_attrs: PayloadOrAttributes<'_, Payload, Type>,
603) -> Result<(), EngineObjectValidationError>
604where
605    Payload: ExecutionPayload,
606    Type: PayloadAttributes,
607    T: EthereumHardforks,
608{
609    // BAL only exists in ExecutionPayload, not PayloadAttributes (EIP-7928)
610    if let PayloadOrAttributes::ExecutionPayload(_) = payload_or_attrs {
611        validate_block_access_list_presence(
612            version,
613            payload_or_attrs.message_validation_kind(),
614            payload_or_attrs.block_access_list().is_some(),
615        )?;
616    }
617
618    validate_slot_number_presence(
619        version,
620        payload_or_attrs.message_validation_kind(),
621        payload_or_attrs.slot_number().is_some(),
622    )?;
623
624    validate_target_gas_limit_presence(
625        version,
626        payload_or_attrs.message_validation_kind(),
627        payload_or_attrs.target_gas_limit().is_some(),
628    )?;
629
630    validate_withdrawals_presence(
631        chain_spec,
632        version,
633        payload_or_attrs.message_validation_kind(),
634        payload_or_attrs.timestamp(),
635        payload_or_attrs.withdrawals().is_some(),
636    )?;
637    validate_parent_beacon_block_root_presence(
638        chain_spec,
639        version,
640        payload_or_attrs.message_validation_kind(),
641        payload_or_attrs.timestamp(),
642        payload_or_attrs.parent_beacon_block_root().is_some(),
643    )
644}
645
646/// The version of Engine API message.
647#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
648pub enum EngineApiMessageVersion {
649    /// Version 1
650    V1 = 1,
651    /// Version 2
652    ///
653    /// Added in the Shanghai hardfork.
654    V2 = 2,
655    /// Version 3
656    ///
657    /// Added in the Cancun hardfork.
658    V3 = 3,
659    /// Version 4
660    ///
661    /// Added in the Prague hardfork.
662    #[default]
663    V4 = 4,
664    /// Version 5
665    ///
666    /// Added in the Osaka hardfork.
667    V5 = 5,
668    /// Version 6
669    ///
670    /// Added in the Amsterdam hardfork.
671    V6 = 6,
672}
673
674impl EngineApiMessageVersion {
675    /// Returns true if the version is V1.
676    pub const fn is_v1(&self) -> bool {
677        matches!(self, Self::V1)
678    }
679
680    /// Returns true if the version is V2.
681    pub const fn is_v2(&self) -> bool {
682        matches!(self, Self::V2)
683    }
684
685    /// Returns true if the version is V3.
686    pub const fn is_v3(&self) -> bool {
687        matches!(self, Self::V3)
688    }
689
690    /// Returns true if the version is V4.
691    pub const fn is_v4(&self) -> bool {
692        matches!(self, Self::V4)
693    }
694
695    /// Returns true if the version is V5.
696    pub const fn is_v5(&self) -> bool {
697        matches!(self, Self::V5)
698    }
699
700    /// Returns true if the version is V6.
701    pub const fn is_v6(&self) -> bool {
702        matches!(self, Self::V6)
703    }
704
705    /// Returns the method name for the given version.
706    pub const fn method_name(&self) -> &'static str {
707        match self {
708            Self::V1 => "engine_newPayloadV1",
709            Self::V2 => "engine_newPayloadV2",
710            Self::V3 => "engine_newPayloadV3",
711            Self::V4 => "engine_newPayloadV4",
712            Self::V5 | Self::V6 => "engine_newPayloadV5",
713        }
714    }
715}
716
717/// Determines how we should choose the payload to return.
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
719pub enum PayloadKind {
720    /// Returns the next best available payload (the earliest available payload).
721    /// This does not wait for a real for pending job to finish if there's no best payload yet and
722    /// is allowed to race various payload jobs (empty, pending best) against each other and
723    /// returns whichever job finishes faster.
724    ///
725    /// This should be used when it's more important to return a valid payload as fast as possible.
726    /// For example, the engine API timeout for `engine_getPayload` is 1s and clients should rather
727    /// return an empty payload than indefinitely waiting for the pending payload job to finish and
728    /// risk missing the deadline.
729    #[default]
730    Earliest,
731    /// Only returns once we have at least one built payload.
732    ///
733    /// Compared to [`PayloadKind::Earliest`] this does not race an empty payload job against the
734    /// already in progress one, and returns the best available built payload or awaits the job in
735    /// progress.
736    WaitForPending,
737}
738
739/// Validates that execution requests are valid according to Engine API specification.
740///
741/// `executionRequests`: `Array of DATA` - List of execution layer triggered requests. Each list
742/// element is a `requests` byte array as defined by [EIP-7685](https://eips.ethereum.org/EIPS/eip-7685).
743/// The first byte of each element is the `request_type` and the remaining bytes are the
744/// `request_data`. Elements of the list **MUST** be ordered by `request_type` in ascending order.
745/// Elements with empty `request_data` **MUST** be excluded from the list. If any element is out of
746/// order, has a length of 1-byte or shorter, or more than one element has the same type byte,
747/// client software **MUST** return `-32602: Invalid params` error.
748pub fn validate_execution_requests(requests: &[Bytes]) -> Result<(), EngineObjectValidationError> {
749    let mut last_request_type = None;
750    for request in requests {
751        if request.len() <= 1 {
752            return Err(EngineObjectValidationError::InvalidParams("EmptyExecutionRequest".into()))
753        }
754
755        let request_type = request[0];
756        if Some(request_type) < last_request_type {
757            return Err(EngineObjectValidationError::InvalidParams(
758                "OutOfOrderExecutionRequest".into(),
759            ))
760        }
761
762        if Some(request_type) == last_request_type {
763            return Err(EngineObjectValidationError::InvalidParams(
764                "DuplicatedExecutionRequestType".into(),
765            ))
766        }
767
768        last_request_type = Some(request_type);
769    }
770    Ok(())
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776    use assert_matches::assert_matches;
777    use reth_chainspec::{ChainSpecBuilder, EthereumHardfork, ForkCondition};
778
779    #[test]
780    fn version_ord() {
781        assert!(EngineApiMessageVersion::V4 > EngineApiMessageVersion::V3);
782    }
783
784    #[test]
785    fn validate_osaka_get_payload_restrictions() {
786        // Osaka activates at timestamp 1000
787        let osaka_activation = 1000;
788        let chain_spec = ChainSpecBuilder::mainnet()
789            .with_fork(EthereumHardfork::Prague, ForkCondition::Timestamp(0))
790            .with_fork(EthereumHardfork::Osaka, ForkCondition::Timestamp(osaka_activation))
791            .build();
792
793        // Osaka is Active + V4 + GetPayload
794        let res = validate_payload_timestamp(
795            &chain_spec,
796            EngineApiMessageVersion::V4,
797            osaka_activation,
798            MessageValidationKind::GetPayload,
799        );
800        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
801
802        // Osaka is Active + V4 + Payload (NewPayload)
803        let res = validate_payload_timestamp(
804            &chain_spec,
805            EngineApiMessageVersion::V4,
806            osaka_activation,
807            MessageValidationKind::Payload,
808        );
809        assert_matches!(res, Ok(()));
810    }
811
812    #[test]
813    fn validate_prague_v3_restrictions() {
814        // Prague activates at timestamp 1000
815        let prague_activation = 1000;
816        let chain_spec = ChainSpecBuilder::mainnet()
817            .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(0))
818            .with_fork(EthereumHardfork::Prague, ForkCondition::Timestamp(prague_activation))
819            .build();
820
821        // `engine_newPayloadV3` and `engine_getPayloadV3` reject a Prague timestamp
822        for kind in [MessageValidationKind::Payload, MessageValidationKind::GetPayload] {
823            let res = validate_payload_timestamp(
824                &chain_spec,
825                EngineApiMessageVersion::V3,
826                prague_activation,
827                kind,
828            );
829            assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
830
831            let res = validate_payload_timestamp(
832                &chain_spec,
833                EngineApiMessageVersion::V3,
834                prague_activation - 1,
835                kind,
836            );
837            assert_matches!(res, Ok(()));
838        }
839
840        // `engine_forkchoiceUpdatedV3` takes Prague payload attributes
841        let res = validate_payload_timestamp(
842            &chain_spec,
843            EngineApiMessageVersion::V3,
844            prague_activation,
845            MessageValidationKind::PayloadAttributes,
846        );
847        assert_matches!(res, Ok(()));
848    }
849
850    #[test]
851    fn validate_amsterdam_staggered_version_restrictions() {
852        let chain_spec = ChainSpecBuilder::mainnet().amsterdam_activated().build();
853
854        let res = validate_payload_timestamp(
855            &chain_spec,
856            EngineApiMessageVersion::V3,
857            0,
858            MessageValidationKind::PayloadAttributes,
859        );
860        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
861
862        let res = validate_payload_timestamp(
863            &chain_spec,
864            EngineApiMessageVersion::V4,
865            0,
866            MessageValidationKind::Payload,
867        );
868        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
869
870        let res = validate_payload_timestamp(
871            &chain_spec,
872            EngineApiMessageVersion::V5,
873            0,
874            MessageValidationKind::GetPayload,
875        );
876        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
877
878        let res = validate_payload_timestamp(
879            &chain_spec,
880            EngineApiMessageVersion::V6,
881            0,
882            MessageValidationKind::GetPayload,
883        );
884        assert_matches!(res, Ok(()));
885    }
886
887    #[test]
888    fn validate_bogota_fork_timeframe() {
889        // Amsterdam active, Bogota not scheduled: the Bogota-specific methods must reject
890        let chain_spec = ChainSpecBuilder::mainnet().amsterdam_activated().build();
891
892        // `engine_newPayloadV6` requires a Bogota timestamp
893        let res = validate_payload_timestamp(
894            &chain_spec,
895            EngineApiMessageVersion::V6,
896            0,
897            MessageValidationKind::Payload,
898        );
899        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
900
901        // `engine_forkchoiceUpdatedV5` requires Bogota payload attributes
902        let res = validate_payload_timestamp(
903            &chain_spec,
904            EngineApiMessageVersion::V5,
905            0,
906            MessageValidationKind::PayloadAttributes,
907        );
908        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
909
910        // the Amsterdam methods remain valid pre-Bogota
911        let res = validate_payload_timestamp(
912            &chain_spec,
913            EngineApiMessageVersion::V5,
914            0,
915            MessageValidationKind::Payload,
916        );
917        assert_matches!(res, Ok(()));
918        let res = validate_payload_timestamp(
919            &chain_spec,
920            EngineApiMessageVersion::V4,
921            0,
922            MessageValidationKind::PayloadAttributes,
923        );
924        assert_matches!(res, Ok(()));
925    }
926
927    #[test]
928    fn validate_bogota_staggered_version_restrictions() {
929        let chain_spec = ChainSpecBuilder::mainnet().bogota_activated().build();
930
931        // `engine_newPayloadV5` must reject Bogota payloads
932        let res = validate_payload_timestamp(
933            &chain_spec,
934            EngineApiMessageVersion::V5,
935            0,
936            MessageValidationKind::Payload,
937        );
938        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
939
940        // `engine_forkchoiceUpdatedV4` must reject Bogota payload attributes
941        let res = validate_payload_timestamp(
942            &chain_spec,
943            EngineApiMessageVersion::V4,
944            0,
945            MessageValidationKind::PayloadAttributes,
946        );
947        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
948
949        // the Bogota-specific methods are accepted
950        let res = validate_payload_timestamp(
951            &chain_spec,
952            EngineApiMessageVersion::V6,
953            0,
954            MessageValidationKind::Payload,
955        );
956        assert_matches!(res, Ok(()));
957        let res = validate_payload_timestamp(
958            &chain_spec,
959            EngineApiMessageVersion::V5,
960            0,
961            MessageValidationKind::PayloadAttributes,
962        );
963        assert_matches!(res, Ok(()));
964
965        // Bogota defines no new getPayload version, `engine_getPayloadV6` remains valid
966        let res = validate_payload_timestamp(
967            &chain_spec,
968            EngineApiMessageVersion::V6,
969            0,
970            MessageValidationKind::GetPayload,
971        );
972        assert_matches!(res, Ok(()));
973    }
974
975    #[test]
976    fn validate_amsterdam_slot_and_bal_presence() {
977        let res = validate_slot_number_presence(
978            EngineApiMessageVersion::V4,
979            MessageValidationKind::PayloadAttributes,
980            true,
981        );
982        assert_matches!(res, Ok(()));
983
984        let res = validate_slot_number_presence(
985            EngineApiMessageVersion::V5,
986            MessageValidationKind::Payload,
987            true,
988        );
989        assert_matches!(res, Ok(()));
990
991        let res = validate_slot_number_presence(
992            EngineApiMessageVersion::V5,
993            MessageValidationKind::PayloadAttributes,
994            true,
995        );
996        assert_matches!(res, Ok(()));
997
998        let res = validate_block_access_list_presence(
999            EngineApiMessageVersion::V5,
1000            MessageValidationKind::Payload,
1001            true,
1002        );
1003        assert_matches!(res, Ok(()));
1004    }
1005
1006    #[test]
1007    fn validate_amsterdam_fork_timeframe() {
1008        // Osaka active, Amsterdam not scheduled: the Amsterdam methods must reject.
1009        let chain_spec = ChainSpecBuilder::mainnet().osaka_activated().build();
1010        assert!(!chain_spec.is_amsterdam_active_at_timestamp(0));
1011
1012        // `engine_newPayloadV5` requires an Amsterdam timestamp.
1013        let res = validate_payload_timestamp(
1014            &chain_spec,
1015            EngineApiMessageVersion::V5,
1016            0,
1017            MessageValidationKind::Payload,
1018        );
1019        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
1020
1021        // `engine_forkchoiceUpdatedV4` requires Amsterdam payload attributes.
1022        let res = validate_payload_timestamp(
1023            &chain_spec,
1024            EngineApiMessageVersion::V4,
1025            0,
1026            MessageValidationKind::PayloadAttributes,
1027        );
1028        assert_matches!(res, Err(EngineObjectValidationError::UnsupportedFork));
1029
1030        // `engine_getPayloadV5` is the Osaka method and remains valid pre-Amsterdam.
1031        let res = validate_payload_timestamp(
1032            &chain_spec,
1033            EngineApiMessageVersion::V5,
1034            0,
1035            MessageValidationKind::GetPayload,
1036        );
1037        assert_matches!(res, Ok(()));
1038
1039        // `engine_newPayloadV4` remains valid pre-Amsterdam.
1040        let res = validate_payload_timestamp(
1041            &chain_spec,
1042            EngineApiMessageVersion::V4,
1043            0,
1044            MessageValidationKind::Payload,
1045        );
1046        assert_matches!(res, Ok(()));
1047    }
1048
1049    #[test]
1050    fn validate_slot_and_bal_presence_is_structural() {
1051        // The presence checks take no timestamp, a well-formed V5 payload passes them and the
1052        // fork timeframe check rejects it afterwards.
1053        let res = validate_block_access_list_presence(
1054            EngineApiMessageVersion::V5,
1055            MessageValidationKind::Payload,
1056            true,
1057        );
1058        assert_matches!(res, Ok(()));
1059        let res = validate_slot_number_presence(
1060            EngineApiMessageVersion::V5,
1061            MessageValidationKind::Payload,
1062            true,
1063        );
1064        assert_matches!(res, Ok(()));
1065        let res = validate_slot_number_presence(
1066            EngineApiMessageVersion::V4,
1067            MessageValidationKind::PayloadAttributes,
1068            true,
1069        );
1070        assert_matches!(res, Ok(()));
1071
1072        // Missing fields are structural errors.
1073        let res = validate_block_access_list_presence(
1074            EngineApiMessageVersion::V5,
1075            MessageValidationKind::Payload,
1076            false,
1077        );
1078        assert_matches!(
1079            res,
1080            Err(EngineObjectValidationError::Payload(
1081                VersionSpecificValidationError::NoBlockAccessListPostAmsterdam
1082            ))
1083        );
1084        let res = validate_block_access_list_presence(
1085            EngineApiMessageVersion::V6,
1086            MessageValidationKind::Payload,
1087            false,
1088        );
1089        assert_matches!(
1090            res,
1091            Err(EngineObjectValidationError::Payload(
1092                VersionSpecificValidationError::NoBlockAccessListPostAmsterdam
1093            ))
1094        );
1095        let res = validate_slot_number_presence(
1096            EngineApiMessageVersion::V5,
1097            MessageValidationKind::Payload,
1098            false,
1099        );
1100        assert_matches!(
1101            res,
1102            Err(EngineObjectValidationError::Payload(
1103                VersionSpecificValidationError::NoSlotNumberPostAmsterdam
1104            ))
1105        );
1106        let res = validate_slot_number_presence(
1107            EngineApiMessageVersion::V4,
1108            MessageValidationKind::PayloadAttributes,
1109            false,
1110        );
1111        assert_matches!(
1112            res,
1113            Err(EngineObjectValidationError::PayloadAttributes(
1114                VersionSpecificValidationError::NoSlotNumberPostAmsterdam
1115            ))
1116        );
1117
1118        // Methods that predate Amsterdam still reject the fields.
1119        let res = validate_block_access_list_presence(
1120            EngineApiMessageVersion::V4,
1121            MessageValidationKind::Payload,
1122            true,
1123        );
1124        assert_matches!(
1125            res,
1126            Err(EngineObjectValidationError::Payload(
1127                VersionSpecificValidationError::BlockAccessListNotSupported
1128            ))
1129        );
1130        let res = validate_slot_number_presence(
1131            EngineApiMessageVersion::V4,
1132            MessageValidationKind::Payload,
1133            true,
1134        );
1135        assert_matches!(
1136            res,
1137            Err(EngineObjectValidationError::Payload(
1138                VersionSpecificValidationError::SlotNumberNotSupported
1139            ))
1140        );
1141    }
1142
1143    #[test]
1144    fn execution_requests_validation() {
1145        assert_matches!(validate_execution_requests(&[]), Ok(()));
1146
1147        let valid_requests = [
1148            Bytes::from_iter([1, 2]),
1149            Bytes::from_iter([2, 3]),
1150            Bytes::from_iter([3, 4]),
1151            Bytes::from_iter([4, 5]),
1152        ];
1153        assert_matches!(validate_execution_requests(&valid_requests), Ok(()));
1154
1155        let requests_with_empty = [
1156            Bytes::from_iter([1, 2]),
1157            Bytes::from_iter([2, 3]),
1158            Bytes::new(),
1159            Bytes::from_iter([3, 4]),
1160        ];
1161        assert_matches!(
1162            validate_execution_requests(&requests_with_empty),
1163            Err(EngineObjectValidationError::InvalidParams(_))
1164        );
1165
1166        let mut requests_valid_reversed = valid_requests;
1167        requests_valid_reversed.reverse();
1168        assert_matches!(
1169            validate_execution_requests(&requests_valid_reversed),
1170            Err(EngineObjectValidationError::InvalidParams(_))
1171        );
1172
1173        let requests_out_of_order = [
1174            Bytes::from_iter([1, 2]),
1175            Bytes::from_iter([2, 3]),
1176            Bytes::from_iter([4, 5]),
1177            Bytes::from_iter([3, 4]),
1178        ];
1179        assert_matches!(
1180            validate_execution_requests(&requests_out_of_order),
1181            Err(EngineObjectValidationError::InvalidParams(_))
1182        );
1183
1184        let duplicate_request_types = [
1185            Bytes::from_iter([1, 2]),
1186            Bytes::from_iter([3, 3]),
1187            Bytes::from_iter([4, 5]),
1188            Bytes::from_iter([4, 4]),
1189        ];
1190        assert_matches!(
1191            validate_execution_requests(&duplicate_request_types),
1192            Err(EngineObjectValidationError::InvalidParams(_))
1193        );
1194    }
1195
1196    #[test]
1197    fn validate_v2_withdrawals_follow_timestamp() {
1198        let chain_spec = ChainSpecBuilder::mainnet()
1199            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(100))
1200            .build();
1201        for (timestamp, has_withdrawals) in [(99, false), (100, true)] {
1202            assert_matches!(
1203                validate_withdrawals_presence(
1204                    &chain_spec,
1205                    EngineApiMessageVersion::V2,
1206                    MessageValidationKind::Payload,
1207                    timestamp,
1208                    has_withdrawals,
1209                ),
1210                Ok(())
1211            );
1212        }
1213        assert_matches!(
1214            validate_withdrawals_presence(
1215                &chain_spec,
1216                EngineApiMessageVersion::V2,
1217                MessageValidationKind::Payload,
1218                99,
1219                true,
1220            ),
1221            Err(EngineObjectValidationError::Payload(
1222                VersionSpecificValidationError::HasWithdrawalsPreShanghai
1223            ))
1224        );
1225        assert_matches!(
1226            validate_withdrawals_presence(
1227                &chain_spec,
1228                EngineApiMessageVersion::V2,
1229                MessageValidationKind::Payload,
1230                100,
1231                false,
1232            ),
1233            Err(EngineObjectValidationError::Payload(
1234                VersionSpecificValidationError::NoWithdrawalsPostShanghai
1235            ))
1236        );
1237    }
1238
1239    #[test]
1240    fn validate_v3_and_later_withdrawals_are_structural() {
1241        let chain_spec = ChainSpecBuilder::mainnet()
1242            .with_fork(EthereumHardfork::Shanghai, ForkCondition::Timestamp(100))
1243            .build();
1244        for version in [
1245            EngineApiMessageVersion::V3,
1246            EngineApiMessageVersion::V4,
1247            EngineApiMessageVersion::V5,
1248            EngineApiMessageVersion::V6,
1249        ] {
1250            for timestamp in [99, 100] {
1251                assert_matches!(
1252                    validate_withdrawals_presence(
1253                        &chain_spec,
1254                        version,
1255                        MessageValidationKind::Payload,
1256                        timestamp,
1257                        true,
1258                    ),
1259                    Ok(())
1260                );
1261                assert_matches!(
1262                    validate_withdrawals_presence(
1263                        &chain_spec,
1264                        version,
1265                        MessageValidationKind::Payload,
1266                        timestamp,
1267                        false,
1268                    ),
1269                    Err(EngineObjectValidationError::Payload(
1270                        VersionSpecificValidationError::NoWithdrawalsPostShanghai
1271                    ))
1272                );
1273            }
1274        }
1275    }
1276
1277    #[test]
1278    fn validate_target_gas_limit_presence_in_attributes() {
1279        // The fcU V4 and V5 attributes require the field.
1280        for version in [EngineApiMessageVersion::V4, EngineApiMessageVersion::V5] {
1281            let res = validate_target_gas_limit_presence(
1282                version,
1283                MessageValidationKind::PayloadAttributes,
1284                true,
1285            );
1286            assert_matches!(res, Ok(()));
1287            let res = validate_target_gas_limit_presence(
1288                version,
1289                MessageValidationKind::PayloadAttributes,
1290                false,
1291            );
1292            assert_matches!(
1293                res,
1294                Err(EngineObjectValidationError::PayloadAttributes(
1295                    VersionSpecificValidationError::NoTargetGasLimitPostAmsterdam
1296                ))
1297            );
1298        }
1299
1300        // Earlier attributes and execution payloads do not carry the field.
1301        let res = validate_target_gas_limit_presence(
1302            EngineApiMessageVersion::V3,
1303            MessageValidationKind::PayloadAttributes,
1304            false,
1305        );
1306        assert_matches!(res, Ok(()));
1307        let res = validate_target_gas_limit_presence(
1308            EngineApiMessageVersion::V5,
1309            MessageValidationKind::Payload,
1310            false,
1311        );
1312        assert_matches!(res, Ok(()));
1313    }
1314}