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