diff --git a/src/node.rs b/src/node.rs index 627ca3a..a051f4d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -293,14 +293,7 @@ impl Node { /// so this is about leaving less to replay (and less on disk) if the /// process is killed right after teardown — not about correctness. fn checkpoint(&self) { - let store = match self.store.lock() { - Ok(s) => s, - Err(e) => { - eprintln!("wal checkpoint: store lock poisoned: {e}"); - return; - } - }; - if let Err(e) = store.checkpoint_wal() { + if let Err(e) = checkpoint_wal(&self.home) { eprintln!("wal checkpoint: {e}"); } } @@ -1043,6 +1036,49 @@ fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { }); } +/// Checkpoint the sqlite WAL into the main db file and truncate it. +/// +/// `Store` owns the write connection and deliberately does not lend it out, and +/// a checkpoint is a property of the *database*, not of one connection — so a +/// short-lived second connection to the same file is the least invasive way to +/// reach it from the node without widening `Store`'s API. +/// +/// That works because the connection needs no passphrase: it moves +/// already-committed pages, it does not decrypt them. It stops working the +/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only +/// inside `Store` and a second connection cannot read the file at all. That case +/// is detected and reported as a skip rather than a failure: nothing is lost +/// (sqlite folds the WAL into the db when the last connection closes) — the +/// explicit truncation just has to move inside `Store` to happen here. +fn checkpoint_wal(home: &Path) -> Result<(), String> { + let db = home.join("onionwire.db"); + if !db.exists() { + return Ok(()); + } + let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?; + let (busy, log, checkpointed): (i64, i64, i64) = conn + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map_err(|e| { + let msg = e.to_string(); + if msg.contains("not a database") { + // SQLCipher store: no key here, so this connection sees noise. + format!("store is SQLCipher-encrypted — skipped ({msg})") + } else { + format!("wal_checkpoint: {msg}") + } + })?; + if busy != 0 { + // Another connection is reading/writing: pages are still safe in the + // WAL, they just were not moved this time. + return Err(format!( + "busy ({checkpointed}/{log} pages moved, another connection active)" + )); + } + Ok(()) +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") @@ -1086,3 +1122,56 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { false } +#[cfg(test)] +mod lifecycle_tests { + //! Offline half of the shutdown contract. The live-Tor half lives in + //! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI. + + use super::*; + + /// `checkpoint_wal` reaches the database through a *second* connection, + /// because `Store` owns the write one. That assumption is the whole reason + /// the helper can live in `node.rs`, so prove it against a real WAL. + #[test] + fn checkpoint_wal_truncates_a_live_wal() { + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path(); + let db = home.join("onionwire.db"); + let conn = rusqlite::Connection::open(&db).expect("open db"); + let mode: String = conn + .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)) + .expect("wal mode"); + assert_eq!(mode.to_lowercase(), "wal"); + conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") + .expect("create table"); + for _ in 0..64 { + conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) + .expect("insert"); + } + + let wal = home.join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).expect("wal file").len(); + assert!(before > 0, "expected pending WAL frames, got {before}"); + + checkpoint_wal(home).expect("checkpoint"); + + let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); + + // The rows are still there — a checkpoint moves pages, it never drops + // committed data. + let n: i64 = conn + .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)) + .expect("count"); + assert_eq!(n, 64); + } + + /// A home directory with no store yet is not an error: `shutdown` and + /// `flush` are safe to call on a node whose db was never created (tests, + /// wiped installs). + #[test] + fn checkpoint_wal_is_a_no_op_without_a_database() { + let root = tempfile::tempdir().expect("tempdir"); + checkpoint_wal(root.path()).expect("no db, no error"); + } +} diff --git a/src/store.rs b/src/store.rs index 726e169..a90666f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1047,31 +1047,6 @@ impl Store { Ok(out) } - /// Fold the WAL into the main db file and truncate it. - /// - /// Runs on this store's own keyed connection: a second, unkeyed connection - /// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint - /// has to happen here, not from `node.rs`. - /// - /// Best effort on purpose: WAL replay on open recovers everything committed, - /// so this is about leaving less to replay (and less on disk) if the process - /// is killed right after teardown — not about correctness. - pub fn checkpoint_wal(&self) -> Result<()> { - let (busy, log, checkpointed): (i64, i64, i64) = - self.conn - .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { - Ok((row.get(0)?, row.get(1)?, row.get(2)?)) - })?; - if busy != 0 { - // Another connection is reading/writing: pages are still safe in the - // WAL, they just were not moved this time. - return Err(Error(format!( - "busy ({checkpointed}/{log} pages moved, another connection active)" - ))); - } - Ok(()) - } - /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { @@ -1083,7 +1058,7 @@ impl Store { self.conn.execute("DELETE FROM messages", [])?; self.conn.execute("DELETE FROM payments", [])?; self.conn.execute_batch("VACUUM")?; - self.checkpoint_wal()?; + self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; Ok(()) } @@ -1397,33 +1372,6 @@ mod at_rest { use super::*; use zeroize::Zeroize; - /// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has - /// to run on the store's own keyed connection: a second, unkeyed one cannot - /// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently - /// never happened. - #[test] - fn checkpoint_wal_truncates_an_encrypted_store_wal() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap(); - let pk = [3u8; 32]; - store.upsert_friend(&pk, "peer.onion", None).unwrap(); - for _ in 0..64 { - store.append_message(&pk, "out", &[7u8; 512]).unwrap(); - } - - let wal = dir.path().join("onionwire.db-wal"); - let before = std::fs::metadata(&wal).expect("wal file").len(); - assert!(before > 0, "expected pending WAL frames, got {before}"); - - store.checkpoint_wal().expect("checkpoint"); - - let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); - assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); - - // A checkpoint moves pages into the db; it never drops committed data. - assert_eq!(store.list_messages(&pk).unwrap().len(), 64); - } - #[test] fn store_data_key_is_a_zeroizing_wrapper_that_wipes() { let dir = tempfile::tempdir().unwrap(); diff --git a/tests/tor_lifecycle.rs b/tests/tor_lifecycle.rs index 6aad70e..c74b081 100644 --- a/tests/tor_lifecycle.rs +++ b/tests/tor_lifecycle.rs @@ -10,7 +10,7 @@ //! //! The offline half of this contract — the Arti-status projection, the WAL //! checkpoint, and the SDK's typed error after shutdown — runs in the normal -//! suite (`tests/hs.rs`, `src/store.rs`, `crates/onionwire-sdk/src/lib.rs`). +//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`). use onionwire::node::{FlushOutcome, Node}; use onionwire::hs::TorState; @@ -52,25 +52,10 @@ async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() { "start returned Ok but tor_state() is {started_state:?}" ); - // Rows written by `start` (self row, current onion) are still in the WAL at - // this point: no checkpoint has run, and the connection that wrote them is - // still open. - let wal = home.join("onionwire.db-wal"); - let before = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); - assert!( - before > 0, - "expected pending WAL frames before flush, got {before}" - ); - // A flush with nothing queued is a no-op that reports it, not an error. let drained: FlushOutcome = node.flush().await.expect("flush on a live node"); assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}"); - // `flush` promises a truncated WAL, and on an encrypted store that only - // works through the store's own keyed connection. - let left = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); - assert_eq!(left, 0, "flush left {left} bytes of WAL to replay"); - node.shutdown().await.expect("shutdown"); assert_eq!(