Skip to main content

reth_engine_tree/tree/
canonical.rs

1//! Canonical chain updates of the engine API tree handler.
2
3use crate::tree::{payload_validator::EngineValidator, EngineApiTreeHandler, WaitForCaches};
4use alloy_consensus::BlockHeader;
5use alloy_eips::NumHash;
6use alloy_primitives::B256;
7use reth_chain_state::{ExecutedBlock, NewCanonicalChain};
8use reth_concurrency::sync::time::FastInstant as Instant;
9use reth_engine_primitives::ConsensusEngineEvent;
10use reth_errors::ProviderResult;
11use reth_evm::{debug_unreachable, ConfigureEvm};
12use reth_payload_primitives::{BuiltPayload, PayloadTypes};
13use reth_primitives_traits::{NodePrimitives, RecoveredBlock, SealedHeader};
14use reth_provider::{
15    BalProvider, BlockExecutionOutput, BlockExecutionResult, BlockReader, ChangeSetReader,
16    DatabaseProviderFactory, ProviderError, PruneCheckpointReader, StageCheckpointReader,
17    StateProviderFactory, StateReader, StorageChangeSetReader, StorageSettingsCache,
18    TransactionVariant,
19};
20use reth_trie::{HashedPostState, KeccakKeyHasher, SortedTrieData};
21use std::sync::Arc;
22use tracing::{debug, instrument, trace, warn};
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    /// Returns the new chain for the given head.
46    ///
47    /// This also handles reorgs.
48    ///
49    /// Note: This does not update the tracked state and instead returns the new chain based on the
50    /// given head.
51    pub(super) fn on_new_head(
52        &self,
53        new_head: B256,
54    ) -> ProviderResult<Option<NewCanonicalChain<N>>> {
55        // get the executed new head block
56        let Some(new_head_block) = self.state.tree_state.executed_block_by_hash(new_head) else {
57            debug!(target: "engine::tree", new_head=?new_head, "New head block not found in inmemory tree state");
58            self.metrics.engine.executed_new_block_cache_miss.increment(1);
59            return Ok(None)
60        };
61
62        let new_head_number = new_head_block.recovered_block().number();
63        let mut current_canonical_number = self.state.tree_state.current_canonical_head.number;
64
65        // The genesis block has no parent to walk back to. It is only tracked after it was loaded
66        // from disk as a canonical ancestor, and never is a new head.
67        let Some(mut current_number) = new_head_number.checked_sub(1) else { return Ok(None) };
68        let mut current_hash = new_head_block.recovered_block().parent_hash();
69        let mut new_chain = vec![new_head_block];
70
71        // Walk back the new chain until we reach a block we know about
72        //
73        // This is only done for in-memory blocks, because we should not have persisted any blocks
74        // that are _above_ the current canonical head.
75        while current_number > current_canonical_number {
76            if let Some(block) = self.state.tree_state.executed_block_by_hash(current_hash) {
77                current_hash = block.recovered_block().parent_hash();
78                current_number -= 1;
79                new_chain.push(block);
80            } else {
81                warn!(target: "engine::tree", current_hash=?current_hash, "Sidechain block not found in TreeState");
82                // This should never happen as we're walking back a chain that should connect to
83                // the canonical chain
84                return Ok(None)
85            }
86        }
87
88        // If we have reached the current canonical head by walking back from the target, then we
89        // know this represents an extension of the canonical chain.
90        if current_hash == self.state.tree_state.current_canonical_head.hash {
91            new_chain.reverse();
92
93            // Simple extension of the current chain
94            return Ok(Some(NewCanonicalChain::Commit { new: new_chain }))
95        }
96
97        // We have a reorg. Walk back both chains to find the fork point.
98        let mut old_chain = Vec::new();
99        let mut old_hash = self.state.tree_state.current_canonical_head.hash;
100
101        // If the canonical chain is ahead of the new chain,
102        // gather all blocks until new head number.
103        while current_canonical_number > current_number {
104            let block = self.canonical_block_by_hash(old_hash)?;
105            old_hash = block.recovered_block().parent_hash();
106            old_chain.push(block);
107            current_canonical_number -= 1;
108        }
109
110        // Both new and old chain pointers are now at the same height.
111        debug_assert_eq!(current_number, current_canonical_number);
112
113        // Walk both chains from specified hashes at same height until
114        // a common ancestor (fork block) is reached.
115        while old_hash != current_hash {
116            let block = self.canonical_block_by_hash(old_hash)?;
117            old_hash = block.recovered_block().parent_hash();
118            old_chain.push(block);
119
120            if let Some(block) = self.state.tree_state.executed_block_by_hash(current_hash) {
121                current_hash = block.recovered_block().parent_hash();
122                new_chain.push(block);
123            } else {
124                // This shouldn't happen as we've already walked this path
125                warn!(target: "engine::tree", invalid_hash=?current_hash, "New chain block not found in TreeState");
126                return Ok(None)
127            }
128        }
129        new_chain.reverse();
130        old_chain.reverse();
131
132        Ok(Some(NewCanonicalChain::Reorg { new: new_chain, old: old_chain }))
133    }
134
135    /// Updates the latest block state to the specified canonical ancestor.
136    ///
137    /// This method ensures that the latest block tracks the given canonical header by resetting
138    ///
139    /// # Arguments
140    /// * `canonical_header` - The canonical header to set as the new head
141    ///
142    /// # Returns
143    /// * `ProviderResult<()>` - Ok(()) on success, error if state update fails
144    ///
145    /// Caution: This unwinds the canonical chain
146    pub(super) fn update_latest_block_to_canonical_ancestor(
147        &mut self,
148        canonical_header: &SealedHeader<N::BlockHeader>,
149    ) -> ProviderResult<()> {
150        debug!(target: "engine::tree", head = ?canonical_header.num_hash(), "Update latest block to canonical ancestor");
151        let current_head_number = self.state.tree_state.canonical_block_number();
152        let new_head_number = canonical_header.number();
153        let new_head_hash = canonical_header.hash();
154
155        // Update tree state with the new canonical head
156        self.state.tree_state.set_canonical_head(canonical_header.num_hash());
157
158        // Handle the state update based on whether this is an unwind scenario
159        if new_head_number < current_head_number {
160            debug!(
161                target: "engine::tree",
162                current_head = current_head_number,
163                new_head = new_head_number,
164                new_head_hash = ?new_head_hash,
165                "FCU unwind detected: reverting to canonical ancestor"
166            );
167
168            self.handle_canonical_chain_unwind(current_head_number, canonical_header)
169        } else {
170            debug!(
171                target: "engine::tree",
172                previous_head = current_head_number,
173                new_head = new_head_number,
174                new_head_hash = ?new_head_hash,
175                "Advancing latest block to canonical ancestor"
176            );
177            self.handle_chain_advance_or_same_height(canonical_header)
178        }
179    }
180
181    /// Handles chain unwind scenarios by collecting blocks to remove and performing an unwind back
182    /// to the canonical header
183    fn handle_canonical_chain_unwind(
184        &mut self,
185        current_head_number: u64,
186        canonical_header: &SealedHeader<N::BlockHeader>,
187    ) -> ProviderResult<()> {
188        let new_head_number = canonical_header.number();
189        debug!(
190            target: "engine::tree",
191            from = current_head_number,
192            to = new_head_number,
193            "Handling unwind: collecting blocks to remove from in-memory state"
194        );
195
196        // Collect blocks that need to be removed from memory
197        let old_blocks =
198            self.collect_blocks_for_canonical_unwind(new_head_number, current_head_number);
199
200        // Load and apply the canonical ancestor block
201        self.apply_canonical_ancestor_via_reorg(canonical_header, old_blocks)
202    }
203
204    /// Collects blocks from memory that need to be removed during an unwind to a canonical block.
205    fn collect_blocks_for_canonical_unwind(
206        &self,
207        new_head_number: u64,
208        current_head_number: u64,
209    ) -> Vec<ExecutedBlock<N>> {
210        let mut old_blocks =
211            Vec::with_capacity((current_head_number.saturating_sub(new_head_number)) as usize);
212
213        for block_num in (new_head_number + 1)..=current_head_number {
214            if let Some(block_state) = self.canonical_in_memory_state().state_by_number(block_num) {
215                let executed_block = block_state.block_ref().clone();
216                old_blocks.push(executed_block);
217                debug!(
218                    target: "engine::tree",
219                    block_number = block_num,
220                    "Collected block for removal from in-memory state"
221                );
222            }
223        }
224
225        if old_blocks.is_empty() {
226            debug!(
227                target: "engine::tree",
228                "No blocks found in memory to remove, will clear and reset state"
229            );
230        }
231
232        old_blocks
233    }
234
235    /// Applies the canonical ancestor block via a reorg operation.
236    fn apply_canonical_ancestor_via_reorg(
237        &mut self,
238        canonical_header: &SealedHeader<N::BlockHeader>,
239        old_blocks: Vec<ExecutedBlock<N>>,
240    ) -> ProviderResult<()> {
241        let new_head_hash = canonical_header.hash();
242        let new_head_number = canonical_header.number();
243
244        // Load the canonical ancestor's block
245        let executed_block = self.canonical_block_by_hash(new_head_hash)?;
246        // Perform the reorg to properly handle the unwind, which also makes the canonical ancestor
247        // the canonical head.
248        self.canonical_in_memory_state_writer
249            .update_chain(NewCanonicalChain::Reorg { new: vec![executed_block], old: old_blocks });
250        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
251
252        debug!(
253            target: "engine::tree",
254            block_number = new_head_number,
255            block_hash = ?new_head_hash,
256            "Successfully loaded canonical ancestor into memory via reorg"
257        );
258
259        Ok(())
260    }
261
262    /// Handles chain advance or same height scenarios.
263    fn handle_chain_advance_or_same_height(
264        &mut self,
265        canonical_header: &SealedHeader<N::BlockHeader>,
266    ) -> ProviderResult<()> {
267        // Load the block into memory if it's not already present
268        self.ensure_block_in_memory(canonical_header.number(), canonical_header.hash())?;
269
270        // Update the canonical head header, which loading the block did, but a block that was
271        // already in memory did not.
272        self.canonical_in_memory_state_writer.set_canonical_head(canonical_header.clone());
273
274        Ok(())
275    }
276
277    /// Ensures a block is loaded into memory if not already present.
278    fn ensure_block_in_memory(
279        &mut self,
280        block_number: u64,
281        block_hash: B256,
282    ) -> ProviderResult<()> {
283        // Check if block is already in memory
284        if self.canonical_in_memory_state().state_by_number(block_number).is_some() {
285            return Ok(());
286        }
287
288        // Load the block from storage
289        let executed_block = self.canonical_block_by_hash(block_hash)?;
290        self.canonical_in_memory_state_writer
291            .update_chain(NewCanonicalChain::Commit { new: vec![executed_block] });
292        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
293
294        debug!(
295            target: "engine::tree",
296            block_number,
297            block_hash = ?block_hash,
298            "Added canonical block to in-memory state"
299        );
300
301        Ok(())
302    }
303
304    /// Attempts to make the given target canonical.
305    ///
306    /// This will update the tracked canonical in memory state and do the necessary housekeeping.
307    pub(super) fn make_canonical(&mut self, target: B256) -> ProviderResult<()> {
308        if let Some(chain_update) = self.on_new_head(target)? {
309            self.on_canonical_chain_update(chain_update);
310        }
311
312        self.on_canonicalized_sync_target(target);
313
314        Ok(())
315    }
316
317    /// Applies the tracked forkchoice state once its sync target head becomes canonical.
318    pub(super) fn on_canonicalized_sync_target(&mut self, target: B256) {
319        let Some(sync_target_state) = self
320            .state
321            .forkchoice_state_tracker
322            .sync_target_state()
323            .filter(|state| state.head_block_hash == target)
324        else {
325            return;
326        };
327
328        if let Err(outcome) = self.ensure_consistent_forkchoice_state(sync_target_state) {
329            debug!(
330                target: "engine::tree",
331                head = %sync_target_state.head_block_hash,
332                safe = %sync_target_state.safe_block_hash,
333                finalized = %sync_target_state.finalized_block_hash,
334                ?outcome,
335                "Canonicalized sync target head before safe/finalized could be applied"
336            );
337            return;
338        }
339
340        self.state.forkchoice_state_tracker.promote_sync_target_to_valid(sync_target_state);
341    }
342
343    /// Return an [`ExecutedBlock`] from database or in-memory state by hash.
344    ///
345    /// Note: This function attempts to fetch the `ExecutedBlock` from either in-memory state
346    /// or the database. If the required historical data (such as trie change sets) has been
347    /// pruned for a given block, this operation will return an error. On archive nodes, it
348    /// can retrieve any block.
349    #[instrument(level = "debug", target = "engine::tree", skip(self))]
350    fn canonical_block_by_hash(&self, hash: B256) -> ProviderResult<ExecutedBlock<N>> {
351        trace!(target: "engine::tree", ?hash, "Fetching executed block by hash");
352        // check memory first
353        if let Some(block) = self.state.tree_state.executed_block_by_hash(hash) {
354            return Ok(block)
355        }
356
357        let (block, senders) = self
358            .provider
359            .sealed_block_with_senders(hash.into(), TransactionVariant::WithHash)?
360            .ok_or_else(|| ProviderError::HeaderNotFound(hash.into()))?
361            .split_sealed();
362        let mut execution_output = self
363            .provider
364            .get_state(block.header().number())?
365            .ok_or_else(|| ProviderError::StateForNumberNotFound(block.header().number()))?;
366        let bundle_state = execution_output.state();
367        // `get_state` can return an in-memory execution outcome that retains destruction statuses.
368        // Hashing it requires the parent provider to expand a pre-existing destroyed account's
369        // storage into zero-valued slots. Genesis has no parent state, and no account existed
370        // before it to be destroyed.
371        let hashed_state = if block.parent_hash().is_zero() {
372            HashedPostState::from_bundle_state::<KeccakKeyHasher>(bundle_state.state())
373        } else {
374            self.provider
375                .state_by_block_hash(block.parent_hash())?
376                .hashed_post_state(bundle_state)?
377        };
378
379        debug!(
380            target: "engine::tree",
381            number = ?block.number(),
382            "computing block trie updates",
383        );
384        let db_provider = self.provider.database_provider_ro()?;
385        let trie_updates = self
386            .state
387            .tree_state
388            .overlay_manager
389            .compute_block_trie_updates(&db_provider, block.number())?;
390
391        let sorted_hashed_state = Arc::new(hashed_state.into_sorted());
392        let sorted_trie_updates = Arc::new(trie_updates);
393        let trie_data = SortedTrieData::new(sorted_hashed_state, sorted_trie_updates);
394
395        let execution_output = Arc::new(BlockExecutionOutput {
396            state: execution_output.bundle,
397            result: BlockExecutionResult {
398                receipts: execution_output.receipts.pop().unwrap_or_default(),
399                requests: execution_output.requests.pop().unwrap_or_default(),
400                gas_used: block.gas_used(),
401                blob_gas_used: block.blob_gas_used().unwrap_or_default(),
402            },
403        });
404
405        Ok(ExecutedBlock::new(
406            Arc::new(RecoveredBlock::new_sealed(block, senders)),
407            execution_output,
408            trie_data,
409        ))
410    }
411
412    /// Invoked when we the canonical chain has been updated.
413    ///
414    /// This is invoked on a valid forkchoice update, or if we can make the target block canonical.
415    pub(super) fn on_canonical_chain_update(&mut self, chain_update: NewCanonicalChain<N>) {
416        trace!(target: "engine::tree", new_blocks = %chain_update.new_block_count(), reorged_blocks =  %chain_update.reorged_block_count(), "applying new chain update");
417        let start = Instant::now();
418
419        // update the tracked canonical head
420        self.state.tree_state.set_canonical_head(chain_update.tip().num_hash());
421
422        let tip = chain_update.tip().clone_sealed_header();
423        let notification = chain_update.to_chain_notification();
424
425        if let NewCanonicalChain::Reorg { new, old } = &chain_update {
426            let new_first = new.first().map(|first| first.recovered_block().num_hash());
427            let old_first = old.first().map(|first| first.recovered_block().num_hash());
428            trace!(target: "engine::tree", ?new_first, ?old_first, "Reorg detected, new and old first blocks");
429
430            self.state.set_pending_sparse_trie_prune(false);
431            self.update_reorg_metrics(old.len(), old_first);
432        }
433
434        // update the tracked in-memory state with the new chain, which also tracks the blocks of a
435        // reorg that are missing from it, and makes the tip the canonical head in the same update.
436        self.canonical_in_memory_state_writer.update_chain(chain_update);
437        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
438        self.payload_validator.on_canonical_head_changed(tip.hash(), &self.state);
439
440        // Update metrics based on new tip
441        self.metrics.tree.canonical_chain_height.set(tip.number() as f64);
442
443        // sends an event to all active listeners about the new canonical chain
444        self.canonical_in_memory_state_writer.notify_canon_state(notification);
445
446        // emit event
447        self.emit_event(ConsensusEngineEvent::CanonicalChainCommitted(
448            Box::new(tip),
449            start.elapsed(),
450        ));
451    }
452
453    /// This updates metrics based on the given reorg length and first reorged block number.
454    pub(super) fn update_reorg_metrics(
455        &self,
456        old_chain_length: usize,
457        first_reorged_block: Option<NumHash>,
458    ) {
459        if let Some(first_reorged_block) = first_reorged_block.map(|block| block.number) {
460            if let Some(finalized) = self.canonical_in_memory_state().get_finalized_num_hash() &&
461                first_reorged_block <= finalized.number
462            {
463                self.metrics.tree.reorgs.finalized.increment(1);
464            } else if let Some(safe) = self.canonical_in_memory_state().get_safe_num_hash() &&
465                first_reorged_block <= safe.number
466            {
467                self.metrics.tree.reorgs.safe.increment(1);
468            } else {
469                self.metrics.tree.reorgs.head.increment(1);
470            }
471        } else {
472            debug_unreachable!("Reorged chain doesn't have any blocks");
473        }
474        self.metrics.tree.latest_reorg_depth.set(old_chain_length as f64);
475    }
476}