Skip to main content

reth_chain_state/in_memory/
new_canonical_chain.rs

1use super::ExecutedBlock;
2use crate::CanonStateNotification;
3use alloy_primitives::B256;
4use reth_ethereum_primitives::EthPrimitives;
5use reth_execution_types::{Chain, ExecutionOutcome};
6use reth_primitives_traits::{NodePrimitives, RecoveredBlock, SignedTransaction};
7use std::sync::Arc;
8
9/// Non-empty chain of blocks.
10#[derive(Debug)]
11pub enum NewCanonicalChain<N: NodePrimitives = EthPrimitives> {
12    /// A simple append to the current canonical head
13    Commit {
14        /// all blocks that lead back to the canonical head
15        new: Vec<ExecutedBlock<N>>,
16    },
17    /// A reorged chain consists of two chains that trace back to a shared ancestor block at which
18    /// point they diverge.
19    Reorg {
20        /// All blocks of the _new_ chain
21        new: Vec<ExecutedBlock<N>>,
22        /// All blocks of the _old_ chain
23        old: Vec<ExecutedBlock<N>>,
24    },
25}
26
27impl<N: NodePrimitives<SignedTx: SignedTransaction>> NewCanonicalChain<N> {
28    /// Returns the length of the new chain.
29    pub const fn new_block_count(&self) -> usize {
30        match self {
31            Self::Commit { new } | Self::Reorg { new, .. } => new.len(),
32        }
33    }
34
35    /// Returns the length of the reorged chain.
36    pub const fn reorged_block_count(&self) -> usize {
37        match self {
38            Self::Commit { .. } => 0,
39            Self::Reorg { old, .. } => old.len(),
40        }
41    }
42
43    /// Converts the new chain into a notification that will be emitted to listeners
44    pub fn to_chain_notification(&self) -> CanonStateNotification<N> {
45        match self {
46            Self::Commit { new } => {
47                CanonStateNotification::Commit { new: Arc::new(Self::blocks_to_chain(new)) }
48            }
49            Self::Reorg { new, old } => CanonStateNotification::Reorg {
50                new: Arc::new(Self::blocks_to_chain(new)),
51                old: Arc::new(Self::blocks_to_chain(old)),
52            },
53        }
54    }
55
56    /// Converts a slice of executed blocks into a [`Chain`].
57    fn blocks_to_chain(blocks: &[ExecutedBlock<N>]) -> Chain<N> {
58        let mut chain = match blocks {
59            [] => Chain::default(),
60            [first, rest @ ..] => {
61                let mut chain = Chain::from_block(
62                    Arc::clone(&first.recovered_block),
63                    ExecutionOutcome::from((
64                        first.execution_outcome().clone(),
65                        first.block_number(),
66                    )),
67                    first.trie_data_handle(),
68                );
69                for exec in rest {
70                    chain.append_block(
71                        Arc::clone(&exec.recovered_block),
72                        ExecutionOutcome::from((
73                            exec.execution_outcome().clone(),
74                            exec.block_number(),
75                        )),
76                        exec.trie_data_handle(),
77                    );
78                }
79                chain
80            }
81        };
82        for exec in blocks {
83            if let Some(bal) = exec.bal() {
84                chain.insert_bal(exec.block_number(), Arc::clone(bal));
85            }
86        }
87        chain
88    }
89
90    /// Returns the new tip of the chain.
91    ///
92    /// Returns the new tip for [`Self::Reorg`] and [`Self::Commit`] variants which commit at least
93    /// 1 new block.
94    pub fn tip(&self) -> &RecoveredBlock<N::Block> {
95        self.new_blocks().last().expect("non empty blocks").recovered_block()
96    }
97
98    /// Returns the blocks added to the canonical chain by this update.
99    pub fn new_blocks(&self) -> &[ExecutedBlock<N>] {
100        match self {
101            Self::Commit { new } | Self::Reorg { new, .. } => new,
102        }
103    }
104
105    /// Returns whether the newly canonicalized blocks contain the given hash.
106    ///
107    /// This does not include the unchanged canonical prefix before the first new block.
108    pub fn contains(&self, hash: B256) -> bool {
109        self.new_blocks().iter().any(|block| block.recovered_block().hash() == hash)
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::test_utils::TestBlockBuilder;
117    use alloy_eips::eip7685::Requests;
118    use alloy_primitives::Bytes;
119    use reth_execution_types::DecodedEvmBal;
120    use reth_trie::LazyTrieData;
121    use std::collections::BTreeMap;
122
123    #[test]
124    fn test_to_chain_notification() {
125        // Generate 4 blocks
126        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
127        let block0 = test_block_builder.get_executed_block_with_number(0, B256::random());
128        let block1 =
129            test_block_builder.get_executed_block_with_number(1, block0.recovered_block.hash());
130        let block1a =
131            test_block_builder.get_executed_block_with_number(1, block0.recovered_block.hash());
132        let block2 =
133            test_block_builder.get_executed_block_with_number(2, block1.recovered_block.hash());
134        let block2a =
135            test_block_builder.get_executed_block_with_number(2, block1.recovered_block.hash());
136
137        // Test commit notification
138        let chain_commit = NewCanonicalChain::Commit { new: vec![block0.clone(), block1.clone()] };
139
140        // Build expected trie data map
141        let mut expected_trie_data = BTreeMap::new();
142        expected_trie_data.insert(0, LazyTrieData::ready(block0.trie_data()));
143        expected_trie_data.insert(1, LazyTrieData::ready(block1.trie_data()));
144
145        // Build expected execution outcome (first_block matches first block number)
146        let commit_execution_outcome = ExecutionOutcome {
147            receipts: vec![vec![], vec![]],
148            requests: vec![Requests::default(), Requests::default()],
149            first_block: 0,
150            ..Default::default()
151        };
152
153        assert_eq!(
154            chain_commit.to_chain_notification(),
155            CanonStateNotification::Commit {
156                new: Arc::new(Chain::new(
157                    vec![block0.recovered_block().clone(), block1.recovered_block().clone()],
158                    commit_execution_outcome,
159                    expected_trie_data,
160                ))
161            }
162        );
163
164        // Test reorg notification
165        let chain_reorg = NewCanonicalChain::Reorg {
166            new: vec![block1a.clone(), block2a.clone()],
167            old: vec![block1.clone(), block2.clone()],
168        };
169
170        // Build expected trie data for old chain
171        let mut old_trie_data = BTreeMap::new();
172        old_trie_data.insert(1, LazyTrieData::ready(block1.trie_data()));
173        old_trie_data.insert(2, LazyTrieData::ready(block2.trie_data()));
174
175        // Build expected trie data for new chain
176        let mut new_trie_data = BTreeMap::new();
177        new_trie_data.insert(1, LazyTrieData::ready(block1a.trie_data()));
178        new_trie_data.insert(2, LazyTrieData::ready(block2a.trie_data()));
179
180        // Build expected execution outcome for reorg chains (first_block matches first block
181        // number)
182        let reorg_execution_outcome = ExecutionOutcome {
183            receipts: vec![vec![], vec![]],
184            requests: vec![Requests::default(), Requests::default()],
185            first_block: 1,
186            ..Default::default()
187        };
188
189        assert_eq!(
190            chain_reorg.to_chain_notification(),
191            CanonStateNotification::Reorg {
192                old: Arc::new(Chain::new(
193                    vec![block1.recovered_block().clone(), block2.recovered_block().clone()],
194                    reorg_execution_outcome.clone(),
195                    old_trie_data,
196                )),
197                new: Arc::new(Chain::new(
198                    vec![block1a.recovered_block().clone(), block2a.recovered_block().clone()],
199                    reorg_execution_outcome,
200                    new_trie_data,
201                ))
202            }
203        );
204    }
205
206    #[test]
207    fn test_to_chain_notification_carries_prepared_bal() {
208        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
209        let block0 = test_block_builder.get_executed_block_with_number(0, B256::random());
210        let block1 = test_block_builder
211            .get_executed_block_with_number(1, block0.recovered_block.hash())
212            .with_bal(Some(Arc::new(DecodedEvmBal::new(
213                Arc::default(),
214                Bytes::from_static(&[0xc0]),
215            ))));
216
217        let chain = NewCanonicalChain::Commit { new: vec![block0, block1.clone()] };
218        let CanonStateNotification::Commit { new } = chain.to_chain_notification() else {
219            panic!("expected a commit notification")
220        };
221
222        // Only the block whose payload carried a BAL contributes one.
223        assert_eq!(new.bals().len(), 1);
224        assert_eq!(new.bal_at(1), block1.bal());
225
226        let mut blocks_and_bals = new.blocks_and_bals();
227        let (block, bal) = blocks_and_bals.next().expect("block with BAL");
228        assert_eq!(block.hash(), block1.recovered_block.hash());
229        assert_eq!(Some(bal), block1.bal());
230        assert!(blocks_and_bals.next().is_none());
231    }
232}