Skip to main content

reth_engine_tree/tree/
insert.rs

1//! Payload and block insertion of the engine API tree handler.
2
3use crate::{
4    engine::EngineApiEvent,
5    tree::{
6        error::{
7            InsertBlockError, InsertBlockFatalError, InsertBlockProcessingError,
8            InsertBlockValidationError, InsertPayloadError,
9        },
10        payload_validator::{EngineValidator, TreeCtx},
11        types::ValidationOutput,
12        BlockStatus, EngineApiTreeHandler, InsertPayloadOk, TreeAction, TreeEvent, TreeOutcome,
13        TryInsertPayloadResult, WaitForCaches,
14    },
15};
16use alloy_consensus::BlockHeader;
17use alloy_eips::{eip1898::BlockWithParent, BlockNumHash, NumHash};
18use alloy_primitives::B256;
19use alloy_rpc_types_engine::{PayloadStatus, PayloadStatusEnum};
20use reth_concurrency::sync::time::FastInstant as Instant;
21use reth_consensus::Consensus;
22use reth_engine_primitives::{ConsensusEngineEvent, ExecutionPayload, SlowBlockInfo};
23use reth_errors::{ConsensusError, ProviderResult};
24use reth_evm::ConfigureEvm;
25use reth_network_p2p::full_block::SealedBlockWithAccessList;
26use reth_payload_primitives::{BuiltPayload, NewPayloadError, PayloadTypes};
27use reth_primitives_traits::{NodePrimitives, SealedBlock, SealedHeader};
28use reth_provider::{
29    BalProvider, BlockReader, ChangeSetReader, DatabaseProviderFactory, PruneCheckpointReader,
30    StageCheckpointReader, StateProviderFactory, StateReader, StorageChangeSetReader,
31    StorageSettingsCache,
32};
33use tracing::{debug, error, instrument, trace, warn};
34
35impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
36where
37    N: NodePrimitives,
38    P: DatabaseProviderFactory
39        + BlockReader<Block = N::Block, Header = N::BlockHeader>
40        + StateProviderFactory
41        + StateReader<Receipt = N::Receipt>
42        + BalProvider
43        + Clone
44        + 'static,
45    P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
46        + PruneCheckpointReader
47        + StageCheckpointReader
48        + ChangeSetReader
49        + StorageChangeSetReader
50        + StorageSettingsCache
51        + 'static,
52    C: ConfigureEvm<Primitives = N> + 'static,
53    T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
54    V: EngineValidator<T> + WaitForCaches,
55{
56    /// When the Consensus layer receives a new block via the consensus gossip protocol,
57    /// the transactions in the block are sent to the execution layer in the form of a
58    /// [`PayloadTypes::ExecutionData`], for example
59    /// [`ExecutionData`](reth_payload_primitives::PayloadTypes::ExecutionData). The
60    /// Execution layer executes the transactions and validates the state in the block header,
61    /// then passes validation data back to Consensus layer, that adds the block to the head of
62    /// its own blockchain and attests to it. The block is then broadcast over the consensus p2p
63    /// network in the form of a "Beacon block".
64    ///
65    /// These responses should adhere to the [Engine API Spec for
66    /// `engine_newPayload`](https://github.com/ethereum/execution-apis/blob/main/src/engine/paris.md#specification).
67    ///
68    /// This returns a [`PayloadStatus`] that represents the outcome of a processed new payload and
69    /// returns an error if an internal error occurred.
70    #[instrument(
71        level = "debug",
72        target = "engine::tree",
73        skip_all,
74        fields(block_hash = %payload.block_hash(), block_num = %payload.block_number()),
75    )]
76    pub(super) fn on_new_payload(
77        &mut self,
78        payload: T::ExecutionData,
79    ) -> Result<TreeOutcome<PayloadStatus>, InsertBlockProcessingError> {
80        let _thread_resource_usage =
81            self.metrics.engine.new_payload.measure_thread_resource_usage();
82        trace!(target: "engine::tree", "invoked new payload");
83
84        // start timing for the new payload process
85        let start = Instant::now();
86
87        // Ensures that the given payload does not violate any consensus rules that concern the
88        // block's layout, like:
89        //    - missing or invalid base fee
90        //    - invalid extra data
91        //    - invalid transactions
92        //    - incorrect hash
93        //    - the versioned hashes passed with the payload do not exactly match transaction
94        //      versioned hashes
95        //    - the block does not contain blob transactions if it is pre-cancun
96        //
97        // This validates the following engine API rule:
98        //
99        // 3. Given the expected array of blob versioned hashes client software **MUST** run its
100        //    validation by taking the following steps:
101        //
102        //   1. Obtain the actual array by concatenating blob versioned hashes lists
103        //      (`tx.blob_versioned_hashes`) of each [blob
104        //      transaction](https://eips.ethereum.org/EIPS/eip-4844#new-transaction-type) included
105        //      in the payload, respecting the order of inclusion. If the payload has no blob
106        //      transactions the expected array **MUST** be `[]`.
107        //
108        //   2. Return `{status: INVALID, latestValidHash: null, validationError: errorMessage |
109        //      null}` if the expected and the actual arrays don't match.
110        //
111        // This validation **MUST** be instantly run in all cases even during active sync process.
112
113        let num_hash = payload.num_hash();
114        let engine_event = ConsensusEngineEvent::BlockReceived(num_hash);
115        self.emit_event(EngineApiEvent::BeaconConsensus(engine_event));
116
117        let block_hash = num_hash.hash;
118
119        // Check for invalid ancestors
120        if let Some(invalid) = self.find_invalid_ancestor(&payload) {
121            let status = self.handle_invalid_ancestor_payload(payload, invalid)?;
122            return Ok(TreeOutcome::new(status));
123        }
124
125        // record pre-execution phase duration
126        self.metrics.block_validation.record_payload_validation(start.elapsed().as_secs_f64());
127
128        let mut outcome = if self.backfill_sync_state.is_idle() {
129            self.try_insert_payload(payload)?.into_outcome()
130        } else {
131            TreeOutcome::new(self.try_buffer_payload(payload)?)
132        };
133
134        // if the block is valid and it is the current sync target head, make it canonical
135        if outcome.outcome.is_valid() && self.is_sync_target_head(block_hash) {
136            // Only create the canonical event if this block isn't already the canonical head
137            if self.state.tree_state.canonical_block_hash() != block_hash {
138                outcome = outcome.with_event(TreeEvent::TreeAction(TreeAction::MakeCanonical {
139                    sync_target_head: block_hash,
140                }));
141            }
142        }
143
144        // record total newPayload duration
145        self.metrics.block_validation.total_duration.record(start.elapsed().as_secs_f64());
146
147        Ok(outcome)
148    }
149
150    /// Processes a payload during normal sync operation.
151    #[instrument(level = "debug", target = "engine::tree", skip_all)]
152    pub(super) fn try_insert_payload(
153        &mut self,
154        payload: T::ExecutionData,
155    ) -> Result<TryInsertPayloadResult, InsertBlockProcessingError> {
156        let block_hash = payload.block_hash();
157        let num_hash = payload.num_hash();
158        let parent_hash = payload.parent_hash();
159        let mut latest_valid_hash = None;
160
161        match self.insert_payload(payload) {
162            Ok(status) => {
163                let (status, already_seen) = match status {
164                    InsertPayloadOk::Inserted(BlockStatus::Valid) => {
165                        latest_valid_hash = Some(block_hash);
166                        self.try_connect_buffered_blocks(num_hash)?;
167                        (PayloadStatusEnum::Valid, false)
168                    }
169                    InsertPayloadOk::AlreadySeen(BlockStatus::Valid) => {
170                        latest_valid_hash = Some(block_hash);
171                        (PayloadStatusEnum::Valid, true)
172                    }
173                    InsertPayloadOk::Inserted(BlockStatus::Disconnected { .. }) => {
174                        (PayloadStatusEnum::Syncing, false)
175                    }
176                    InsertPayloadOk::AlreadySeen(BlockStatus::Disconnected { .. }) => {
177                        // not known to be invalid, but we don't know anything else
178                        (PayloadStatusEnum::Syncing, true)
179                    }
180                };
181
182                Ok(TryInsertPayloadResult {
183                    status: PayloadStatus::new(status, latest_valid_hash),
184                    already_seen,
185                })
186            }
187            Err(error) => {
188                let status = match error {
189                    InsertPayloadError::Block(error) => self.on_insert_block_error(error)?,
190                    InsertPayloadError::Payload(error) => self
191                        .on_new_payload_error(error, num_hash, parent_hash)
192                        .map_err(InsertBlockFatalError::from)?,
193                };
194
195                Ok(TryInsertPayloadResult { status, already_seen: false })
196            }
197        }
198    }
199
200    /// Stores a payload for later processing during backfill sync.
201    ///
202    /// During backfill, the node lacks the state needed to validate payloads,
203    /// so they are buffered (stored in memory) until their parent blocks are synced.
204    ///
205    /// Returns:
206    /// - `Syncing`: Payload successfully buffered
207    /// - Error status: Payload is malformed or invalid
208    pub(super) fn try_buffer_payload(
209        &mut self,
210        payload: T::ExecutionData,
211    ) -> Result<PayloadStatus, InsertBlockProcessingError> {
212        let parent_hash = payload.parent_hash();
213        let num_hash = payload.num_hash();
214
215        match self.payload_validator.convert_payload_to_block(payload) {
216            // if the block is well-formed, buffer it for later
217            Ok(block) => {
218                if let Err(error) = self.buffer_block(block) {
219                    self.on_insert_block_error(error)
220                } else {
221                    Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing))
222                }
223            }
224            Err(error) => Ok(self
225                .on_new_payload_error(error, num_hash, parent_hash)
226                .map_err(InsertBlockFatalError::from)?),
227        }
228    }
229
230    /// Returns `true` if a block with the given hash is known, either in memory or in the
231    /// database. This is a lightweight existence check that avoids constructing a full
232    /// [`SealedHeader`].
233    pub(super) fn has_block_by_hash(&self, hash: B256) -> ProviderResult<bool> {
234        if self.state.tree_state.contains_hash(&hash) {
235            Ok(true)
236        } else {
237            self.provider.is_known(hash)
238        }
239    }
240
241    /// Return sealed block header from in-memory state or database by hash.
242    pub(super) fn sealed_header_by_hash(
243        &self,
244        hash: B256,
245    ) -> ProviderResult<Option<SealedHeader<N::BlockHeader>>> {
246        // check memory first
247        let header = self.state.tree_state.sealed_header_by_hash(&hash);
248
249        if header.is_some() {
250            Ok(header)
251        } else {
252            self.provider.sealed_header_by_hash(hash)
253        }
254    }
255
256    /// Return the parent hash of the lowest buffered ancestor for the requested block, if there
257    /// are any buffered ancestors. If there are no buffered ancestors, and the block itself does
258    /// not exist in the buffer, this returns the hash that is passed in.
259    ///
260    /// Returns the parent hash of the block itself if the block is buffered and has no other
261    /// buffered ancestors.
262    pub(super) fn lowest_buffered_ancestor_or(&self, hash: B256) -> B256 {
263        self.state
264            .buffer
265            .lowest_ancestor(&hash)
266            .map(|block| block.parent_hash())
267            .unwrap_or_else(|| hash)
268    }
269
270    /// Validate if block is correct and satisfies all the consensus rules that concern the header
271    /// and block body itself.
272    fn validate_block(&self, block: &SealedBlock<N::Block>) -> Result<(), ConsensusError> {
273        if let Err(e) = self.consensus.validate_header(block.sealed_header()) {
274            error!(target: "engine::tree", block = ?block.block_with_parent(), %e, "Failed to validate header");
275            return Err(e)
276        }
277
278        if let Err(e) = self.consensus.validate_block_pre_execution(block) {
279            error!(target: "engine::tree", block = ?block.block_with_parent(), %e, "Failed to validate block");
280            return Err(e)
281        }
282
283        Ok(())
284    }
285
286    /// Attempts to connect any buffered blocks that are connected to the given parent hash.
287    #[instrument(level = "debug", target = "engine::tree", skip(self))]
288    pub(super) fn try_connect_buffered_blocks(
289        &mut self,
290        parent: BlockNumHash,
291    ) -> Result<(), InsertBlockFatalError> {
292        let blocks = self.state.buffer.remove_block_with_children(&parent.hash);
293
294        if blocks.is_empty() {
295            // nothing to append
296            return Ok(())
297        }
298
299        let now = Instant::now();
300        let block_count = blocks.len();
301        for child in blocks {
302            let child_num_hash = child.num_hash();
303            match self.insert_block(child) {
304                Ok(res) => {
305                    debug!(target: "engine::tree", child =?child_num_hash, ?res, "connected buffered block");
306                    if self.is_any_sync_target(child_num_hash.hash) &&
307                        matches!(res, InsertPayloadOk::Inserted(BlockStatus::Valid))
308                    {
309                        debug!(target: "engine::tree", child =?child_num_hash, "connected sync target block");
310                        // we just inserted a block that we know is part of the canonical chain, so
311                        // we can make it canonical
312                        self.make_canonical(child_num_hash.hash)?;
313                    }
314                }
315                Err(err) => {
316                    if let InsertPayloadError::Block(err) = err {
317                        debug!(target: "engine::tree", ?err, "failed to connect buffered block to tree");
318                        if let Err(InsertBlockProcessingError::Fatal(fatal)) =
319                            self.on_insert_block_error(err)
320                        {
321                            warn!(target: "engine::tree", %fatal, "fatal error occurred while connecting buffered blocks");
322                        }
323                    }
324                }
325            }
326        }
327
328        debug!(target: "engine::tree", elapsed = ?now.elapsed(), %block_count, "connected buffered blocks");
329        Ok(())
330    }
331
332    /// Pre-validates the block and inserts it into the buffer.
333    fn buffer_block(
334        &mut self,
335        block: SealedBlock<N::Block>,
336    ) -> Result<(), InsertBlockError<N::Block>> {
337        if let Err(err) = self.validate_block(&block) {
338            return Err(InsertBlockError::consensus_error(err, block))
339        }
340        self.state.buffer.insert_block(block.into());
341        Ok(())
342    }
343
344    /// Inserts a payload into the tree and executes it.
345    ///
346    /// This function validates the payload's basic structure, then executes it using the
347    /// payload validator. The execution includes running all transactions in the payload
348    /// and validating the resulting state transitions.
349    ///
350    /// Returns `InsertPayloadOk` if the payload was successfully inserted and executed,
351    /// or `InsertPayloadError` if validation or execution failed.
352    fn insert_payload(
353        &mut self,
354        payload: T::ExecutionData,
355    ) -> Result<InsertPayloadOk, InsertPayloadError<N::Block>> {
356        self.insert_block_or_payload(
357            payload.block_with_parent(),
358            payload,
359            |validator, payload, ctx| validator.validate_payload(payload, ctx),
360            |this, payload| Ok(this.payload_validator.convert_payload_to_block(payload)?.into()),
361        )
362    }
363
364    pub(super) fn insert_block(
365        &mut self,
366        block: SealedBlockWithAccessList<N::Block>,
367    ) -> Result<InsertPayloadOk, InsertPayloadError<N::Block>> {
368        self.insert_block_or_payload(
369            block.block_with_parent(),
370            block,
371            |validator, block, ctx| validator.validate_block(block, ctx),
372            |_, block| Ok(block),
373        )
374    }
375
376    /// Inserts a block or payload into the blockchain tree with full execution.
377    ///
378    /// This is a generic function that handles both blocks and payloads by accepting
379    /// a block identifier, input data, and execution/validation functions. It performs
380    /// comprehensive checks and execution:
381    ///
382    /// - Validates that the block doesn't already exist in the tree
383    /// - Ensures parent state is available, buffering if necessary
384    /// - Executes the block/payload using the provided execute function
385    /// - Handles both canonical and fork chain insertions
386    /// - Updates pending block state when appropriate
387    /// - Emits consensus engine events and records metrics
388    ///
389    /// Returns `InsertPayloadOk::Inserted(BlockStatus::Valid)` on successful execution,
390    /// `InsertPayloadOk::AlreadySeen` if the block already exists, or
391    /// `InsertPayloadOk::Inserted(BlockStatus::Disconnected)` if parent state is missing.
392    #[instrument(level = "debug", target = "engine::tree", skip_all, fields(?block_id))]
393    pub(super) fn insert_block_or_payload<Input, Err>(
394        &mut self,
395        block_id: BlockWithParent,
396        input: Input,
397        execute: impl FnOnce(&mut V, Input, TreeCtx<'_, N>) -> Result<ValidationOutput<N>, Err>,
398        convert_to_block: impl FnOnce(
399            &mut Self,
400            Input,
401        ) -> Result<SealedBlockWithAccessList<N::Block>, Err>,
402    ) -> Result<InsertPayloadOk, Err>
403    where
404        Err: From<InsertBlockError<N::Block>>,
405    {
406        let block_insert_start = Instant::now();
407        let block_num_hash = block_id.block;
408        debug!(target: "engine::tree", block=?block_num_hash, parent = ?block_id.parent, "Inserting new block into tree");
409
410        // Check if block already exists - first in memory, then DB only if it could be persisted
411        if self.state.tree_state.contains_hash(&block_num_hash.hash) {
412            convert_to_block(self, input)?;
413            return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid));
414        }
415
416        // Only query DB if block could be persisted (number <= last persisted block).
417        // New blocks from CL always have number > last persisted, so skip DB lookup for them.
418        if block_num_hash.number <= self.persistence_state.last_persisted_block.number {
419            match self.provider.sealed_header_by_hash(block_num_hash.hash) {
420                Err(err) => {
421                    let block = convert_to_block(self, input)?;
422                    return Err(InsertBlockError::new(block.split().0, err.into()).into());
423                }
424                Ok(Some(_)) => {
425                    convert_to_block(self, input)?;
426                    return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid));
427                }
428                Ok(None) => {}
429            }
430        }
431
432        // Ensure that the parent state is available.
433        if !self.state.tree_state.contains_hash(&block_id.parent) {
434            let parent_exists = match self.provider.header(block_id.parent) {
435                Ok(header) => header.is_some(),
436                Err(err) => {
437                    let block = convert_to_block(self, input)?;
438                    return Err(InsertBlockError::new(block.split().0, err.into()).into());
439                }
440            };
441
442            if !parent_exists {
443                let block = convert_to_block(self, input)?;
444                // we don't have the state required to execute this block, buffering it and find the
445                // missing parent block
446                let missing_ancestor = self
447                    .state
448                    .buffer
449                    .lowest_ancestor(&block.parent_hash())
450                    .map(|block| block.parent_num_hash())
451                    .unwrap_or_else(|| block.parent_num_hash());
452
453                self.state.buffer.insert_block(block);
454
455                return Ok(InsertPayloadOk::Inserted(BlockStatus::Disconnected {
456                    head: self.state.tree_state.current_canonical_head,
457                    missing_ancestor,
458                }))
459            }
460        }
461
462        // determine whether we are on a fork chain by comparing the block number with the
463        // canonical head. This is a simple check that is sufficient for the event emission below.
464        // A block is considered a fork if its number is less than or equal to the canonical head,
465        // as this indicates there's already a canonical block at that height.
466        let is_fork = block_id.block.number <= self.state.tree_state.current_canonical_head.number;
467
468        let ctx = TreeCtx::new(
469            &mut self.state,
470            self.canonical_in_memory_state_writer.canonical_in_memory_state(),
471        );
472
473        let start = Instant::now();
474
475        let ValidationOutput { executed_block: executed, execution_timing_stats: timing_stats } =
476            execute(&mut self.payload_validator, input, ctx)?;
477
478        if let Some(raw_bal) = executed.bal().map(|bal| bal.as_raw_bal().clone()) {
479            let num_hash = executed.recovered_block().num_hash();
480            if let Err(err) = self.provider.bal_store().insert(num_hash, raw_bal) {
481                warn!(
482                    target: "engine::tree",
483                    ?num_hash,
484                    %err,
485                    "Failed to store validated block access list"
486                );
487            }
488        }
489
490        // Emit slow block event immediately after execution so it appears even when
491        // persistence hasn't completed yet (e.g. blocks arriving faster than persistence).
492        if let Some(stats) = timing_stats {
493            if let Some(threshold) = self.config.slow_block_threshold() {
494                let total_duration = stats.execution_duration + stats.state_hash_duration;
495                if total_duration > threshold {
496                    self.emit_event(ConsensusEngineEvent::SlowBlock(SlowBlockInfo {
497                        stats: stats.clone(),
498                        commit_duration: None,
499                        total_duration,
500                    }));
501                }
502            }
503            self.execution_timing_stats.insert(executed.recovered_block().hash(), stats);
504        }
505
506        let is_pending = self.state.tree_state.canonical_block_hash() ==
507            executed.recovered_block().parent_hash();
508
509        if is_pending {
510            debug!(target: "engine::tree", pending=?block_num_hash, "updating pending block");
511            self.canonical_in_memory_state_writer.set_pending_block(executed.clone());
512        } else {
513            self.canonical_in_memory_state_writer.insert_executed(executed.clone());
514        }
515        self.state
516            .tree_state
517            .overlay_manager
518            .precompute_child_execution_overlays(executed.recovered_block().hash());
519
520        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
521
522        // emit insert event
523        let elapsed = start.elapsed();
524        let engine_event = if is_fork {
525            ConsensusEngineEvent::ForkBlockAdded(executed, elapsed)
526        } else {
527            ConsensusEngineEvent::CanonicalBlockAdded(executed, elapsed)
528        };
529        self.emit_event(EngineApiEvent::BeaconConsensus(engine_event));
530
531        self.metrics
532            .engine
533            .block_insert_total_duration
534            .record(block_insert_start.elapsed().as_secs_f64());
535        debug!(target: "engine::tree", block=?block_num_hash, "Finished inserting block");
536        Ok(InsertPayloadOk::Inserted(BlockStatus::Valid))
537    }
538
539    /// Handles an error that occurred while inserting a block.
540    ///
541    /// If this is a validation error this will mark the block as invalid.
542    ///
543    /// Returns the proper payload status response if the block is invalid.
544    pub(super) fn on_insert_block_error(
545        &mut self,
546        error: InsertBlockError<N::Block>,
547    ) -> Result<PayloadStatus, InsertBlockProcessingError> {
548        let (block, error) = error.split();
549
550        let validation_err = error.ensure_validation_error()?;
551
552        // If the error was due to an invalid payload, the payload is added to the
553        // invalid headers cache and `Ok` with [PayloadStatusEnum::Invalid] is
554        // returned.
555        warn!(
556            target: "engine::tree",
557            invalid_hash=%block.hash(),
558            invalid_number=block.number(),
559            %validation_err,
560            "Invalid block error on new payload",
561        );
562        // The Amsterdam Engine API requires `latestValidHash: null` for an undecodable BAL.
563        // <https://github.com/ethereum/execution-apis/blob/df75e230befef0de56ee8833322ed714bacb479c/src/engine/amsterdam.md?plain=1#L129>
564        let latest_valid_hash =
565            if matches!(&validation_err, InsertBlockValidationError::BlockAccessListDecode(_)) {
566                None
567            } else {
568                self.latest_valid_hash_for_invalid_payload(block.parent_hash())
569                    .map_err(InsertBlockFatalError::from)?
570            };
571
572        // keep track of the invalid header unless the consensus impl considers it transient
573        let is_transient = match &validation_err {
574            InsertBlockValidationError::Consensus(err) => self.consensus.is_transient_error(err),
575            _ => false,
576        };
577        if is_transient {
578            warn!(
579                target: "engine::tree",
580                invalid_hash=%block.hash(),
581                invalid_number=block.number(),
582                %validation_err,
583                "Skipping invalid header cache insert for transient validation error",
584            );
585        } else {
586            self.state.invalid_headers.insert(block.block_with_parent());
587        }
588        self.emit_event(EngineApiEvent::BeaconConsensus(ConsensusEngineEvent::InvalidBlock {
589            block: Box::new(block),
590            error: validation_err.to_string(),
591        }));
592
593        Ok(PayloadStatus::new(
594            PayloadStatusEnum::Invalid { validation_error: validation_err.to_string() },
595            latest_valid_hash,
596        ))
597    }
598
599    /// Handles a [`NewPayloadError`] by converting it to a [`PayloadStatus`].
600    pub(super) fn on_new_payload_error(
601        &mut self,
602        error: NewPayloadError,
603        payload_num_hash: NumHash,
604        parent_hash: B256,
605    ) -> ProviderResult<PayloadStatus> {
606        error!(target: "engine::tree", payload=?payload_num_hash, %error, "Invalid payload");
607        // we need to convert the error to a payload status (response to the CL)
608
609        let latest_valid_hash = if error.is_block_hash_mismatch() ||
610            error.is_invalid_versioned_hashes() ||
611            error.is_decode_error()
612        {
613            // Engine-API rules:
614            // > `latestValidHash: null` if the blockHash validation has failed (<https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/shanghai.md?plain=1#L113>)
615            // > `latestValidHash: null` if the expected and the actual arrays don't match (<https://github.com/ethereum/execution-apis/blob/fe8e13c288c592ec154ce25c534e26cb7ce0530d/src/engine/cancun.md?plain=1#L103>)
616            // > `latestValidHash: null` if `transactions` contains zero length or invalid entries (<https://github.com/ethereum/execution-apis/blob/981aa66d79364be8322a9c358aaf0a571cca0873/src/engine/paris.md?plain=1#L175>)
617            None
618        } else {
619            self.latest_valid_hash_for_invalid_payload(parent_hash)?
620        };
621
622        let status = PayloadStatusEnum::from(error);
623        Ok(PayloadStatus::new(status, latest_valid_hash))
624    }
625}