diff --git a/payjoin-mailroom/CHANGELOG.md b/payjoin-mailroom/CHANGELOG.md index 9a5c0ccfc..0fc688730 100644 --- a/payjoin-mailroom/CHANGELOG.md +++ b/payjoin-mailroom/CHANGELOG.md @@ -4,6 +4,7 @@ - Let relay operators accept gateway purposes besides BIP77 with `[ohttp_relay] extra_allowed_purposes` (#2024) - Reject mailbox payloads too large to return through the OHTTP gateway with 413, and V1 requests too large to relay with `original-psbt-rejected`, instead of truncating the response (#1983) +- Stop mailbox requests and the background prune task from panicking when the system clock steps back ## 0.1.3 diff --git a/payjoin-mailroom/src/db/files.rs b/payjoin-mailroom/src/db/files.rs index 1f6a77ece..f2dc13659 100644 --- a/payjoin-mailroom/src/db/files.rs +++ b/payjoin-mailroom/src/db/files.rs @@ -11,7 +11,7 @@ use rand::RngCore; use tokio::fs::{self, File}; use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; use tokio::sync::{oneshot, Mutex}; -use tracing::{trace, warn}; +use tracing::{debug, trace, warn}; use crate::db::{Db as DbTrait, Error as DbError}; @@ -485,9 +485,16 @@ impl Mailboxes { self.insert_order .front() .map(|(created, _id)| { - self.ttl - .checked_sub(created.elapsed().expect("system clock moved back")) - .unwrap_or(self.ttl) + // A timestamp in the future means the clock was stepped back + // since the mailbox was written. Treat it as just created. + let elapsed = created.elapsed().unwrap_or_else(|e| { + debug!( + "System clock moved back by {:?} since mailbox was written", + e.duration() + ); + Duration::ZERO + }); + self.ttl.checked_sub(elapsed).unwrap_or(self.ttl) }) .unwrap_or(self.ttl) } @@ -971,6 +978,42 @@ mod tests { Ok(()) } + #[tokio::test] + async fn test_prune_with_future_timestamp() -> std::io::Result<()> { + let dir = tempfile::tempdir()?; + let ttl = Duration::from_secs(600); + + let db = FilesDb::init(Duration::from_millis(2), dir.path().to_owned(), ttl) + .await + .expect("initializing mailbox database should succeed"); + + let id = ShortId([0u8; 8]); + db.post_v2_payload(&id, b"fooo".to_vec()) + .await + .expect("posting payload should succeed") + .expect("contents should be accepted"); + + // Simulate the system clock being stepped back after the write + { + let mut guard = db.mailboxes.lock().await; + for (ts, _) in guard.insert_order.iter_mut() { + *ts += Duration::from_secs(60); + } + } + + assert_eq!(db.prune().await.expect("pruning should not fail"), ttl); + assert_eq!(db.mailboxes.lock().await.len(), 1); + + // Other requests must keep working while the clock catches up + db.post_v2_payload(&ShortId([1u8; 8]), b"barr".to_vec()) + .await + .expect("posting payload should succeed") + .expect("contents should be accepted"); + assert_eq!(db.mailboxes.lock().await.len(), 2); + + Ok(()) + } + async fn assert_all_paths_over_capacity(db: &FilesDb) { let id = ShortId([0; 8]);