Skip to main content

reth_provider/bal/
rocksdb.rs

1use crate::providers::RocksDBProvider;
2use alloy_eip7928::BAL_RETENTION_PERIOD_SLOTS;
3use alloy_eips::NumHash;
4use alloy_primitives::{map::B256Map, BlockHash, BlockNumber, Bytes};
5use parking_lot::RwLock;
6use reth_db_api::{
7    models::{StoredBlockAccessList, StoredBlockAccessListKey},
8    table::{Decode, Decompress},
9    tables, DatabaseError,
10};
11use reth_prune_types::PruneMode;
12use reth_storage_api::{BalStore, GetBlockAccessListLimit, RawBal};
13use reth_storage_errors::provider::{ProviderError, ProviderResult};
14use std::{
15    collections::{BTreeMap, BTreeSet},
16    sync::Arc,
17};
18
19/// Number of recent blocks kept in the in-memory `RocksDB` BAL buffer.
20const DEFAULT_BAL_BUFFER_RETENTION_DISTANCE: u64 = 32;
21
22/// RocksDB-backed BAL store.
23///
24/// Persisted BALs are keyed by `(block_number, block_hash)` for ordered pruning and indexed by
25/// block hash for direct [`BalStore`] lookups. Validated BALs enter a shared in-memory buffer
26/// first; [`BalStore::flush`] makes confirmed canonical entries durable while retaining them in the
27/// read cache until its shorter retention window expires.
28#[derive(Clone)]
29pub struct RocksDBBalStore {
30    /// Number of recent blocks whose persisted BALs are retained.
31    retention_distance: u64,
32    /// Number of recent blocks retained in the in-memory buffer.
33    buffer_retention_distance: u64,
34    /// `RocksDB` provider used for persisted BAL reads and writes.
35    rocksdb: RocksDBProvider,
36    /// Shared recent-read cache and pending-write state.
37    buffer: Arc<RwLock<RocksDBBalStoreBuffer>>,
38}
39
40impl RocksDBBalStore {
41    /// Creates a new store with the EIP-defined retention distance.
42    pub fn new(rocksdb: RocksDBProvider) -> Self {
43        Self::with_buffer_retention_distance(rocksdb, DEFAULT_BAL_BUFFER_RETENTION_DISTANCE)
44    }
45
46    /// Creates a new store that retains buffered BALs for the given block distance.
47    ///
48    /// This does not change the EIP-defined retention distance for persisted BALs.
49    pub fn with_buffer_retention_distance(rocksdb: RocksDBProvider, blocks: u64) -> Self {
50        Self {
51            retention_distance: BAL_RETENTION_PERIOD_SLOTS,
52            buffer_retention_distance: blocks,
53            rocksdb,
54            buffer: Arc::new(RwLock::new(RocksDBBalStoreBuffer::default())),
55        }
56    }
57
58    /// Caps the persisted BAL retention at the block bodies prune distance, if it is shorter.
59    ///
60    /// A node that prunes bodies earlier already keeps less history than EIP-7928 requires, so its
61    /// BALs need not outlive the bodies. [`PruneMode::Full`] keeps `minimum_pruning_distance`
62    /// blocks, which is never less than the pruner keeps for bodies.
63    pub fn with_bodies_prune_mode(
64        mut self,
65        mode: Option<PruneMode>,
66        minimum_pruning_distance: u64,
67    ) -> Self {
68        let distance = match mode {
69            Some(PruneMode::Full) => minimum_pruning_distance,
70            Some(PruneMode::Distance(distance)) => distance,
71            // `Before` is a fixed block, not a distance; BALs below it expire with the EIP window.
72            Some(PruneMode::Before(_)) | None => return self,
73        };
74        self.retention_distance = self.retention_distance.min(distance);
75        self
76    }
77
78    #[cfg(test)]
79    const fn rocksdb_provider(&self) -> &RocksDBProvider {
80        &self.rocksdb
81    }
82
83    fn keys_to_prune(&self, tip: BlockNumber) -> ProviderResult<Vec<StoredBlockAccessListKey>> {
84        let retention = PruneMode::Distance(self.retention_distance);
85        let mut keys = Vec::new();
86        let iter = self.rocksdb.raw_key_iter_from::<tables::BlockAccessLists>(
87            StoredBlockAccessListKey::first_at_number(0),
88        )?;
89
90        for key_bytes in iter {
91            let key_bytes = key_bytes?;
92            let key = StoredBlockAccessListKey::decode(&key_bytes)
93                .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
94            if !retention.should_prune(key.number(), tip) {
95                break
96            }
97            keys.push(key);
98        }
99
100        Ok(keys)
101    }
102
103    fn delete_keys(&self, keys: &[StoredBlockAccessListKey]) -> ProviderResult<usize> {
104        if keys.is_empty() {
105            return Ok(0)
106        }
107
108        let mut batch = self.rocksdb.batch();
109        for key in keys {
110            batch.delete::<tables::BlockAccessLists>(*key)?;
111            batch.delete::<tables::BlockAccessListBlockNumbers>(key.hash())?;
112        }
113        batch.commit()?;
114        Ok(keys.len())
115    }
116
117    fn read_one_from_disk(&self, key: StoredBlockAccessListKey) -> ProviderResult<Option<Bytes>> {
118        let Some(value) = self.rocksdb.get_raw::<tables::BlockAccessLists>(key)? else {
119            return Ok(None)
120        };
121        let stored = StoredBlockAccessList::decompress(&value)
122            .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
123        Ok(Some(stored.into_raw()))
124    }
125
126    fn read_one_by_hash(&self, block_hash: BlockHash) -> ProviderResult<Option<Bytes>> {
127        if let Some(bal) = self.buffer.read().get_by_hash(block_hash) {
128            return Ok(Some(bal))
129        }
130
131        // Read-only legacy databases predate both BAL tables.
132        if self.rocksdb.is_read_only() &&
133            !self.rocksdb.has_table::<tables::BlockAccessLists>() &&
134            !self.rocksdb.has_table::<tables::BlockAccessListBlockNumbers>()
135        {
136            return Ok(None)
137        }
138
139        let Some(block_number) =
140            self.rocksdb.get::<tables::BlockAccessListBlockNumbers>(block_hash)?
141        else {
142            return Ok(None)
143        };
144        self.read_one_from_disk(StoredBlockAccessListKey::new(block_number, block_hash))
145    }
146}
147
148impl std::fmt::Debug for RocksDBBalStore {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("RocksDBBalStore")
151            .field("retention_distance", &self.retention_distance)
152            .field("buffer_retention_distance", &self.buffer_retention_distance)
153            .field("rocksdb", &self.rocksdb)
154            .finish_non_exhaustive()
155    }
156}
157
158impl BalStore for RocksDBBalStore {
159    fn insert(&self, block: NumHash, bal: RawBal) -> ProviderResult<()> {
160        self.buffer.write().insert(block, bal);
161        Ok(())
162    }
163
164    fn insert_many(&self, entries: Vec<(NumHash, RawBal)>) -> ProviderResult<()> {
165        if entries.is_empty() {
166            return Ok(())
167        }
168
169        let mut buffer = self.buffer.write();
170        buffer.entries.reserve(entries.len());
171        for (block, bal) in entries {
172            buffer.insert(block, bal);
173        }
174        Ok(())
175    }
176
177    fn flush(&self, blocks: &[NumHash]) -> ProviderResult<()> {
178        let pending = {
179            let mut buffer = self.buffer.write();
180            buffer.mark_canonical(blocks);
181            buffer.canonical_pending_entries()
182        };
183        if !pending.is_empty() {
184            let mut batch = self.rocksdb.batch();
185            for (key, bal) in &pending {
186                let value = StoredBlockAccessList::new_unchecked(bal.hash(), bal.as_raw().clone());
187                batch.put::<tables::BlockAccessLists>(*key, &value)?;
188                batch.put::<tables::BlockAccessListBlockNumbers>(key.hash(), &key.number())?;
189            }
190            batch.commit()?;
191
192            self.buffer.write().remove_flushed_pending(&pending);
193        }
194
195        if let Some(tip) = blocks.iter().map(|block| block.number).max() {
196            self.buffer.write().prune(self.buffer_retention_distance, tip);
197        }
198        Ok(())
199    }
200
201    fn prune(&self, tip: BlockNumber) -> ProviderResult<usize> {
202        let keys = self.keys_to_prune(tip)?;
203        let pruned = self.delete_keys(&keys)?;
204        self.buffer.write().remove_keys(&keys);
205        Ok(pruned)
206    }
207
208    fn get_by_hashes(&self, block_hashes: &[BlockHash]) -> ProviderResult<Vec<Option<Bytes>>> {
209        block_hashes.iter().map(|hash| self.read_one_by_hash(*hash)).collect()
210    }
211
212    fn append_by_hashes_with_limit(
213        &self,
214        block_hashes: &[BlockHash],
215        limit: GetBlockAccessListLimit,
216        out: &mut Vec<Option<Bytes>>,
217    ) -> ProviderResult<()> {
218        let mut size = 0;
219        for block_hash in block_hashes {
220            let bal = self.read_one_by_hash(*block_hash)?;
221            size += bal.as_ref().map_or(1, |bytes| bytes.len());
222            out.push(bal);
223
224            if limit.exceeds(size) {
225                break
226            }
227        }
228        Ok(())
229    }
230}
231
232/// Shared in-memory state for recent reads and writes awaiting canonical confirmation.
233///
234/// Successful flushes clear only the pending-write state. Cached entries remain available until
235/// the buffer retention window evicts them.
236#[derive(Debug, Default)]
237struct RocksDBBalStoreBuffer {
238    /// Hash index for serving recent hash-only lookups.
239    entries: B256Map<RocksDBBalEntry>,
240    /// Block-number index for pruning buffered entries.
241    hashes_by_number: BTreeMap<BlockNumber, Vec<BlockHash>>,
242    /// Validated BALs waiting to be confirmed canonical and flushed.
243    pending: BTreeMap<StoredBlockAccessListKey, RawBal>,
244    /// Pending writes confirmed canonical, including writes retained for retry after failure.
245    canonical_pending: BTreeSet<StoredBlockAccessListKey>,
246}
247
248impl RocksDBBalStoreBuffer {
249    fn insert(&mut self, block: NumHash, bal: RawBal) {
250        let pending = bal.clone();
251        if let Some(entry) =
252            self.entries.insert(block.hash, RocksDBBalEntry { block_number: block.number, bal })
253        {
254            self.remove_hash_from_number(entry.block_number, block.hash);
255            self.pending.remove(&StoredBlockAccessListKey::new(entry.block_number, block.hash));
256            self.canonical_pending
257                .remove(&StoredBlockAccessListKey::new(entry.block_number, block.hash));
258        }
259
260        self.hashes_by_number.entry(block.number).or_default().push(block.hash);
261        self.pending.insert(StoredBlockAccessListKey::new(block.number, block.hash), pending);
262    }
263
264    /// Marks exact pending block identities as eligible for the next flush.
265    fn mark_canonical(&mut self, blocks: &[NumHash]) {
266        self.canonical_pending.extend(
267            blocks
268                .iter()
269                .map(|block| StoredBlockAccessListKey::new(block.number, block.hash))
270                .filter(|key| self.pending.contains_key(key)),
271        );
272    }
273
274    /// Snapshots confirmed writes so `RocksDB` I/O can run without holding the buffer lock.
275    fn canonical_pending_entries(&self) -> Vec<(StoredBlockAccessListKey, RawBal)> {
276        self.canonical_pending
277            .iter()
278            .filter_map(|key| self.pending.get(key).map(|bal| (*key, bal.clone())))
279            .collect()
280    }
281
282    fn keys_to_prune(
283        &self,
284        retention_distance: u64,
285        tip: BlockNumber,
286    ) -> Vec<StoredBlockAccessListKey> {
287        let prune_mode = PruneMode::Distance(retention_distance);
288        self.hashes_by_number
289            .iter()
290            .take_while(|(block_number, _)| prune_mode.should_prune(**block_number, tip))
291            .flat_map(|(block_number, hashes)| {
292                hashes.iter().map(move |hash| StoredBlockAccessListKey::new(*block_number, *hash))
293            })
294            .filter(|key| !self.canonical_pending.contains(key))
295            .collect()
296    }
297
298    fn get_by_hash(&self, hash: BlockHash) -> Option<Bytes> {
299        self.entries.get(&hash).map(|entry| entry.bal.as_raw().clone())
300    }
301
302    /// Clears pending state only if it still matches the snapshot written to `RocksDB`.
303    ///
304    /// A concurrent replacement for the same key must remain pending for a later flush.
305    fn remove_flushed_pending(&mut self, flushed: &[(StoredBlockAccessListKey, RawBal)]) {
306        for (key, bal) in flushed {
307            let pending_matches =
308                self.pending.get(key).is_some_and(|pending| pending.as_raw() == bal.as_raw());
309            if pending_matches {
310                self.pending.remove(key);
311                self.canonical_pending.remove(key);
312            }
313        }
314    }
315
316    fn prune(&mut self, retention_distance: u64, tip: BlockNumber) {
317        let keys = self.keys_to_prune(retention_distance, tip);
318        self.remove_keys(&keys);
319    }
320
321    fn remove_keys(&mut self, keys: &[StoredBlockAccessListKey]) -> usize {
322        let mut removed = 0;
323        for key in keys {
324            let block = NumHash::new(key.number(), key.hash());
325            let pending_removed = self.pending.remove(key).is_some();
326            self.canonical_pending.remove(key);
327            let entry_removed = if self
328                .entries
329                .get(&block.hash)
330                .is_some_and(|entry| entry.block_number == block.number)
331            {
332                self.entries.remove(&block.hash).is_some()
333            } else {
334                false
335            };
336
337            if entry_removed {
338                self.remove_hash_from_number(block.number, block.hash);
339            }
340            removed += usize::from(pending_removed || entry_removed);
341        }
342        removed
343    }
344
345    fn remove_hash_from_number(&mut self, block_number: BlockNumber, block_hash: BlockHash) {
346        let empty = self.hashes_by_number.get_mut(&block_number).is_some_and(|hashes| {
347            hashes.retain(|hash| *hash != block_hash);
348            hashes.is_empty()
349        });
350        if empty {
351            self.hashes_by_number.remove(&block_number);
352        }
353    }
354}
355
356/// Buffered BAL entry with its block number.
357#[derive(Debug)]
358struct RocksDBBalEntry {
359    /// Block number for this hash-indexed BAL.
360    block_number: BlockNumber,
361    /// Raw BAL payload.
362    bal: RawBal,
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::providers::RocksDBBuilder;
369    use alloy_primitives::B256;
370
371    fn test_store() -> (tempfile::TempDir, RocksDBBalStore) {
372        let dir = tempfile::tempdir().unwrap();
373        let rocksdb = RocksDBBuilder::new(dir.path()).with_default_tables().build().unwrap();
374        (dir, RocksDBBalStore::new(rocksdb))
375    }
376
377    fn disk_bal(store: &RocksDBBalStore, block: NumHash) -> Option<Bytes> {
378        store
379            .rocksdb_provider()
380            .get_raw::<tables::BlockAccessLists>(StoredBlockAccessListKey::new(
381                block.number,
382                block.hash,
383            ))
384            .unwrap()
385            .map(|value| StoredBlockAccessList::decompress(&value).unwrap().into_raw())
386    }
387
388    fn read_many(store: &RocksDBBalStore, blocks: &[NumHash]) -> Vec<Option<Bytes>> {
389        blocks.iter().map(|block| store.get_by_hash(block.hash).unwrap()).collect()
390    }
391
392    #[test]
393    fn flush_prunes_buffer_retention() {
394        let (_dir, store) = test_store();
395        let old = NumHash::new(1, B256::with_last_byte(1));
396        let retained =
397            NumHash::new(DEFAULT_BAL_BUFFER_RETENTION_DISTANCE + 2, B256::with_last_byte(2));
398        let old_bal = Bytes::from_static(&[0xc1, 0x01]);
399        let retained_bal = Bytes::from_static(&[0xc1, 0x02]);
400
401        store.insert(old, RawBal::from(old_bal.clone())).unwrap();
402        store.insert(retained, RawBal::from(retained_bal.clone())).unwrap();
403
404        assert_eq!(
405            store.get_by_hashes(&[old.hash, retained.hash]).unwrap(),
406            vec![Some(old_bal), Some(retained_bal.clone())]
407        );
408
409        store.flush(&[retained]).unwrap();
410
411        assert_eq!(
412            store.get_by_hashes(&[old.hash, retained.hash]).unwrap(),
413            vec![None, Some(retained_bal)]
414        );
415        assert_eq!(disk_bal(&store, old), None);
416    }
417
418    #[test]
419    fn flush_prunes_only_durable_cache_entries() {
420        let (_dir, store) = test_store();
421        let old = NumHash::new(1, B256::with_last_byte(1));
422        let tip = NumHash::new(DEFAULT_BAL_BUFFER_RETENTION_DISTANCE + 2, B256::with_last_byte(2));
423        let old_bal = Bytes::from_static(&[0xc1, 0x01]);
424
425        store.insert(old, RawBal::from(old_bal.clone())).unwrap();
426        store.flush(&[old]).unwrap();
427        store.flush(&[tip]).unwrap();
428
429        assert!(!store.buffer.read().entries.contains_key(&old.hash));
430        assert_eq!(disk_bal(&store, old), Some(old_bal.clone()));
431        assert_eq!(store.get_by_hash(old.hash).unwrap(), Some(old_bal));
432    }
433
434    #[test]
435    fn configured_buffer_retention_distance_is_used() {
436        let dir = tempfile::tempdir().unwrap();
437        let rocksdb = RocksDBBuilder::new(dir.path()).with_default_tables().build().unwrap();
438        let store = RocksDBBalStore::with_buffer_retention_distance(rocksdb, 64);
439        let old = NumHash::new(1, B256::with_last_byte(1));
440        let tip = NumHash::new(34, B256::with_last_byte(2));
441
442        store.insert(old, RawBal::from(Bytes::from_static(&[0xc1, 0x01]))).unwrap();
443        store.flush(&[old]).unwrap();
444        store.flush(&[tip]).unwrap();
445
446        assert!(store.buffer.read().entries.contains_key(&old.hash));
447    }
448
449    #[test]
450    fn flush_writes_only_requested_pending_bals() {
451        let (_dir, store) = test_store();
452        let block_1 = NumHash::new(1, B256::with_last_byte(1));
453        let block_1_fork = NumHash::new(1, B256::with_last_byte(9));
454        let block_2 = NumHash::new(2, B256::with_last_byte(2));
455        let bal_1 = Bytes::from_static(&[0xc1, 0x01]);
456        let bal_1_fork = Bytes::from_static(&[0xc1, 0x09]);
457        let bal_2 = Bytes::from_static(&[0xc1, 0x02]);
458
459        store.insert(block_1, RawBal::from(bal_1.clone())).unwrap();
460        store.insert(block_1_fork, RawBal::from(bal_1_fork.clone())).unwrap();
461        store.insert(block_2, RawBal::from(bal_2.clone())).unwrap();
462
463        store.flush(&[block_1]).unwrap();
464
465        assert_eq!(disk_bal(&store, block_1), Some(bal_1.clone()));
466        assert_eq!(disk_bal(&store, block_1_fork), None);
467        assert_eq!(disk_bal(&store, block_2), None);
468        assert_eq!(
469            store.get_by_hashes(&[block_1.hash, block_1_fork.hash, block_2.hash]).unwrap(),
470            vec![Some(bal_1.clone()), Some(bal_1_fork), Some(bal_2)]
471        );
472
473        let store_with_empty_buffer = RocksDBBalStore::new(store.rocksdb_provider().clone());
474        assert_eq!(
475            store_with_empty_buffer
476                .get_by_hashes(&[block_1.hash, block_1_fork.hash, block_2.hash])
477                .unwrap(),
478            vec![Some(bal_1), None, None]
479        );
480    }
481
482    #[test]
483    fn missing_and_empty_bal_are_distinct() {
484        let (_dir, store) = test_store();
485        let empty_hash = B256::with_last_byte(1);
486        let missing_hash = B256::with_last_byte(2);
487        let empty_bal = Bytes::from_static(&[0xc0]);
488
489        store.insert(NumHash::new(1, empty_hash), RawBal::from(empty_bal.clone())).unwrap();
490
491        assert_eq!(
492            read_many(&store, &[NumHash::new(1, empty_hash), NumHash::new(1, missing_hash)]),
493            vec![Some(empty_bal), None]
494        );
495    }
496
497    #[test]
498    fn prune_uses_eip_retention() {
499        let (_dir, store) = test_store();
500        let old_hash = B256::with_last_byte(1);
501        let retained_hash = B256::with_last_byte(2);
502        let retained_bal = Bytes::from_static(&[0xc1, 0x02]);
503        let tip = BAL_RETENTION_PERIOD_SLOTS + 2;
504
505        store
506            .insert(NumHash::new(1, old_hash), RawBal::from(Bytes::from_static(&[0xc1, 0x01])))
507            .unwrap();
508        store.insert(NumHash::new(2, retained_hash), RawBal::from(retained_bal.clone())).unwrap();
509        store.flush(&[NumHash::new(1, old_hash), NumHash::new(2, retained_hash)]).unwrap();
510
511        assert_eq!(store.prune(tip).unwrap(), 1);
512        assert_eq!(disk_bal(&store, NumHash::new(1, old_hash)), None);
513        assert_eq!(disk_bal(&store, NumHash::new(2, retained_hash)), Some(retained_bal.clone()));
514        assert_eq!(
515            read_many(&store, &[NumHash::new(1, old_hash), NumHash::new(2, retained_hash)]),
516            vec![None, Some(retained_bal)]
517        );
518    }
519
520    #[test]
521    fn prune_caps_retention_at_bodies_distance() {
522        let (_dir, store) = test_store();
523        let store = store.with_bodies_prune_mode(Some(PruneMode::Distance(10)), 100);
524        let old = NumHash::new(1, B256::with_last_byte(1));
525        let retained = NumHash::new(2, B256::with_last_byte(2));
526        let retained_bal = Bytes::from_static(&[0xc1, 0x02]);
527
528        store.insert(old, RawBal::from(Bytes::from_static(&[0xc1, 0x01]))).unwrap();
529        store.insert(retained, RawBal::from(retained_bal.clone())).unwrap();
530        store.flush(&[old, retained]).unwrap();
531
532        assert_eq!(store.prune(12).unwrap(), 1);
533        assert_eq!(disk_bal(&store, old), None);
534        assert_eq!(disk_bal(&store, retained), Some(retained_bal));
535
536        let (_dir, store) = test_store();
537        let store = store.with_bodies_prune_mode(Some(PruneMode::Full), 100);
538        assert_eq!(store.retention_distance, 100);
539
540        let (_dir, store) = test_store();
541        let store = store.with_bodies_prune_mode(Some(PruneMode::Distance(u64::MAX)), 100);
542        assert_eq!(store.retention_distance, BAL_RETENTION_PERIOD_SLOTS);
543    }
544
545    #[test]
546    fn stored_payload_hash_is_not_reverified() {
547        let (_dir, store) = test_store();
548        let block = NumHash::new(1, B256::with_last_byte(1));
549        let key = StoredBlockAccessListKey::new(block.number, block.hash);
550        let value = StoredBlockAccessList::new_unchecked(B256::ZERO, Bytes::from_static(&[0xc0]));
551
552        store.rocksdb_provider().put::<tables::BlockAccessLists>(key, &value).unwrap();
553        store
554            .rocksdb_provider()
555            .put::<tables::BlockAccessListBlockNumbers>(block.hash, &block.number)
556            .unwrap();
557
558        assert_eq!(store.get_by_hash(block.hash).unwrap(), Some(Bytes::from_static(&[0xc0])));
559    }
560
561    #[test]
562    fn canonical_pending_entries_are_retried() {
563        let mut buffer = RocksDBBalStoreBuffer::default();
564        let first = NumHash::new(1, B256::with_last_byte(1));
565        let second = NumHash::new(2, B256::with_last_byte(2));
566        buffer.insert(first, RawBal::from(Bytes::from_static(&[0xc1, 0x01])));
567        buffer.mark_canonical(&[first]);
568
569        assert_eq!(buffer.canonical_pending_entries().len(), 1);
570
571        // A failed flush leaves the canonical entry pending for the next attempt.
572        buffer.insert(second, RawBal::from(Bytes::from_static(&[0xc1, 0x02])));
573        buffer.mark_canonical(&[second]);
574        let retry = buffer.canonical_pending_entries();
575
576        assert_eq!(
577            retry.iter().map(|(key, _)| NumHash::new(key.number(), key.hash())).collect::<Vec<_>>(),
578            vec![first, second]
579        );
580    }
581
582    #[test]
583    fn read_only_legacy_database_has_no_persisted_bals() {
584        let dir = tempfile::tempdir().unwrap();
585        let path = dir.path().join("db");
586        let hash = B256::with_last_byte(1);
587        let rocksdb = RocksDBBuilder::new(&path)
588            .with_table::<tables::TransactionHashNumbers>()
589            .with_table::<tables::AccountsHistory>()
590            .with_table::<tables::StoragesHistory>()
591            .build()
592            .unwrap();
593        rocksdb.put::<tables::TransactionHashNumbers>(hash, &42).unwrap();
594        drop(rocksdb);
595
596        let rocksdb = RocksDBBuilder::new(&path)
597            .with_default_tables()
598            .with_table::<tables::BlockAccessLists>()
599            .with_table::<tables::BlockAccessListBlockNumbers>()
600            .with_read_only(true)
601            .build()
602            .unwrap();
603        assert_eq!(rocksdb.get::<tables::TransactionHashNumbers>(hash).unwrap(), Some(42));
604        let store = RocksDBBalStore::new(rocksdb);
605        assert_eq!(store.get_by_hash(hash).unwrap(), None);
606
607        let raw = Bytes::from_static(&[0xc0]);
608        store.insert(NumHash::new(42, hash), RawBal::from(raw.clone())).unwrap();
609        assert_eq!(store.get_by_hash(hash).unwrap(), Some(raw));
610        drop(store);
611
612        // The secondary open must not add tables to the primary database.
613        let rocksdb = RocksDBBuilder::new(&path)
614            .with_table::<tables::TransactionHashNumbers>()
615            .with_table::<tables::AccountsHistory>()
616            .with_table::<tables::StoragesHistory>()
617            .build()
618            .unwrap();
619        assert!(!rocksdb.has_table::<tables::BlockAccessLists>());
620        assert!(!rocksdb.has_table::<tables::BlockAccessListBlockNumbers>());
621    }
622
623    #[test]
624    fn read_only_database_reads_persisted_bals() {
625        let dir = tempfile::tempdir().unwrap();
626        let path = dir.path().join("db");
627        let rocksdb = RocksDBBuilder::new(&path)
628            .with_default_tables()
629            .with_table::<tables::BlockAccessLists>()
630            .with_table::<tables::BlockAccessListBlockNumbers>()
631            .build()
632            .unwrap();
633        let store = RocksDBBalStore::new(rocksdb);
634        let block = NumHash::new(42, B256::with_last_byte(1));
635        let raw = Bytes::from_static(&[0xc0]);
636        store.insert(block, RawBal::from(raw.clone())).unwrap();
637        store.flush(&[block]).unwrap();
638        drop(store);
639
640        let rocksdb = RocksDBBuilder::new(&path)
641            .with_default_tables()
642            .with_table::<tables::BlockAccessLists>()
643            .with_table::<tables::BlockAccessListBlockNumbers>()
644            .with_read_only(true)
645            .build()
646            .unwrap();
647        let store = RocksDBBalStore::new(rocksdb);
648        assert_eq!(store.get_by_hash(block.hash).unwrap(), Some(raw));
649    }
650}