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