From 43dd7ad79339b8dfdaf0161cae35acaf55e74ad2 Mon Sep 17 00:00:00 2001 From: Buffrr Date: Tue, 17 Mar 2026 13:58:33 +0100 Subject: [PATCH] Support reset to undo all snapshots --- Cargo.toml | 2 +- src/db.rs | 8 ++++++++ tests/integration_test.rs | 40 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 430d3a1..0726da9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ workspace = { members = ["example"] } [package] name = "spacedb" -version = "0.0.11" +version = "0.0.12" edition = "2021" description = "A cryptographically verifiable data store and universal accumulator for the Spaces protocol." repository = "https://github.com/spacesprotocol/spacedb" diff --git a/src/db.rs b/src/db.rs index 01cd239..2a637c2 100644 --- a/src/db.rs +++ b/src/db.rs @@ -207,6 +207,14 @@ impl Database { Ok(save_point) } + pub fn reset(&self) -> Result<()> { + let mut header = self.header.lock().expect("acquire lock"); + *header = DatabaseHeader::new(); + self.write_header(&header)?; + self.file.set_len(header.len())?; + Ok(()) + } + pub fn begin_write(&self) -> Result> { Ok(WriteTransaction::new(self)) } diff --git a/tests/integration_test.rs b/tests/integration_test.rs index 14a8e29..1287fc5 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -1359,3 +1359,43 @@ fn read_only_while_writer_holds_db() { drop(db); let _ = fs::remove_file(&db_path); } + +#[test] +fn reset_to_empty() { + let db = Database::memory().unwrap(); + let empty_root = db.begin_read().unwrap().compute_root().unwrap(); + + // Insert data across multiple snapshots + let mut write = db.begin_write().unwrap(); + for i in 0u8..10 { + let mut k = [0u8; 32]; + k[0] = i; + write = write.insert(k, vec![i]).unwrap(); + } + write.commit().unwrap(); + + db.begin_write().unwrap() + .insert([0xFFu8; 32], vec![0xFF]).unwrap() + .commit().unwrap(); + + assert_eq!(db.iter().count(), 2, "should have 2 snapshots"); + assert_ne!(db.begin_read().unwrap().compute_root().unwrap(), empty_root); + + // Reset to empty + db.reset().unwrap(); + + // Should behave like a fresh database + let mut snapshot = db.begin_read().unwrap(); + assert_eq!(snapshot.compute_root().unwrap(), empty_root); + assert_eq!(snapshot.get(&[0u8; 32]).unwrap(), None); + assert_eq!(db.iter().count(), 0, "should have 0 snapshots after reset"); + + // Should be able to write again after reset + db.begin_write().unwrap() + .insert([0x42u8; 32], vec![1, 2, 3]).unwrap() + .commit().unwrap(); + + let mut snapshot = db.begin_read().unwrap(); + assert_eq!(snapshot.get(&[0x42u8; 32]).unwrap(), Some(vec![1, 2, 3])); + assert_ne!(snapshot.compute_root().unwrap(), empty_root); +}