Skip to main content

reth_db/
lib.rs

1//! MDBX implementation for reth's database abstraction layer.
2//!
3//! This crate is an implementation of `reth-db-api` for MDBX, as well as a few other common
4//! database types.
5//!
6//! # Overview
7//!
8//! An overview of the current data model of reth can be found in the [`mod@tables`] module.
9
10#![doc(
11    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
12    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
13    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
14)]
15#![cfg_attr(not(test), warn(unused_crate_dependencies))]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17
18mod implementation;
19pub mod lockfile;
20#[cfg(feature = "mdbx")]
21mod metrics;
22pub mod static_file;
23#[cfg(feature = "mdbx")]
24mod utils;
25pub mod version;
26
27#[cfg(feature = "mdbx")]
28pub mod mdbx;
29
30pub use reth_storage_errors::db::{DatabaseError, DatabaseWriteOperation};
31#[cfg(feature = "mdbx")]
32pub use utils::is_database_empty;
33
34#[cfg(feature = "mdbx")]
35pub use mdbx::{create_db, init_db, open_db, open_db_read_only, DatabaseEnv, DatabaseEnvKind};
36
37pub use models::ClientVersion;
38pub use reth_db_api::*;
39
40/// Collection of database test utilities
41#[cfg(any(test, feature = "test-utils"))]
42pub mod test_utils {
43    use super::*;
44    use crate::mdbx::DatabaseArguments;
45    use parking_lot::RwLock;
46    use reth_db_api::{database::Database, database_metrics::DatabaseMetrics};
47    use reth_fs_util;
48    use std::{
49        fmt::Formatter,
50        path::{Path, PathBuf},
51        sync::Arc,
52    };
53    use tempfile::TempDir;
54
55    /// Error during database open
56    pub const ERROR_DB_OPEN: &str = "could not open the database file";
57    /// Error during database creation
58    pub const ERROR_DB_CREATION: &str = "could not create the database file";
59    /// Error during database creation
60    pub const ERROR_STATIC_FILES_CREATION: &str = "could not create the static file path";
61    /// Error during table creation
62    pub const ERROR_TABLE_CREATION: &str = "could not create tables in the database";
63    /// Error during tempdir creation
64    pub const ERROR_TEMPDIR: &str = "could not create a temporary directory";
65
66    /// A database will delete the db dir when dropped.
67    pub struct TempDatabase<DB> {
68        db: Option<DB>,
69        path: PathBuf,
70        /// Executed right before a database transaction is created.
71        pre_tx_hook: RwLock<Box<dyn Fn() + Send + Sync>>,
72        /// Executed right after a database transaction is created.
73        post_tx_hook: RwLock<Box<dyn Fn() + Send + Sync>>,
74    }
75
76    impl<DB: std::fmt::Debug> std::fmt::Debug for TempDatabase<DB> {
77        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
78            f.debug_struct("TempDatabase").field("db", &self.db).field("path", &self.path).finish()
79        }
80    }
81
82    impl<DB> Drop for TempDatabase<DB> {
83        fn drop(&mut self) {
84            if let Some(db) = self.db.take() {
85                drop(db);
86                let _ = reth_fs_util::remove_dir_all(&self.path);
87            }
88        }
89    }
90
91    impl<DB> TempDatabase<DB> {
92        /// Create new [`TempDatabase`] instance.
93        pub fn new(db: DB, path: PathBuf) -> Self {
94            Self {
95                db: Some(db),
96                path,
97                pre_tx_hook: RwLock::new(Box::new(|| ())),
98                post_tx_hook: RwLock::new(Box::new(|| ())),
99            }
100        }
101
102        /// Returns the reference to inner db.
103        pub const fn db(&self) -> &DB {
104            self.db.as_ref().unwrap()
105        }
106
107        /// Returns the path to the database.
108        pub fn path(&self) -> &Path {
109            &self.path
110        }
111
112        /// Convert temp database into inner.
113        pub fn into_inner_db(mut self) -> DB {
114            self.db.take().unwrap() // take out db to avoid clean path in drop fn
115        }
116
117        /// Sets [`TempDatabase`] new pre transaction creation hook.
118        pub fn set_pre_transaction_hook(&self, hook: Box<dyn Fn() + Send + Sync>) {
119            let mut db_hook = self.pre_tx_hook.write();
120            *db_hook = hook;
121        }
122
123        /// Sets [`TempDatabase`] new post transaction creation hook.
124        pub fn set_post_transaction_hook(&self, hook: Box<dyn Fn() + Send + Sync>) {
125            let mut db_hook = self.post_tx_hook.write();
126            *db_hook = hook;
127        }
128    }
129
130    impl<DB: Database> Database for TempDatabase<DB> {
131        type TX = <DB as Database>::TX;
132        type TXMut = <DB as Database>::TXMut;
133        fn tx(&self) -> Result<Self::TX, DatabaseError> {
134            self.pre_tx_hook.read()();
135            let tx = self.db().tx()?;
136            self.post_tx_hook.read()();
137            Ok(tx)
138        }
139
140        fn tx_mut(&self) -> Result<Self::TXMut, DatabaseError> {
141            self.db().tx_mut()
142        }
143
144        fn path(&self) -> std::path::PathBuf {
145            self.db().path()
146        }
147
148        fn oldest_reader_txnid(&self) -> Option<u64> {
149            self.db().oldest_reader_txnid()
150        }
151
152        fn last_txnid(&self) -> Option<u64> {
153            self.db().last_txnid()
154        }
155
156        fn reader_check(&self) -> Result<(), DatabaseError> {
157            self.db().reader_check()
158        }
159    }
160
161    impl<DB: DatabaseMetrics> DatabaseMetrics for TempDatabase<DB> {
162        fn report_metrics(&self) {
163            self.db().report_metrics()
164        }
165    }
166
167    /// Create `static_files` path for testing
168    #[track_caller]
169    pub fn create_test_static_files_dir() -> (TempDir, PathBuf) {
170        let temp_dir = TempDir::with_prefix("reth-test-static-").expect(ERROR_TEMPDIR);
171        let path = temp_dir.path().to_path_buf();
172        (temp_dir, path)
173    }
174
175    /// Create `rocksdb` path for testing
176    #[track_caller]
177    pub fn create_test_rocksdb_dir() -> (TempDir, PathBuf) {
178        let temp_dir = TempDir::with_prefix("reth-test-rocksdb-").expect(ERROR_TEMPDIR);
179        let path = temp_dir.path().to_path_buf();
180        (temp_dir, path)
181    }
182
183    /// Get a temporary directory path to use for the database
184    pub fn tempdir_path() -> PathBuf {
185        let builder = tempfile::Builder::new().prefix("reth-test-").rand_bytes(8).tempdir();
186        builder.expect(ERROR_TEMPDIR).keep()
187    }
188
189    /// Create read/write database for testing
190    #[track_caller]
191    pub fn create_test_rw_db() -> Arc<TempDatabase<DatabaseEnv>> {
192        let path = tempdir_path();
193        let emsg = format!("{ERROR_DB_CREATION}: {path:?}");
194
195        let db = init_db(&path, DatabaseArguments::test()).expect(&emsg);
196
197        Arc::new(TempDatabase::new(db, path))
198    }
199
200    /// Create read/write database for testing
201    #[track_caller]
202    pub fn create_test_rw_db_with_path<P: AsRef<Path>>(path: P) -> Arc<TempDatabase<DatabaseEnv>> {
203        let path = path.as_ref().to_path_buf();
204        let emsg = format!("{ERROR_DB_CREATION}: {path:?}");
205        let db = init_db(path.as_path(), DatabaseArguments::test()).expect(&emsg);
206        Arc::new(TempDatabase::new(db, path))
207    }
208
209    /// Create read/write database for testing within a data directory.
210    ///
211    /// The database is created at `datadir/db`, and `TempDatabase` will clean up the entire
212    /// `datadir` on drop.
213    #[track_caller]
214    pub fn create_test_rw_db_with_datadir<P: AsRef<Path>>(
215        datadir: P,
216    ) -> Arc<TempDatabase<DatabaseEnv>> {
217        let datadir = datadir.as_ref().to_path_buf();
218        let db_path = datadir.join("db");
219        let emsg = format!("{ERROR_DB_CREATION}: {db_path:?}");
220        let db = init_db(&db_path, DatabaseArguments::test()).expect(&emsg);
221        Arc::new(TempDatabase::new(db, datadir))
222    }
223
224    /// Create read only database for testing
225    #[track_caller]
226    pub fn create_test_ro_db() -> Arc<TempDatabase<DatabaseEnv>> {
227        let args = DatabaseArguments::test();
228
229        let path = tempdir_path();
230        let emsg = format!("{ERROR_DB_CREATION}: {path:?}");
231        {
232            init_db(path.as_path(), args.clone()).expect(&emsg);
233        }
234        let db = open_db_read_only(path.as_path(), args).expect(ERROR_DB_OPEN);
235        Arc::new(TempDatabase::new(db, path))
236    }
237
238    /// Enables MDBX legacy multi-open mode, allowing the same database to be opened
239    /// multiple times within a single process. This is needed for tests that simulate
240    /// concurrent primary + read-only secondary provider scenarios.
241    ///
242    /// Must be called before any MDBX environment is opened.
243    ///
244    /// # Safety
245    ///
246    /// This uses `MDBX_DBG_LEGACY_MULTIOPEN` which recovers POSIX file locks on close.
247    /// It may cause unexpected pauses and does not perfectly mirror multi-process behavior.
248    /// Use only in tests.
249    pub fn enable_legacy_multiopen() {
250        unsafe {
251            reth_libmdbx::ffi::mdbx_setup_debug(
252                reth_libmdbx::ffi::MDBX_LOG_DONTCHANGE,
253                reth_libmdbx::ffi::MDBX_DBG_LEGACY_MULTIOPEN as reth_libmdbx::ffi::MDBX_debug_flags,
254                None,
255            );
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use crate::{
263        init_db,
264        mdbx::DatabaseArguments,
265        open_db, tables,
266        version::{db_version_file_path, DatabaseVersionError},
267    };
268    use assert_matches::assert_matches;
269    use reth_db_api::{
270        cursor::DbCursorRO, database::Database, models::ClientVersion, transaction::DbTx,
271    };
272    use reth_libmdbx::MaxReadTransactionDuration;
273    use std::time::Duration;
274    use tempfile::tempdir;
275
276    #[test]
277    fn test_temp_database_cleanup() {
278        // Test that TempDatabase properly cleans up its directory when dropped
279        let temp_path = {
280            let db = crate::test_utils::create_test_rw_db();
281            let path = db.path();
282            assert!(path.exists(), "Database directory should exist while TempDatabase is alive");
283            path
284            // TempDatabase dropped here
285        };
286
287        // Verify the directory was cleaned up
288        assert!(
289            !temp_path.exists(),
290            "Database directory should be cleaned up after TempDatabase is dropped"
291        );
292    }
293
294    #[test]
295    fn db_version() {
296        let path = tempdir().unwrap();
297
298        let args = DatabaseArguments::new(ClientVersion::default())
299            .with_max_read_transaction_duration(Some(MaxReadTransactionDuration::Unbounded));
300
301        // Database is empty
302        {
303            let db = init_db(&path, args.clone());
304            assert_matches!(db, Ok(_));
305        }
306
307        // Database is not empty, current version is the same as in the file
308        {
309            let db = init_db(&path, args.clone());
310            assert_matches!(db, Ok(_));
311        }
312
313        // Database is not empty, version file is malformed
314        {
315            reth_fs_util::write(path.path().join(db_version_file_path(&path)), "invalid-version")
316                .unwrap();
317            let db = init_db(&path, args.clone());
318            assert!(db.is_err());
319            assert_matches!(
320                db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
321                Some(DatabaseVersionError::MalformedFile)
322            )
323        }
324
325        // Database is not empty, version file contains not matching version
326        {
327            reth_fs_util::write(path.path().join(db_version_file_path(&path)), "0").unwrap();
328            let db = init_db(&path, args);
329            assert!(db.is_err());
330            assert_matches!(
331                db.unwrap_err().downcast_ref::<DatabaseVersionError>(),
332                Some(DatabaseVersionError::VersionMismatch { version: 0 })
333            )
334        }
335    }
336
337    #[test]
338    fn db_client_version() {
339        let path = tempdir().unwrap();
340
341        // Empty client version is not recorded
342        {
343            let db = init_db(&path, DatabaseArguments::new(ClientVersion::default())).unwrap();
344            let tx = db.tx().unwrap();
345            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
346            assert_matches!(cursor.first(), Ok(None));
347        }
348
349        // Client version is recorded
350        let first_version = ClientVersion { version: String::from("v1"), ..Default::default() };
351        {
352            let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
353            let tx = db.tx().unwrap();
354            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
355            assert_eq!(
356                cursor
357                    .walk_range(..)
358                    .unwrap()
359                    .map(|x| x.map(|(_, v)| v))
360                    .collect::<Result<Vec<_>, _>>()
361                    .unwrap(),
362                vec![first_version.clone()]
363            );
364        }
365
366        // Same client version is not duplicated.
367        {
368            let db = init_db(&path, DatabaseArguments::new(first_version.clone())).unwrap();
369            let tx = db.tx().unwrap();
370            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
371            assert_eq!(
372                cursor
373                    .walk_range(..)
374                    .unwrap()
375                    .map(|x| x.map(|(_, v)| v))
376                    .collect::<Result<Vec<_>, _>>()
377                    .unwrap(),
378                vec![first_version.clone()]
379            );
380        }
381
382        // Different client version is recorded
383        std::thread::sleep(Duration::from_secs(1));
384        let second_version = ClientVersion { version: String::from("v2"), ..Default::default() };
385        {
386            let db = init_db(&path, DatabaseArguments::new(second_version.clone())).unwrap();
387            let tx = db.tx().unwrap();
388            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
389            assert_eq!(
390                cursor
391                    .walk_range(..)
392                    .unwrap()
393                    .map(|x| x.map(|(_, v)| v))
394                    .collect::<Result<Vec<_>, _>>()
395                    .unwrap(),
396                vec![first_version.clone(), second_version.clone()]
397            );
398        }
399
400        // Different client version is recorded on db open.
401        std::thread::sleep(Duration::from_secs(1));
402        let third_version = ClientVersion { version: String::from("v3"), ..Default::default() };
403        {
404            let db = open_db(path.path(), DatabaseArguments::new(third_version.clone())).unwrap();
405            let tx = db.tx().unwrap();
406            let mut cursor = tx.cursor_read::<tables::VersionHistory>().unwrap();
407            assert_eq!(
408                cursor
409                    .walk_range(..)
410                    .unwrap()
411                    .map(|x| x.map(|(_, v)| v))
412                    .collect::<Result<Vec<_>, _>>()
413                    .unwrap(),
414                vec![first_version, second_version, third_version]
415            );
416        }
417    }
418}