Skip to main content

reth_engine_tree/tree/
invalid.rs

1//! Invalid payload and invalid ancestor handling of the engine API tree handler.
2
3use crate::tree::{
4    error::InsertBlockFatalError, payload_validator::EngineValidator, EngineApiTreeHandler,
5    WaitForCaches,
6};
7use alloy_consensus::BlockHeader;
8use alloy_eip7928::bal::DecodedBal;
9use alloy_eips::eip1898::BlockWithParent;
10use alloy_primitives::B256;
11use alloy_rpc_types_engine::{PayloadStatus, PayloadStatusEnum, PayloadValidationError};
12use reth_engine_primitives::{BlockAccessListDecodeError, ConsensusEngineEvent, ExecutionPayload};
13use reth_errors::ProviderResult;
14use reth_evm::ConfigureEvm;
15use reth_payload_primitives::{BuiltPayload, PayloadTypes};
16use reth_primitives_traits::{NodePrimitives, SealedBlock};
17use reth_provider::{
18    BalProvider, BlockReader, ChangeSetReader, DatabaseProviderFactory, PruneCheckpointReader,
19    StageCheckpointReader, StateProviderFactory, StateReader, StorageChangeSetReader,
20    StorageSettingsCache,
21};
22use tracing::debug;
23
24impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
25where
26    N: NodePrimitives,
27    P: DatabaseProviderFactory
28        + BlockReader<Block = N::Block, Header = N::BlockHeader>
29        + StateProviderFactory
30        + StateReader<Receipt = N::Receipt>
31        + BalProvider
32        + Clone
33        + 'static,
34    P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
35        + PruneCheckpointReader
36        + StageCheckpointReader
37        + ChangeSetReader
38        + StorageChangeSetReader
39        + StorageSettingsCache
40        + 'static,
41    C: ConfigureEvm<Primitives = N> + 'static,
42    T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
43    V: EngineValidator<T> + WaitForCaches,
44{
45    /// If validation fails, the response MUST contain the latest valid hash:
46    ///
47    ///   - The block hash of the ancestor of the invalid payload satisfying the following two
48    ///     conditions:
49    ///     - It is fully validated and deemed VALID
50    ///     - Any other ancestor of the invalid payload with a higher blockNumber is INVALID
51    ///   - 0x0000000000000000000000000000000000000000000000000000000000000000 if the above
52    ///     conditions are satisfied by a `PoW` block.
53    ///   - null if client software cannot determine the ancestor of the invalid payload satisfying
54    ///     the above conditions.
55    pub(super) fn latest_valid_hash_for_invalid_payload(
56        &mut self,
57        parent_hash: B256,
58    ) -> ProviderResult<Option<B256>> {
59        // Check if parent exists in side chain or in canonical chain.
60        if self.has_block_by_hash(parent_hash)? {
61            return Ok(Some(parent_hash))
62        }
63
64        // iterate over ancestors in the invalid cache
65        // until we encounter the first valid ancestor
66        let mut current_hash = parent_hash;
67        let mut current_block = self.state.invalid_headers.get(&current_hash);
68        while let Some(block_with_parent) = current_block {
69            current_hash = block_with_parent.parent;
70            current_block = self.state.invalid_headers.get(&current_hash);
71
72            // If current_header is None, then the current_hash does not have an invalid
73            // ancestor in the cache, check its presence in blockchain tree
74            if current_block.is_none() && self.has_block_by_hash(current_hash)? {
75                return Ok(Some(current_hash))
76            }
77        }
78        Ok(None)
79    }
80
81    /// Prepares the invalid payload response for the given hash, checking the
82    /// database for the parent hash and populating the payload status with the latest valid hash
83    /// according to the engine api spec.
84    fn prepare_invalid_response(&mut self, parent_hash: B256) -> ProviderResult<PayloadStatus> {
85        let valid_parent_hash = match self.sealed_header_by_hash(parent_hash)? {
86            // Edge case: the `latestValid` field is the zero hash if the parent block is the
87            // terminal PoW block, which we need to identify by looking at the parent's block
88            // difficulty
89            Some(parent) if !parent.difficulty().is_zero() => Some(B256::ZERO),
90            Some(_) => Some(parent_hash),
91            None => self.latest_valid_hash_for_invalid_payload(parent_hash)?,
92        };
93
94        Ok(PayloadStatus::from_status(PayloadStatusEnum::Invalid {
95            validation_error: PayloadValidationError::LinksToRejectedPayload.to_string(),
96        })
97        .maybe_latest_valid_hash(valid_parent_hash))
98    }
99
100    /// Returns true if the given hash is the last received sync target block.
101    ///
102    /// See [`ForkchoiceStateTracker::sync_target_state`]
103    ///
104    /// [`ForkchoiceStateTracker::sync_target_state`]: reth_engine_primitives::ForkchoiceStateTracker::sync_target_state
105    pub(super) fn is_sync_target_head(&self, block_hash: B256) -> bool {
106        if let Some(target) = self.state.forkchoice_state_tracker.sync_target_state() {
107            return target.head_block_hash == block_hash
108        }
109        false
110    }
111
112    /// Returns true if the given hash is part of the last received sync target fork choice update.
113    ///
114    /// See [`ForkchoiceStateTracker::sync_target_state`]
115    ///
116    /// [`ForkchoiceStateTracker::sync_target_state`]: reth_engine_primitives::ForkchoiceStateTracker::sync_target_state
117    pub(super) fn is_any_sync_target(&self, block_hash: B256) -> bool {
118        if let Some(target) = self.state.forkchoice_state_tracker.sync_target_state() {
119            return target.contains(block_hash)
120        }
121        false
122    }
123
124    /// Checks if the given `check` hash points to an invalid header, inserting the given `head`
125    /// block into the invalid header cache if the `check` hash has a known invalid ancestor.
126    ///
127    /// Returns a payload status response according to the engine API spec if the block is known to
128    /// be invalid.
129    pub(super) fn check_invalid_ancestor_with_head(
130        &mut self,
131        check: B256,
132        head: &SealedBlock<N::Block>,
133    ) -> ProviderResult<Option<PayloadStatus>> {
134        // check if the check hash was previously marked as invalid
135        let Some(header) = self.state.invalid_headers.get(&check) else { return Ok(None) };
136
137        Ok(Some(self.on_invalid_new_payload(head.clone(), header)?))
138    }
139
140    /// Invoked when a new payload received is invalid.
141    fn on_invalid_new_payload(
142        &mut self,
143        head: SealedBlock<N::Block>,
144        invalid: BlockWithParent,
145    ) -> ProviderResult<PayloadStatus> {
146        // populate the latest valid hash field
147        let status = self.prepare_invalid_response(invalid.parent)?;
148
149        // insert the head block into the invalid header cache
150        self.state.invalid_headers.insert_with_invalid_ancestor(head.hash(), invalid);
151        self.emit_event(ConsensusEngineEvent::InvalidBlock {
152            block: Box::new(head),
153            error: PayloadValidationError::LinksToRejectedPayload.to_string(),
154        });
155
156        Ok(status)
157    }
158
159    /// Finds any invalid ancestor for the given payload.
160    ///
161    /// This function first checks if the block itself is in the invalid headers cache (to
162    /// avoid re-executing a known-invalid block). Then it walks up the chain of buffered
163    /// ancestors and checks if any ancestor is marked as invalid.
164    ///
165    /// The check works by:
166    /// 1. Checking if the block hash itself is in the `invalid_headers` map
167    /// 2. Finding the lowest buffered ancestor for the given block hash
168    /// 3. If the ancestor is the same as the block hash itself, using the parent hash instead
169    /// 4. Checking if this ancestor is in the `invalid_headers` map
170    ///
171    /// Returns the invalid ancestor block info if found, or None if no invalid ancestor exists.
172    pub(super) fn find_invalid_ancestor(
173        &mut self,
174        payload: &T::ExecutionData,
175    ) -> Option<BlockWithParent> {
176        let parent_hash = payload.parent_hash();
177        let block_hash = payload.block_hash();
178
179        // Check if the block itself is already known to be invalid, avoiding re-execution
180        if let Some(entry) = self.state.invalid_headers.get(&block_hash) {
181            return Some(entry);
182        }
183
184        let mut lowest_buffered_ancestor = self.lowest_buffered_ancestor_or(block_hash);
185        if lowest_buffered_ancestor == block_hash {
186            lowest_buffered_ancestor = parent_hash;
187        }
188
189        // Check if the block has an invalid ancestor
190        self.state.invalid_headers.get(&lowest_buffered_ancestor)
191    }
192
193    /// Handles a payload that has an invalid ancestor.
194    ///
195    /// This function validates the payload and processes it according to whether it's
196    /// well-formed or malformed:
197    /// 1. **Well-formed payload**: The payload is marked as invalid since it descends from a
198    ///    known-bad block, which violates consensus rules
199    /// 2. **Malformed payload**: Returns an appropriate error status since the payload cannot be
200    ///    validated due to its own structural issues
201    ///
202    /// A payload whose block access list does not decode is still remembered as invalid, but is
203    /// answered with `latestValidHash: null`.
204    pub(super) fn handle_invalid_ancestor_payload(
205        &mut self,
206        payload: T::ExecutionData,
207        invalid: BlockWithParent,
208    ) -> Result<PayloadStatus, InsertBlockFatalError> {
209        let parent_hash = payload.parent_hash();
210        let num_hash = payload.num_hash();
211        // The invalid header cache does not record why a block was rejected, so a resend of a
212        // payload rejected for its block access list reaches this path as well.
213        let bal_decode_error = payload
214            .block_access_list()
215            .and_then(|bal| DecodedBal::from_rlp_bytes(bal.clone()).err());
216
217        // Here we might have 2 cases
218        // 1. the block is well formed and indeed links to an invalid header, meaning we should
219        //    remember it as invalid
220        // 2. the block is not well formed (i.e block hash is incorrect), and we should just return
221        //    an error and forget it
222        let block = match self.payload_validator.convert_payload_to_block(payload) {
223            Ok(block) => block,
224            Err(error) => return Ok(self.on_new_payload_error(error, num_hash, parent_hash)?),
225        };
226
227        let status = self.on_invalid_new_payload(block, invalid)?;
228
229        // The Amsterdam Engine API requires `latestValidHash: null` for an undecodable BAL.
230        // <https://github.com/ethereum/execution-apis/blob/df75e230befef0de56ee8833322ed714bacb479c/src/engine/amsterdam.md?plain=1#L129>
231        if let Some(error) = bal_decode_error {
232            return Ok(PayloadStatus::new(
233                PayloadStatusEnum::Invalid {
234                    validation_error: BlockAccessListDecodeError::new(error).to_string(),
235                },
236                None,
237            ))
238        }
239
240        Ok(status)
241    }
242
243    /// Checks if the given `head` points to an invalid header, which requires a specific response
244    /// to a forkchoice update.
245    pub(super) fn check_invalid_ancestor(
246        &mut self,
247        head: B256,
248    ) -> ProviderResult<Option<PayloadStatus>> {
249        // check if the head was previously marked as invalid
250        let Some(header) = self.state.invalid_headers.get(&head) else { return Ok(None) };
251
252        // Try to prepare invalid response, but handle errors gracefully
253        match self.prepare_invalid_response(header.parent) {
254            Ok(status) => Ok(Some(status)),
255            Err(err) => {
256                debug!(target: "engine::tree", %err, "Failed to prepare invalid response for ancestor check");
257                // Return a basic invalid status without latest valid hash
258                Ok(Some(PayloadStatus::from_status(PayloadStatusEnum::Invalid {
259                    validation_error: PayloadValidationError::LinksToRejectedPayload.to_string(),
260                })))
261            }
262        }
263    }
264}