Skip to main content

reth_provider/
bal.rs

1use alloy_eip7928::BAL_RETENTION_PERIOD_SLOTS;
2use alloy_eips::NumHash;
3use alloy_primitives::{BlockHash, BlockNumber, Bytes};
4use parking_lot::RwLock;
5use reth_prune_types::PruneMode;
6use reth_storage_api::{
7    BalNotification, BalNotificationStream, BalStore, GetBlockAccessListLimit, SealedBal,
8};
9use reth_storage_errors::provider::ProviderResult;
10use reth_tokio_util::EventSender;
11use std::{
12    collections::{BTreeMap, HashMap},
13    sync::Arc,
14};
15
16/// Basic in-memory BAL store keyed by block hash.
17#[derive(Debug, Clone)]
18pub struct InMemoryBalStore {
19    config: BalConfig,
20    inner: Arc<RwLock<InMemoryBalStoreInner>>,
21    notifications: EventSender<BalNotification>,
22}
23
24impl InMemoryBalStore {
25    /// Creates a new in-memory BAL store with the given config.
26    pub fn new(config: BalConfig) -> Self {
27        let notifications = EventSender::new(DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE);
28        Self {
29            config,
30            inner: Arc::new(RwLock::new(InMemoryBalStoreInner::default())),
31            notifications,
32        }
33    }
34}
35
36// Match the canonical state broadcast buffer so BAL subscriptions behave like the existing
37// in-memory notification path. This is a bounded best-effort channel, not a durability boundary.
38const DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE: usize = 256;
39
40impl Default for InMemoryBalStore {
41    fn default() -> Self {
42        Self::new(BalConfig::default())
43    }
44}
45
46/// Configuration for BAL storage.
47#[derive(Debug, Clone, Copy, Eq, PartialEq)]
48pub struct BalConfig {
49    /// Retention policy for BALs kept in memory.
50    in_memory_retention: Option<PruneMode>,
51}
52
53impl BalConfig {
54    /// Default block distance for BALs kept in memory.
55    pub const DEFAULT_IN_MEMORY_RETENTION_DISTANCE: u64 = BAL_RETENTION_PERIOD_SLOTS;
56
57    /// Returns a config with no in-memory BAL retention limit.
58    pub const fn unbounded() -> Self {
59        Self { in_memory_retention: None }
60    }
61
62    /// Returns a config that keeps BALs within the given block distance in memory.
63    pub const fn with_in_memory_retention_distance(blocks: u64) -> Self {
64        Self::with_in_memory_retention(PruneMode::Distance(blocks))
65    }
66
67    /// Returns a config with the given in-memory BAL retention policy.
68    pub const fn with_in_memory_retention(in_memory_retention: PruneMode) -> Self {
69        Self { in_memory_retention: Some(in_memory_retention) }
70    }
71}
72
73impl Default for BalConfig {
74    fn default() -> Self {
75        Self::with_in_memory_retention_distance(Self::DEFAULT_IN_MEMORY_RETENTION_DISTANCE)
76    }
77}
78
79#[derive(Debug, Default)]
80struct InMemoryBalStoreInner {
81    entries: HashMap<BlockHash, BalEntry>,
82    hashes_by_number: BTreeMap<BlockNumber, Vec<BlockHash>>,
83    highest_block_number: Option<BlockNumber>,
84}
85
86impl InMemoryBalStoreInner {
87    // Inserts a BAL and keeps the block-number index in sync.
88    fn insert(&mut self, block_hash: BlockHash, block_number: BlockNumber, bal: Bytes) {
89        let empty_block_number =
90            self.entries.insert(block_hash, BalEntry { block_number, bal }).and_then(|entry| {
91                let hashes = self.hashes_by_number.get_mut(&entry.block_number)?;
92                hashes.retain(|hash| *hash != block_hash);
93                hashes.is_empty().then_some(entry.block_number)
94            });
95
96        if let Some(block_number) = empty_block_number {
97            self.hashes_by_number.remove(&block_number);
98        }
99
100        self.hashes_by_number.entry(block_number).or_default().push(block_hash);
101        self.highest_block_number = Some(
102            self.highest_block_number.map_or(block_number, |highest| highest.max(block_number)),
103        );
104    }
105
106    // Removes BALs outside the configured retention window for the given chain tip.
107    fn prune(&mut self, prune_mode: Option<PruneMode>, tip: BlockNumber) -> usize {
108        let Some(prune_mode) = prune_mode else { return 0 };
109
110        let mut pruned = 0;
111        while let Some((&block_number, _)) = self.hashes_by_number.first_key_value() {
112            if !prune_mode.should_prune(block_number, tip) {
113                break
114            }
115
116            let Some((_, hashes)) = self.hashes_by_number.pop_first() else { break };
117            for hash in hashes {
118                pruned += usize::from(self.entries.remove(&hash).is_some());
119            }
120        }
121        pruned
122    }
123}
124
125#[derive(Debug)]
126struct BalEntry {
127    block_number: BlockNumber,
128    bal: Bytes,
129}
130
131impl BalStore for InMemoryBalStore {
132    fn insert(&self, num_hash: NumHash, bal: SealedBal) -> ProviderResult<()> {
133        let mut inner = self.inner.write();
134        inner.insert(num_hash.hash, num_hash.number, bal.clone_inner());
135        if let Some(highest_block_number) = inner.highest_block_number {
136            // This preserves insert-time cleanup based on the highest inserted BAL block.
137            inner.prune(self.config.in_memory_retention, highest_block_number);
138        }
139        self.notifications.notify(BalNotification::new(num_hash, bal));
140        Ok(())
141    }
142
143    fn insert_many(&self, entries: Vec<(NumHash, SealedBal)>) -> ProviderResult<()> {
144        if entries.is_empty() {
145            return Ok(())
146        }
147
148        let mut inner = self.inner.write();
149        inner.entries.reserve(entries.len());
150        for (num_hash, bal) in &entries {
151            inner.insert(num_hash.hash, num_hash.number, bal.clone_inner());
152        }
153        if let Some(highest_block_number) = inner.highest_block_number {
154            inner.prune(self.config.in_memory_retention, highest_block_number);
155        }
156        drop(inner);
157
158        for (num_hash, bal) in entries {
159            self.notifications.notify(BalNotification::new(num_hash, bal));
160        }
161        Ok(())
162    }
163
164    fn flush(&self) -> ProviderResult<()> {
165        Ok(())
166    }
167
168    fn prune(&self, tip: BlockNumber) -> ProviderResult<usize> {
169        Ok(self.inner.write().prune(self.config.in_memory_retention, tip))
170    }
171
172    fn get_by_hashes(&self, block_hashes: &[BlockHash]) -> ProviderResult<Vec<Option<Bytes>>> {
173        let inner = self.inner.read();
174        let mut result = Vec::with_capacity(block_hashes.len());
175
176        for hash in block_hashes {
177            result.push(inner.entries.get(hash).map(|entry| entry.bal.clone()));
178        }
179
180        Ok(result)
181    }
182
183    fn append_by_hashes_with_limit(
184        &self,
185        block_hashes: &[BlockHash],
186        limit: GetBlockAccessListLimit,
187        out: &mut Vec<Option<Bytes>>,
188    ) -> ProviderResult<()> {
189        let inner = self.inner.read();
190        let mut size = 0;
191
192        for hash in block_hashes {
193            let bal = inner.entries.get(hash).map(|entry| entry.bal.clone());
194            size += bal.as_ref().map_or(1, |bytes| bytes.len());
195            out.push(bal);
196
197            if limit.exceeds(size) {
198                break
199            }
200        }
201
202        Ok(())
203    }
204
205    fn bal_stream(&self) -> BalNotificationStream {
206        self.notifications.new_listener()
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use alloy_primitives::{keccak256, Sealed, B256};
214    use tokio_stream::StreamExt;
215
216    fn sealed_bal(bal: Bytes) -> SealedBal {
217        Sealed::new_unchecked(bal.clone(), keccak256(&bal))
218    }
219
220    #[test]
221    fn insert_and_lookup_by_hash() {
222        let store = InMemoryBalStore::default();
223        let hash = B256::random();
224        let missing = B256::random();
225        let bal = Bytes::from_static(b"bal");
226
227        store.insert(NumHash::new(1, hash), sealed_bal(bal.clone())).unwrap();
228
229        assert_eq!(store.get_by_hashes(&[hash, missing]).unwrap(), vec![Some(bal), None]);
230    }
231
232    #[test]
233    fn insert_many_and_lookup_by_hash() {
234        let store = InMemoryBalStore::default();
235        let hash0 = B256::random();
236        let hash1 = B256::random();
237        let bal0 = sealed_bal(Bytes::from_static(b"bal0"));
238        let bal1 = sealed_bal(Bytes::from_static(b"bal1"));
239
240        store
241            .insert_many(vec![
242                (NumHash::new(1, hash0), bal0.clone()),
243                (NumHash::new(2, hash1), bal1),
244            ])
245            .unwrap();
246
247        assert_eq!(
248            store.get_by_hashes(&[hash0, hash1]).unwrap(),
249            vec![Some(bal0.clone_inner()), Some(Bytes::from_static(b"bal1"))]
250        );
251    }
252
253    #[test]
254    fn flush_is_noop() {
255        let store = InMemoryBalStore::default();
256
257        store.flush().unwrap();
258    }
259
260    #[test]
261    fn limited_lookup_returns_prefix() {
262        let store = InMemoryBalStore::default();
263        let hash0 = B256::random();
264        let hash1 = B256::random();
265        let hash2 = B256::random();
266        let bal0 = Bytes::from_static(&[0xc1, 0x01]);
267        let bal1 = Bytes::from_static(&[0xc1, 0x02]);
268        let bal2 = Bytes::from_static(&[0xc1, 0x03]);
269
270        store.insert(NumHash::new(1, hash0), sealed_bal(bal0.clone())).unwrap();
271        store.insert(NumHash::new(2, hash1), sealed_bal(bal1.clone())).unwrap();
272        store.insert(NumHash::new(3, hash2), sealed_bal(bal2)).unwrap();
273
274        let limited = store
275            .get_by_hashes_with_limit(
276                &[hash0, hash1, hash2],
277                GetBlockAccessListLimit::ResponseSizeSoftLimit(2),
278            )
279            .unwrap();
280
281        assert_eq!(limited, vec![Some(bal0), Some(bal1)]);
282    }
283
284    #[test]
285    fn default_retention_prunes_old_bals() {
286        let store = InMemoryBalStore::default();
287        let old_hash = B256::random();
288        let retained_hash = B256::random();
289        let tip_hash = B256::random();
290        let old_bal = Bytes::from_static(b"old");
291        let retained_bal = Bytes::from_static(b"retained");
292        let tip_bal = Bytes::from_static(b"tip");
293
294        store.insert(NumHash::new(1, old_hash), sealed_bal(old_bal)).unwrap();
295        store
296            .insert(
297                NumHash::new(BAL_RETENTION_PERIOD_SLOTS, retained_hash),
298                sealed_bal(retained_bal.clone()),
299            )
300            .unwrap();
301        store
302            .insert(
303                NumHash::new(BAL_RETENTION_PERIOD_SLOTS + 2, tip_hash),
304                sealed_bal(tip_bal.clone()),
305            )
306            .unwrap();
307
308        assert_eq!(
309            store.get_by_hashes(&[old_hash, retained_hash, tip_hash]).unwrap(),
310            vec![None, Some(retained_bal), Some(tip_bal)]
311        );
312    }
313
314    #[test]
315    fn prune_uses_chain_tip() {
316        let store =
317            InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Distance(2)));
318        let old_hash = B256::random();
319        let retained_hash = B256::random();
320        let old_bal = Bytes::from_static(b"old");
321        let retained_bal = Bytes::from_static(b"retained");
322
323        store.insert(NumHash::new(7, old_hash), sealed_bal(old_bal)).unwrap();
324        store.insert(NumHash::new(8, retained_hash), sealed_bal(retained_bal.clone())).unwrap();
325
326        assert_eq!(store.prune(10).unwrap(), 1);
327        assert_eq!(
328            store.get_by_hashes(&[old_hash, retained_hash]).unwrap(),
329            vec![None, Some(retained_bal)]
330        );
331    }
332
333    #[test]
334    fn insert_prunes_from_highest_inserted_block() {
335        let store =
336            InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Distance(2)));
337        let old_hash = B256::random();
338        let high_hash = B256::random();
339        let late_hash = B256::random();
340        let high_bal = Bytes::from_static(b"high");
341        let late_bal = Bytes::from_static(b"late");
342
343        store.insert(NumHash::new(7, old_hash), sealed_bal(Bytes::from_static(b"old"))).unwrap();
344        store.insert(NumHash::new(10, high_hash), sealed_bal(high_bal.clone())).unwrap();
345        store.insert(NumHash::new(8, late_hash), sealed_bal(late_bal.clone())).unwrap();
346
347        assert_eq!(
348            store.get_by_hashes(&[old_hash, high_hash, late_hash]).unwrap(),
349            vec![None, Some(high_bal), Some(late_bal)]
350        );
351    }
352
353    #[test]
354    fn unbounded_retention_keeps_old_bals() {
355        let store = InMemoryBalStore::new(BalConfig::unbounded());
356        let old_hash = B256::random();
357        let tip_hash = B256::random();
358        let old_bal = Bytes::from_static(b"old");
359        let tip_bal = Bytes::from_static(b"tip");
360
361        store.insert(NumHash::new(1, old_hash), sealed_bal(old_bal.clone())).unwrap();
362        store
363            .insert(
364                NumHash::new(BAL_RETENTION_PERIOD_SLOTS + 1, tip_hash),
365                sealed_bal(tip_bal.clone()),
366            )
367            .unwrap();
368
369        assert_eq!(
370            store.get_by_hashes(&[old_hash, tip_hash]).unwrap(),
371            vec![Some(old_bal), Some(tip_bal)]
372        );
373        assert_eq!(store.prune(BAL_RETENTION_PERIOD_SLOTS + 2).unwrap(), 0);
374    }
375
376    #[test]
377    fn in_memory_retention_distance_prunes_old_bals() {
378        let store = InMemoryBalStore::new(BalConfig::with_in_memory_retention_distance(2));
379        let old_hash = B256::random();
380        let retained_hash = B256::random();
381        let tip_hash = B256::random();
382        let old_bal = Bytes::from_static(b"old");
383        let retained_bal = Bytes::from_static(b"retained");
384        let tip_bal = Bytes::from_static(b"tip");
385
386        store.insert(NumHash::new(1, old_hash), sealed_bal(old_bal)).unwrap();
387        store.insert(NumHash::new(2, retained_hash), sealed_bal(retained_bal.clone())).unwrap();
388        store.insert(NumHash::new(4, tip_hash), sealed_bal(tip_bal.clone())).unwrap();
389
390        assert_eq!(
391            store.get_by_hashes(&[old_hash, retained_hash, tip_hash]).unwrap(),
392            vec![None, Some(retained_bal), Some(tip_bal)]
393        );
394    }
395
396    #[test]
397    fn reinserting_hash_updates_number_index() {
398        let store =
399            InMemoryBalStore::new(BalConfig::with_in_memory_retention(PruneMode::Before(2)));
400        let hash = B256::random();
401        let bal = Bytes::from_static(b"bal");
402
403        store.insert(NumHash::new(1, hash), sealed_bal(Bytes::from_static(b"old"))).unwrap();
404        store.insert(NumHash::new(2, hash), sealed_bal(bal.clone())).unwrap();
405
406        assert_eq!(store.get_by_hashes(&[hash]).unwrap(), vec![Some(bal)]);
407    }
408
409    #[tokio::test]
410    async fn insert_notifies_subscribers() {
411        let store = InMemoryBalStore::default();
412        let hash = B256::random();
413        let block_number = 7;
414        let bal = Bytes::from_static(b"bal");
415        let mut stream = store.bal_stream();
416
417        let sealed_bal = sealed_bal(bal);
418
419        store.insert(NumHash::new(block_number, hash), sealed_bal.clone()).unwrap();
420
421        assert_eq!(
422            stream.next().await.unwrap(),
423            BalNotification::new(NumHash::new(block_number, hash), sealed_bal)
424        );
425    }
426
427    #[tokio::test]
428    async fn insert_many_notifies_subscribers() {
429        let store = InMemoryBalStore::default();
430        let mut stream = store.bal_stream();
431        let hash0 = B256::random();
432        let hash1 = B256::random();
433        let bal0 = sealed_bal(Bytes::from_static(b"bal0"));
434        let bal1 = sealed_bal(Bytes::from_static(b"bal1"));
435
436        store
437            .insert_many(vec![
438                (NumHash::new(1, hash0), bal0.clone()),
439                (NumHash::new(2, hash1), bal1.clone()),
440            ])
441            .unwrap();
442
443        assert_eq!(
444            stream.next().await.unwrap(),
445            BalNotification::new(NumHash::new(1, hash0), bal0)
446        );
447        assert_eq!(
448            stream.next().await.unwrap(),
449            BalNotification::new(NumHash::new(2, hash1), bal1)
450        );
451    }
452
453    #[test]
454    fn insert_without_subscribers_still_succeeds() {
455        let store = InMemoryBalStore::default();
456
457        assert!(store
458            .insert(NumHash::new(1, B256::random()), sealed_bal(Bytes::from_static(b"bal")))
459            .is_ok());
460    }
461
462    #[tokio::test]
463    async fn bal_stream_skips_lagged_notifications() {
464        let store = InMemoryBalStore::new(BalConfig::unbounded());
465        let mut stream = store.bal_stream();
466
467        for number in 0..=DEFAULT_BAL_NOTIFICATION_CHANNEL_SIZE as u64 {
468            store
469                .insert(
470                    NumHash::new(number, B256::random()),
471                    sealed_bal(Bytes::from(vec![number as u8])),
472                )
473                .unwrap();
474        }
475
476        let first = stream.next().await.unwrap();
477        let second = stream.next().await.unwrap();
478
479        assert_eq!(first.num_hash.number, 1);
480        assert_eq!(second.num_hash.number, 2);
481    }
482
483    #[tokio::test]
484    async fn cloned_store_shares_notification_channel() {
485        let store = InMemoryBalStore::default();
486        let clone = store.clone();
487        let hash = B256::random();
488        let block_number = 9;
489        let bal = Bytes::from_static(b"bal");
490        let mut stream = clone.bal_stream();
491
492        let sealed_bal = sealed_bal(bal);
493
494        store.insert(NumHash::new(block_number, hash), sealed_bal.clone()).unwrap();
495
496        assert_eq!(
497            stream.next().await.unwrap(),
498            BalNotification::new(NumHash::new(block_number, hash), sealed_bal)
499        );
500    }
501}