reth_stages/test_utils/
test_db.rs

1use alloy_primitives::{keccak256, Address, BlockNumber, TxHash, TxNumber, B256, U256};
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,
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    /// Check that there is no table entry above a given
107    /// number by [`Table::Key`]
108    pub fn ensure_no_entry_above<T, F>(&self, num: u64, mut selector: F) -> ProviderResult<()>
109    where
110        T: Table,
111        F: FnMut(T::Key) -> BlockNumber,
112    {
113        self.query(|tx| {
114            let mut cursor = tx.cursor_read::<T>()?;
115            if let Some((key, _)) = cursor.last()? {
116                assert!(selector(key) <= num);
117            }
118            Ok(())
119        })
120    }
121
122    /// Check that there is no table entry above a given
123    /// number by [`Table::Value`]
124    pub fn ensure_no_entry_above_by_value<T, F>(
125        &self,
126        num: u64,
127        mut selector: F,
128    ) -> ProviderResult<()>
129    where
130        T: Table,
131        F: FnMut(T::Value) -> BlockNumber,
132    {
133        self.query(|tx| {
134            let mut cursor = tx.cursor_read::<T>()?;
135            let mut rev_walker = cursor.walk_back(None)?;
136            while let Some((_, value)) = rev_walker.next().transpose()? {
137                assert!(selector(value) <= num);
138            }
139            Ok(())
140        })
141    }
142
143    /// Insert header to static file if `writer` exists, otherwise to DB.
144    pub fn insert_header<TX: DbTx + DbTxMut>(
145        writer: Option<&mut StaticFileProviderRWRefMut<'_, EthPrimitives>>,
146        tx: &TX,
147        header: &SealedHeader,
148        td: U256,
149    ) -> ProviderResult<()> {
150        if let Some(writer) = writer {
151            // Backfill: some tests start at a forward block number, but static files require no
152            // gaps.
153            let segment_header = writer.user_header();
154            if segment_header.block_end().is_none() && segment_header.expected_block_start() == 0 {
155                for block_number in 0..header.number {
156                    let mut prev = header.clone_header();
157                    prev.number = block_number;
158                    writer.append_header(&prev, U256::ZERO, &B256::ZERO)?;
159                }
160            }
161
162            writer.append_header(header.header(), td, &header.hash())?;
163        } else {
164            tx.put::<tables::CanonicalHeaders>(header.number, header.hash())?;
165            tx.put::<tables::HeaderTerminalDifficulties>(header.number, td.into())?;
166            tx.put::<tables::Headers>(header.number, header.header().clone())?;
167        }
168
169        tx.put::<tables::HeaderNumbers>(header.hash(), header.number)?;
170        Ok(())
171    }
172
173    fn insert_headers_inner<'a, I, const TD: bool>(&self, headers: I) -> ProviderResult<()>
174    where
175        I: IntoIterator<Item = &'a SealedHeader>,
176    {
177        let provider = self.factory.static_file_provider();
178        let mut writer = provider.latest_writer(StaticFileSegment::Headers)?;
179        let tx = self.factory.provider_rw()?.into_tx();
180        let mut td = U256::ZERO;
181
182        for header in headers {
183            if TD {
184                td += header.difficulty;
185            }
186            Self::insert_header(Some(&mut writer), &tx, header, td)?;
187        }
188
189        writer.commit()?;
190        tx.commit()?;
191
192        Ok(())
193    }
194
195    /// Insert ordered collection of [`SealedHeader`] into the corresponding static file and tables
196    /// that are supposed to be populated by the headers stage.
197    pub fn insert_headers<'a, I>(&self, headers: I) -> ProviderResult<()>
198    where
199        I: IntoIterator<Item = &'a SealedHeader>,
200    {
201        self.insert_headers_inner::<I, false>(headers)
202    }
203
204    /// Inserts total difficulty of headers into the corresponding static file and tables.
205    ///
206    /// Superset functionality of [`TestStageDB::insert_headers`].
207    pub fn insert_headers_with_td<'a, I>(&self, headers: I) -> ProviderResult<()>
208    where
209        I: IntoIterator<Item = &'a SealedHeader>,
210    {
211        self.insert_headers_inner::<I, true>(headers)
212    }
213
214    /// Insert ordered collection of [`SealedBlock`] into corresponding tables.
215    /// Superset functionality of [`TestStageDB::insert_headers`].
216    ///
217    /// If `tx_offset` is set to `None`, then transactions will be stored on static files, otherwise
218    /// database.
219    ///
220    /// Assumes that there's a single transition for each transaction (i.e. no block rewards).
221    pub fn insert_blocks<'a, I>(&self, blocks: I, storage_kind: StorageKind) -> ProviderResult<()>
222    where
223        I: IntoIterator<Item = &'a SealedBlock<Block>>,
224    {
225        let provider = self.factory.static_file_provider();
226
227        let tx = self.factory.provider_rw().unwrap().into_tx();
228        let mut next_tx_num = storage_kind.tx_offset();
229
230        let blocks = blocks.into_iter().collect::<Vec<_>>();
231
232        {
233            let mut headers_writer = storage_kind
234                .is_static()
235                .then(|| provider.latest_writer(StaticFileSegment::Headers).unwrap());
236
237            blocks.iter().try_for_each(|block| {
238                Self::insert_header(headers_writer.as_mut(), &tx, block.sealed_header(), U256::ZERO)
239            })?;
240
241            if let Some(mut writer) = headers_writer {
242                writer.commit()?;
243            }
244        }
245
246        {
247            let mut txs_writer = storage_kind
248                .is_static()
249                .then(|| provider.latest_writer(StaticFileSegment::Transactions).unwrap());
250
251            blocks.into_iter().try_for_each(|block| {
252                // Insert into body tables.
253                let block_body_indices = StoredBlockBodyIndices {
254                    first_tx_num: next_tx_num,
255                    tx_count: block.transaction_count() as u64,
256                };
257
258                if !block.body().transactions.is_empty() {
259                    tx.put::<tables::TransactionBlocks>(
260                        block_body_indices.last_tx_num(),
261                        block.number,
262                    )?;
263                }
264                tx.put::<tables::BlockBodyIndices>(block.number, block_body_indices)?;
265
266                let res = block.body().transactions.iter().try_for_each(|body_tx| {
267                    if let Some(txs_writer) = &mut txs_writer {
268                        txs_writer.append_transaction(next_tx_num, body_tx)?;
269                    } else {
270                        tx.put::<tables::Transactions>(next_tx_num, body_tx.clone())?
271                    }
272                    next_tx_num += 1;
273                    Ok::<(), ProviderError>(())
274                });
275
276                if let Some(txs_writer) = &mut txs_writer {
277                    // Backfill: some tests start at a forward block number, but static files
278                    // require no gaps.
279                    let segment_header = txs_writer.user_header();
280                    if segment_header.block_end().is_none() &&
281                        segment_header.expected_block_start() == 0
282                    {
283                        for block in 0..block.number {
284                            txs_writer.increment_block(block)?;
285                        }
286                    }
287                    txs_writer.increment_block(block.number)?;
288                }
289                res
290            })?;
291
292            if let Some(txs_writer) = &mut txs_writer {
293                txs_writer.commit()?;
294            }
295        }
296
297        tx.commit()?;
298
299        Ok(())
300    }
301
302    pub fn insert_tx_hash_numbers<I>(&self, tx_hash_numbers: I) -> ProviderResult<()>
303    where
304        I: IntoIterator<Item = (TxHash, TxNumber)>,
305    {
306        self.commit(|tx| {
307            tx_hash_numbers.into_iter().try_for_each(|(tx_hash, tx_num)| {
308                // Insert into tx hash numbers table.
309                Ok(tx.put::<tables::TransactionHashNumbers>(tx_hash, tx_num)?)
310            })
311        })
312    }
313
314    /// Insert collection of ([`TxNumber`], [Receipt]) into the corresponding table.
315    pub fn insert_receipts<I>(&self, receipts: I) -> ProviderResult<()>
316    where
317        I: IntoIterator<Item = (TxNumber, Receipt)>,
318    {
319        self.commit(|tx| {
320            receipts.into_iter().try_for_each(|(tx_num, receipt)| {
321                // Insert into receipts table.
322                Ok(tx.put::<tables::Receipts>(tx_num, receipt)?)
323            })
324        })
325    }
326
327    /// Insert collection of ([`TxNumber`], [Receipt]) organized by respective block numbers into
328    /// the corresponding table or static file segment.
329    pub fn insert_receipts_by_block<I, J>(
330        &self,
331        receipts: I,
332        storage_kind: StorageKind,
333    ) -> ProviderResult<()>
334    where
335        I: IntoIterator<Item = (BlockNumber, J)>,
336        J: IntoIterator<Item = (TxNumber, Receipt)>,
337    {
338        match storage_kind {
339            StorageKind::Database(_) => self.commit(|tx| {
340                receipts.into_iter().try_for_each(|(_, receipts)| {
341                    for (tx_num, receipt) in receipts {
342                        tx.put::<tables::Receipts>(tx_num, receipt)?;
343                    }
344                    Ok(())
345                })
346            }),
347            StorageKind::Static => {
348                let provider = self.factory.static_file_provider();
349                let mut writer = provider.latest_writer(StaticFileSegment::Receipts)?;
350                let res = receipts.into_iter().try_for_each(|(block_num, receipts)| {
351                    writer.increment_block(block_num)?;
352                    writer.append_receipts(receipts.into_iter().map(Ok))?;
353                    Ok(())
354                });
355                writer.commit_without_sync_all()?;
356                res
357            }
358        }
359    }
360
361    pub fn insert_transaction_senders<I>(&self, transaction_senders: I) -> ProviderResult<()>
362    where
363        I: IntoIterator<Item = (TxNumber, Address)>,
364    {
365        self.commit(|tx| {
366            transaction_senders.into_iter().try_for_each(|(tx_num, sender)| {
367                // Insert into receipts table.
368                Ok(tx.put::<tables::TransactionSenders>(tx_num, sender)?)
369            })
370        })
371    }
372
373    /// Insert collection of ([Address], [Account]) into corresponding tables.
374    pub fn insert_accounts_and_storages<I, S>(&self, accounts: I) -> ProviderResult<()>
375    where
376        I: IntoIterator<Item = (Address, (Account, S))>,
377        S: IntoIterator<Item = StorageEntry>,
378    {
379        self.commit(|tx| {
380            accounts.into_iter().try_for_each(|(address, (account, storage))| {
381                let hashed_address = keccak256(address);
382
383                // Insert into account tables.
384                tx.put::<tables::PlainAccountState>(address, account)?;
385                tx.put::<tables::HashedAccounts>(hashed_address, account)?;
386
387                // Insert into storage tables.
388                storage.into_iter().filter(|e| !e.value.is_zero()).try_for_each(|entry| {
389                    let hashed_entry = StorageEntry { key: keccak256(entry.key), ..entry };
390
391                    let mut cursor = tx.cursor_dup_write::<tables::PlainStorageState>()?;
392                    if cursor
393                        .seek_by_key_subkey(address, entry.key)?
394                        .filter(|e| e.key == entry.key)
395                        .is_some()
396                    {
397                        cursor.delete_current()?;
398                    }
399                    cursor.upsert(address, &entry)?;
400
401                    let mut cursor = tx.cursor_dup_write::<tables::HashedStorages>()?;
402                    if cursor
403                        .seek_by_key_subkey(hashed_address, hashed_entry.key)?
404                        .filter(|e| e.key == hashed_entry.key)
405                        .is_some()
406                    {
407                        cursor.delete_current()?;
408                    }
409                    cursor.upsert(hashed_address, &hashed_entry)?;
410
411                    Ok(())
412                })
413            })
414        })
415    }
416
417    /// Insert collection of [`ChangeSet`] into corresponding tables.
418    pub fn insert_changesets<I>(
419        &self,
420        changesets: I,
421        block_offset: Option<u64>,
422    ) -> ProviderResult<()>
423    where
424        I: IntoIterator<Item = ChangeSet>,
425    {
426        let offset = block_offset.unwrap_or_default();
427        self.commit(|tx| {
428            changesets.into_iter().enumerate().try_for_each(|(block, changeset)| {
429                changeset.into_iter().try_for_each(|(address, old_account, old_storage)| {
430                    let block = offset + block as u64;
431                    // Insert into account changeset.
432                    tx.put::<tables::AccountChangeSets>(
433                        block,
434                        AccountBeforeTx { address, info: Some(old_account) },
435                    )?;
436
437                    let block_address = (block, address).into();
438
439                    // Insert into storage changeset.
440                    old_storage.into_iter().try_for_each(|entry| {
441                        Ok(tx.put::<tables::StorageChangeSets>(block_address, entry)?)
442                    })
443                })
444            })
445        })
446    }
447
448    pub fn insert_history<I>(&self, changesets: I, _block_offset: Option<u64>) -> ProviderResult<()>
449    where
450        I: IntoIterator<Item = ChangeSet>,
451    {
452        let mut accounts = BTreeMap::<Address, Vec<u64>>::new();
453        let mut storages = BTreeMap::<(Address, B256), Vec<u64>>::new();
454
455        for (block, changeset) in changesets.into_iter().enumerate() {
456            for (address, _, storage_entries) in changeset {
457                accounts.entry(address).or_default().push(block as u64);
458                for storage_entry in storage_entries {
459                    storages.entry((address, storage_entry.key)).or_default().push(block as u64);
460                }
461            }
462        }
463
464        let provider_rw = self.factory.provider_rw()?;
465        provider_rw.insert_account_history_index(accounts)?;
466        provider_rw.insert_storage_history_index(storages)?;
467        provider_rw.commit()?;
468
469        Ok(())
470    }
471}
472
473/// Used to identify where to store data when setting up a test.
474#[derive(Debug)]
475pub enum StorageKind {
476    Database(Option<u64>),
477    Static,
478}
479
480impl StorageKind {
481    #[allow(dead_code)]
482    const fn is_database(&self) -> bool {
483        matches!(self, Self::Database(_))
484    }
485
486    const fn is_static(&self) -> bool {
487        matches!(self, Self::Static)
488    }
489
490    fn tx_offset(&self) -> u64 {
491        if let Self::Database(offset) = self {
492            return offset.unwrap_or_default();
493        }
494        0
495    }
496}