Skip to main content

reth_db/implementation/mdbx/
mod.rs

1//! Module that interacts with MDBX.
2
3use crate::{
4    lockfile::StorageLock,
5    metrics::DatabaseEnvMetrics,
6    tables::{self, Tables},
7    utils::default_page_size,
8    DatabaseError, TableSet,
9};
10use eyre::Context;
11use metrics::{gauge, Label};
12use reth_db_api::{
13    cursor::{DbCursorRO, DbCursorRW},
14    database::Database,
15    database_metrics::DatabaseMetrics,
16    models::ClientVersion,
17    transaction::{DbTx, DbTxMut},
18};
19use reth_libmdbx::{
20    ffi, DatabaseFlags, Environment, EnvironmentFlags, Geometry, HandleSlowReadersReturnCode,
21    MaxReadTransactionDuration, Mode, PageSize, SyncMode, RO, RW,
22};
23use reth_storage_errors::db::LogLevel;
24use rustc_hash::FxHashMap;
25use std::{
26    ops::{Deref, Range},
27    path::{Path, PathBuf},
28    sync::Arc,
29    time::{Duration, SystemTime, UNIX_EPOCH},
30};
31use tracing::error;
32use tx::Tx;
33
34pub mod cursor;
35pub mod tx;
36
37mod utils;
38#[cfg(target_os = "linux")]
39mod value_prefetch;
40
41/// 1 KB in bytes
42pub const KILOBYTE: usize = 1024;
43/// 1 MB in bytes
44pub const MEGABYTE: usize = KILOBYTE * 1024;
45/// 1 GB in bytes
46pub const GIGABYTE: usize = MEGABYTE * 1024;
47/// 1 TB in bytes
48pub const TERABYTE: usize = GIGABYTE * 1024;
49
50/// MDBX allows up to 32767 readers (`MDBX_READERS_LIMIT`), but we limit it to slightly below that
51const DEFAULT_MAX_READERS: u64 = 32_000;
52
53/// Space that a read-only transaction can occupy until the warning is emitted.
54/// See [`reth_libmdbx::EnvironmentBuilder::set_handle_slow_readers`] for more information.
55const MAX_SAFE_READER_SPACE: usize = 10 * GIGABYTE;
56
57/// Longest time a [`SyncMode::SafeNoSync`] or [`SyncMode::UtterlyNoSync`] environment goes
58/// without a steady (synced) commit.
59///
60/// Commits in these modes are weak. After an unclean shutdown on a new boot (host reboot or power
61/// loss) MDBX discards all weak commits and rolls back to the last steady one, while static files
62/// and `RocksDB` sync on every commit and stay ahead. Without a period, steady commits only happen
63/// on a clean close or when the file fills up, so the rollback can span days and land below data
64/// that static file pruning already deleted, which startup healing cannot repair. MDBX checks the
65/// period on each commit.
66const NON_DURABLE_SYNC_PERIOD: Duration = Duration::from_secs(60);
67
68/// Environment used when opening a MDBX environment. RO/RW.
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub enum DatabaseEnvKind {
71    /// Read-only MDBX environment.
72    RO,
73    /// Read-write MDBX environment.
74    RW,
75}
76
77impl DatabaseEnvKind {
78    /// Returns `true` if the environment is read-write.
79    pub const fn is_rw(&self) -> bool {
80        matches!(self, Self::RW)
81    }
82}
83
84/// Arguments for database initialization.
85#[derive(Clone, Debug)]
86pub struct DatabaseArguments {
87    /// Client version that accesses the database.
88    client_version: ClientVersion,
89    /// Database geometry settings.
90    geometry: Geometry<Range<usize>>,
91    /// Database log level. If [None], the default value is used.
92    log_level: Option<LogLevel>,
93    /// Maximum duration of a read transaction. If [None], the default value is used.
94    max_read_transaction_duration: Option<MaxReadTransactionDuration>,
95    /// Open environment in exclusive/monopolistic mode. If [None], the default value is used.
96    ///
97    /// This can be used as a replacement for `MDB_NOLOCK`, which don't supported by MDBX. In this
98    /// way, you can get the minimal overhead, but with the correct multi-process and multi-thread
99    /// locking.
100    ///
101    /// If `true` = open environment in exclusive/monopolistic mode or return `MDBX_BUSY` if
102    /// environment already used by other process. The main feature of the exclusive mode is the
103    /// ability to open the environment placed on a network share.
104    ///
105    /// If `false` = open environment in cooperative mode, i.e. for multi-process
106    /// access/interaction/cooperation. The main requirements of the cooperative mode are:
107    /// - Data files MUST be placed in the LOCAL file system, but NOT on a network share.
108    /// - Environment MUST be opened only by LOCAL processes, but NOT over a network.
109    /// - OS kernel (i.e. file system and memory mapping implementation) and all processes that
110    ///   open the given environment MUST be running in the physically single RAM with
111    ///   cache-coherency. The only exception for cache-consistency requirement is Linux on MIPS
112    ///   architecture, but this case has not been tested for a long time).
113    ///
114    /// This flag affects only at environment opening but can't be changed after.
115    exclusive: Option<bool>,
116    /// MDBX allows up to 32767 readers (`MDBX_READERS_LIMIT`). This arg is to configure the max
117    /// readers.
118    max_readers: Option<u64>,
119    /// Defines the synchronization strategy used by the MDBX database when writing data to disk.
120    ///
121    /// This determines how aggressively MDBX ensures data durability versus prioritizing
122    /// performance. The available modes are:
123    ///
124    /// - [`SyncMode::Durable`]: Ensures all transactions are fully flushed to disk before they are
125    ///   considered committed.   This provides the highest level of durability and crash safety
126    ///   but may have a performance cost.
127    /// - [`SyncMode::SafeNoSync`]: Skips certain fsync operations to improve write performance.
128    ///   This mode still maintains database integrity but may lose the transactions committed
129    ///   within the last [`NON_DURABLE_SYNC_PERIOD`] if the system crashes unexpectedly.
130    ///
131    /// Choose `Durable` if consistency and crash safety are critical (e.g., production
132    /// environments). Choose `SafeNoSync` if performance is more important and occasional data
133    /// loss is acceptable (e.g., testing or ephemeral data).
134    sync_mode: SyncMode,
135}
136
137impl Default for DatabaseArguments {
138    fn default() -> Self {
139        Self::new(ClientVersion::default())
140    }
141}
142
143impl DatabaseArguments {
144    /// Create new database arguments with given client version.
145    pub fn new(client_version: ClientVersion) -> Self {
146        Self {
147            client_version,
148            geometry: Geometry {
149                size: Some(0..(8 * TERABYTE)),
150                growth_step: Some(4 * GIGABYTE as isize),
151                shrink_threshold: Some(0),
152                page_size: Some(PageSize::Set(default_page_size())),
153            },
154            log_level: None,
155            max_read_transaction_duration: None,
156            exclusive: None,
157            max_readers: None,
158            sync_mode: SyncMode::Durable,
159        }
160    }
161
162    /// Create database arguments suitable for testing.
163    ///
164    /// Uses a small geometry (64MB max, 4MB growth) to avoid exhausting the system's
165    /// virtual memory map limit (`vm.max_map_count`) when many test databases are open
166    /// concurrently.
167    pub fn test() -> Self {
168        Self {
169            geometry: Geometry {
170                size: Some(0..(64 * MEGABYTE)),
171                growth_step: Some(4 * MEGABYTE as isize),
172                shrink_threshold: Some(0),
173                page_size: Some(PageSize::Set(default_page_size())),
174            },
175            max_read_transaction_duration: Some(MaxReadTransactionDuration::Unbounded),
176            ..Self::new(ClientVersion::default())
177        }
178    }
179
180    /// Sets the upper size limit of the db environment, the maximum database size in bytes.
181    pub const fn with_geometry_max_size(mut self, max_size: Option<usize>) -> Self {
182        if let Some(max_size) = max_size {
183            self.geometry.size = Some(0..max_size);
184        }
185        self
186    }
187
188    /// Sets the database page size value.
189    pub const fn with_geometry_page_size(mut self, page_size: Option<usize>) -> Self {
190        if let Some(size) = page_size {
191            self.geometry.page_size = Some(reth_libmdbx::PageSize::Set(size));
192        }
193
194        self
195    }
196
197    /// Sets the database sync mode.
198    pub const fn with_sync_mode(mut self, sync_mode: Option<SyncMode>) -> Self {
199        if let Some(sync_mode) = sync_mode {
200            self.sync_mode = sync_mode;
201        }
202
203        self
204    }
205
206    /// Configures the database growth step in bytes.
207    pub const fn with_growth_step(mut self, growth_step: Option<usize>) -> Self {
208        if let Some(growth_step) = growth_step {
209            self.geometry.growth_step = Some(growth_step as isize);
210        }
211        self
212    }
213
214    /// Set the log level.
215    pub const fn with_log_level(mut self, log_level: Option<LogLevel>) -> Self {
216        self.log_level = log_level;
217        self
218    }
219
220    /// Set the maximum duration of a read transaction.
221    pub const fn max_read_transaction_duration(
222        &mut self,
223        max_read_transaction_duration: Option<MaxReadTransactionDuration>,
224    ) {
225        self.max_read_transaction_duration = max_read_transaction_duration;
226    }
227
228    /// Set the maximum duration of a read transaction.
229    pub const fn with_max_read_transaction_duration(
230        mut self,
231        max_read_transaction_duration: Option<MaxReadTransactionDuration>,
232    ) -> Self {
233        self.max_read_transaction_duration(max_read_transaction_duration);
234        self
235    }
236
237    /// Set the mdbx exclusive flag.
238    pub const fn with_exclusive(mut self, exclusive: Option<bool>) -> Self {
239        self.exclusive = exclusive;
240        self
241    }
242
243    /// Set `max_readers` flag.
244    pub const fn with_max_readers(mut self, max_readers: Option<u64>) -> Self {
245        self.max_readers = max_readers;
246        self
247    }
248
249    /// Returns the client version if any.
250    pub const fn client_version(&self) -> &ClientVersion {
251        &self.client_version
252    }
253}
254
255/// Wrapper for the libmdbx environment: [Environment]
256#[derive(Debug, Clone)]
257pub struct DatabaseEnv {
258    /// Libmdbx-sys environment.
259    inner: Environment,
260    /// Path to the database directory.
261    path: PathBuf,
262    /// Opened DBIs for reuse.
263    /// Important: Do not manually close these DBIs, like via `mdbx_dbi_close`.
264    /// More generally, do not dynamically create, re-open, or drop tables at
265    /// runtime. It's better to perform table creation and migration only once
266    /// at startup.
267    dbis: Arc<TableDbis>,
268    /// Cache for metric handles. If `None`, metrics are not recorded.
269    metrics: Option<Arc<DatabaseEnvMetrics>>,
270    /// Disables long-lived read safety on transactions opened through this handle.
271    disable_long_read_transaction_safety: bool,
272    /// Write lock for when dealing with a read-write environment.
273    _lock_file: Option<StorageLock>,
274}
275
276/// MDBX DBIs of the tables tracked by a [`DatabaseEnv`].
277#[derive(Debug, Clone)]
278pub(crate) struct TableDbis {
279    /// DBIs of [`Tables`] entries, indexed by the entry's position in [`Tables::ALL`].
280    tables: [Option<ffi::MDBX_dbi>; Tables::COUNT],
281    /// DBIs of tables defined outside of [`Tables`], by name.
282    other: FxHashMap<&'static str, ffi::MDBX_dbi>,
283}
284
285impl Default for TableDbis {
286    fn default() -> Self {
287        Self { tables: [None; Tables::COUNT], other: FxHashMap::default() }
288    }
289}
290
291impl TableDbis {
292    /// Returns the tracked DBI of a table, which is looked up by `table` if it is a [`Tables`]
293    /// entry and by `name` otherwise.
294    ///
295    /// Returns `None` if the table is not tracked.
296    pub(crate) fn get(&self, table: Option<Tables>, name: &str) -> Option<ffi::MDBX_dbi> {
297        match table {
298            Some(table) => self.tables[table as usize],
299            None => self.other.get(name).copied(),
300        }
301    }
302
303    /// Tracks the DBI of the table with the given name.
304    fn insert(&mut self, name: &'static str, dbi: ffi::MDBX_dbi) {
305        match name.parse::<Tables>() {
306            Ok(table) => self.tables[table as usize] = Some(dbi),
307            Err(_) => {
308                self.other.insert(name, dbi);
309            }
310        }
311    }
312}
313
314impl Database for DatabaseEnv {
315    type TX = tx::Tx<RO>;
316    type TXMut = tx::Tx<RW>;
317
318    fn tx(&self) -> Result<Self::TX, DatabaseError> {
319        let mut tx = Tx::new(
320            self.inner.begin_ro_txn().map_err(|e| DatabaseError::InitTx(e.into()))?,
321            self.dbis.clone(),
322            self.metrics.clone(),
323        )
324        .map_err(|e| DatabaseError::InitTx(e.into()))?;
325        if self.disable_long_read_transaction_safety {
326            tx.disable_long_read_transaction_safety();
327        }
328        Ok(tx)
329    }
330
331    fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
332        let mut tx = Tx::new(
333            self.inner.begin_rw_txn().map_err(|e| DatabaseError::InitTx(e.into()))?,
334            self.dbis.clone(),
335            self.metrics.clone(),
336        )
337        .map_err(|e| DatabaseError::InitTx(e.into()))?;
338        if self.disable_long_read_transaction_safety {
339            tx.disable_long_read_transaction_safety();
340        }
341        Ok(tx)
342    }
343
344    fn path(&self) -> PathBuf {
345        self.path.clone()
346    }
347
348    fn oldest_reader_txnid(&self) -> Option<u64> {
349        let info = self.inner.info().ok()?;
350        let txnid = info.latter_reader_txnid();
351        if txnid == 0 {
352            None
353        } else {
354            Some(txnid)
355        }
356    }
357
358    fn last_txnid(&self) -> Option<u64> {
359        let info = self.inner.info().ok()?;
360        let txnid = info.last_txnid();
361        if txnid == 0 {
362            None
363        } else {
364            Some(txnid as u64)
365        }
366    }
367
368    fn reader_check(&self) -> Result<(), DatabaseError> {
369        self.inner.reader_check().map(|_| ()).map_err(|e| DatabaseError::Read(e.into()))
370    }
371}
372
373impl DatabaseMetrics for DatabaseEnv {
374    fn report_metrics(&self) {
375        for (name, value, labels) in self.gauge_metrics() {
376            gauge!(name, labels).set(value);
377        }
378    }
379
380    fn gauge_metrics(&self) -> Vec<(&'static str, f64, Vec<Label>)> {
381        let mut metrics = Vec::new();
382
383        let _ = self
384            .view(|tx| {
385                for table in Tables::ALL.iter().map(Tables::name) {
386                    let table_db =
387                        tx.inner().open_db(Some(table)).wrap_err("Could not open db.")?;
388
389                    let stats = tx
390                        .inner()
391                        .db_stat(table_db.dbi())
392                        .wrap_err(format!("Could not find table: {table}"))?;
393
394                    let page_size = stats.page_size() as usize;
395                    let leaf_pages = stats.leaf_pages();
396                    let branch_pages = stats.branch_pages();
397                    let overflow_pages = stats.overflow_pages();
398                    let num_pages = leaf_pages + branch_pages + overflow_pages;
399                    let table_size = page_size * num_pages;
400                    let entries = stats.entries();
401
402                    metrics.push((
403                        "db.table_size",
404                        table_size as f64,
405                        vec![Label::new("table", table)],
406                    ));
407                    metrics.push((
408                        "db.table_pages",
409                        leaf_pages as f64,
410                        vec![Label::new("table", table), Label::new("type", "leaf")],
411                    ));
412                    metrics.push((
413                        "db.table_pages",
414                        branch_pages as f64,
415                        vec![Label::new("table", table), Label::new("type", "branch")],
416                    ));
417                    metrics.push((
418                        "db.table_pages",
419                        overflow_pages as f64,
420                        vec![Label::new("table", table), Label::new("type", "overflow")],
421                    ));
422                    metrics.push((
423                        "db.table_entries",
424                        entries as f64,
425                        vec![Label::new("table", table)],
426                    ));
427                }
428
429                Ok::<(), eyre::Report>(())
430            })
431            .map_err(|error| error!(%error, "Failed to read db table stats"));
432
433        if let Ok(freelist) =
434            self.freelist().map_err(|error| error!(%error, "Failed to read db.freelist"))
435        {
436            metrics.push(("db.freelist", freelist as f64, vec![]));
437        }
438
439        if let Ok(stat) = self.stat().map_err(|error| error!(%error, "Failed to read db.stat")) {
440            metrics.push(("db.page_size", stat.page_size() as f64, vec![]));
441        }
442
443        metrics.push((
444            "db.timed_out_not_aborted_transactions",
445            self.timed_out_not_aborted_transactions() as f64,
446            vec![],
447        ));
448
449        metrics
450    }
451}
452
453impl DatabaseEnv {
454    /// Opens the database at the specified path with the given `EnvKind`.
455    ///
456    /// It does not create the tables, for that call [`DatabaseEnv::create_tables`].
457    pub fn open(
458        path: &Path,
459        kind: DatabaseEnvKind,
460        args: DatabaseArguments,
461    ) -> Result<Self, DatabaseError> {
462        let _lock_file = if kind.is_rw() {
463            StorageLock::try_acquire(path)
464                .map_err(|err| DatabaseError::Other(err.to_string()))?
465                .into()
466        } else {
467            None
468        };
469
470        let mut inner_env = Environment::builder();
471
472        let mode = match kind {
473            DatabaseEnvKind::RO => Mode::ReadOnly,
474            DatabaseEnvKind::RW => {
475                // enable writemap mode in RW mode
476                inner_env.write_map();
477                if matches!(args.sync_mode, SyncMode::SafeNoSync | SyncMode::UtterlyNoSync) {
478                    inner_env.set_sync_period(NON_DURABLE_SYNC_PERIOD);
479                }
480                Mode::ReadWrite { sync_mode: args.sync_mode }
481            }
482        };
483
484        // Note: We set max dbs to 256 here to allow for custom tables. This needs to be set on
485        // environment creation.
486        debug_assert!(Tables::ALL.len() <= 256, "number of tables exceed max dbs");
487        inner_env.set_max_dbs(256);
488        inner_env.set_geometry(args.geometry);
489
490        fn is_current_process(id: u32) -> bool {
491            #[cfg(unix)]
492            {
493                id == std::os::unix::process::parent_id() || id == std::process::id()
494            }
495
496            #[cfg(not(unix))]
497            {
498                id == std::process::id()
499            }
500        }
501
502        extern "C" fn handle_slow_readers(
503            _env: *const ffi::MDBX_env,
504            _txn: *const ffi::MDBX_txn,
505            process_id: ffi::mdbx_pid_t,
506            thread_id: ffi::mdbx_tid_t,
507            read_txn_id: u64,
508            gap: std::ffi::c_uint,
509            space: usize,
510            retry: std::ffi::c_int,
511        ) -> HandleSlowReadersReturnCode {
512            if space > MAX_SAFE_READER_SPACE {
513                let message = if is_current_process(process_id as u32) {
514                    "Current process has a long-lived database transaction that grows the database file."
515                } else {
516                    "External process has a long-lived database transaction that grows the database file. \
517                     Use shorter-lived read transactions or shut down the node."
518                };
519                tracing::warn!(
520                    target: "storage::db::mdbx",
521                    ?process_id,
522                    ?thread_id,
523                    ?read_txn_id,
524                    ?gap,
525                    ?space,
526                    ?retry,
527                    "{message}"
528                )
529            }
530
531            reth_libmdbx::HandleSlowReadersReturnCode::ProceedWithoutKillingReader
532        }
533        inner_env.set_handle_slow_readers(handle_slow_readers);
534
535        inner_env.set_flags(EnvironmentFlags {
536            mode,
537            // We disable readahead because it improves performance for linear scans, but
538            // worsens it for random access (which is our access pattern outside of sync)
539            no_rdahead: true,
540            coalesce: true,
541            exclusive: args.exclusive.unwrap_or_default(),
542            ..Default::default()
543        });
544        // Configure more readers
545        inner_env.set_max_readers(args.max_readers.unwrap_or(DEFAULT_MAX_READERS));
546        // This parameter sets the maximum size of the "reclaimed list", and the unit of measurement
547        // is "pages". Reclaimed list is the list of freed pages that's populated during the
548        // lifetime of DB transaction, and through which MDBX searches when it needs to insert new
549        // record with overflow pages. The flow is roughly the following:
550        // 0. We need to insert a record that requires N number of overflow pages (in consecutive
551        //    sequence inside the DB file).
552        // 1. Get some pages from the freelist, put them into the reclaimed list.
553        // 2. Search through the reclaimed list for the sequence of size N.
554        // 3. a. If found, return the sequence.
555        // 3. b. If not found, repeat steps 1-3. If the reclaimed list size is larger than
556        //    the `rp augment limit`, stop the search and allocate new pages at the end of the file:
557        //    https://github.com/paradigmxyz/reth/blob/2a4c78759178f66e30c8976ec5d243b53102fc9a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/mdbx.c#L11479-L11480.
558        //
559        // Basically, this parameter controls for how long do we search through the freelist before
560        // trying to allocate new pages. Smaller value will make MDBX to fallback to
561        // allocation faster, higher value will force MDBX to search through the freelist
562        // longer until the sequence of pages is found.
563        //
564        // The default value of this parameter is set depending on the DB size. The bigger the
565        // database, the larger is `rp augment limit`.
566        // https://github.com/paradigmxyz/reth/blob/2a4c78759178f66e30c8976ec5d243b53102fc9a/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/mdbx.c#L10018-L10024.
567        //
568        // Previously, MDBX set this value as `256 * 1024` constant. Let's fallback to this,
569        // because we want to prioritize freelist lookup speed over database growth.
570        // https://github.com/paradigmxyz/reth/blob/fa2b9b685ed9787636d962f4366caf34a9186e66/crates/storage/libmdbx-rs/mdbx-sys/libmdbx/mdbx.c#L16017.
571        inner_env.set_rp_augment_limit(256 * 1024);
572
573        if let Some(log_level) = args.log_level {
574            // Levels higher than [LogLevel::Notice] require libmdbx built with `MDBX_DEBUG` option.
575            let is_log_level_available = if cfg!(debug_assertions) {
576                true
577            } else {
578                matches!(
579                    log_level,
580                    LogLevel::Fatal | LogLevel::Error | LogLevel::Warn | LogLevel::Notice
581                )
582            };
583            if is_log_level_available {
584                inner_env.set_log_level(match log_level {
585                    LogLevel::Fatal => 0,
586                    LogLevel::Error => 1,
587                    LogLevel::Warn => 2,
588                    LogLevel::Notice => 3,
589                    LogLevel::Verbose => 4,
590                    LogLevel::Debug => 5,
591                    LogLevel::Trace => 6,
592                    LogLevel::Extra => 7,
593                });
594            } else {
595                return Err(DatabaseError::LogLevelUnavailable(log_level))
596            }
597        }
598
599        if let Some(max_read_transaction_duration) = args.max_read_transaction_duration {
600            inner_env.set_max_read_transaction_duration(max_read_transaction_duration);
601        }
602
603        let env = Self {
604            inner: inner_env.open(path).map_err(|e| DatabaseError::Open(e.into()))?,
605            path: path.to_path_buf(),
606            dbis: Arc::default(),
607            metrics: None,
608            disable_long_read_transaction_safety: false,
609            _lock_file,
610        };
611
612        Ok(env)
613    }
614
615    /// Enables metrics on the database.
616    pub fn with_metrics(mut self) -> Self {
617        self.metrics = Some(DatabaseEnvMetrics::new().into());
618        self
619    }
620
621    /// Enables metrics on the database if requested.
622    pub fn with_metrics_if(self, enabled: bool) -> Self {
623        if enabled {
624            self.with_metrics()
625        } else {
626            self
627        }
628    }
629
630    /// Creates all the tables defined in [`Tables`], if necessary.
631    ///
632    /// This keeps tracks of the created table handles and stores them for better efficiency.
633    pub fn create_tables(&mut self) -> Result<(), DatabaseError> {
634        self.create_and_track_tables_for::<Tables>()
635    }
636
637    /// Creates all the tables defined in the given [`TableSet`], if necessary.
638    ///
639    /// This keeps tracks of the created table handles and stores them for better efficiency.
640    pub fn create_and_track_tables_for<TS: TableSet>(&mut self) -> Result<(), DatabaseError> {
641        let handles = self._create_tables::<TS>()?;
642        // Note: This is okay because self has mutable access here and `DatabaseEnv` must be Arc'ed
643        // before it can be shared.
644        let dbis = Arc::make_mut(&mut self.dbis);
645        for (name, dbi) in handles {
646            dbis.insert(name, dbi);
647        }
648
649        Ok(())
650    }
651
652    /// Creates all the tables defined in [`Tables`], if necessary.
653    ///
654    /// If this type is unique the created handle for the tables will be updated.
655    ///
656    /// This is recommended to be called during initialization to create and track additional tables
657    /// after the default [`Self::create_tables`] are created.
658    pub fn create_tables_for<TS: TableSet>(self: &mut Arc<Self>) -> Result<(), DatabaseError> {
659        let handles = self._create_tables::<TS>()?;
660        if let Some(db) = Arc::get_mut(self) {
661            // Note: The db is unique and the dbis as well, and they can also be cloned.
662            let dbis = Arc::make_mut(&mut db.dbis);
663            for (name, dbi) in handles {
664                dbis.insert(name, dbi);
665            }
666        }
667        Ok(())
668    }
669
670    /// Creates the tables and returns the identifiers of the tables.
671    fn _create_tables<TS: TableSet>(
672        &self,
673    ) -> Result<Vec<(&'static str, ffi::MDBX_dbi)>, DatabaseError> {
674        let mut handles = Vec::new();
675        let tx = self.inner.begin_rw_txn().map_err(|e| DatabaseError::InitTx(e.into()))?;
676
677        for table in TS::tables() {
678            let flags =
679                if table.is_dupsort() { DatabaseFlags::DUP_SORT } else { DatabaseFlags::default() };
680
681            let db = tx
682                .create_db(Some(table.name()), flags)
683                .map_err(|e| DatabaseError::CreateTable(e.into()))?;
684            handles.push((table.name(), db.dbi()));
685        }
686
687        tx.commit().map_err(|e| DatabaseError::Commit(e.into()))?;
688        Ok(handles)
689    }
690
691    /// Drops an orphaned table by name.
692    ///
693    /// This is used to clean up tables that are no longer defined in the schema but may still
694    /// exist on disk from previous versions.
695    ///
696    /// Returns `Ok(true)` if the table existed and was dropped, `Ok(false)` if the table was not
697    /// found.
698    ///
699    /// # Safety
700    /// This permanently deletes the table and all its data. Only use for tables that are
701    /// confirmed to be obsolete.
702    pub fn drop_orphan_table(&self, name: &str) -> Result<bool, DatabaseError> {
703        let tx = self.inner.begin_rw_txn().map_err(|e| DatabaseError::InitTx(e.into()))?;
704
705        match tx.open_db(Some(name)) {
706            Ok(db) => {
707                // SAFETY: We just opened the db handle and will commit immediately after dropping.
708                // No other cursors or handles exist for this table.
709                unsafe {
710                    tx.drop_db(db.dbi()).map_err(|e| DatabaseError::Delete(e.into()))?;
711                }
712                tx.commit().map_err(|e| DatabaseError::Commit(e.into()))?;
713                Ok(true)
714            }
715            Err(reth_libmdbx::Error::NotFound) => Ok(false),
716            Err(e) => Err(DatabaseError::Open(e.into())),
717        }
718    }
719
720    /// Records version that accesses the database with write privileges.
721    pub fn record_client_version(&self, version: ClientVersion) -> Result<(), DatabaseError> {
722        if version.is_empty() {
723            return Ok(())
724        }
725
726        let tx = self.tx_mut()?;
727        let mut version_cursor = tx.cursor_write::<tables::VersionHistory>()?;
728
729        let last_version = version_cursor.last()?.map(|(_, v)| v);
730        if Some(&version) != last_version.as_ref() {
731            version_cursor.upsert(
732                SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(),
733                &version,
734            )?;
735            tx.commit()?;
736        }
737
738        Ok(())
739    }
740
741    /// Disables timeouts and long-read backtrace reporting for transactions opened through this
742    /// handle. Existing transactions and other previously cloned handles are unaffected.
743    ///
744    /// Use for offline work that intentionally holds transactions open.
745    pub const fn with_disable_long_read_transaction_safety(mut self) -> Self {
746        self.disable_long_read_transaction_safety = true;
747        self
748    }
749}
750
751impl Deref for DatabaseEnv {
752    type Target = Environment;
753
754    fn deref(&self) -> &Self::Target {
755        &self.inner
756    }
757}
758
759#[cfg(test)]
760mod tests {
761
762    use super::*;
763    use crate::{
764        tables::{
765            AccountsHistory, CanonicalHeaders, Headers, PlainAccountState, PlainStorageState,
766        },
767        test_utils::*,
768        AccountChangeSets,
769    };
770    use alloy_consensus::Header;
771    use alloy_primitives::{address, Address, B256, U256};
772    use reth_db_api::{
773        cursor::{DbDupCursorRO, DbDupCursorRW, ReverseWalker, Walker},
774        models::{AccountBeforeTx, IntegerList, ShardedKey},
775        table::{Encode, Table, TableInfo},
776        tables_to_generic,
777    };
778    use reth_libmdbx::Error;
779    use reth_primitives_traits::{Account, StorageEntry};
780    use reth_storage_errors::db::{DatabaseWriteError, DatabaseWriteOperation};
781    use tempfile::TempDir;
782
783    #[cfg(unix)]
784    use reth_db_api::database::ReaderTxnTracker;
785    #[cfg(unix)]
786    use std::{
787        io::{BufRead, BufReader, Read},
788        process::{Command, Stdio},
789        sync::mpsc,
790    };
791
792    /// Create database for testing. Returns the `TempDir` to prevent cleanup until test ends.
793    fn create_test_db(kind: DatabaseEnvKind) -> (TempDir, DatabaseEnv) {
794        let tempdir = tempfile::TempDir::new().expect(ERROR_TEMPDIR);
795        let env = create_test_db_with_path(kind, tempdir.path());
796        (tempdir, env)
797    }
798
799    /// Create database for testing with specified path
800    fn create_test_db_with_path(kind: DatabaseEnvKind, path: &Path) -> DatabaseEnv {
801        let mut env =
802            DatabaseEnv::open(path, kind, DatabaseArguments::new(ClientVersion::default()))
803                .expect(ERROR_DB_CREATION);
804        env.create_tables().expect(ERROR_TABLE_CREATION);
805        env
806    }
807
808    const ERROR_DB_CREATION: &str = "Not able to create the mdbx file.";
809    const ERROR_PUT: &str = "Not able to insert value into table.";
810    const ERROR_APPEND: &str = "Not able to append the value to the table.";
811    const ERROR_UPSERT: &str = "Not able to upsert the value to the table.";
812    const ERROR_GET: &str = "Not able to get value from table.";
813    const ERROR_DEL: &str = "Not able to delete from table.";
814    const ERROR_COMMIT: &str = "Not able to commit transaction.";
815    const ERROR_RETURN_VALUE: &str = "Mismatching result.";
816    const ERROR_INIT_TX: &str = "Failed to create a MDBX transaction.";
817
818    #[test]
819    fn db_creation() {
820        let _tempdir = create_test_db(DatabaseEnvKind::RW);
821    }
822
823    #[test]
824    fn db_drop_orphan_table() {
825        let tempdir = tempfile::TempDir::new().expect(ERROR_TEMPDIR);
826        let db = create_test_db_with_path(DatabaseEnvKind::RW, tempdir.path());
827
828        // Create an orphan table by manually creating it
829        let orphan_table_name = "OrphanTestTable";
830        {
831            let tx = db.inner.begin_rw_txn().expect(ERROR_INIT_TX);
832            tx.create_db(Some(orphan_table_name), DatabaseFlags::empty())
833                .expect("Failed to create orphan table");
834            tx.commit().expect(ERROR_COMMIT);
835        }
836
837        // Verify the table exists by opening it
838        {
839            let tx = db.inner.begin_ro_txn().expect(ERROR_INIT_TX);
840            assert!(tx.open_db(Some(orphan_table_name)).is_ok(), "Orphan table should exist");
841        }
842
843        // Drop the orphan table
844        let result = db.drop_orphan_table(orphan_table_name);
845        assert!(result.is_ok(), "drop_orphan_table should succeed");
846        assert!(result.unwrap(), "drop_orphan_table should return true for existing table");
847
848        // Verify the table no longer exists
849        {
850            let tx = db.inner.begin_ro_txn().expect(ERROR_INIT_TX);
851            assert!(
852                tx.open_db(Some(orphan_table_name)).is_err(),
853                "Orphan table should no longer exist"
854            );
855        }
856
857        // Dropping a non-existent table should return Ok(false)
858        let result = db.drop_orphan_table("NonExistentTable");
859        assert!(result.is_ok(), "drop_orphan_table should succeed for non-existent table");
860        assert!(!result.unwrap(), "drop_orphan_table should return false for non-existent table");
861    }
862
863    #[test]
864    fn db_manual_put_get() {
865        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
866
867        let value = Header::default();
868        let key = 1u64;
869
870        // PUT
871        let tx = env.tx_mut().expect(ERROR_INIT_TX);
872        tx.put::<Headers>(key, value.clone()).expect(ERROR_PUT);
873        tx.commit().expect(ERROR_COMMIT);
874
875        // GET
876        let tx = env.tx().expect(ERROR_INIT_TX);
877        let result = tx.get::<Headers>(key).expect(ERROR_GET);
878        assert_eq!(result.expect(ERROR_RETURN_VALUE), value);
879        tx.commit().expect(ERROR_COMMIT);
880    }
881
882    #[test]
883    fn db_dup_cursor_delete_first() {
884        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
885        let tx = db.tx_mut().expect(ERROR_INIT_TX);
886
887        let mut dup_cursor = tx.cursor_dup_write::<PlainStorageState>().unwrap();
888
889        let entry_0 = StorageEntry { key: B256::with_last_byte(1), value: U256::ZERO };
890        let entry_1 = StorageEntry { key: B256::with_last_byte(1), value: U256::ONE };
891
892        dup_cursor.upsert(Address::with_last_byte(1), &entry_0).expect(ERROR_UPSERT);
893        dup_cursor.upsert(Address::with_last_byte(1), &entry_1).expect(ERROR_UPSERT);
894
895        assert_eq!(
896            dup_cursor.walk(None).unwrap().collect::<Result<Vec<_>, _>>().unwrap(),
897            vec![(Address::with_last_byte(1), entry_0), (Address::with_last_byte(1), entry_1),]
898        );
899
900        let mut walker = dup_cursor.walk(None).unwrap();
901        walker.delete_current().expect(ERROR_DEL);
902
903        assert_eq!(walker.next().unwrap().unwrap(), (Address::with_last_byte(1), entry_1));
904
905        // Check the tx view - it correctly holds entry_1
906        assert_eq!(
907            tx.cursor_dup_read::<PlainStorageState>()
908                .unwrap()
909                .walk(None)
910                .unwrap()
911                .collect::<Result<Vec<_>, _>>()
912                .unwrap(),
913            vec![
914                (Address::with_last_byte(1), entry_1), // This is ok - we removed entry_0
915            ]
916        );
917
918        // Check the remainder of walker
919        assert!(walker.next().is_none());
920    }
921
922    #[test]
923    fn db_cursor_walk() {
924        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
925
926        let value = Header::default();
927        let key = 1u64;
928
929        // PUT
930        let tx = env.tx_mut().expect(ERROR_INIT_TX);
931        tx.put::<Headers>(key, value.clone()).expect(ERROR_PUT);
932        tx.commit().expect(ERROR_COMMIT);
933
934        // Cursor
935        let tx = env.tx().expect(ERROR_INIT_TX);
936        let mut cursor = tx.cursor_read::<Headers>().unwrap();
937
938        let first = cursor.first().unwrap();
939        assert!(first.is_some(), "First should be our put");
940
941        // Walk
942        let walk = cursor.walk(Some(key)).unwrap();
943        let first = walk.into_iter().next().unwrap().unwrap();
944        assert_eq!(first.1, value, "First next should be put value");
945    }
946
947    #[test]
948    fn db_cursor_walk_range() {
949        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
950
951        // PUT (0, 0), (1, 0), (2, 0), (3, 0)
952        let tx = db.tx_mut().expect(ERROR_INIT_TX);
953        vec![0, 1, 2, 3]
954            .into_iter()
955            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
956            .expect(ERROR_PUT);
957        tx.commit().expect(ERROR_COMMIT);
958
959        let tx = db.tx().expect(ERROR_INIT_TX);
960        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
961
962        // [1, 3)
963        let mut walker = cursor.walk_range(1..3).unwrap();
964        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
965        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
966        assert!(walker.next().is_none());
967        // next() returns None after walker is done
968        assert!(walker.next().is_none());
969
970        // [1, 2]
971        let mut walker = cursor.walk_range(1..=2).unwrap();
972        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
973        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
974        // next() returns None after walker is done
975        assert!(walker.next().is_none());
976
977        // [1, ∞)
978        let mut walker = cursor.walk_range(1..).unwrap();
979        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
980        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
981        assert_eq!(walker.next().unwrap().unwrap(), (3, B256::ZERO));
982        // next() returns None after walker is done
983        assert!(walker.next().is_none());
984
985        // [2, 4)
986        let mut walker = cursor.walk_range(2..4).unwrap();
987        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
988        assert_eq!(walker.next().unwrap().unwrap(), (3, B256::ZERO));
989        assert!(walker.next().is_none());
990        // next() returns None after walker is done
991        assert!(walker.next().is_none());
992
993        // (∞, 3)
994        let mut walker = cursor.walk_range(..3).unwrap();
995        assert_eq!(walker.next().unwrap().unwrap(), (0, B256::ZERO));
996        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
997        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
998        // next() returns None after walker is done
999        assert!(walker.next().is_none());
1000
1001        // (∞, ∞)
1002        let mut walker = cursor.walk_range(..).unwrap();
1003        assert_eq!(walker.next().unwrap().unwrap(), (0, B256::ZERO));
1004        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
1005        assert_eq!(walker.next().unwrap().unwrap(), (2, B256::ZERO));
1006        assert_eq!(walker.next().unwrap().unwrap(), (3, B256::ZERO));
1007        // next() returns None after walker is done
1008        assert!(walker.next().is_none());
1009    }
1010
1011    #[test]
1012    fn db_cursor_walk_range_on_dup_table() {
1013        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1014
1015        let address0 = Address::ZERO;
1016        let address1 = Address::with_last_byte(1);
1017        let address2 = Address::with_last_byte(2);
1018
1019        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1020        tx.put::<AccountChangeSets>(0, AccountBeforeTx { address: address0, info: None })
1021            .expect(ERROR_PUT);
1022        tx.put::<AccountChangeSets>(0, AccountBeforeTx { address: address1, info: None })
1023            .expect(ERROR_PUT);
1024        tx.put::<AccountChangeSets>(0, AccountBeforeTx { address: address2, info: None })
1025            .expect(ERROR_PUT);
1026        tx.put::<AccountChangeSets>(1, AccountBeforeTx { address: address0, info: None })
1027            .expect(ERROR_PUT);
1028        tx.put::<AccountChangeSets>(1, AccountBeforeTx { address: address1, info: None })
1029            .expect(ERROR_PUT);
1030        tx.put::<AccountChangeSets>(1, AccountBeforeTx { address: address2, info: None })
1031            .expect(ERROR_PUT);
1032        tx.put::<AccountChangeSets>(2, AccountBeforeTx { address: address0, info: None }) // <- should not be returned by the walker
1033            .expect(ERROR_PUT);
1034        tx.commit().expect(ERROR_COMMIT);
1035
1036        let tx = db.tx().expect(ERROR_INIT_TX);
1037        let mut cursor = tx.cursor_read::<AccountChangeSets>().unwrap();
1038
1039        let entries = cursor.walk_range(..).unwrap().collect::<Result<Vec<_>, _>>().unwrap();
1040        assert_eq!(entries.len(), 7);
1041
1042        let mut walker = cursor.walk_range(0..=1).unwrap();
1043        assert_eq!(
1044            walker.next().unwrap().unwrap(),
1045            (0, AccountBeforeTx { address: address0, info: None })
1046        );
1047        assert_eq!(
1048            walker.next().unwrap().unwrap(),
1049            (0, AccountBeforeTx { address: address1, info: None })
1050        );
1051        assert_eq!(
1052            walker.next().unwrap().unwrap(),
1053            (0, AccountBeforeTx { address: address2, info: None })
1054        );
1055        assert_eq!(
1056            walker.next().unwrap().unwrap(),
1057            (1, AccountBeforeTx { address: address0, info: None })
1058        );
1059        assert_eq!(
1060            walker.next().unwrap().unwrap(),
1061            (1, AccountBeforeTx { address: address1, info: None })
1062        );
1063        assert_eq!(
1064            walker.next().unwrap().unwrap(),
1065            (1, AccountBeforeTx { address: address2, info: None })
1066        );
1067        assert!(walker.next().is_none());
1068    }
1069
1070    #[expect(clippy::reversed_empty_ranges)]
1071    #[test]
1072    fn db_cursor_walk_range_invalid() {
1073        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1074
1075        // PUT (0, 0), (1, 0), (2, 0), (3, 0)
1076        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1077        vec![0, 1, 2, 3]
1078            .into_iter()
1079            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1080            .expect(ERROR_PUT);
1081        tx.commit().expect(ERROR_COMMIT);
1082
1083        let tx = db.tx().expect(ERROR_INIT_TX);
1084        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1085
1086        // start bound greater than end bound
1087        let mut res = cursor.walk_range(3..1).unwrap();
1088        assert!(res.next().is_none());
1089
1090        // start bound greater than end bound
1091        let mut res = cursor.walk_range(15..=2).unwrap();
1092        assert!(res.next().is_none());
1093
1094        // returning nothing
1095        let mut walker = cursor.walk_range(1..1).unwrap();
1096        assert!(walker.next().is_none());
1097    }
1098
1099    #[test]
1100    fn db_walker() {
1101        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1102
1103        // PUT (0, 0), (1, 0), (3, 0)
1104        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1105        vec![0, 1, 3]
1106            .into_iter()
1107            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1108            .expect(ERROR_PUT);
1109        tx.commit().expect(ERROR_COMMIT);
1110
1111        let tx = db.tx().expect(ERROR_INIT_TX);
1112        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1113
1114        let mut walker = Walker::new(&mut cursor, None);
1115
1116        assert_eq!(walker.next().unwrap().unwrap(), (0, B256::ZERO));
1117        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
1118        assert_eq!(walker.next().unwrap().unwrap(), (3, B256::ZERO));
1119        assert!(walker.next().is_none());
1120
1121        // transform to ReverseWalker
1122        let mut reverse_walker = walker.rev();
1123        assert_eq!(reverse_walker.next().unwrap().unwrap(), (3, B256::ZERO));
1124        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1125        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1126        assert!(reverse_walker.next().is_none());
1127    }
1128
1129    #[test]
1130    fn db_reverse_walker() {
1131        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1132
1133        // PUT (0, 0), (1, 0), (3, 0)
1134        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1135        vec![0, 1, 3]
1136            .into_iter()
1137            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1138            .expect(ERROR_PUT);
1139        tx.commit().expect(ERROR_COMMIT);
1140
1141        let tx = db.tx().expect(ERROR_INIT_TX);
1142        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1143
1144        let mut reverse_walker = ReverseWalker::new(&mut cursor, None);
1145
1146        assert_eq!(reverse_walker.next().unwrap().unwrap(), (3, B256::ZERO));
1147        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1148        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1149        assert!(reverse_walker.next().is_none());
1150
1151        // transform to Walker
1152        let mut walker = reverse_walker.forward();
1153        assert_eq!(walker.next().unwrap().unwrap(), (0, B256::ZERO));
1154        assert_eq!(walker.next().unwrap().unwrap(), (1, B256::ZERO));
1155        assert_eq!(walker.next().unwrap().unwrap(), (3, B256::ZERO));
1156        assert!(walker.next().is_none());
1157    }
1158
1159    #[test]
1160    fn db_walk_back() {
1161        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1162
1163        // PUT (0, 0), (1, 0), (3, 0)
1164        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1165        vec![0, 1, 3]
1166            .into_iter()
1167            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1168            .expect(ERROR_PUT);
1169        tx.commit().expect(ERROR_COMMIT);
1170
1171        let tx = db.tx().expect(ERROR_INIT_TX);
1172        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1173
1174        let mut reverse_walker = cursor.walk_back(Some(1)).unwrap();
1175        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1176        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1177        assert!(reverse_walker.next().is_none());
1178
1179        let mut reverse_walker = cursor.walk_back(Some(2)).unwrap();
1180        assert_eq!(reverse_walker.next().unwrap().unwrap(), (3, B256::ZERO));
1181        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1182        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1183        assert!(reverse_walker.next().is_none());
1184
1185        let mut reverse_walker = cursor.walk_back(Some(4)).unwrap();
1186        assert_eq!(reverse_walker.next().unwrap().unwrap(), (3, B256::ZERO));
1187        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1188        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1189        assert!(reverse_walker.next().is_none());
1190
1191        let mut reverse_walker = cursor.walk_back(None).unwrap();
1192        assert_eq!(reverse_walker.next().unwrap().unwrap(), (3, B256::ZERO));
1193        assert_eq!(reverse_walker.next().unwrap().unwrap(), (1, B256::ZERO));
1194        assert_eq!(reverse_walker.next().unwrap().unwrap(), (0, B256::ZERO));
1195        assert!(reverse_walker.next().is_none());
1196    }
1197
1198    #[test]
1199    fn db_cursor_seek_exact_or_previous_key() {
1200        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1201
1202        // PUT
1203        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1204        vec![0, 1, 3]
1205            .into_iter()
1206            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1207            .expect(ERROR_PUT);
1208        tx.commit().expect(ERROR_COMMIT);
1209
1210        // Cursor
1211        let missing_key = 2;
1212        let tx = db.tx().expect(ERROR_INIT_TX);
1213        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1214        assert!(cursor.current().unwrap().is_none());
1215
1216        // Seek exact
1217        let exact = cursor.seek_exact(missing_key).unwrap();
1218        assert_eq!(exact, None);
1219        assert!(cursor.current().unwrap().is_none());
1220    }
1221
1222    #[test]
1223    fn db_cursor_insert() {
1224        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1225
1226        // PUT
1227        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1228        vec![0, 1, 3, 4, 5]
1229            .into_iter()
1230            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1231            .expect(ERROR_PUT);
1232        tx.commit().expect(ERROR_COMMIT);
1233
1234        let key_to_insert = 2;
1235        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1236        let mut cursor = tx.cursor_write::<CanonicalHeaders>().unwrap();
1237
1238        // INSERT
1239        assert!(cursor.insert(key_to_insert, &B256::ZERO).is_ok());
1240        assert_eq!(cursor.current().unwrap(), Some((key_to_insert, B256::ZERO)));
1241        // INSERT (failure)
1242        assert!(matches!(
1243        cursor.insert(key_to_insert, &B256::ZERO).unwrap_err(),
1244        DatabaseError::Write(err) if *err == DatabaseWriteError {
1245            info: Error::KeyExist.into(),
1246            operation: DatabaseWriteOperation::CursorInsert,
1247            table_name: CanonicalHeaders::NAME,
1248            key: key_to_insert.encode().into(),
1249        }));
1250        assert_eq!(cursor.current().unwrap(), Some((key_to_insert, B256::ZERO)));
1251
1252        tx.commit().expect(ERROR_COMMIT);
1253
1254        // Confirm the result
1255        let tx = db.tx().expect(ERROR_INIT_TX);
1256        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1257        let res = cursor.walk(None).unwrap().map(|res| res.unwrap().0).collect::<Vec<_>>();
1258        assert_eq!(res, vec![0, 1, 2, 3, 4, 5]);
1259        tx.commit().expect(ERROR_COMMIT);
1260    }
1261
1262    #[test]
1263    fn db_cursor_insert_dup() {
1264        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1265        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1266
1267        let mut dup_cursor = tx.cursor_dup_write::<PlainStorageState>().unwrap();
1268        let key = Address::random();
1269        let subkey1 = B256::random();
1270        let subkey2 = B256::random();
1271
1272        let entry1 = StorageEntry { key: subkey1, value: U256::ZERO };
1273        assert!(dup_cursor.insert(key, &entry1).is_ok());
1274
1275        // Can't insert
1276        let entry2 = StorageEntry { key: subkey2, value: U256::ZERO };
1277        assert!(dup_cursor.insert(key, &entry2).is_err());
1278    }
1279
1280    #[test]
1281    fn db_cursor_delete_current_non_existent() {
1282        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1283        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1284
1285        let key1 = Address::with_last_byte(1);
1286        let key2 = Address::with_last_byte(2);
1287        let key3 = Address::with_last_byte(3);
1288        let mut cursor = tx.cursor_write::<PlainAccountState>().unwrap();
1289
1290        assert!(cursor.insert(key1, &Account::default()).is_ok());
1291        assert!(cursor.insert(key2, &Account::default()).is_ok());
1292        assert!(cursor.insert(key3, &Account::default()).is_ok());
1293
1294        // Seek & delete key2
1295        cursor.seek_exact(key2).unwrap();
1296        assert!(cursor.delete_current().is_ok());
1297        assert!(cursor.seek_exact(key2).unwrap().is_none());
1298
1299        // Seek & delete key2 again
1300        assert!(cursor.seek_exact(key2).unwrap().is_none());
1301        assert!(matches!(
1302            cursor.delete_current().unwrap_err(),
1303            DatabaseError::Delete(err) if err == reth_libmdbx::Error::NoData.into()));
1304        // Assert that key1 is still there
1305        assert_eq!(cursor.seek_exact(key1).unwrap(), Some((key1, Account::default())));
1306        // Assert that key3 is still there
1307        assert_eq!(cursor.seek_exact(key3).unwrap(), Some((key3, Account::default())));
1308    }
1309
1310    #[test]
1311    fn db_cursor_insert_wherever_cursor_is() {
1312        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1313        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1314
1315        // PUT
1316        vec![0, 1, 3, 5, 7, 9]
1317            .into_iter()
1318            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1319            .expect(ERROR_PUT);
1320        tx.commit().expect(ERROR_COMMIT);
1321
1322        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1323        let mut cursor = tx.cursor_write::<CanonicalHeaders>().unwrap();
1324
1325        // INSERT (cursor starts at last)
1326        cursor.last().unwrap();
1327        assert_eq!(cursor.current().unwrap(), Some((9, B256::ZERO)));
1328
1329        for pos in (2..=8).step_by(2) {
1330            assert!(cursor.insert(pos, &B256::ZERO).is_ok());
1331            assert_eq!(cursor.current().unwrap(), Some((pos, B256::ZERO)));
1332        }
1333        tx.commit().expect(ERROR_COMMIT);
1334
1335        // Confirm the result
1336        let tx = db.tx().expect(ERROR_INIT_TX);
1337        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1338        let res = cursor.walk(None).unwrap().map(|res| res.unwrap().0).collect::<Vec<_>>();
1339        assert_eq!(res, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1340        tx.commit().expect(ERROR_COMMIT);
1341    }
1342
1343    #[test]
1344    fn db_cursor_append() {
1345        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1346
1347        // PUT
1348        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1349        vec![0, 1, 2, 3, 4]
1350            .into_iter()
1351            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1352            .expect(ERROR_PUT);
1353        tx.commit().expect(ERROR_COMMIT);
1354
1355        // APPEND
1356        let key_to_append = 5;
1357        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1358        let mut cursor = tx.cursor_write::<CanonicalHeaders>().unwrap();
1359        assert!(cursor.append(key_to_append, &B256::ZERO).is_ok());
1360        tx.commit().expect(ERROR_COMMIT);
1361
1362        // Confirm the result
1363        let tx = db.tx().expect(ERROR_INIT_TX);
1364        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1365        let res = cursor.walk(None).unwrap().map(|res| res.unwrap().0).collect::<Vec<_>>();
1366        assert_eq!(res, vec![0, 1, 2, 3, 4, 5]);
1367        tx.commit().expect(ERROR_COMMIT);
1368    }
1369
1370    #[test]
1371    fn db_cursor_append_failure() {
1372        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1373
1374        // PUT
1375        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1376        vec![0, 1, 3, 4, 5]
1377            .into_iter()
1378            .try_for_each(|key| tx.put::<CanonicalHeaders>(key, B256::ZERO))
1379            .expect(ERROR_PUT);
1380        tx.commit().expect(ERROR_COMMIT);
1381
1382        // APPEND
1383        let key_to_append = 2;
1384        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1385        let mut cursor = tx.cursor_write::<CanonicalHeaders>().unwrap();
1386        assert!(matches!(
1387        cursor.append(key_to_append, &B256::ZERO).unwrap_err(),
1388        DatabaseError::Write(err) if *err == DatabaseWriteError {
1389            info: Error::KeyMismatch.into(),
1390            operation: DatabaseWriteOperation::CursorAppend,
1391            table_name: CanonicalHeaders::NAME,
1392            key: key_to_append.encode().into(),
1393        }));
1394        assert_eq!(cursor.current().unwrap(), Some((5, B256::ZERO))); // the end of table
1395        tx.commit().expect(ERROR_COMMIT);
1396
1397        // Confirm the result
1398        let tx = db.tx().expect(ERROR_INIT_TX);
1399        let mut cursor = tx.cursor_read::<CanonicalHeaders>().unwrap();
1400        let res = cursor.walk(None).unwrap().map(|res| res.unwrap().0).collect::<Vec<_>>();
1401        assert_eq!(res, vec![0, 1, 3, 4, 5]);
1402        tx.commit().expect(ERROR_COMMIT);
1403    }
1404
1405    #[test]
1406    fn db_cursor_upsert() {
1407        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1408        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1409
1410        let mut cursor = tx.cursor_write::<PlainAccountState>().unwrap();
1411        let key = Address::random();
1412
1413        let account = Account::default();
1414        cursor.upsert(key, &account).expect(ERROR_UPSERT);
1415        assert_eq!(cursor.seek_exact(key).unwrap(), Some((key, account)));
1416
1417        let account = Account { nonce: 1, ..Default::default() };
1418        cursor.upsert(key, &account).expect(ERROR_UPSERT);
1419        assert_eq!(cursor.seek_exact(key).unwrap(), Some((key, account)));
1420
1421        let account = Account { nonce: 2, ..Default::default() };
1422        cursor.upsert(key, &account).expect(ERROR_UPSERT);
1423        assert_eq!(cursor.seek_exact(key).unwrap(), Some((key, account)));
1424
1425        let mut dup_cursor = tx.cursor_dup_write::<PlainStorageState>().unwrap();
1426        let subkey = B256::random();
1427
1428        let value = U256::ONE;
1429        let entry1 = StorageEntry { key: subkey, value };
1430        dup_cursor.upsert(key, &entry1).expect(ERROR_UPSERT);
1431        assert_eq!(dup_cursor.seek_by_key_subkey(key, subkey).unwrap(), Some(entry1));
1432
1433        let value = U256::from(2);
1434        let entry2 = StorageEntry { key: subkey, value };
1435        dup_cursor.upsert(key, &entry2).expect(ERROR_UPSERT);
1436        assert_eq!(dup_cursor.seek_by_key_subkey(key, subkey).unwrap(), Some(entry1));
1437        assert_eq!(dup_cursor.next_dup_val().unwrap(), Some(entry2));
1438    }
1439
1440    #[test]
1441    fn db_cursor_dupsort_append() {
1442        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1443
1444        let transition_id = 2;
1445
1446        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1447        let mut cursor = tx.cursor_write::<AccountChangeSets>().unwrap();
1448        vec![0, 1, 3, 4, 5]
1449            .into_iter()
1450            .try_for_each(|val| {
1451                cursor.append(
1452                    transition_id,
1453                    &AccountBeforeTx { address: Address::with_last_byte(val), info: None },
1454                )
1455            })
1456            .expect(ERROR_APPEND);
1457        tx.commit().expect(ERROR_COMMIT);
1458
1459        // APPEND DUP & APPEND
1460        let subkey_to_append = 2;
1461        let tx = db.tx_mut().expect(ERROR_INIT_TX);
1462        let mut cursor = tx.cursor_write::<AccountChangeSets>().unwrap();
1463        assert!(matches!(
1464        cursor
1465            .append_dup(
1466                transition_id,
1467                AccountBeforeTx {
1468                    address: Address::with_last_byte(subkey_to_append),
1469                    info: None
1470                }
1471            )
1472            .unwrap_err(),
1473        DatabaseError::Write(err) if *err == DatabaseWriteError {
1474            info: Error::KeyMismatch.into(),
1475            operation: DatabaseWriteOperation::CursorAppendDup,
1476            table_name: AccountChangeSets::NAME,
1477            key: transition_id.encode().into(),
1478        }));
1479        assert!(matches!(
1480            cursor
1481                .append(
1482                    transition_id - 1,
1483                    &AccountBeforeTx {
1484                        address: Address::with_last_byte(subkey_to_append),
1485                        info: None
1486                    }
1487                )
1488                .unwrap_err(),
1489            DatabaseError::Write(err) if *err == DatabaseWriteError {
1490                info: Error::KeyMismatch.into(),
1491                operation: DatabaseWriteOperation::CursorAppend,
1492                table_name: AccountChangeSets::NAME,
1493                key: (transition_id - 1).encode().into(),
1494            }
1495        ));
1496        assert!(cursor
1497            .append(
1498                transition_id,
1499                &AccountBeforeTx { address: Address::with_last_byte(subkey_to_append), info: None }
1500            )
1501            .is_ok());
1502    }
1503
1504    #[test]
1505    #[allow(clippy::needless_update)]
1506    #[allow(clippy::clone_on_copy)]
1507    fn db_closure_put_get() {
1508        let tempdir = TempDir::new().expect(ERROR_TEMPDIR);
1509        let path = tempdir.path();
1510
1511        let value = Account {
1512            nonce: 18446744073709551615,
1513            bytecode_hash: Some(B256::random()),
1514            balance: U256::MAX,
1515            ..Default::default()
1516        };
1517        let key = address!("0xa2c122be93b0074270ebee7f6b7292c7deb45047");
1518
1519        {
1520            let env = create_test_db_with_path(DatabaseEnvKind::RW, path);
1521
1522            // PUT
1523            let result = env.update(|tx| {
1524                tx.put::<PlainAccountState>(key, value.clone()).expect(ERROR_PUT);
1525                200
1526            });
1527            assert_eq!(result.expect(ERROR_RETURN_VALUE), 200);
1528        }
1529
1530        let env = DatabaseEnv::open(
1531            path,
1532            DatabaseEnvKind::RO,
1533            DatabaseArguments::new(ClientVersion::default()),
1534        )
1535        .expect(ERROR_DB_CREATION);
1536
1537        // GET
1538        let result =
1539            env.view(|tx| tx.get::<PlainAccountState>(key).expect(ERROR_GET)).expect(ERROR_GET);
1540
1541        assert_eq!(result, Some(value))
1542    }
1543
1544    #[test]
1545    fn db_dup_sort() {
1546        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
1547        let key = address!("0xa2c122be93b0074270ebee7f6b7292c7deb45047");
1548
1549        // PUT (0,0)
1550        let value00 = StorageEntry::default();
1551        env.update(|tx| tx.put::<PlainStorageState>(key, value00).expect(ERROR_PUT)).unwrap();
1552
1553        // PUT (2,2)
1554        let value22 = StorageEntry { key: B256::with_last_byte(2), value: U256::from(2) };
1555        env.update(|tx| tx.put::<PlainStorageState>(key, value22).expect(ERROR_PUT)).unwrap();
1556
1557        // PUT (1,1)
1558        let value11 = StorageEntry { key: B256::with_last_byte(1), value: U256::ONE };
1559        env.update(|tx| tx.put::<PlainStorageState>(key, value11).expect(ERROR_PUT)).unwrap();
1560
1561        // Iterate with cursor
1562        {
1563            let tx = env.tx().expect(ERROR_INIT_TX);
1564            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1565
1566            // Notice that value11 and value22 have been ordered in the DB.
1567            assert_eq!(Some(value00), cursor.next_dup_val().unwrap());
1568            assert_eq!(Some(value11), cursor.next_dup_val().unwrap());
1569            assert_eq!(Some(value22), cursor.next_dup_val().unwrap());
1570        }
1571
1572        // Seek value with exact subkey
1573        {
1574            let tx = env.tx().expect(ERROR_INIT_TX);
1575            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1576            let mut walker = cursor.walk_dup(Some(key), Some(B256::with_last_byte(1))).unwrap();
1577            assert_eq!(
1578                (key, value11),
1579                walker
1580                    .next()
1581                    .expect("element should exist.")
1582                    .expect("should be able to retrieve it.")
1583            );
1584        }
1585    }
1586
1587    #[test]
1588    fn db_walk_dup_with_not_existing_key() {
1589        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
1590        let key = address!("0xa2c122be93b0074270ebee7f6b7292c7deb45047");
1591
1592        // PUT (0,0)
1593        let value00 = StorageEntry::default();
1594        env.update(|tx| tx.put::<PlainStorageState>(key, value00).expect(ERROR_PUT)).unwrap();
1595
1596        // PUT (2,2)
1597        let value22 = StorageEntry { key: B256::with_last_byte(2), value: U256::from(2) };
1598        env.update(|tx| tx.put::<PlainStorageState>(key, value22).expect(ERROR_PUT)).unwrap();
1599
1600        // PUT (1,1)
1601        let value11 = StorageEntry { key: B256::with_last_byte(1), value: U256::ONE };
1602        env.update(|tx| tx.put::<PlainStorageState>(key, value11).expect(ERROR_PUT)).unwrap();
1603
1604        // Try to walk_dup with not existing key should immediately return None
1605        {
1606            let tx = env.tx().expect(ERROR_INIT_TX);
1607            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1608            let not_existing_key = Address::ZERO;
1609            let mut walker = cursor.walk_dup(Some(not_existing_key), None).unwrap();
1610            assert!(walker.next().is_none());
1611        }
1612    }
1613
1614    #[test]
1615    fn db_iterate_over_all_dup_values() {
1616        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
1617        let key1 = Address::repeat_byte(0x11);
1618        let key2 = Address::repeat_byte(0x22);
1619
1620        // PUT key1 (0,0)
1621        let value00 = StorageEntry::default();
1622        env.update(|tx| tx.put::<PlainStorageState>(key1, value00).expect(ERROR_PUT)).unwrap();
1623
1624        // PUT key1 (1,1)
1625        let value11 = StorageEntry { key: B256::with_last_byte(1), value: U256::ONE };
1626        env.update(|tx| tx.put::<PlainStorageState>(key1, value11).expect(ERROR_PUT)).unwrap();
1627
1628        // PUT key2 (2,2)
1629        let value22 = StorageEntry { key: B256::with_last_byte(2), value: U256::from(2) };
1630        env.update(|tx| tx.put::<PlainStorageState>(key2, value22).expect(ERROR_PUT)).unwrap();
1631
1632        // Iterate with walk_dup
1633        {
1634            let tx = env.tx().expect(ERROR_INIT_TX);
1635            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1636            let mut walker = cursor.walk_dup(None, None).unwrap();
1637
1638            // Notice that value11 and value22 have been ordered in the DB.
1639            assert_eq!((key1, value00), walker.next().unwrap().unwrap());
1640            assert_eq!((key1, value11), walker.next().unwrap().unwrap());
1641            // NOTE: Dup cursor does NOT iterates on all values but only on duplicated values of the
1642            // same key. assert_eq!(Ok(Some(value22.clone())), walker.next());
1643            assert!(walker.next().is_none());
1644        }
1645
1646        // Iterate by using `walk`
1647        {
1648            let tx = env.tx().expect(ERROR_INIT_TX);
1649            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1650            let first = cursor.first().unwrap().unwrap();
1651            let mut walker = cursor.walk(Some(first.0)).unwrap();
1652            assert_eq!((key1, value00), walker.next().unwrap().unwrap());
1653            assert_eq!((key1, value11), walker.next().unwrap().unwrap());
1654            assert_eq!((key2, value22), walker.next().unwrap().unwrap());
1655        }
1656    }
1657
1658    #[test]
1659    fn dup_value_with_same_subkey() {
1660        let (_tempdir, env) = create_test_db(DatabaseEnvKind::RW);
1661        let key1 = Address::repeat_byte(0x11);
1662        let key2 = Address::repeat_byte(0x22);
1663
1664        // PUT key1 (0,1)
1665        let value01 = StorageEntry { key: B256::with_last_byte(0), value: U256::ONE };
1666        env.update(|tx| tx.put::<PlainStorageState>(key1, value01).expect(ERROR_PUT)).unwrap();
1667
1668        // PUT key1 (0,0)
1669        let value00 = StorageEntry::default();
1670        env.update(|tx| tx.put::<PlainStorageState>(key1, value00).expect(ERROR_PUT)).unwrap();
1671
1672        // PUT key2 (2,2)
1673        let value22 = StorageEntry { key: B256::with_last_byte(2), value: U256::from(2) };
1674        env.update(|tx| tx.put::<PlainStorageState>(key2, value22).expect(ERROR_PUT)).unwrap();
1675
1676        // Iterate with walk
1677        {
1678            let tx = env.tx().expect(ERROR_INIT_TX);
1679            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1680            let first = cursor.first().unwrap().unwrap();
1681            let mut walker = cursor.walk(Some(first.0)).unwrap();
1682
1683            // NOTE: Both values are present
1684            assert_eq!((key1, value00), walker.next().unwrap().unwrap());
1685            assert_eq!((key1, value01), walker.next().unwrap().unwrap());
1686            assert_eq!((key2, value22), walker.next().unwrap().unwrap());
1687        }
1688
1689        // seek_by_key_subkey
1690        {
1691            let tx = env.tx().expect(ERROR_INIT_TX);
1692            let mut cursor = tx.cursor_dup_read::<PlainStorageState>().unwrap();
1693
1694            // NOTE: There are two values with same SubKey but only first one is shown
1695            assert_eq!(value00, cursor.seek_by_key_subkey(key1, value00.key).unwrap().unwrap());
1696            // key1 but value is greater than the one in the DB
1697            assert_eq!(None, cursor.seek_by_key_subkey(key1, value22.key).unwrap());
1698        }
1699    }
1700
1701    #[test]
1702    fn db_sharded_key() {
1703        let (_tempdir, db) = create_test_db(DatabaseEnvKind::RW);
1704        let real_key = address!("0xa2c122be93b0074270ebee7f6b7292c7deb45047");
1705
1706        let shards = 5;
1707        for i in 1..=shards {
1708            let key = ShardedKey::new(real_key, if i == shards { u64::MAX } else { i * 100 });
1709            let list = IntegerList::new_pre_sorted([i * 100u64]);
1710
1711            db.update(|tx| tx.put::<AccountsHistory>(key.clone(), list.clone()).expect(""))
1712                .unwrap();
1713        }
1714
1715        // Seek value with non existing key.
1716        {
1717            let tx = db.tx().expect(ERROR_INIT_TX);
1718            let mut cursor = tx.cursor_read::<AccountsHistory>().unwrap();
1719
1720            // It will seek the one greater or equal to the query. Since we have `Address | 100`,
1721            // `Address | 200` in the database and we're querying `Address | 150` it will return us
1722            // `Address | 200`.
1723            let mut walker = cursor.walk(Some(ShardedKey::new(real_key, 150))).unwrap();
1724            let (key, list) = walker
1725                .next()
1726                .expect("element should exist.")
1727                .expect("should be able to retrieve it.");
1728
1729            assert_eq!(ShardedKey::new(real_key, 200), key);
1730            let list200 = IntegerList::new_pre_sorted([200u64]);
1731            assert_eq!(list200, list);
1732        }
1733        // Seek greatest index
1734        {
1735            let tx = db.tx().expect(ERROR_INIT_TX);
1736            let mut cursor = tx.cursor_read::<AccountsHistory>().unwrap();
1737
1738            // It will seek the MAX value of transition index and try to use prev to get first
1739            // biggers.
1740            let _unknown = cursor.seek_exact(ShardedKey::new(real_key, u64::MAX)).unwrap();
1741            let (key, list) = cursor
1742                .prev()
1743                .expect("element should exist.")
1744                .expect("should be able to retrieve it.");
1745
1746            assert_eq!(ShardedKey::new(real_key, 400), key);
1747            let list400 = IntegerList::new_pre_sorted([400u64]);
1748            assert_eq!(list400, list);
1749        }
1750    }
1751
1752    #[test]
1753    fn db_tracks_table_dbis() {
1754        #[derive(Debug)]
1755        struct CustomTable;
1756
1757        impl Table for CustomTable {
1758            const NAME: &'static str = "CustomTable";
1759            const DUPSORT: bool = false;
1760
1761            type Key = u64;
1762            type Value = u64;
1763        }
1764
1765        impl TableInfo for CustomTable {
1766            fn name(&self) -> &'static str {
1767                Self::NAME
1768            }
1769
1770            fn is_dupsort(&self) -> bool {
1771                Self::DUPSORT
1772            }
1773        }
1774
1775        impl TableSet for CustomTable {
1776            fn tables() -> Box<dyn Iterator<Item = Box<dyn TableInfo>>> {
1777                Box::new(std::iter::once(Box::new(Self) as Box<dyn TableInfo>))
1778            }
1779        }
1780
1781        let (_tempdir, mut env) = create_test_db(DatabaseEnvKind::RW);
1782        env.create_and_track_tables_for::<CustomTable>().expect(ERROR_TABLE_CREATION);
1783        let env = env.with_metrics();
1784
1785        let tx = env.tx_mut().expect(ERROR_INIT_TX);
1786        for table in Tables::ALL {
1787            let dbi = tables_to_generic!(table, |T| tx.get_dbi::<T>()).unwrap();
1788            assert_eq!(env.dbis.get(Some(*table), table.name()), Some(dbi), "{table}");
1789            assert_eq!(tx.inner().open_db(Some(table.name())).unwrap().dbi(), dbi, "{table}");
1790        }
1791
1792        let dbi = tx.get_dbi::<CustomTable>().unwrap();
1793        assert_eq!(env.dbis.get(None, CustomTable::NAME), Some(dbi));
1794        assert_eq!(tx.inner().open_db(Some(CustomTable::NAME)).unwrap().dbi(), dbi);
1795        tx.put::<CustomTable>(1, 2).expect(ERROR_PUT);
1796        tx.cursor_write::<CustomTable>().unwrap().upsert(3, &4).expect(ERROR_UPSERT);
1797        tx.commit().expect(ERROR_COMMIT);
1798
1799        let tx = env.tx().expect(ERROR_INIT_TX);
1800        assert_eq!(tx.get::<CustomTable>(1).expect(ERROR_GET), Some(2));
1801        assert_eq!(tx.get::<CustomTable>(3).expect(ERROR_GET), Some(4));
1802    }
1803
1804    #[test]
1805    fn non_durable_sync_period() {
1806        let sync_period = |sync_mode| {
1807            let tempdir = tempfile::TempDir::new().expect(ERROR_TEMPDIR);
1808            let env = DatabaseEnv::open(
1809                tempdir.path(),
1810                DatabaseEnvKind::RW,
1811                DatabaseArguments::test().with_sync_mode(Some(sync_mode)),
1812            )
1813            .expect(ERROR_DB_CREATION);
1814            let mut period = 0;
1815            // SAFETY: the pointer is only used within the closure, while `env` is open.
1816            let rc = env.with_raw_env_ptr(|env| unsafe {
1817                ffi::mdbx_env_get_option(env, ffi::MDBX_opt_sync_period, &raw mut period)
1818            });
1819            assert_eq!(rc, ffi::MDBX_SUCCESS);
1820            // MDBX reports the period in 1/65536 of a second.
1821            Duration::from_secs_f64(period as f64 / 65536.0)
1822        };
1823
1824        assert_eq!(sync_period(SyncMode::Durable), Duration::ZERO);
1825        assert_eq!(sync_period(SyncMode::SafeNoSync), NON_DURABLE_SYNC_PERIOD);
1826        assert_eq!(sync_period(SyncMode::UtterlyNoSync), NON_DURABLE_SYNC_PERIOD);
1827    }
1828
1829    /// A reader slot left behind by a `SIGKILL`ed process must not block
1830    /// [`ReaderTxnTracker::wait_for_pre_commit_readers`] forever.
1831    #[cfg(unix)]
1832    #[test]
1833    fn wait_for_pre_commit_readers_clears_dead_process_reader() {
1834        const CHILD_DB_PATH_ENV: &str = "RETH_TEST_STALE_READER_DB_PATH";
1835
1836        // Child process: hold a read transaction until killed or until the parent closes stdin.
1837        if let Some(path) = std::env::var_os(CHILD_DB_PATH_ENV) {
1838            let env = DatabaseEnv::open(
1839                Path::new(&path),
1840                DatabaseEnvKind::RO,
1841                DatabaseArguments::new(ClientVersion::default()),
1842            )
1843            .unwrap();
1844            let _tx = env.tx().unwrap();
1845            println!("ready");
1846            let _ = std::io::stdin().read_to_end(&mut Vec::new());
1847            std::process::exit(0);
1848        }
1849
1850        let (dir, env) = create_test_db(DatabaseEnvKind::RW);
1851        let mut child = Command::new(std::env::current_exe().unwrap())
1852            .args([
1853                "--exact",
1854                "implementation::mdbx::tests::wait_for_pre_commit_readers_clears_dead_process_reader",
1855                "--nocapture",
1856            ])
1857            .env(CHILD_DB_PATH_ENV, dir.path())
1858            .stdin(Stdio::piped())
1859            .stdout(Stdio::piped())
1860            .spawn()
1861            .unwrap();
1862        let stdout = BufReader::new(child.stdout.take().unwrap());
1863        let (ready_tx, ready_rx) = mpsc::channel();
1864        std::thread::spawn(move || {
1865            // With one test thread, libtest prints `test <name> ... ` on the same line first.
1866            let ready =
1867                stdout.lines().any(|line| line.is_ok_and(|l| l.trim_end().ends_with("ready")));
1868            let _ = ready_tx.send(ready);
1869        });
1870        let ready = ready_rx.recv_timeout(Duration::from_secs(10));
1871        if ready != Ok(true) {
1872            let _ = child.kill();
1873            let _ = child.wait();
1874            panic!("child did not open a read transaction: {ready:?}");
1875        }
1876
1877        // `Child::kill` sends `SIGKILL`, so the child's reader slot is never released.
1878        child.kill().unwrap();
1879        child.wait().unwrap();
1880
1881        env.update(|tx| tx.put::<CanonicalHeaders>(1, B256::ZERO)).unwrap().unwrap();
1882        assert!(
1883            env.oldest_reader_txnid().unwrap() < env.last_txnid().unwrap(),
1884            "dead reader slot must still be counted before the wait"
1885        );
1886
1887        let env = Arc::new(env);
1888        let (done_tx, done_rx) = mpsc::channel();
1889        let waiter = Arc::clone(&env);
1890        std::thread::spawn(move || {
1891            waiter.wait_for_pre_commit_readers().unwrap();
1892            let _ = done_tx.send(());
1893        });
1894        done_rx
1895            .recv_timeout(Duration::from_secs(10))
1896            .expect("wait_for_pre_commit_readers hung on a dead process's reader slot");
1897        // This process's own idle slot may remain, but no slot may predate the last commit.
1898        let last_txnid = env.last_txnid().unwrap();
1899        assert!(
1900            env.oldest_reader_txnid().is_none_or(|oldest| oldest >= last_txnid),
1901            "dead reader slot must be cleared"
1902        );
1903    }
1904
1905    #[test]
1906    fn commit_durable_syncs_non_durable_env() {
1907        let tempdir = tempfile::TempDir::new().expect(ERROR_TEMPDIR);
1908        let mut env = DatabaseEnv::open(
1909            tempdir.path(),
1910            DatabaseEnvKind::RW,
1911            DatabaseArguments::test().with_sync_mode(Some(SyncMode::SafeNoSync)),
1912        )
1913        .expect(ERROR_DB_CREATION);
1914        env.create_tables().expect(ERROR_TABLE_CREATION);
1915        let info = || env.info().unwrap();
1916
1917        let tx = env.tx_mut().expect(ERROR_INIT_TX);
1918        tx.put::<CanonicalHeaders>(1, B256::ZERO).expect(ERROR_PUT);
1919        tx.commit().expect(ERROR_COMMIT);
1920        assert!(info().last_steady_txnid() < Some(info().last_txnid() as u64));
1921
1922        // Read-only transactions don't sync.
1923        env.tx().expect(ERROR_INIT_TX).commit_durable().expect(ERROR_COMMIT);
1924        assert!(info().last_steady_txnid() < Some(info().last_txnid() as u64));
1925
1926        let tx = env.tx_mut().expect(ERROR_INIT_TX);
1927        tx.put::<CanonicalHeaders>(2, B256::ZERO).expect(ERROR_PUT);
1928        tx.commit_durable().expect(ERROR_COMMIT);
1929        assert_eq!(info().last_steady_txnid(), Some(info().last_txnid() as u64));
1930    }
1931}