reth_db_api/tables/
mod.rs

1//! Tables and data models.
2//!
3//! # Overview
4//!
5//! This module defines the tables in reth, as well as some table-related abstractions:
6//!
7//! - [`codecs`] integrates different codecs into [`Encode`] and [`Decode`]
8//! - [`models`](crate::models) defines the values written to tables
9//!
10//! # Database Tour
11//!
12//! TODO(onbjerg): Find appropriate format for this...
13
14pub mod codecs;
15
16mod raw;
17pub use raw::{RawDupSort, RawKey, RawTable, RawValue, TableRawRow};
18
19use crate::{
20    models::{
21        accounts::BlockNumberAddress,
22        blocks::{HeaderHash, StoredBlockOmmers},
23        storage_sharded_key::StorageShardedKey,
24        AccountBeforeTx, ClientVersion, CompactU256, IntegerList, ShardedKey,
25        StoredBlockBodyIndices, StoredBlockWithdrawals,
26    },
27    table::{Decode, DupSort, Encode, Table, TableInfo},
28};
29use alloy_consensus::Header;
30use alloy_primitives::{Address, BlockHash, BlockNumber, TxHash, TxNumber, B256};
31use reth_ethereum_primitives::{Receipt, TransactionSigned};
32use reth_primitives_traits::{Account, Bytecode, StorageEntry};
33use reth_prune_types::{PruneCheckpoint, PruneSegment};
34use reth_stages_types::StageCheckpoint;
35use reth_trie_common::{BranchNodeCompact, StorageTrieEntry, StoredNibbles, StoredNibblesSubKey};
36use serde::{Deserialize, Serialize};
37use std::fmt;
38
39/// Enum for the types of tables present in libmdbx.
40#[derive(Debug, PartialEq, Eq, Copy, Clone)]
41pub enum TableType {
42    /// key value table
43    Table,
44    /// Duplicate key value table
45    DupSort,
46}
47
48/// The general purpose of this is to use with a combination of Tables enum,
49/// by implementing a `TableViewer` trait you can operate on db tables in an abstract way.
50///
51/// # Example
52///
53/// ```
54/// use reth_db_api::{
55///     table::{DupSort, Table},
56///     TableViewer, Tables,
57/// };
58///
59/// struct MyTableViewer;
60///
61/// impl TableViewer<()> for MyTableViewer {
62///     type Error = &'static str;
63///
64///     fn view<T: Table>(&self) -> Result<(), Self::Error> {
65///         // operate on table in a generic way
66///         Ok(())
67///     }
68///
69///     fn view_dupsort<T: DupSort>(&self) -> Result<(), Self::Error> {
70///         // operate on a dupsort table in a generic way
71///         Ok(())
72///     }
73/// }
74///
75/// let viewer = MyTableViewer {};
76///
77/// let _ = Tables::Headers.view(&viewer);
78/// let _ = Tables::Transactions.view(&viewer);
79/// ```
80pub trait TableViewer<R> {
81    /// The error type returned by the viewer.
82    type Error;
83
84    /// Calls `view` with the correct table type.
85    fn view_rt(&self, table: Tables) -> Result<R, Self::Error> {
86        table.view(self)
87    }
88
89    /// Operate on the table in a generic way.
90    fn view<T: Table>(&self) -> Result<R, Self::Error>;
91
92    /// Operate on the dupsort table in a generic way.
93    ///
94    /// By default, the `view` function is invoked unless overridden.
95    fn view_dupsort<T: DupSort>(&self) -> Result<R, Self::Error> {
96        self.view::<T>()
97    }
98}
99
100/// General trait for defining the set of tables
101/// Used to initialize database
102pub trait TableSet {
103    /// Returns an iterator over the tables
104    fn tables() -> Box<dyn Iterator<Item = Box<dyn TableInfo>>>;
105}
106
107/// Defines all the tables in the database.
108#[macro_export]
109macro_rules! tables {
110    (@bool) => { false };
111    (@bool $($t:tt)+) => { true };
112
113    (@view $name:ident $v:ident) => { $v.view::<$name>() };
114    (@view $name:ident $v:ident $_subkey:ty) => { $v.view_dupsort::<$name>() };
115
116    (@value_doc $key:ty, $value:ty) => {
117        concat!("[`", stringify!($value), "`]")
118    };
119    // Don't generate links if we have generics
120    (@value_doc $key:ty, $value:ty, $($generic:ident),*) => {
121        concat!("`", stringify!($value), "`")
122    };
123
124    ($($(#[$attr:meta])* table $name:ident$(<$($generic:ident $(= $default:ty)?),*>)? { type Key = $key:ty; type Value = $value:ty; $(type SubKey = $subkey:ty;)? } )*) => {
125        // Table marker types.
126        $(
127            $(#[$attr])*
128            ///
129            #[doc = concat!("Marker type representing a database table mapping [`", stringify!($key), "`] to ", tables!(@value_doc $key, $value, $($($generic),*)?), ".")]
130            $(
131                #[doc = concat!("\n\nThis table's `DUPSORT` subkey is [`", stringify!($subkey), "`].")]
132            )?
133            pub struct $name$(<$($generic $( = $default)?),*>)? {
134                _private: std::marker::PhantomData<($($($generic,)*)?)>,
135            }
136
137            // Ideally this implementation wouldn't exist, but it is necessary to derive `Debug`
138            // when a type is generic over `T: Table`. See: https://github.com/rust-lang/rust/issues/26925
139            impl$(<$($generic),*>)? fmt::Debug for $name$(<$($generic),*>)? {
140                fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
141                    unreachable!("this type cannot be instantiated")
142                }
143            }
144
145            impl$(<$($generic),*>)? $crate::table::Table for $name$(<$($generic),*>)?
146            where
147                $value: $crate::table::Value + 'static
148                $($(,$generic: Send + Sync)*)?
149            {
150                const NAME: &'static str = table_names::$name;
151                const DUPSORT: bool = tables!(@bool $($subkey)?);
152
153                type Key = $key;
154                type Value = $value;
155            }
156
157            $(
158                impl DupSort for $name {
159                    type SubKey = $subkey;
160                }
161            )?
162        )*
163
164        // Tables enum.
165
166        /// A table in the database.
167        #[derive(Clone, Copy, PartialEq, Eq, Hash)]
168        pub enum Tables {
169            $(
170                #[doc = concat!("The [`", stringify!($name), "`] database table.")]
171                $name,
172            )*
173        }
174
175        impl Tables {
176            /// All the tables in the database.
177            pub const ALL: &'static [Self] = &[$(Self::$name,)*];
178
179            /// The number of tables in the database.
180            pub const COUNT: usize = Self::ALL.len();
181
182            /// Returns the name of the table as a string.
183            pub const fn name(&self) -> &'static str {
184                match self {
185                    $(
186                        Self::$name => table_names::$name,
187                    )*
188                }
189            }
190
191            /// Returns `true` if the table is a `DUPSORT` table.
192            pub const fn is_dupsort(&self) -> bool {
193                match self {
194                    $(
195                        Self::$name => tables!(@bool $($subkey)?),
196                    )*
197                }
198            }
199
200            /// The type of the given table in database.
201            pub const fn table_type(&self) -> TableType {
202                if self.is_dupsort() {
203                    TableType::DupSort
204                } else {
205                    TableType::Table
206                }
207            }
208
209            /// Allows to operate on specific table type
210            pub fn view<T, R>(&self, visitor: &T) -> Result<R, T::Error>
211            where
212                T: ?Sized + TableViewer<R>,
213            {
214                match self {
215                    $(
216                        Self::$name => tables!(@view $name visitor $($subkey)?),
217                    )*
218                }
219            }
220        }
221
222        impl fmt::Debug for Tables {
223            #[inline]
224            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225                f.write_str(self.name())
226            }
227        }
228
229        impl fmt::Display for Tables {
230            #[inline]
231            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232                self.name().fmt(f)
233            }
234        }
235
236        impl std::str::FromStr for Tables {
237            type Err = String;
238
239            fn from_str(s: &str) -> Result<Self, Self::Err> {
240                match s {
241                    $(
242                        table_names::$name => Ok(Self::$name),
243                    )*
244                    s => Err(format!("unknown table: {s:?}")),
245                }
246            }
247        }
248
249        impl TableInfo for Tables {
250            fn name(&self) -> &'static str {
251                self.name()
252            }
253
254            fn is_dupsort(&self) -> bool {
255                self.is_dupsort()
256            }
257        }
258
259        impl TableSet for Tables {
260            fn tables() -> Box<dyn Iterator<Item = Box<dyn TableInfo>>> {
261                Box::new(Self::ALL.iter().map(|table| Box::new(*table) as Box<dyn TableInfo>))
262            }
263        }
264
265        // Need constants to match on in the `FromStr` implementation.
266        #[expect(non_upper_case_globals)]
267        mod table_names {
268            $(
269                pub(super) const $name: &'static str = stringify!($name);
270            )*
271        }
272
273        /// Maps a run-time [`Tables`] enum value to its corresponding compile-time [`Table`] type.
274        ///
275        /// This is a simpler alternative to [`TableViewer`].
276        ///
277        /// # Examples
278        ///
279        /// ```
280        /// use reth_db_api::{table::Table, Tables, tables_to_generic};
281        ///
282        /// let table = Tables::Headers;
283        /// let result = tables_to_generic!(table, |GenericTable| <GenericTable as Table>::NAME);
284        /// assert_eq!(result, table.name());
285        /// ```
286        #[macro_export]
287        macro_rules! tables_to_generic {
288            ($table:expr, |$generic_name:ident| $e:expr) => {
289                match $table {
290                    $(
291                        Tables::$name => {
292                            use $crate::tables::$name as $generic_name;
293                            $e
294                        },
295                    )*
296                }
297            };
298        }
299    };
300}
301
302tables! {
303    /// Stores the header hashes belonging to the canonical chain.
304    table CanonicalHeaders {
305        type Key = BlockNumber;
306        type Value = HeaderHash;
307    }
308
309    /// Stores the total difficulty from a block header.
310    table HeaderTerminalDifficulties {
311        type Key = BlockNumber;
312        type Value = CompactU256;
313    }
314
315    /// Stores the block number corresponding to a header.
316    table HeaderNumbers {
317        type Key = BlockHash;
318        type Value = BlockNumber;
319    }
320
321    /// Stores header bodies.
322    table Headers<H = Header> {
323        type Key = BlockNumber;
324        type Value = H;
325    }
326
327    /// Stores block indices that contains indexes of transaction and the count of them.
328    ///
329    /// More information about stored indices can be found in the [`StoredBlockBodyIndices`] struct.
330    table BlockBodyIndices {
331        type Key = BlockNumber;
332        type Value = StoredBlockBodyIndices;
333    }
334
335    /// Stores the uncles/ommers of the block.
336    table BlockOmmers<H = Header> {
337        type Key = BlockNumber;
338        type Value = StoredBlockOmmers<H>;
339    }
340
341    /// Stores the block withdrawals.
342    table BlockWithdrawals {
343        type Key = BlockNumber;
344        type Value = StoredBlockWithdrawals;
345    }
346
347    /// Canonical only Stores the transaction body for canonical transactions.
348    table Transactions<T = TransactionSigned> {
349        type Key = TxNumber;
350        type Value = T;
351    }
352
353    /// Stores the mapping of the transaction hash to the transaction number.
354    table TransactionHashNumbers {
355        type Key = TxHash;
356        type Value = TxNumber;
357    }
358
359    /// Stores the mapping of transaction number to the blocks number.
360    ///
361    /// The key is the highest transaction ID in the block.
362    table TransactionBlocks {
363        type Key = TxNumber;
364        type Value = BlockNumber;
365    }
366
367    /// Canonical only Stores transaction receipts.
368    table Receipts<R = Receipt> {
369        type Key = TxNumber;
370        type Value = R;
371    }
372
373    /// Stores all smart contract bytecodes.
374    /// There will be multiple accounts that have same bytecode
375    /// So we would need to introduce reference counter.
376    /// This will be small optimization on state.
377    table Bytecodes {
378        type Key = B256;
379        type Value = Bytecode;
380    }
381
382    /// Stores the current state of an [`Account`].
383    table PlainAccountState {
384        type Key = Address;
385        type Value = Account;
386    }
387
388    /// Stores the current value of a storage key.
389    table PlainStorageState {
390        type Key = Address;
391        type Value = StorageEntry;
392        type SubKey = B256;
393    }
394
395    /// Stores pointers to block changeset with changes for each account key.
396    ///
397    /// Last shard key of the storage will contain `u64::MAX` `BlockNumber`,
398    /// this would allows us small optimization on db access when change is in plain state.
399    ///
400    /// Imagine having shards as:
401    /// * `Address | 100`
402    /// * `Address | u64::MAX`
403    ///
404    /// What we need to find is number that is one greater than N. Db `seek` function allows us to fetch
405    /// the shard that equal or more than asked. For example:
406    /// * For N=50 we would get first shard.
407    /// * for N=150 we would get second shard.
408    /// * If max block number is 200 and we ask for N=250 we would fetch last shard and know that needed entry is in `AccountPlainState`.
409    /// * If there were no shard we would get `None` entry or entry of different storage key.
410    ///
411    /// Code example can be found in `reth_provider::HistoricalStateProviderRef`
412    table AccountsHistory {
413        type Key = ShardedKey<Address>;
414        type Value = BlockNumberList;
415    }
416
417    /// Stores pointers to block number changeset with changes for each storage key.
418    ///
419    /// Last shard key of the storage will contain `u64::MAX` `BlockNumber`,
420    /// this would allows us small optimization on db access when change is in plain state.
421    ///
422    /// Imagine having shards as:
423    /// * `Address | StorageKey | 100`
424    /// * `Address | StorageKey | u64::MAX`
425    ///
426    /// What we need to find is number that is one greater than N. Db `seek` function allows us to fetch
427    /// the shard that equal or more than asked. For example:
428    /// * For N=50 we would get first shard.
429    /// * for N=150 we would get second shard.
430    /// * If max block number is 200 and we ask for N=250 we would fetch last shard and know that needed entry is in `StoragePlainState`.
431    /// * If there were no shard we would get `None` entry or entry of different storage key.
432    ///
433    /// Code example can be found in `reth_provider::HistoricalStateProviderRef`
434    table StoragesHistory {
435        type Key = StorageShardedKey;
436        type Value = BlockNumberList;
437    }
438
439    /// Stores the state of an account before a certain transaction changed it.
440    /// Change on state can be: account is created, selfdestructed, touched while empty
441    /// or changed balance,nonce.
442    table AccountChangeSets {
443        type Key = BlockNumber;
444        type Value = AccountBeforeTx;
445        type SubKey = Address;
446    }
447
448    /// Stores the state of a storage key before a certain transaction changed it.
449    /// If [`StorageEntry::value`] is zero, this means storage was not existing
450    /// and needs to be removed.
451    table StorageChangeSets {
452        type Key = BlockNumberAddress;
453        type Value = StorageEntry;
454        type SubKey = B256;
455    }
456
457    /// Stores the current state of an [`Account`] indexed with `keccak256Address`
458    /// This table is in preparation for merklization and calculation of state root.
459    /// We are saving whole account data as it is needed for partial update when
460    /// part of storage is changed. Benefit for merklization is that hashed addresses are sorted.
461    table HashedAccounts {
462        type Key = B256;
463        type Value = Account;
464    }
465
466    /// Stores the current storage values indexed with `keccak256Address` and
467    /// hash of storage key `keccak256key`.
468    /// This table is in preparation for merklization and calculation of state root.
469    /// Benefit for merklization is that hashed addresses/keys are sorted.
470    table HashedStorages {
471        type Key = B256;
472        type Value = StorageEntry;
473        type SubKey = B256;
474    }
475
476    /// Stores the current state's Merkle Patricia Tree.
477    table AccountsTrie {
478        type Key = StoredNibbles;
479        type Value = BranchNodeCompact;
480    }
481
482    /// From `HashedAddress` => `NibblesSubKey` => Intermediate value
483    table StoragesTrie {
484        type Key = B256;
485        type Value = StorageTrieEntry;
486        type SubKey = StoredNibblesSubKey;
487    }
488
489    /// Stores the transaction sender for each canonical transaction.
490    /// It is needed to speed up execution stage and allows fetching signer without doing
491    /// transaction signed recovery
492    table TransactionSenders {
493        type Key = TxNumber;
494        type Value = Address;
495    }
496
497    /// Stores the highest synced block number and stage-specific checkpoint of each stage.
498    table StageCheckpoints {
499        type Key = StageId;
500        type Value = StageCheckpoint;
501    }
502
503    /// Stores arbitrary data to keep track of a stage first-sync progress.
504    table StageCheckpointProgresses {
505        type Key = StageId;
506        type Value = Vec<u8>;
507    }
508
509    /// Stores the highest pruned block number and prune mode of each prune segment.
510    table PruneCheckpoints {
511        type Key = PruneSegment;
512        type Value = PruneCheckpoint;
513    }
514
515    /// Stores the history of client versions that have accessed the database with write privileges by unix timestamp in seconds.
516    table VersionHistory {
517        type Key = u64;
518        type Value = ClientVersion;
519    }
520
521    /// Stores generic chain state info, like the last finalized block.
522    table ChainState {
523        type Key = ChainStateKey;
524        type Value = BlockNumber;
525    }
526}
527
528/// Keys for the `ChainState` table.
529#[derive(Ord, Clone, Eq, PartialOrd, PartialEq, Debug, Deserialize, Serialize, Hash)]
530pub enum ChainStateKey {
531    /// Last finalized block key
532    LastFinalizedBlock,
533    /// Last safe block key
534    LastSafeBlockBlock,
535}
536
537impl Encode for ChainStateKey {
538    type Encoded = [u8; 1];
539
540    fn encode(self) -> Self::Encoded {
541        match self {
542            Self::LastFinalizedBlock => [0],
543            Self::LastSafeBlockBlock => [1],
544        }
545    }
546}
547
548impl Decode for ChainStateKey {
549    fn decode(value: &[u8]) -> Result<Self, crate::DatabaseError> {
550        match value {
551            [0] => Ok(Self::LastFinalizedBlock),
552            [1] => Ok(Self::LastSafeBlockBlock),
553            _ => Err(crate::DatabaseError::Decode),
554        }
555    }
556}
557
558// Alias types.
559
560/// List with transaction numbers.
561pub type BlockNumberList = IntegerList;
562
563/// Encoded stage id.
564pub type StageId = String;
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569    use std::str::FromStr;
570
571    #[test]
572    fn parse_table_from_str() {
573        for table in Tables::ALL {
574            assert_eq!(format!("{table:?}"), table.name());
575            assert_eq!(table.to_string(), table.name());
576            assert_eq!(Tables::from_str(table.name()).unwrap(), *table);
577        }
578    }
579}