Skip to main content

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