Skip to main content

reth_stages/test_utils/
test_db.rs

1use alloy_primitives::{keccak256, Address, BlockNumber, TxHash, TxNumber, B256};
2use reth_chainspec::MAINNET;
3use reth_db::{
4    test_utils::{
5        create_test_rocksdb_dir, create_test_rw_db, create_test_rw_db_with_path,
6        create_test_static_files_dir,
7    },
8    DatabaseEnv,
9};
10use reth_db_api::{
11    common::KeyValue,
12    cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO},
13    database::Database,
14    models::{AccountBeforeTx, StorageBeforeTx, StoredBlockBodyIndices},
15    table::Table,
16    tables,
17    transaction::{DbTx, DbTxMut},
18    DatabaseError as DbError,
19};
20use reth_ethereum_primitives::{Block, EthPrimitives, Receipt};
21use reth_primitives_traits::{Account, SealedBlock, SealedHeader, StorageEntry};
22use reth_provider::{
23    providers::{
24        RocksDBProvider, StaticFileProvider, StaticFileProviderRWRefMut, StaticFileWriter,
25    },
26    test_utils::MockNodeTypesWithDB,
27    DatabaseProviderFactory, EitherWriter, HistoryWriter, ProviderError, ProviderFactory,
28    RocksBatchArg, StaticFileProviderFactory, StatsReader,
29};
30use reth_static_file_types::StaticFileSegment;
31use reth_storage_errors::provider::ProviderResult;
32use reth_storage_overlay::OverlayManager;
33use reth_testing_utils::generators::ChangeSet;
34use std::{collections::BTreeMap, fmt::Debug, path::Path};
35use tempfile::TempDir;
36
37/// Test database that is used for testing stage implementations.
38#[derive(Debug)]
39pub struct TestStageDB {
40    pub factory: ProviderFactory<MockNodeTypesWithDB>,
41    pub temp_static_files_dir: TempDir,
42    pub temp_rocksdb_dir: TempDir,
43}
44
45impl Default for TestStageDB {
46    /// Create a new instance of [`TestStageDB`]
47    fn default() -> Self {
48        let (static_dir, static_dir_path) = create_test_static_files_dir();
49        let (rocksdb_dir, rocksdb_dir_path) = create_test_rocksdb_dir();
50        Self {
51            temp_static_files_dir: static_dir,
52            temp_rocksdb_dir: rocksdb_dir,
53            factory: ProviderFactory::new(
54                create_test_rw_db(),
55                MAINNET.clone(),
56                StaticFileProvider::read_write(static_dir_path).unwrap(),
57                RocksDBProvider::builder(rocksdb_dir_path).with_default_tables().build().unwrap(),
58                OverlayManager::default(),
59                reth_tasks::Runtime::test(),
60            )
61            .expect("failed to create test provider factory"),
62        }
63    }
64}
65
66impl TestStageDB {
67    pub fn new(path: &Path) -> Self {
68        let (static_dir, static_dir_path) = create_test_static_files_dir();
69        let (rocksdb_dir, rocksdb_dir_path) = create_test_rocksdb_dir();
70
71        Self {
72            temp_static_files_dir: static_dir,
73            temp_rocksdb_dir: rocksdb_dir,
74            factory: ProviderFactory::new(
75                create_test_rw_db_with_path(path),
76                MAINNET.clone(),
77                StaticFileProvider::read_write(static_dir_path).unwrap(),
78                RocksDBProvider::builder(rocksdb_dir_path).with_default_tables().build().unwrap(),
79                OverlayManager::default(),
80                reth_tasks::Runtime::test(),
81            )
82            .expect("failed to create test provider factory"),
83        }
84    }
85
86    /// Invoke a callback with transaction committing it afterwards
87    pub fn commit<F>(&self, f: F) -> ProviderResult<()>
88    where
89        F: FnOnce(&<DatabaseEnv as Database>::TXMut) -> ProviderResult<()>,
90    {
91        let tx = self.factory.provider_rw()?;
92        f(tx.tx_ref())?;
93        tx.commit().expect("failed to commit");
94        Ok(())
95    }
96
97    /// Invoke a callback with a read transaction
98    pub fn query<F, Ok>(&self, f: F) -> ProviderResult<Ok>
99    where
100        F: FnOnce(&<DatabaseEnv as Database>::TX) -> ProviderResult<Ok>,
101    {
102        f(self.factory.provider()?.tx_ref())
103    }
104
105    /// Invoke a callback with a provider that can be used to create transactions or fetch from
106    /// static files.
107    pub fn query_with_provider<F, Ok>(&self, f: F) -> ProviderResult<Ok>
108    where
109        F: FnOnce(
110            <ProviderFactory<MockNodeTypesWithDB> as DatabaseProviderFactory>::Provider,
111        ) -> ProviderResult<Ok>,
112    {
113        f(self.factory.provider()?)
114    }
115
116    /// Invoke a callback with a writable provider, committing afterwards.
117    pub fn commit_with_provider<F>(&self, f: F) -> ProviderResult<()>
118    where
119        F: FnOnce(
120            &<ProviderFactory<MockNodeTypesWithDB> as DatabaseProviderFactory>::ProviderRW,
121        ) -> ProviderResult<()>,
122    {
123        let provider = self.factory.provider_rw()?;
124        f(&provider)?;
125        provider.commit().expect("failed to commit");
126        Ok(())
127    }
128
129    /// Check if the table is empty
130    pub fn table_is_empty<T: Table>(&self) -> ProviderResult<bool> {
131        self.query(|tx| {
132            let last = tx.cursor_read::<T>()?.last()?;
133            Ok(last.is_none())
134        })
135    }
136
137    /// Return full table as Vec
138    pub fn table<T: Table>(&self) -> ProviderResult<Vec<KeyValue<T>>>
139    where
140        T::Key: Default + Ord,
141    {
142        self.query(|tx| {
143            Ok(tx
144                .cursor_read::<T>()?
145                .walk(Some(T::Key::default()))?
146                .collect::<Result<Vec<_>, DbError>>()?)
147        })
148    }
149
150    /// Return the number of entries in the table or static file segment
151    pub fn count_entries<T: Table>(&self) -> ProviderResult<usize> {
152        self.factory.provider()?.count_entries::<T>()
153    }
154
155    /// Check that there is no table entry above a given
156    /// number by [`Table::Key`]
157    pub fn ensure_no_entry_above<T, F>(&self, num: u64, mut selector: F) -> ProviderResult<()>
158    where
159        T: Table,
160        F: FnMut(T::Key) -> BlockNumber,
161    {
162        self.query(|tx| {
163            let mut cursor = tx.cursor_read::<T>()?;
164            if let Some((key, _)) = cursor.last()? {
165                assert!(selector(key) <= num);
166            }
167            Ok(())
168        })
169    }
170
171    /// Check that there is no table entry above a given
172    /// number by [`Table::Value`]
173    pub fn ensure_no_entry_above_by_value<T, F>(
174        &self,
175        num: u64,
176        mut selector: F,
177    ) -> ProviderResult<()>
178    where
179        T: Table,
180        F: FnMut(T::Value) -> BlockNumber,
181    {
182        self.query(|tx| {
183            let mut cursor = tx.cursor_read::<T>()?;
184            let mut rev_walker = cursor.walk_back(None)?;
185            while let Some((_, value)) = rev_walker.next().transpose()? {
186                assert!(selector(value) <= num);
187            }
188            Ok(())
189        })
190    }
191
192    /// Insert header to static file if `writer` exists, otherwise to DB.
193    pub fn insert_header<TX: DbTx + DbTxMut>(
194        writer: Option<&mut StaticFileProviderRWRefMut<'_, EthPrimitives>>,
195        tx: &TX,
196        header: &SealedHeader,
197    ) -> ProviderResult<()> {
198        if let Some(writer) = writer {
199            // Backfill: some tests start at a forward block number, but static files require no
200            // gaps.
201            let segment_header = writer.user_header();
202            if segment_header.block_end().is_none() && segment_header.expected_block_start() == 0 {
203                for block_number in 0..header.number {
204                    let mut prev = header.clone_header();
205                    prev.number = block_number;
206                    writer.append_header(&prev, &B256::ZERO)?;
207                }
208            }
209
210            writer.append_header(header.header(), &header.hash())?;
211        } else {
212            tx.put::<tables::CanonicalHeaders>(header.number, header.hash())?;
213            tx.put::<tables::Headers>(header.number, header.header().clone())?;
214        }
215
216        tx.put::<tables::HeaderNumbers>(header.hash(), header.number)?;
217        Ok(())
218    }
219
220    fn insert_headers_inner<'a, I>(&self, headers: I) -> ProviderResult<()>
221    where
222        I: IntoIterator<Item = &'a SealedHeader>,
223    {
224        let provider = self.factory.static_file_provider();
225        let mut writer = provider.latest_writer(StaticFileSegment::Headers)?;
226        let tx = self.factory.provider_rw()?.into_tx();
227
228        for header in headers {
229            Self::insert_header(Some(&mut writer), &tx, header)?;
230        }
231
232        writer.commit()?;
233        tx.commit()?;
234
235        Ok(())
236    }
237
238    /// Insert ordered collection of [`SealedHeader`] into the corresponding static file and tables
239    /// that are supposed to be populated by the headers stage.
240    pub fn insert_headers<'a, I>(&self, headers: I) -> ProviderResult<()>
241    where
242        I: IntoIterator<Item = &'a SealedHeader>,
243    {
244        self.insert_headers_inner::<I>(headers)
245    }
246
247    /// Insert ordered collection of [`SealedBlock`] into corresponding tables.
248    /// Superset functionality of [`TestStageDB::insert_headers`].
249    ///
250    /// If `tx_offset` is set to `None`, then transactions will be stored on static files, otherwise
251    /// database.
252    ///
253    /// Assumes that there's a single transition for each transaction (i.e. no block rewards).
254    pub fn insert_blocks<'a, I>(&self, blocks: I, storage_kind: StorageKind) -> ProviderResult<()>
255    where
256        I: IntoIterator<Item = &'a SealedBlock<Block>>,
257    {
258        let provider = self.factory.static_file_provider();
259
260        let tx = self.factory.provider_rw().unwrap().into_tx();
261        let mut next_tx_num = storage_kind.tx_offset();
262
263        let blocks = blocks.into_iter().collect::<Vec<_>>();
264
265        {
266            let mut headers_writer = storage_kind
267                .is_static()
268                .then(|| provider.latest_writer(StaticFileSegment::Headers).unwrap());
269
270            blocks.iter().try_for_each(|block| {
271                Self::insert_header(headers_writer.as_mut(), &tx, block.sealed_header())
272            })?;
273
274            if let Some(mut writer) = headers_writer {
275                writer.commit()?;
276            }
277        }
278
279        {
280            let mut txs_writer = storage_kind
281                .is_static()
282                .then(|| provider.latest_writer(StaticFileSegment::Transactions).unwrap());
283
284            blocks.into_iter().try_for_each(|block| {
285                // Insert into body tables.
286                let block_body_indices = StoredBlockBodyIndices {
287                    first_tx_num: next_tx_num,
288                    tx_count: block.transaction_count() as u64,
289                };
290
291                if !block.body().transactions.is_empty() {
292                    tx.put::<tables::TransactionBlocks>(
293                        block_body_indices.last_tx_num(),
294                        block.number,
295                    )?;
296                }
297                tx.put::<tables::BlockBodyIndices>(block.number, block_body_indices)?;
298
299                let res = block.body().transactions.iter().try_for_each(|body_tx| {
300                    if let Some(txs_writer) = &mut txs_writer {
301                        txs_writer.append_transaction(next_tx_num, body_tx)?;
302                    } else {
303                        tx.put::<tables::Transactions>(next_tx_num, body_tx.clone())?
304                    }
305                    next_tx_num += 1;
306                    Ok::<(), ProviderError>(())
307                });
308
309                if let Some(txs_writer) = &mut txs_writer {
310                    // Backfill: some tests start at a forward block number, but static files
311                    // require no gaps.
312                    let segment_header = txs_writer.user_header();
313                    if segment_header.block_end().is_none() &&
314                        segment_header.expected_block_start() == 0
315                    {
316                        for block in 0..block.number {
317                            txs_writer.increment_block(block)?;
318                        }
319                    }
320                    txs_writer.increment_block(block.number)?;
321                }
322                res
323            })?;
324
325            if let Some(txs_writer) = &mut txs_writer {
326                txs_writer.commit()?;
327            }
328        }
329
330        tx.commit()?;
331
332        Ok(())
333    }
334
335    pub fn insert_tx_hash_numbers<I>(&self, tx_hash_numbers: I) -> ProviderResult<()>
336    where
337        I: IntoIterator<Item = (TxHash, TxNumber)>,
338    {
339        self.commit_with_provider(|provider| {
340            provider.with_rocksdb_batch(|batch: RocksBatchArg<'_>| {
341                let mut writer = EitherWriter::new_transaction_hash_numbers(provider, batch)?;
342                for (tx_hash, tx_num) in tx_hash_numbers {
343                    writer.put_transaction_hash_number(tx_hash, tx_num, false)?;
344                }
345                Ok(((), writer.into_raw_rocksdb_batch()))
346            })
347        })
348    }
349
350    /// Insert collection of ([`TxNumber`], [Receipt]) into the corresponding table.
351    pub fn insert_receipts<I>(&self, receipts: I) -> ProviderResult<()>
352    where
353        I: IntoIterator<Item = (TxNumber, Receipt)>,
354    {
355        self.commit(|tx| {
356            receipts.into_iter().try_for_each(|(tx_num, receipt)| {
357                // Insert into receipts table.
358                Ok(tx.put::<tables::Receipts>(tx_num, receipt)?)
359            })
360        })
361    }
362
363    /// Insert collection of ([`TxNumber`], [Receipt]) organized by respective block numbers into
364    /// the corresponding table or static file segment.
365    pub fn insert_receipts_by_block<I, J>(
366        &self,
367        receipts: I,
368        storage_kind: StorageKind,
369    ) -> ProviderResult<()>
370    where
371        I: IntoIterator<Item = (BlockNumber, J)>,
372        J: IntoIterator<Item = (TxNumber, Receipt)>,
373    {
374        match storage_kind {
375            StorageKind::Database(_) => self.commit(|tx| {
376                receipts.into_iter().try_for_each(|(_, receipts)| {
377                    for (tx_num, receipt) in receipts {
378                        tx.put::<tables::Receipts>(tx_num, receipt)?;
379                    }
380                    Ok(())
381                })
382            }),
383            StorageKind::Static => {
384                let provider = self.factory.static_file_provider();
385                let mut writer = provider.latest_writer(StaticFileSegment::Receipts)?;
386                let res = receipts.into_iter().try_for_each(|(block_num, receipts)| {
387                    writer.increment_block(block_num)?;
388                    writer.append_receipts(receipts.into_iter().map(Ok))?;
389                    Ok(())
390                });
391                writer.commit_without_sync_all()?;
392                res
393            }
394        }
395    }
396
397    pub fn insert_transaction_senders<I>(&self, transaction_senders: I) -> ProviderResult<()>
398    where
399        I: IntoIterator<Item = (TxNumber, Address)>,
400    {
401        self.commit(|tx| {
402            transaction_senders.into_iter().try_for_each(|(tx_num, sender)| {
403                // Insert into receipts table.
404                Ok(tx.put::<tables::TransactionSenders>(tx_num, sender)?)
405            })
406        })
407    }
408
409    /// Insert collection of ([Address], [Account]) into corresponding tables.
410    #[allow(clippy::clone_on_copy)]
411    pub fn insert_accounts_and_storages<I, S>(&self, accounts: I) -> ProviderResult<()>
412    where
413        I: IntoIterator<Item = (Address, (Account, S))>,
414        S: IntoIterator<Item = StorageEntry>,
415    {
416        self.commit(|tx| {
417            accounts.into_iter().try_for_each(|(address, (account, storage))| {
418                let hashed_address = keccak256(address);
419
420                // Insert into account tables.
421                tx.put::<tables::PlainAccountState>(address, account.clone())?;
422                tx.put::<tables::HashedAccounts>(hashed_address, account)?;
423
424                // Insert into storage tables.
425                storage.into_iter().filter(|e| !e.value.is_zero()).try_for_each(|entry| {
426                    let hashed_entry = StorageEntry { key: keccak256(entry.key), ..entry };
427
428                    let mut cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
429                    if cursor
430                        .seek_by_key_subkey(address, entry.key)?
431                        .is_some_and(|e| e.key == entry.key)
432                    {
433                        cursor.delete_current()?;
434                    }
435                    cursor.upsert(address, &entry)?;
436
437                    let mut cursor = tx.cursor_dup_write::<tables::HashedStorages>()?;
438                    if cursor
439                        .seek_by_key_subkey(hashed_address, hashed_entry.key)?
440                        .is_some_and(|e| e.key == hashed_entry.key)
441                    {
442                        cursor.delete_current()?;
443                    }
444                    cursor.upsert(hashed_address, &hashed_entry)?;
445
446                    Ok(())
447                })
448            })
449        })
450    }
451
452    /// Insert collection of [`ChangeSet`] into corresponding tables.
453    pub fn insert_changesets<I>(
454        &self,
455        changesets: I,
456        block_offset: Option<u64>,
457    ) -> ProviderResult<()>
458    where
459        I: IntoIterator<Item = ChangeSet>,
460    {
461        let offset = block_offset.unwrap_or_default();
462        self.commit(|tx| {
463            changesets.into_iter().enumerate().try_for_each(|(block, changeset)| {
464                changeset.into_iter().try_for_each(|(address, old_account, old_storage)| {
465                    let block = offset + block as u64;
466                    // Insert into account changeset.
467                    tx.put::<tables::AccountChangeSets>(
468                        block,
469                        AccountBeforeTx { address, info: Some(old_account) },
470                    )?;
471
472                    let block_address = (block, address).into();
473
474                    // Insert into storage changeset.
475                    old_storage.into_iter().try_for_each(|entry| {
476                        Ok(tx.put::<tables::StorageChangeSets>(block_address, entry)?)
477                    })
478                })
479            })
480        })
481    }
482
483    /// Insert collection of [`ChangeSet`] into static files (account and storage changesets).
484    pub fn insert_changesets_to_static_files<I>(
485        &self,
486        changesets: I,
487        block_offset: Option<u64>,
488    ) -> ProviderResult<()>
489    where
490        I: IntoIterator<Item = ChangeSet>,
491    {
492        let offset = block_offset.unwrap_or_default();
493        let static_file_provider = self.factory.static_file_provider();
494
495        let mut account_changeset_writer =
496            static_file_provider.latest_writer(StaticFileSegment::AccountChangeSets)?;
497        let mut storage_changeset_writer =
498            static_file_provider.latest_writer(StaticFileSegment::StorageChangeSets)?;
499
500        for (block, changeset) in changesets.into_iter().enumerate() {
501            let block_number = offset + block as u64;
502
503            let mut account_changesets = Vec::new();
504            let mut storage_changesets = Vec::new();
505
506            for (address, old_account, old_storage) in changeset {
507                account_changesets.push(AccountBeforeTx { address, info: Some(old_account) });
508
509                for entry in old_storage {
510                    storage_changesets.push(StorageBeforeTx {
511                        address,
512                        key: entry.key,
513                        value: entry.value,
514                    });
515                }
516            }
517
518            account_changeset_writer.append_account_changeset(account_changesets, block_number)?;
519            storage_changeset_writer.append_storage_changeset(storage_changesets, block_number)?;
520        }
521
522        account_changeset_writer.commit()?;
523        storage_changeset_writer.commit()?;
524
525        Ok(())
526    }
527
528    pub fn insert_history<I>(&self, changesets: I, _block_offset: Option<u64>) -> ProviderResult<()>
529    where
530        I: IntoIterator<Item = ChangeSet>,
531    {
532        let mut accounts = BTreeMap::<Address, Vec<u64>>::new();
533        let mut storages = BTreeMap::<(Address, B256), Vec<u64>>::new();
534
535        for (block, changeset) in changesets.into_iter().enumerate() {
536            for (address, _, storage_entries) in changeset {
537                accounts.entry(address).or_default().push(block as u64);
538                for storage_entry in storage_entries {
539                    storages.entry((address, storage_entry.key)).or_default().push(block as u64);
540                }
541            }
542        }
543
544        let provider_rw = self.factory.provider_rw()?;
545        provider_rw.insert_account_history_index(accounts)?;
546        provider_rw.insert_storage_history_index(storages)?;
547        provider_rw.commit()?;
548
549        Ok(())
550    }
551}
552
553/// Used to identify where to store data when setting up a test.
554#[derive(Debug)]
555pub enum StorageKind {
556    Database(Option<u64>),
557    Static,
558}
559
560impl StorageKind {
561    #[expect(dead_code)]
562    const fn is_database(&self) -> bool {
563        matches!(self, Self::Database(_))
564    }
565
566    const fn is_static(&self) -> bool {
567        matches!(self, Self::Static)
568    }
569
570    fn tx_offset(&self) -> u64 {
571        if let Self::Database(offset) = self {
572            return offset.unwrap_or_default();
573        }
574        0
575    }
576}