Skip to main content

ethrex_storage/
block_data_buffer.rs

1use std::collections::VecDeque;
2use std::sync::Arc;
3
4use ethrex_common::H256;
5use ethrex_common::seeded_hash::SeededHashMap;
6use ethrex_common::types::{
7    Block, BlockBody, BlockHash, BlockHeader, BlockNumber, Code, Receipt, Transaction,
8};
9use ethrex_crypto::NativeCrypto;
10use rustc_hash::{FxHashMap, FxHashSet};
11
12/// Block data held in memory after `newPayload` returns, before the background
13/// flusher writes it to RocksDB. One per block hash (holds reorg siblings).
14#[derive(Debug, Clone)]
15pub struct BufferedBlock {
16    pub header: BlockHeader,
17    pub body: BlockBody,
18    pub number: BlockNumber,
19    pub receipts: Vec<Receipt>,
20}
21
22/// In-memory overlay for not-yet-flushed block data. Consulted before disk by
23/// every read of headers/bodies/numbers/receipts/codes/tx-locations.
24///
25/// Held behind `Arc<RwLock<Arc<BlockDataBuffer>>>` in `Store`. Readers clone
26/// the inner `Arc` under a brief read lock and then work lock-free; the single
27/// writer mutates a clone and RCU-swaps the `Arc` in. Both critical sections
28/// are O(1) pointer operations.
29#[derive(Debug, Clone)]
30pub struct BlockDataBuffer {
31    by_hash: FxHashMap<BlockHash, Arc<BufferedBlock>>,
32    by_number: FxHashMap<BlockNumber, Vec<BlockHash>>,
33    tx_index: FxHashMap<H256, Vec<(BlockNumber, BlockHash, u64)>>,
34    /// Content-addressed code introduced by buffered blocks, with the block
35    /// number that introduced it (for eviction). Seeded: a deployer can grind its code hash
36    /// into a chosen bucket (see `ethrex_common::seeded_hash`).
37    codes: SeededHashMap<H256, (Code, BlockNumber)>,
38    /// Hashes not yet known to be on disk, oldest first.
39    unflushed: VecDeque<BlockHash>,
40    /// Highest block number whose data is durably on disk.
41    flushed_upto: BlockNumber,
42}
43
44impl Default for BlockDataBuffer {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl BlockDataBuffer {
51    pub fn new() -> Self {
52        Self {
53            by_hash: FxHashMap::default(),
54            by_number: FxHashMap::default(),
55            tx_index: FxHashMap::default(),
56            codes: SeededHashMap::default(),
57            unflushed: VecDeque::new(),
58            flushed_upto: 0,
59        }
60    }
61
62    /// Takes ownership of `block` and moves its header/body into the buffer (the
63    /// caller hands ownership over the flush channel and drops it right after, so
64    /// cloning would be pure waste).
65    pub fn insert(&mut self, block: Block, receipts: Vec<Receipt>, codes: Vec<(H256, Code)>) {
66        let hash = block.hash();
67        let number = block.header.number;
68        if self.by_hash.contains_key(&hash) {
69            return; // duplicate guard
70        }
71        for (index, tx) in block.body.transactions.iter().enumerate() {
72            self.tx_index
73                .entry(tx.hash(&NativeCrypto))
74                .or_default()
75                .push((number, hash, index as u64));
76        }
77        for (code_hash, code) in codes {
78            self.codes.entry(code_hash).or_insert((code, number));
79        }
80        self.by_number.entry(number).or_default().push(hash);
81        let Block { header, body } = block;
82        self.by_hash.insert(
83            hash,
84            Arc::new(BufferedBlock {
85                header,
86                body,
87                number,
88                receipts,
89            }),
90        );
91        self.unflushed.push_back(hash);
92    }
93
94    pub fn get_header(&self, hash: &BlockHash) -> Option<BlockHeader> {
95        self.by_hash.get(hash).map(|b| b.header.clone())
96    }
97
98    pub fn get_body(&self, hash: &BlockHash) -> Option<BlockBody> {
99        self.by_hash.get(hash).map(|b| b.body.clone())
100    }
101
102    /// The transaction at `index` of a buffered block's body: `None` if the block
103    /// is not buffered, `Some(None)` if its body has no such transaction.
104    pub fn get_transaction(&self, hash: &BlockHash, index: usize) -> Option<Option<Transaction>> {
105        self.by_hash
106            .get(hash)
107            .map(|b| b.body.transactions.get(index).cloned())
108    }
109
110    pub fn get_number(&self, hash: &BlockHash) -> Option<BlockNumber> {
111        self.by_hash.get(hash).map(|b| b.number)
112    }
113
114    pub fn get_receipt(&self, hash: &BlockHash, index: u64) -> Option<Receipt> {
115        self.by_hash
116            .get(hash)
117            .and_then(|b| b.receipts.get(index as usize).cloned())
118    }
119
120    pub fn get_receipts(&self, hash: &BlockHash) -> Option<Vec<Receipt>> {
121        self.by_hash.get(hash).map(|b| b.receipts.clone())
122    }
123
124    pub fn get_code(&self, code_hash: &H256) -> Option<Code> {
125        self.codes.get(code_hash).map(|(c, _)| c.clone())
126    }
127
128    pub fn get_tx_locations(&self, tx_hash: &H256) -> Vec<(BlockNumber, BlockHash, u64)> {
129        self.tx_index.get(tx_hash).cloned().unwrap_or_default()
130    }
131
132    pub fn flushed_upto(&self) -> BlockNumber {
133        self.flushed_upto
134    }
135
136    pub fn set_flushed_upto(&mut self, n: BlockNumber) {
137        self.flushed_upto = self.flushed_upto.max(n);
138    }
139
140    /// All unflushed blocks, ascending by number (deterministic flush order).
141    pub fn flushable(&self) -> Vec<Arc<BufferedBlock>> {
142        let mut out: Vec<Arc<BufferedBlock>> = self
143            .unflushed
144            .iter()
145            .filter_map(|h| self.by_hash.get(h).cloned())
146            .collect();
147        out.sort_by_key(|b| b.number);
148        out
149    }
150
151    /// Codes introduced by the given block hashes (for the flush write tx).
152    pub fn codes_for(&self, hashes: &[BlockHash]) -> Vec<(H256, Code)> {
153        let numbers: FxHashSet<BlockNumber> =
154            hashes.iter().filter_map(|h| self.get_number(h)).collect();
155        self.codes
156            .iter()
157            .filter(|(_, (_, n))| numbers.contains(n))
158            .map(|(h, (c, _))| (*h, c.clone()))
159            .collect()
160    }
161
162    /// Drop all buffered data for blocks with number <= `new_flushed_upto` and
163    /// advance the durable marker. Called only after the disk write committed.
164    pub fn evict_flushed(&mut self, new_flushed_upto: BlockNumber) {
165        self.set_flushed_upto(new_flushed_upto);
166        let drop_hashes: Vec<BlockHash> = self
167            .by_hash
168            .iter()
169            .filter(|(_, b)| b.number <= new_flushed_upto)
170            .map(|(h, _)| *h)
171            .collect();
172        for h in &drop_hashes {
173            if let Some(b) = self.by_hash.remove(h) {
174                if let Some(v) = self.by_number.get_mut(&b.number) {
175                    v.retain(|x| x != h);
176                    if v.is_empty() {
177                        self.by_number.remove(&b.number);
178                    }
179                }
180                for tx in b.body.transactions.iter() {
181                    if let Some(v) = self.tx_index.get_mut(&tx.hash(&NativeCrypto)) {
182                        v.retain(|(_, bh, _)| bh != h);
183                        if v.is_empty() {
184                            self.tx_index.remove(&tx.hash(&NativeCrypto));
185                        }
186                    }
187                }
188            }
189        }
190        self.unflushed.retain(|h| self.by_hash.contains_key(h));
191        self.codes.retain(|_, (_, n)| *n > new_flushed_upto);
192    }
193}