Skip to main content

reth_chain_state/in_memory/
block_state.rs

1use super::ExecutedBlock;
2use alloy_consensus::{transaction::TransactionMeta, BlockHeader};
3use alloy_eips::{BlockHashOrNumber, BlockNumHash};
4use alloy_primitives::{TxHash, B256};
5use reth_ethereum_primitives::EthPrimitives;
6use reth_primitives_traits::{BlockBody as _, IndexedTx, NodePrimitives};
7use std::sync::Arc;
8
9/// State after applying the given block, this block is part of the canonical chain that partially
10/// stored in memory and can be traced back to a canonical block on disk.
11#[derive(Debug, Clone)]
12pub struct BlockState<N: NodePrimitives = EthPrimitives> {
13    /// The executed block that determines the state after this block has been executed.
14    pub(super) block: ExecutedBlock<N>,
15    /// The block's parent block if it exists.
16    pub(super) parent: Option<Arc<Self>>,
17}
18
19impl<N: NodePrimitives> PartialEq for BlockState<N> {
20    fn eq(&self, other: &Self) -> bool {
21        self.block == other.block && self.parent == other.parent
22    }
23}
24
25impl<N: NodePrimitives> BlockState<N> {
26    /// [`BlockState`] constructor.
27    pub const fn new(block: ExecutedBlock<N>) -> Self {
28        Self { block, parent: None }
29    }
30
31    /// [`BlockState`] constructor with parent.
32    pub const fn with_parent(block: ExecutedBlock<N>, parent: Option<Arc<Self>>) -> Self {
33        Self { block, parent }
34    }
35
36    /// Returns the hash and block of the on disk block this state can be traced back to.
37    pub fn anchor(&self) -> BlockNumHash {
38        let mut current = self;
39        while let Some(parent) = &current.parent {
40            current = parent;
41        }
42        current.block.recovered_block().parent_num_hash()
43    }
44
45    /// Returns the executed block that determines the state.
46    pub fn block(&self) -> ExecutedBlock<N> {
47        self.block.clone()
48    }
49
50    /// Returns a reference to the executed block that determines the state.
51    pub const fn block_ref(&self) -> &ExecutedBlock<N> {
52        &self.block
53    }
54
55    /// Returns the hash of executed block that determines the state.
56    pub fn hash(&self) -> B256 {
57        self.block.recovered_block().hash()
58    }
59
60    /// Returns the block number of executed block that determines the state.
61    pub fn number(&self) -> u64 {
62        self.block.recovered_block().number()
63    }
64
65    /// Returns the hash of the parent block.
66    pub fn parent_hash(&self) -> B256 {
67        self.block.recovered_block().parent_hash()
68    }
69
70    /// Returns the state root after applying the executed block that determines
71    /// the state.
72    pub fn state_root(&self) -> B256 {
73        self.block.recovered_block().state_root()
74    }
75
76    /// Returns the `Receipts` of executed block that determines the state.
77    pub fn receipts(&self) -> &Vec<N::Receipt> {
78        &self.block.execution_outcome().receipts
79    }
80
81    /// Returns a vector of `Receipt` of executed block that determines the state.
82    /// We assume that the `Receipts` in the executed block `ExecutionOutcome`
83    /// has only one element corresponding to the executed block associated to
84    /// the state.
85    ///
86    /// This clones the vector of receipts. To avoid it, use [`Self::executed_block_receipts_ref`].
87    pub fn executed_block_receipts(&self) -> Vec<N::Receipt> {
88        self.receipts().clone()
89    }
90
91    /// Returns a slice of `Receipt` of executed block that determines the state.
92    /// We assume that the `Receipts` in the executed block `ExecutionOutcome`
93    /// has only one element corresponding to the executed block associated to
94    /// the state.
95    pub fn executed_block_receipts_ref(&self) -> &[N::Receipt] {
96        self.receipts()
97    }
98
99    /// Returns an iterator over __parent__ `BlockStates`.
100    ///
101    /// The block state order is newest to oldest (highest to lowest):
102    /// `[5,4,3,2,1]`
103    ///
104    /// Note: This does not include self.
105    pub fn parent_state_chain(&self) -> impl Iterator<Item = &Self> + '_ {
106        std::iter::successors(self.parent.as_deref(), |state| state.parent.as_deref())
107    }
108
109    /// Returns a vector of `BlockStates` representing the entire in memory chain.
110    /// The block state order in the output vector is newest to oldest (highest to lowest),
111    /// including self as the first element.
112    pub fn chain(&self) -> impl Iterator<Item = &Self> {
113        std::iter::successors(Some(self), |state| state.parent.as_deref())
114    }
115
116    /// Appends the parent chain of this [`BlockState`] to the given vector.
117    ///
118    /// Parents are appended in order from newest to oldest (highest to lowest).
119    /// This does not include self, only the parent states.
120    ///
121    /// This is a convenience method equivalent to `chain.extend(self.parent_state_chain())`.
122    pub fn append_parent_chain<'a>(&'a self, chain: &mut Vec<&'a Self>) {
123        chain.extend(self.parent_state_chain());
124    }
125
126    /// Returns an iterator over the atomically captured chain of in memory blocks.
127    ///
128    /// This yields the blocks from newest to oldest (highest to lowest).
129    pub fn iter(self: Arc<Self>) -> impl Iterator<Item = Arc<Self>> {
130        std::iter::successors(Some(self), |state| state.parent.clone())
131    }
132
133    /// Returns the hashes of [`Self::chain`] from newest to oldest, followed by the hash of the
134    /// block the chain builds on, see [`Self::anchor`].
135    pub fn chain_hashes(&self) -> impl Iterator<Item = B256> + '_ {
136        std::iter::once(self.hash()).chain(self.chain().map(Self::parent_hash))
137    }
138
139    /// Tries to find a block by [`BlockHashOrNumber`] in the chain ending at this block.
140    pub fn block_on_chain(&self, hash_or_num: BlockHashOrNumber) -> Option<&Self> {
141        self.chain().find(|block| match hash_or_num {
142            BlockHashOrNumber::Hash(hash) => block.hash() == hash,
143            BlockHashOrNumber::Number(number) => block.number() == number,
144        })
145    }
146
147    /// Tries to find a transaction by [`TxHash`] in the chain ending at this block.
148    pub fn transaction_on_chain(&self, hash: TxHash) -> Option<N::SignedTx> {
149        self.chain().find_map(|block_state| {
150            block_state.block_ref().recovered_block().body().transaction_by_hash(&hash).cloned()
151        })
152    }
153
154    /// Tries to find a transaction with meta by [`TxHash`] in the chain ending at this block.
155    pub fn transaction_meta_on_chain(
156        &self,
157        tx_hash: TxHash,
158    ) -> Option<(N::SignedTx, TransactionMeta)> {
159        self.chain().find_map(|block_state| {
160            block_state.find_indexed(tx_hash).map(|indexed| (indexed.tx().clone(), indexed.meta()))
161        })
162    }
163
164    /// Finds a transaction by hash and returns it with its index and block context.
165    pub fn find_indexed(&self, tx_hash: TxHash) -> Option<IndexedTx<'_, N::Block>> {
166        self.block_ref().recovered_block().find_indexed(tx_hash)
167    }
168}
169
170// The derived drop recurses once per ancestor released here, which can overflow the stack on deep
171// in-memory chains, so detach parents in a loop instead.
172impl<N: NodePrimitives> Drop for BlockState<N> {
173    fn drop(&mut self) {
174        let mut parent = self.parent.take();
175        while let Some(state) = parent {
176            // A shared parent is left to its last owner, which continues the drain. Unlike
177            // `try_unwrap`, `into_inner` hands it to exactly one of several concurrent releasers.
178            let Some(mut state) = Arc::into_inner(state) else { break };
179            // Detach the next parent so dropping `state` here doesn't recurse.
180            parent = state.parent.take();
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::test_utils::TestBlockBuilder;
189    use rand::Rng;
190    use reth_ethereum_primitives::{EthPrimitives, Receipt};
191
192    fn create_mock_state(
193        test_block_builder: &mut TestBlockBuilder<EthPrimitives>,
194        block_number: u64,
195        parent_hash: B256,
196    ) -> BlockState {
197        BlockState::new(
198            test_block_builder.get_executed_block_with_number(block_number, parent_hash),
199        )
200    }
201
202    fn create_mock_state_chain(
203        test_block_builder: &mut TestBlockBuilder<EthPrimitives>,
204        num_blocks: u64,
205    ) -> Vec<BlockState> {
206        let mut chain = Vec::with_capacity(num_blocks as usize);
207        let mut parent_hash = B256::random();
208        let mut parent_state: Option<BlockState> = None;
209
210        for i in 1..=num_blocks {
211            let mut state = create_mock_state(test_block_builder, i, parent_hash);
212            if let Some(parent) = parent_state {
213                state.parent = Some(Arc::new(parent));
214            }
215            parent_hash = state.hash();
216            parent_state = Some(state.clone());
217            chain.push(state);
218        }
219
220        chain
221    }
222
223    #[test]
224    fn test_state() {
225        let number = rand::rng().random::<u64>();
226        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
227        let block = test_block_builder.get_executed_block_with_number(number, B256::random());
228
229        let state = BlockState::new(block.clone());
230
231        assert_eq!(state.block(), block);
232        assert_eq!(state.hash(), block.recovered_block().hash());
233        assert_eq!(state.number(), number);
234        assert_eq!(state.state_root(), block.recovered_block().state_root);
235    }
236
237    #[test]
238    fn test_state_receipts() {
239        let receipts = vec![vec![Receipt::default()]];
240        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
241        let block =
242            test_block_builder.get_executed_block_with_receipts(receipts.clone(), B256::random());
243
244        let state = BlockState::new(block);
245
246        assert_eq!(state.receipts(), receipts.first().unwrap());
247    }
248
249    #[test]
250    fn test_block_state_parent_blocks() {
251        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
252        let chain = create_mock_state_chain(&mut test_block_builder, 4);
253
254        let parents: Vec<_> = chain[3].parent_state_chain().collect();
255        assert_eq!(parents.len(), 3);
256        assert_eq!(parents[0].block().recovered_block().number, 3);
257        assert_eq!(parents[1].block().recovered_block().number, 2);
258        assert_eq!(parents[2].block().recovered_block().number, 1);
259
260        let parents: Vec<_> = chain[2].parent_state_chain().collect();
261        assert_eq!(parents.len(), 2);
262        assert_eq!(parents[0].block().recovered_block().number, 2);
263        assert_eq!(parents[1].block().recovered_block().number, 1);
264
265        assert_eq!(chain[0].parent_state_chain().count(), 0);
266    }
267
268    #[test]
269    fn test_block_state_single_block_state_chain() {
270        let single_block_number = 1;
271        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
272        let single_block =
273            create_mock_state(&mut test_block_builder, single_block_number, B256::random());
274        let single_block_hash = single_block.block().recovered_block().hash();
275
276        assert_eq!(single_block.parent_state_chain().count(), 0);
277
278        let block_state_chain = single_block.chain().collect::<Vec<_>>();
279        assert_eq!(block_state_chain.len(), 1);
280        assert_eq!(block_state_chain[0].block().recovered_block().number, single_block_number);
281        assert_eq!(block_state_chain[0].block().recovered_block().hash(), single_block_hash);
282    }
283
284    #[test]
285    fn test_block_state_chain() {
286        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
287        let chain = create_mock_state_chain(&mut test_block_builder, 3);
288
289        let block_state_chain = chain[2].chain().collect::<Vec<_>>();
290        assert_eq!(block_state_chain.len(), 3);
291        assert_eq!(block_state_chain[0].block().recovered_block().number, 3);
292        assert_eq!(block_state_chain[1].block().recovered_block().number, 2);
293        assert_eq!(block_state_chain[2].block().recovered_block().number, 1);
294
295        let block_state_chain = chain[1].chain().collect::<Vec<_>>();
296        assert_eq!(block_state_chain.len(), 2);
297        assert_eq!(block_state_chain[0].block().recovered_block().number, 2);
298        assert_eq!(block_state_chain[1].block().recovered_block().number, 1);
299
300        let block_state_chain = chain[0].chain().collect::<Vec<_>>();
301        assert_eq!(block_state_chain.len(), 1);
302        assert_eq!(block_state_chain[0].block().recovered_block().number, 1);
303    }
304
305    #[test]
306    fn test_block_state_chain_hashes() {
307        let mut test_block_builder: TestBlockBuilder = TestBlockBuilder::default();
308        let chain = create_mock_state_chain(&mut test_block_builder, 3);
309
310        assert_eq!(
311            chain[2].chain_hashes().collect::<Vec<_>>(),
312            [chain[2].hash(), chain[1].hash(), chain[0].hash(), chain[2].anchor().hash]
313        );
314        assert_eq!(
315            chain[0].chain_hashes().collect::<Vec<_>>(),
316            [chain[0].hash(), chain[0].anchor().hash]
317        );
318    }
319
320    fn block_state_chain(depth: usize, mut parent: Option<Arc<BlockState>>) -> Arc<BlockState> {
321        let block = ExecutedBlock::default();
322        for _ in 0..depth {
323            parent = Some(Arc::new(BlockState::with_parent(block.clone(), parent)));
324        }
325        parent.expect("nonempty chain")
326    }
327
328    #[test]
329    fn deep_chain_drop_preserves_shared_tail() {
330        const DEPTH: usize = 100_000;
331
332        // A recursive drop of either chain would overflow this stack.
333        std::thread::Builder::new()
334            .stack_size(64 * 1024)
335            .spawn(|| {
336                let tail = block_state_chain(DEPTH, None);
337                let tail_payload = Arc::downgrade(&tail.block_ref().execution_output);
338                let head = block_state_chain(DEPTH, Some(tail.clone()));
339                let head_payload = Arc::downgrade(&head.block_ref().execution_output);
340
341                drop(head);
342                assert_eq!(head_payload.strong_count(), 0);
343                assert_eq!(Arc::strong_count(&tail), 1);
344                assert_eq!(tail_payload.strong_count(), DEPTH);
345
346                drop(tail);
347                assert_eq!(tail_payload.strong_count(), 0);
348            })
349            .unwrap()
350            .join()
351            .unwrap();
352    }
353}