Skip to main content

reth_engine_tree/tree/
state.rs

1//! Functionality related to tree state.
2
3use alloy_eips::BlockNumHash;
4use alloy_primitives::{BlockNumber, B256};
5use reth_chain_state::{
6    BlockState, EthPrimitives, ExecutedBlock, InMemoryState, InMemoryStateBlockCounts,
7};
8use reth_primitives_traits::{NodePrimitives, SealedHeader};
9use reth_storage_overlay::OverlayManager;
10
11/// Keeps track of the state of the tree.
12///
13/// The executed blocks are tracked, canonical or not, by the [`InMemoryState`] of the
14/// [`OverlayManager`]. This type only reads them: the engine writes them through its
15/// [`CanonicalInMemoryStateWriter`](reth_chain_state::CanonicalInMemoryStateWriter), whose state
16/// has to share that [`InMemoryState`].
17///
18/// ## Invariants
19///
20/// - All tracked blocks are valid: the engine either validated them, or loaded them from disk as
21///   canonical blocks.
22#[derive(Debug)]
23pub struct TreeState<N: NodePrimitives = EthPrimitives> {
24    /// Currently tracked canonical head of the chain.
25    pub(crate) current_canonical_head: BlockNumHash,
26    /// Manages state trie overlays for in-memory blocks, and holds the in-memory state that
27    /// tracks them.
28    pub(crate) overlay_manager: OverlayManager<N>,
29}
30
31impl<N: NodePrimitives> TreeState<N> {
32    /// Returns a new tree state that points to the given canonical head and reads the executed
33    /// blocks of the in-memory state of `overlay_manager`.
34    pub const fn new(
35        current_canonical_head: BlockNumHash,
36        overlay_manager: OverlayManager<N>,
37    ) -> Self {
38        Self { current_canonical_head, overlay_manager }
39    }
40
41    /// Returns the number of tracked executed blocks, canonical or not.
42    pub fn block_count(&self) -> usize {
43        let InMemoryStateBlockCounts { canonical, non_canonical } =
44            self.in_memory_state().block_counts();
45        canonical + non_canonical
46    }
47
48    /// Returns the tracked [`ExecutedBlock`] with the given hash, canonical or not.
49    pub fn executed_block_by_hash(&self, hash: B256) -> Option<ExecutedBlock<N>> {
50        self.in_memory_state().state_by_hash(hash).map(|state| state.block())
51    }
52
53    /// Returns `true` if a block with the given hash is tracked, canonical or not.
54    pub fn contains_hash(&self, hash: &B256) -> bool {
55        self.in_memory_state().contains(hash)
56    }
57
58    /// Returns the sealed header of the tracked block with the given hash, canonical or not.
59    pub fn sealed_header_by_hash(&self, hash: &B256) -> Option<SealedHeader<N::BlockHeader>> {
60        self.in_memory_state()
61            .state_by_hash(*hash)
62            .map(|state| state.block_ref().sealed_block().sealed_header().clone())
63    }
64
65    /// Returns the tracked block with the given hash and its tracked ancestors, from newest to
66    /// oldest, and the parent hash of the oldest returned block, which is the block this chain
67    /// builds on.
68    ///
69    /// Returns `None` if the block for the given hash is not tracked.
70    pub fn blocks_by_hash(&self, hash: B256) -> Option<(B256, Vec<ExecutedBlock<N>>)> {
71        let state = self.in_memory_state().state_by_hash(hash)?;
72        Some((state.anchor().hash, state.chain().map(BlockState::block).collect()))
73    }
74
75    /// Updates the canonical head to the given block.
76    pub const fn set_canonical_head(&mut self, new_head: BlockNumHash) {
77        self.current_canonical_head = new_head;
78    }
79
80    /// Returns the tracked canonical head.
81    pub const fn canonical_head(&self) -> &BlockNumHash {
82        &self.current_canonical_head
83    }
84
85    /// Returns the block hash of the canonical head.
86    pub const fn canonical_block_hash(&self) -> B256 {
87        self.canonical_head().hash
88    }
89
90    /// Returns the block number of the canonical head.
91    pub const fn canonical_block_number(&self) -> BlockNumber {
92        self.canonical_head().number
93    }
94
95    /// Returns the in-memory state that tracks the executed blocks, canonical or not.
96    fn in_memory_state(&self) -> &InMemoryState<N> {
97        self.overlay_manager.in_memory_state()
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use reth_chain_state::{
105        test_utils::{test_canonical_in_memory_state_writer, TestBlockBuilder},
106        CanonicalInMemoryState, CanonicalInMemoryStateWriter, NewCanonicalChain,
107    };
108    use reth_primitives_traits::AlloyBlockHeader;
109
110    /// Creates a tree state without blocks, the canonical state that shares its blocks and the
111    /// writer of that state. Its canonical head is the default header.
112    fn tree_state() -> (TreeState, CanonicalInMemoryState, CanonicalInMemoryStateWriter) {
113        let (in_memory_state, in_memory_state_writer) = InMemoryState::new();
114        let canonical_in_memory_state_writer =
115            test_canonical_in_memory_state_writer(in_memory_state_writer);
116        (
117            TreeState::new(BlockNumHash::default(), OverlayManager::new(in_memory_state)),
118            canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
119            canonical_in_memory_state_writer,
120        )
121    }
122
123    fn hash(block: &ExecutedBlock) -> B256 {
124        block.recovered_block().hash()
125    }
126
127    /// Returns the hashes of the chain of the tracked block `block`, followed by the hash of the
128    /// block the chain builds on.
129    fn chain_hashes(tree_state: &TreeState, block: &ExecutedBlock) -> Vec<B256> {
130        tree_state.in_memory_state().state_by_hash(hash(block)).unwrap().chain_hashes().collect()
131    }
132
133    #[reth_concurrency::test]
134    fn test_tree_state_insert_executed() {
135        let (tree_state, _, mut canonical_in_memory_state_writer) = tree_state();
136        let blocks = TestBlockBuilder::eth().get_executed_blocks(1..4).collect::<Vec<_>>();
137        let persisted_hash = blocks[0].recovered_block().parent_hash();
138
139        canonical_in_memory_state_writer.insert_executed(blocks[0].clone());
140        canonical_in_memory_state_writer.insert_executed(blocks[1].clone());
141
142        // Block 2 is linked to block 1, and nothing else is tracked.
143        assert_eq!(
144            chain_hashes(&tree_state, &blocks[1]),
145            [hash(&blocks[1]), hash(&blocks[0]), persisted_hash]
146        );
147        assert_eq!(tree_state.block_count(), 2);
148
149        canonical_in_memory_state_writer.insert_executed(blocks[2].clone());
150
151        // Block 3 is linked to block 2, and nothing else is tracked.
152        assert_eq!(
153            chain_hashes(&tree_state, &blocks[2]),
154            [hash(&blocks[2]), hash(&blocks[1]), hash(&blocks[0]), persisted_hash]
155        );
156
157        // Executed blocks are not canonical until a forkchoice update makes them canonical.
158        assert_eq!(
159            tree_state.in_memory_state().block_counts(),
160            InMemoryStateBlockCounts { canonical: 0, non_canonical: 3 }
161        );
162        for block in &blocks {
163            assert!(tree_state.contains_hash(&hash(block)));
164            assert_eq!(tree_state.executed_block_by_hash(hash(block)).as_ref(), Some(block));
165            assert_eq!(tree_state.sealed_header_by_hash(&hash(block)).unwrap().hash(), hash(block));
166        }
167        let (anchor_hash, chain) = tree_state.blocks_by_hash(hash(&blocks[2])).unwrap();
168        assert_eq!(anchor_hash, persisted_hash);
169        assert_eq!(chain, blocks.iter().rev().cloned().collect::<Vec<_>>());
170        assert!(tree_state.blocks_by_hash(B256::random()).is_none());
171    }
172
173    #[reth_concurrency::test]
174    fn test_tree_state_insert_executed_with_reorg() {
175        let (tree_state, canonical_in_memory_state, mut canonical_in_memory_state_writer) =
176            tree_state();
177        let mut test_block_builder = TestBlockBuilder::eth();
178        let blocks = test_block_builder.get_executed_blocks(1..6).collect::<Vec<_>>();
179        let persisted_hash = blocks[0].recovered_block().parent_hash();
180
181        for block in &blocks {
182            canonical_in_memory_state_writer.insert_executed(block.clone());
183        }
184        canonical_in_memory_state_writer
185            .update_chain(NewCanonicalChain::Commit { new: blocks.clone() });
186        assert_eq!(
187            tree_state.in_memory_state().block_counts(),
188            InMemoryStateBlockCounts { canonical: 5, non_canonical: 0 }
189        );
190
191        let fork_block_3 = test_block_builder.get_executed_block_with_number(3, hash(&blocks[1]));
192        let fork_block_4 =
193            test_block_builder.get_executed_block_with_number(4, hash(&fork_block_3));
194        let fork_block_5 =
195            test_block_builder.get_executed_block_with_number(5, hash(&fork_block_4));
196
197        canonical_in_memory_state_writer.insert_executed(fork_block_3.clone());
198        canonical_in_memory_state_writer.insert_executed(fork_block_4.clone());
199        canonical_in_memory_state_writer.insert_executed(fork_block_5.clone());
200
201        assert_eq!(
202            tree_state.in_memory_state().block_counts(),
203            InMemoryStateBlockCounts { canonical: 5, non_canonical: 3 }
204        );
205        // Two blocks at height 3 (original and fork).
206        assert_eq!(canonical_in_memory_state.hash_by_number(3), Some(hash(&blocks[2])));
207        assert!(tree_state.contains_hash(&hash(&fork_block_3)));
208        // The fork block is built on block 2.
209        assert_eq!(
210            chain_hashes(&tree_state, &fork_block_3),
211            [hash(&fork_block_3), hash(&blocks[1]), hash(&blocks[0]), persisted_hash]
212        );
213
214        // Verify that we can insert the same block again without issues.
215        canonical_in_memory_state_writer.insert_executed(fork_block_4.clone());
216        assert_eq!(tree_state.block_count(), 8);
217
218        // The fork blocks are linked to each other.
219        assert_eq!(
220            chain_hashes(&tree_state, &fork_block_5),
221            [
222                hash(&fork_block_5),
223                hash(&fork_block_4),
224                hash(&fork_block_3),
225                hash(&blocks[1]),
226                hash(&blocks[0]),
227                persisted_hash
228            ]
229        );
230
231        // Two blocks at the heights 4 and 5.
232        for (number, canonical, fork) in
233            [(4, &blocks[3], &fork_block_4), (5, &blocks[4], &fork_block_5)]
234        {
235            assert_eq!(canonical_in_memory_state.hash_by_number(number), Some(hash(canonical)));
236            assert!(tree_state.contains_hash(&hash(fork)));
237        }
238
239        // Reorging to the fork moves the replaced canonical blocks to the non-canonical section.
240        canonical_in_memory_state_writer.update_chain(NewCanonicalChain::Reorg {
241            new: vec![fork_block_3.clone(), fork_block_4, fork_block_5],
242            old: blocks[2..].to_vec(),
243        });
244        assert_eq!(
245            tree_state.in_memory_state().block_counts(),
246            InMemoryStateBlockCounts { canonical: 5, non_canonical: 3 }
247        );
248        assert_eq!(canonical_in_memory_state.hash_by_number(3), Some(hash(&fork_block_3)));
249        assert!(tree_state.contains_hash(&hash(&blocks[4])));
250        // The replaced block 3 is a non-canonical block built on block 2.
251        assert_eq!(
252            chain_hashes(&tree_state, &blocks[2]),
253            [hash(&blocks[2]), hash(&blocks[1]), hash(&blocks[0]), persisted_hash]
254        );
255    }
256
257    /// Asserts that blocks 1 and 2 were removed, and blocks 3 to 5 kept.
258    fn assert_removed_through_block_2(
259        tree_state: &TreeState,
260        canonical_in_memory_state: &CanonicalInMemoryState,
261        blocks: &[ExecutedBlock],
262    ) {
263        for (number, block) in (1..).zip(&blocks[..2]) {
264            assert!(!tree_state.contains_hash(&hash(block)));
265            assert!(canonical_in_memory_state.hash_by_number(number).is_none());
266        }
267        for (number, block) in (3..).zip(&blocks[2..]) {
268            assert!(tree_state.contains_hash(&hash(block)));
269            assert_eq!(canonical_in_memory_state.hash_by_number(number), Some(hash(block)));
270        }
271
272        // The remaining chain starts right after the removed blocks.
273        let (anchor_hash, chain) = tree_state.blocks_by_hash(hash(&blocks[4])).unwrap();
274        assert_eq!(chain.len(), 3);
275        assert_eq!(anchor_hash, hash(&blocks[1]));
276    }
277
278    #[reth_concurrency::test]
279    fn test_tree_state_remove_canonical_until() {
280        let (tree_state, canonical_in_memory_state, mut canonical_in_memory_state_writer) =
281            tree_state();
282        let blocks = TestBlockBuilder::eth().get_executed_blocks(1..6).collect::<Vec<_>>();
283
284        for block in &blocks {
285            canonical_in_memory_state_writer.insert_executed(block.clone());
286        }
287        canonical_in_memory_state_writer
288            .update_chain(NewCanonicalChain::Commit { new: blocks.clone() });
289
290        // Inclusive bound, so we should remove anything up to and including 2.
291        canonical_in_memory_state_writer.on_blocks_persisted(
292            BlockNumHash::new(2, hash(&blocks[1])),
293            BlockNumHash::new(2, hash(&blocks[1])),
294            Some(blocks[1].recovered_block().num_hash()),
295        );
296
297        assert_removed_through_block_2(&tree_state, &canonical_in_memory_state, &blocks);
298    }
299
300    #[reth_concurrency::test]
301    fn test_tree_state_remove_canonical_until_finalized() {
302        let (tree_state, canonical_in_memory_state, mut canonical_in_memory_state_writer) =
303            tree_state();
304        let blocks = TestBlockBuilder::eth().get_executed_blocks(1..6).collect::<Vec<_>>();
305
306        for block in &blocks {
307            canonical_in_memory_state_writer.insert_executed(block.clone());
308        }
309        canonical_in_memory_state_writer
310            .update_chain(NewCanonicalChain::Commit { new: blocks.clone() });
311
312        // We should still remove everything up to and including 2.
313        canonical_in_memory_state_writer.on_blocks_persisted(
314            BlockNumHash::new(2, hash(&blocks[1])),
315            BlockNumHash::new(2, hash(&blocks[1])),
316            None,
317        );
318
319        assert_removed_through_block_2(&tree_state, &canonical_in_memory_state, &blocks);
320    }
321
322    #[reth_concurrency::test]
323    fn test_tree_state_remove_canonical_until_lower_finalized() {
324        let (tree_state, canonical_in_memory_state, mut canonical_in_memory_state_writer) =
325            tree_state();
326        let blocks = TestBlockBuilder::eth().get_executed_blocks(1..6).collect::<Vec<_>>();
327
328        for block in &blocks {
329            canonical_in_memory_state_writer.insert_executed(block.clone());
330        }
331        canonical_in_memory_state_writer
332            .update_chain(NewCanonicalChain::Commit { new: blocks.clone() });
333
334        // We have no forks so we should still remove anything up to and including 2.
335        canonical_in_memory_state_writer.on_blocks_persisted(
336            BlockNumHash::new(2, hash(&blocks[1])),
337            BlockNumHash::new(2, hash(&blocks[1])),
338            Some(blocks[0].recovered_block().num_hash()),
339        );
340
341        assert_removed_through_block_2(&tree_state, &canonical_in_memory_state, &blocks);
342    }
343
344    #[reth_concurrency::test]
345    fn test_tree_state_remove_canonical_until_prunes_finalized_sidechains() {
346        let (tree_state, canonical_in_memory_state, mut canonical_in_memory_state_writer) =
347            tree_state();
348        let mut builder = TestBlockBuilder::eth();
349        let blocks = builder.get_executed_blocks(1..6).collect::<Vec<_>>();
350        for block in &blocks {
351            canonical_in_memory_state_writer.insert_executed(block.clone());
352        }
353        canonical_in_memory_state_writer
354            .update_chain(NewCanonicalChain::Commit { new: blocks.clone() });
355
356        // A fork off block 1 can never become canonical once block 2 is finalized, a fork off
357        // block 3 still can.
358        let dead_fork = builder.get_executed_block_with_number(2, hash(&blocks[0]));
359        let dead_fork_child = builder.get_executed_block_with_number(3, hash(&dead_fork));
360        let live_fork = builder.get_executed_block_with_number(4, hash(&blocks[2]));
361        for block in [&dead_fork, &dead_fork_child, &live_fork] {
362            canonical_in_memory_state_writer.insert_executed(block.clone());
363        }
364        assert_eq!(
365            tree_state.in_memory_state().block_counts(),
366            InMemoryStateBlockCounts { canonical: 5, non_canonical: 3 }
367        );
368
369        canonical_in_memory_state_writer.on_blocks_persisted(
370            BlockNumHash::new(2, hash(&blocks[1])),
371            BlockNumHash::new(2, hash(&blocks[1])),
372            Some(blocks[1].recovered_block().num_hash()),
373        );
374
375        assert_removed_through_block_2(&tree_state, &canonical_in_memory_state, &blocks);
376        assert!(!tree_state.contains_hash(&hash(&dead_fork)));
377        assert!(!tree_state.contains_hash(&hash(&dead_fork_child)));
378        assert!(tree_state.contains_hash(&hash(&live_fork)));
379        assert_eq!(
380            tree_state.in_memory_state().block_counts(),
381            InMemoryStateBlockCounts { canonical: 3, non_canonical: 1 }
382        );
383
384        // The chain of the surviving fork starts right after the removed blocks.
385        let (anchor_hash, chain) = tree_state.blocks_by_hash(hash(&live_fork)).unwrap();
386        assert_eq!(chain.len(), 2);
387        assert_eq!(anchor_hash, hash(&blocks[1]));
388    }
389}