reth_chain_state/in_memory/
block_state.rs1use 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#[derive(Debug, Clone)]
12pub struct BlockState<N: NodePrimitives = EthPrimitives> {
13 pub(super) block: ExecutedBlock<N>,
15 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 pub const fn new(block: ExecutedBlock<N>) -> Self {
28 Self { block, parent: None }
29 }
30
31 pub const fn with_parent(block: ExecutedBlock<N>, parent: Option<Arc<Self>>) -> Self {
33 Self { block, parent }
34 }
35
36 pub fn anchor(&self) -> BlockNumHash {
38 let mut current = self;
39 while let Some(parent) = ¤t.parent {
40 current = parent;
41 }
42 current.block.recovered_block().parent_num_hash()
43 }
44
45 pub fn block(&self) -> ExecutedBlock<N> {
47 self.block.clone()
48 }
49
50 pub const fn block_ref(&self) -> &ExecutedBlock<N> {
52 &self.block
53 }
54
55 pub fn hash(&self) -> B256 {
57 self.block.recovered_block().hash()
58 }
59
60 pub fn number(&self) -> u64 {
62 self.block.recovered_block().number()
63 }
64
65 pub fn parent_hash(&self) -> B256 {
67 self.block.recovered_block().parent_hash()
68 }
69
70 pub fn state_root(&self) -> B256 {
73 self.block.recovered_block().state_root()
74 }
75
76 pub fn receipts(&self) -> &Vec<N::Receipt> {
78 &self.block.execution_outcome().receipts
79 }
80
81 pub fn executed_block_receipts(&self) -> Vec<N::Receipt> {
88 self.receipts().clone()
89 }
90
91 pub fn executed_block_receipts_ref(&self) -> &[N::Receipt] {
96 self.receipts()
97 }
98
99 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 pub fn chain(&self) -> impl Iterator<Item = &Self> {
113 std::iter::successors(Some(self), |state| state.parent.as_deref())
114 }
115
116 pub fn append_parent_chain<'a>(&'a self, chain: &mut Vec<&'a Self>) {
123 chain.extend(self.parent_state_chain());
124 }
125
126 pub fn iter(self: Arc<Self>) -> impl Iterator<Item = Arc<Self>> {
130 std::iter::successors(Some(self), |state| state.parent.clone())
131 }
132
133 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 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 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 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 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
170impl<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 let Some(mut state) = Arc::into_inner(state) else { break };
179 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 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}