From 146ade134c9967b7df0713d6e3490589d8a914f8 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:43:36 -0700 Subject: [PATCH] router: keep delivered ids, stamp costs, and tickets in LXMF's state.db Cache files from earlier versions are imported once. A file that cannot be used never stops the router. --- Cargo.lock | 1 + Cargo.toml | 3 + crates/lxmf-core/Cargo.toml | 7 + crates/lxmf-core/src/lib.rs | 1 + crates/lxmf-core/src/message/draft.rs | 20 - crates/lxmf-core/src/message/tests.rs | 16 - crates/lxmf-core/src/persist.rs | 296 +--- crates/lxmf-core/src/router.rs | 1083 +++++++------ crates/lxmf-core/src/state_store.rs | 1659 ++++++++++++++++++++ crates/lxmf-core/tests/durable_delivery.rs | 180 +-- crates/lxmf-tools/src/commands/lxmd.rs | 68 +- crates/lxmf-tools/src/lxmd_runtime.rs | 10 +- 12 files changed, 2358 insertions(+), 986 deletions(-) create mode 100644 crates/lxmf-core/src/state_store.rs diff --git a/Cargo.lock b/Cargo.lock index f25790d..d8b4a64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -743,6 +743,7 @@ dependencies = [ "rns-protocol", "rns-transport", "rns-wire", + "rusqlite", "serde", "sha2", "tempfile", diff --git a/Cargo.toml b/Cargo.toml index c2c6b8f..afdf42c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,9 @@ tracing-subscriber = "0.3" # Error handling thiserror = "2" +# SQLite (router state, LXMF 1.3.0 state.db) +rusqlite = { version = "0.32", features = ["bundled"] } + # Misc hex = "0.4" tempfile = "3" diff --git a/crates/lxmf-core/Cargo.toml b/crates/lxmf-core/Cargo.toml index 81dadbb..2e832e2 100644 --- a/crates/lxmf-core/Cargo.toml +++ b/crates/lxmf-core/Cargo.toml @@ -7,6 +7,12 @@ edition.workspace = true rust-version.workspace = true license-file.workspace = true +[features] +default = ["sqlite-store"] +# SQLite router state at lxmf/state.db, as LXMF 1.3.0 keeps it. Without it the +# router keeps that state in memory only. +sqlite-store = ["dep:rusqlite"] + [dependencies] base64 = { workspace = true } rns-crypto = { workspace = true } @@ -28,6 +34,7 @@ rand = { workspace = true } hex = { workspace = true } unicode-normalization = { workspace = true } unicode-general-category = { workspace = true } +rusqlite = { workspace = true, optional = true } [target.'cfg(target_os = "ios")'.dependencies] objc2 = "0.6" diff --git a/crates/lxmf-core/src/lib.rs b/crates/lxmf-core/src/lib.rs index 3b0fed8..c104448 100644 --- a/crates/lxmf-core/src/lib.rs +++ b/crates/lxmf-core/src/lib.rs @@ -84,6 +84,7 @@ pub mod propagation_store_v2; pub mod propagation_sync; pub mod router; pub mod stamper; +pub mod state_store; pub mod sync; pub mod ticket; pub mod types; diff --git a/crates/lxmf-core/src/message/draft.rs b/crates/lxmf-core/src/message/draft.rs index 8eb0d7d..7427014 100644 --- a/crates/lxmf-core/src/message/draft.rs +++ b/crates/lxmf-core/src/message/draft.rs @@ -19,7 +19,6 @@ pub struct LxMessageDraft { pub include_ticket: bool, pub outbound_ticket: Option<[u8; 16]>, pub stamp_cost: Option, - ticket_barrier: Option>, } impl Deref for LxMessageDraft { type Target = MessageMetadata; @@ -100,7 +99,6 @@ impl LxMessageDraft { include_ticket: false, outbound_ticket: None, stamp_cost: None, - ticket_barrier: None, }; draft.checked_wire_len()?; Ok(draft) @@ -123,21 +121,6 @@ impl LxMessageDraft { pub fn fields(&self) -> &BTreeMap { &self.fields } - pub(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) { - self.ticket_barrier = Some(owner); - } - pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool { - if self - .ticket_barrier - .as_ref() - .is_some_and(|pending| Arc::ptr_eq(pending, owner)) - { - self.ticket_barrier = None; - true - } else { - false - } - } pub fn get_field(&self, id: impl Into) -> Option<&FieldValue> { self.fields.get(&id.into()) } @@ -292,9 +275,6 @@ impl LxMessageDraft { F: FnOnce(&[u8]) -> Result<[u8; 64], E>, E: std::fmt::Display, { - if self.ticket_barrier.is_some() { - return Err(MessageError::TicketNotCommitted); - } let size = self.checked_wire_len()?; let mut signed = Vec::with_capacity(size); signed.extend_from_slice(&self.destination); diff --git a/crates/lxmf-core/src/message/tests.rs b/crates/lxmf-core/src/message/tests.rs index 72e6577..717fd52 100644 --- a/crates/lxmf-core/src/message/tests.rs +++ b/crates/lxmf-core/src/message/tests.rs @@ -608,22 +608,6 @@ fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() { &[2] ); } -#[test] -fn signed_body_finalization_ticket_barrier_blocks_signer() { - let owner = Arc::new(()); - let mut d = draft(); - d.mark_ticket_pending(owner.clone()); - assert!(!d.release_ticket_barrier(&Arc::new(()))); - assert!(matches!( - d.clone() - .sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }), - Err(MessageError::TicketNotCommitted) - )); - assert!(d.release_ticket_barrier(&owner)); - assert!(!d.release_ticket_barrier(&owner)); - assert!(d.sign(&key()).is_ok()); -} - #[test] fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() { for bytes in [ diff --git a/crates/lxmf-core/src/persist.rs b/crates/lxmf-core/src/persist.rs index d41c62e..4c41f05 100644 --- a/crates/lxmf-core/src/persist.rs +++ b/crates/lxmf-core/src/persist.rs @@ -1,77 +1,32 @@ //! Router state files in a caller-supplied directory. //! //! Files: -//! * `outbound_stamp_costs` — destination stamp costs and observation times -//! * `available_tickets` — versioned directional ticket state -//! * `local_deliveries` — delivered transient IDs and timestamps -//! * `locally_processed` — processed transient IDs and timestamps //! * `node_stats` — propagation-node counters -//! * `delivery_claims` — delivered/processed IDs appended since the last full save //! * `propagation_suppression_v1` — bounded download suppression records //! * `propagation_node_policies_v1` — recorded propagation-node policies //! -//! These files use the Rust types' MessagePack representations; matching Python -//! filenames does not establish interchangeable contents. Missing files yield -//! empty/default state. Other I/O, malformed-data and capacity errors propagate -//! to the caller. +//! Stamp costs, tickets, and delivered and processed transient IDs live in +//! `state.db` ([`crate::state_store`]). `delivery_claims`, which earlier +//! releases appended to, is only read here so its records can be imported. +//! +//! Missing files yield empty/default state. Other I/O, malformed-data and +//! capacity errors propagate to the caller. use std::collections::HashMap; use std::fs; use std::io; use std::path::Path; -use crate::router::StampCostEntry; -use crate::ticket::{Ticket, TicketStoreSnapshot}; use crate::types::PropagationTransientId; -pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs"; -pub const TICKETS_FILE: &str = "available_tickets"; -pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries"; -pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed"; pub const NODE_STATS_FILE: &str = "node_stats"; -/// Append-only delivered/processed claims written before delivery callbacks run. -pub const DELIVERY_CLAIMS_FILE: &str = "delivery_claims"; +/// Delivered/processed claims that earlier releases appended before delivery callbacks ran. +const DELIVERY_CLAIMS_FILE: &str = "delivery_claims"; const CLAIM_DELIVERED: u8 = 0; const CLAIM_PROCESSED: u8 = 1; const CLAIM_RECORD_LEN: usize = 1 + 32 + 8; -/// Durably append a claim (`processed = false` for delivered IDs). -pub(crate) fn append_delivery_claim( - dir: &Path, - id: &PropagationTransientId, - processed: bool, - at: f64, -) -> io::Result<()> { - use std::io::Write; - let mut record = [0u8; CLAIM_RECORD_LEN]; - record[0] = if processed { - CLAIM_PROCESSED - } else { - CLAIM_DELIVERED - }; - record[1..33].copy_from_slice(id); - record[33..].copy_from_slice(&at.to_le_bytes()); - let mut file = open_claims_for_append(&dir.join(DELIVERY_CLAIMS_FILE), true)?; - file.write_all(&record)?; - file.sync_data() -} - -/// Open a claims file for appending, first dropping a torn trailing record so -/// later records stay aligned. -fn open_claims_for_append(path: &Path, create: bool) -> io::Result { - let file = fs::OpenOptions::new() - .create(create) - .append(true) - .open(path)?; - let len = file.metadata()?.len(); - let torn = len % CLAIM_RECORD_LEN as u64; - if torn != 0 { - file.set_len(len - torn)?; - } - Ok(file) -} - /// Read appended claims as (delivered, processed). A torn trailing record is ignored. #[allow(clippy::type_complexity)] pub(crate) fn load_delivery_claims( @@ -108,36 +63,15 @@ fn claims_saving(dir: &Path) -> std::path::PathBuf { dir.join(format!("{DELIVERY_CLAIMS_FILE}.saving")) } -/// Set the claims appended so far aside for the snapshot being saved; later -/// claims start a new file. Claims set aside by an unfinished save are kept. -pub(crate) fn rotate_delivery_claims(dir: &Path) -> io::Result<()> { - use std::io::Write; - let current = dir.join(DELIVERY_CLAIMS_FILE); - let saving = claims_saving(dir); - if !saving.exists() { - return match fs::rename(¤t, &saving) { - Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), - _ => Ok(()), - }; - } - let bytes = match fs::read(¤t) { - Ok(bytes) => bytes, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(error), - }; - let whole = bytes.len() - bytes.len() % CLAIM_RECORD_LEN; - let mut file = open_claims_for_append(&saving, false)?; - file.write_all(&bytes[..whole])?; - file.sync_data()?; - fs::remove_file(current) -} - -/// Drop the claims set aside once the caches holding them are saved. -pub(crate) fn clear_rotated_delivery_claims(dir: &Path) -> io::Result<()> { - match fs::remove_file(claims_saving(dir)) { - Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), - _ => Ok(()), +/// Remove every claim file once its records are committed to the LXMF state store. +pub(crate) fn clear_delivery_claims(dir: &Path) -> io::Result<()> { + for path in [claims_saving(dir), dir.join(DELIVERY_CLAIMS_FILE)] { + match fs::remove_file(path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error), + _ => {} + } } + Ok(()) } /// Counters persisted by Python's `LXMRouter.save_node_stats`. @@ -259,130 +193,6 @@ fn read_mpk_bounded( .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) } -pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> { - write_mpk(&dir.join(STAMP_COSTS_FILE), costs) -} - -pub fn load_stamp_costs(dir: &Path) -> io::Result> { - Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default()) -} - -/// Process-local revision of a captured ticket state. All production ticket -/// writes pass through the same path coordinator, so a delayed checkpoint can -/// never replace a ticket that a newer signing intent already committed. -#[derive(Debug, Clone)] -pub(crate) struct TicketPersistenceSnapshot { - revision: u64, - snapshot: std::sync::Arc, -} -impl TicketPersistenceSnapshot { - pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT: AtomicU64 = AtomicU64::new(1); - // Rust 1.99 renamed this operation; keep the identical Rust 1.89 API. - #[allow(deprecated)] - let revision = NEXT - .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) - .expect("ticket checkpoint revision exhausted"); - Self { - revision, - snapshot: std::sync::Arc::new(snapshot), - } - } - pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> { - use std::sync::{Mutex, OnceLock}; - struct Latest { - revision: u64, - committed: bool, - } - static WRITERS: OnceLock>> = OnceLock::new(); - fs::create_dir_all(dir)?; - let path = fs::canonicalize(dir)?.join(TICKETS_FILE); - let mut writers = WRITERS - .get_or_init(|| Mutex::new(HashMap::new())) - .lock() - .map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?; - if !writers.contains_key(&path) && writers.len() >= 4096 { - return Err(io::Error::other("ticket persistence path quota exhausted")); - } - let latest = writers.entry(path.clone()).or_insert(Latest { - revision: self.revision, - committed: false, - }); - if self.revision < latest.revision { - if !latest.committed { - return Err(io::Error::other( - "newer ticket checkpoint is uncertain and must be retried", - )); - } - if let Some(required) = required { - let (stored, _) = load_tickets(dir)?; - if !stored.inbound.contains(required) { - return Err(io::Error::other( - "newer ticket state no longer contains this signing intent", - )); - } - } - return Ok(()); - } - if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) { - return Err(io::Error::other( - "ticket snapshot does not contain this signing intent", - )); - } - latest.revision = self.revision; - latest.committed = false; - // Even an uncertain publication raises the revision floor. Older - // snapshots fail closed until this or a newly captured current state - // reestablishes the strict barrier. No failed payload is retained by - // this bounded process-wide metadata coordinator. - write_mpk(&path, &*self.snapshot)?; - latest.committed = true; - Ok(()) - } -} - -pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> { - TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None) -} - -#[derive(serde::Deserialize)] -#[serde(untagged)] -enum PersistedTickets { - Directional(TicketStoreSnapshot), - Legacy(Vec), -} - -pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option>)> { - Ok(match read_mpk(&dir.join(TICKETS_FILE))? { - Some(PersistedTickets::Directional(snapshot)) => (snapshot, None), - Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)), - None => (TicketStoreSnapshot::default(), None), - }) -} - -pub fn save_local_deliveries( - dir: &Path, - ids: &HashMap, -) -> io::Result<()> { - write_mpk(&dir.join(LOCAL_DELIVERIES_FILE), ids) -} - -pub fn load_local_deliveries(dir: &Path) -> io::Result> { - Ok(read_mpk(&dir.join(LOCAL_DELIVERIES_FILE))?.unwrap_or_default()) -} - -pub fn save_locally_processed( - dir: &Path, - ids: &HashMap, -) -> io::Result<()> { - write_mpk(&dir.join(LOCALLY_PROCESSED_FILE), ids) -} - -pub fn load_locally_processed(dir: &Path) -> io::Result> { - Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default()) -} - pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> { let bytes = rmp_serde::to_vec_named(stats) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; @@ -399,85 +209,15 @@ mod tests { use super::*; use tempfile::TempDir; - #[test] - fn claims_after_a_torn_record_stay_readable() { - let tmp = TempDir::new().unwrap(); - append_delivery_claim(tmp.path(), &[1; 32], false, 1.0).unwrap(); - let path = tmp.path().join(DELIVERY_CLAIMS_FILE); - let mut bytes = fs::read(&path).unwrap(); - bytes.extend_from_slice(&[0xFF; 7]); - fs::write(&path, bytes).unwrap(); - append_delivery_claim(tmp.path(), &[2; 32], true, 2.0).unwrap(); - let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap(); - assert_eq!(delivered, vec![([1; 32], 1.0)]); - assert_eq!(processed, vec![([2; 32], 2.0)]); - } - - #[test] - fn stamp_costs_roundtrip() { - let tmp = TempDir::new().unwrap(); - let mut costs = HashMap::new(); - costs.insert( - [0xAA; 16], - StampCostEntry { - cost: Some(12.5), - recorded_at: 1_700_000_000.0, - }, - ); - save_stamp_costs(tmp.path(), &costs).unwrap(); - let loaded = load_stamp_costs(tmp.path()).unwrap(); - assert_eq!(loaded.len(), 1); - assert_eq!(loaded[&[0xAA; 16]].cost, Some(12.5)); - } - - #[test] - fn tickets_roundtrip() { - let tmp = TempDir::new().unwrap(); - let tickets = TicketStoreSnapshot { - version: 1, - outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)], - inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)], - last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]), - }; - save_tickets(tmp.path(), &tickets).unwrap(); - let (loaded, legacy) = load_tickets(tmp.path()).unwrap(); - assert!(legacy.is_none()); - assert_eq!(loaded, tickets); - } - - #[test] - fn legacy_flat_tickets_are_detected_for_migration() { - let tmp = TempDir::new().unwrap(); - let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)]; - write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap(); - let (snapshot, legacy) = load_tickets(tmp.path()).unwrap(); - assert_eq!(snapshot, TicketStoreSnapshot::default()); - assert_eq!(legacy.unwrap(), tickets); - } - - #[test] - fn local_deliveries_roundtrip() { - let tmp = TempDir::new().unwrap(); - let mut ids = HashMap::new(); - ids.insert([0x03; 32], 1_700_000_000.0); - save_local_deliveries(tmp.path(), &ids).unwrap(); - let loaded = load_local_deliveries(tmp.path()).unwrap(); - assert_eq!(loaded.len(), 1); - } - #[test] fn missing_file_returns_default() { let tmp = TempDir::new().unwrap(); - assert!(load_stamp_costs(tmp.path()).unwrap().is_empty()); - let (tickets, legacy) = load_tickets(tmp.path()).unwrap(); - assert_eq!(tickets, TicketStoreSnapshot::default()); - assert!(legacy.is_none()); - assert!(load_local_deliveries(tmp.path()).unwrap().is_empty()); - assert!(load_locally_processed(tmp.path()).unwrap().is_empty()); assert_eq!( load_node_stats(tmp.path()).unwrap(), PersistedNodeStats::default() ); + let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap(); + assert!(delivered.is_empty() && processed.is_empty()); } #[test] diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index a71e2de..e65d304 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -26,7 +26,8 @@ use crate::peer::LxmPeer; use crate::propagation::PropagationStore; use crate::propagation_client::PropagationTransferStatus; use crate::stamper; -use crate::ticket::{Ticket, TicketStore}; +use crate::state_store::{StateStoreError, StateStoreHandle}; +use crate::ticket::Ticket; use crate::types::PropagationTransientId; mod outbound; @@ -43,35 +44,6 @@ pub struct InboundReservation { nonce: u64, } -/// Persistence barrier for a router-minted reply ticket. Signing the marked -/// draft remains blocked until this intent establishes that the required ticket -/// is durable, either in its snapshot or a newer committed ticket snapshot. -pub struct OutboundTicketIntent { - barrier: Option>, - snapshot: Option, - required_ticket: Option, -} -impl OutboundTicketIntent { - pub fn requires_persistence(&self) -> bool { - self.snapshot.is_some() - } - pub fn persist( - self, - state_dir: &std::path::Path, - draft: &mut LxMessageDraft, - ) -> std::io::Result<()> { - if let Some(snapshot) = self.snapshot { - snapshot.save(state_dir, self.required_ticket.as_ref())?; - if !draft.release_ticket_barrier(self.barrier.as_ref().expect("snapshot barrier")) { - return Err(std::io::Error::other( - "reply ticket intent belongs to a different draft", - )); - } - } - Ok(()) - } -} - /// Router configuration. /// /// Additional settings live in [`RouterConfigExt`] behind the `ext` field. @@ -220,8 +192,6 @@ impl std::error::Error for SendError {} pub enum TicketPreparationError { #[error("reply ticket must be added before the LXMF message is signed")] AlreadySigned, - #[error("another reply-ticket draft is awaiting durable persistence")] - PendingPersistence, #[error("failed to encode LXMF reply ticket: {0}")] Encode(String), } @@ -307,10 +277,6 @@ pub struct LxmRouter { /// Peers that will never be rotated out. pub static_peers: Vec<[u8; 16]>, pub propagation_store: PropagationStore, - /// Cached stamp costs keyed by destination hash. - pub outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>, - pub ticket_store: TicketStore, - ticket_intent_in_flight: std::sync::Weak<()>, /// Destination hash → recorded priority level. The propagation index uses /// membership to apply its fixed priority weight; it does not use the level. pub prioritized: HashMap<[u8; 16], u8>, @@ -342,11 +308,18 @@ pub struct LxmRouter { /// A slow-path message concluded; outbound processing should run again. outbound_kick: bool, propagation_announce_due: bool, - /// Directory given to [`Self::load_state`]; delivered and processed IDs are - /// claimed there durably before delivery callbacks run. - claims_dir: Option, + /// Stamp costs, tickets, and delivered and processed transient IDs, as + /// `LXMFStore` keeps them: in memory until [`Self::load_state`] opens `state.db`. + state_store: StateStoreHandle, } +/// Rows removed per store cull call; `LXMFStore.CULL_CHUNK`. +const STORE_CULL_ROWS: usize = 4096; +/// Cull calls per cleaning pass; `LXMRouter.STORE_CULL_CHUNKS`. +const STORE_CULL_CHUNKS: usize = 16; +/// Pages freed per vacuum call; `LXMFStore.VACUUM_PAGES`. +const STORE_VACUUM_PAGES: usize = 512; + /// Delivered destinations a router holds for the embedder to retain. const MAX_PENDING_RETAINS: usize = 256; @@ -368,47 +341,21 @@ pub struct AutopeerCandidate { pub hops: Option, } -/// Cached stamp cost for a destination; `None` records an announce without -/// a cost. Integer costs stored by older versions still load. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct StampCostEntry { - pub cost: Option, - pub recorded_at: f64, -} - -/// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`]. +/// Owned snapshot of the router state written by [`LxmRouter::save_state`]: +/// the node statistics. Stamp costs, tickets, and transient IDs are written to +/// `state.db` as they change and are not part of it. /// -/// Capturing this snapshot clones in-memory state and assigns a ticket revision. /// The caller can release any router lock before calling [`Self::save_state`], /// keeping filesystem I/O out of the router's critical section. #[derive(Debug, Clone)] pub struct RouterStateSnapshot { - outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>, - tickets: crate::persist::TicketPersistenceSnapshot, - local_deliveries: HashMap, - locally_processed: HashMap, node_stats: crate::persist::PersistedNodeStats, - claims_dir: Option, } impl RouterStateSnapshot { - /// Persist this owned snapshot using the router's MessagePack layout. - /// - /// Each file is written atomically via rename, matching - /// [`LxmRouter::save_state`]. The group is not one transaction: an error can - /// follow successful writes to earlier files. Serialize snapshot writes. + /// Write the node statistics file atomically, as [`LxmRouter::save_state`] does. pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> { - use crate::persist; - - persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?; - self.tickets.save(state_dir, None)?; - persist::save_local_deliveries(state_dir, &self.local_deliveries)?; - persist::save_locally_processed(state_dir, &self.locally_processed)?; - persist::save_node_stats(state_dir, &self.node_stats)?; - if self.claims_dir.as_deref() == Some(state_dir) { - persist::clear_rotated_delivery_claims(state_dir)?; - } - Ok(()) + crate::persist::save_node_stats(state_dir, &self.node_stats) } } @@ -430,9 +377,6 @@ impl LxmRouter { peers: HashMap::new(), static_peers: Vec::new(), propagation_store: PropagationStore::new(), - outbound_stamp_costs: HashMap::new(), - ticket_store: TicketStore::new(), - ticket_intent_in_flight: std::sync::Weak::new(), prioritized: HashMap::new(), delivery_callback: None, transport_tx: None, @@ -453,7 +397,7 @@ impl LxmRouter { path_request_times: HashMap::new(), outbound_kick: false, propagation_announce_due: false, - claims_dir: None, + state_store: StateStoreHandle::in_memory(), } } @@ -603,43 +547,28 @@ impl LxmRouter { Ok(()) } - /// Apply router-owned ticket state before a caller signs `message`. + /// Apply router-owned ticket state before a caller signs `message` + /// (`LXMRouter.handle_outbound`). /// /// Learned outbound tickets do not change signed fields and can be /// attached at any time. A requested reply ticket is a signed LXMF field, - /// so it must be inserted before signing. The method is deliberately - /// signer-agnostic. When the returned intent requires persistence, call - /// [`OutboundTicketIntent::persist`] with this draft before `sign` or - /// `sign_with`; signing remains blocked until that barrier is released. + /// so it must be inserted before signing. The ticket is in the state store + /// when this returns: no message can carry a ticket the router would not + /// recognise after a restart. pub fn prepare_outbound( &mut self, message: &mut LxMessageDraft, - ) -> Result { - let now = now_f64(); + ) -> Result<(), TicketPreparationError> { let destination = message.destination_hash(); if message.outbound_ticket.is_none() { - message.outbound_ticket = self - .ticket_store - .find_outbound(&destination, now) - .map(|t| t.token); + message.outbound_ticket = self.get_outbound_ticket(&destination); } if message.stamp_cost.is_none() { message.stamp_cost = self.get_stamp_cost(&destination); } if message.include_ticket && message.get_field(FIELD_TICKET).is_none() - && self.ticket_intent_in_flight.upgrade().is_some() - { - return Err(TicketPreparationError::PendingPersistence); - } - let mut intent = OutboundTicketIntent { - barrier: None, - snapshot: None, - required_ticket: None, - }; - if message.include_ticket - && message.get_field(FIELD_TICKET).is_none() - && let Some(ticket) = self.ticket_store.issue_for(destination, TICKET_EXPIRY, now) + && let Some(ticket) = self.generate_ticket(destination, None) { let encoded = ticket .encode_field() @@ -647,16 +576,8 @@ impl LxmRouter { message .set_msgpack_field(FIELD_TICKET, encoded) .map_err(|e| TicketPreparationError::Encode(e.to_string()))?; - let barrier = std::sync::Arc::new(()); - message.mark_ticket_pending(barrier.clone()); - self.ticket_intent_in_flight = std::sync::Arc::downgrade(&barrier); - intent.barrier = Some(barrier); - intent.required_ticket = Some(ticket); - intent.snapshot = Some(crate::persist::TicketPersistenceSnapshot::capture( - self.ticket_store.snapshot(), - )); } - Ok(intent) + Ok(()) } /// Signatures freeze the body before recipient work; only finalized messages @@ -998,60 +919,112 @@ impl LxmRouter { self.propagation_store.total_size() } - /// Generate a fresh random ticket for `destination_hash` and add it to the ticket store. + /// The reply ticket to include in a message to `destination_hash` + /// (`LXMRouter.generate_ticket`): none within [`TICKET_INTERVAL`] of the + /// last one delivered there, else the issued ticket with more than + /// [`TICKET_RENEW`] of validity left, else a new one valid for + /// `expiry_secs` (default [`TICKET_EXPIRY`]). /// - /// The returned token can be shared with a peer that should bypass stamp PoW when sending - /// to this router. Default expiry is [`TICKET_EXPIRY`] seconds. - /// - /// This low-level helper always generates a token, without renewal/interval - /// reuse or persistence. Persist ticket state before advertising the token; - /// [`Self::prepare_outbound`] supplies the normal reply-ticket barrier. + /// A new ticket is returned only once the state store has committed it and + /// flushed it to disk. Upstream returns it even when the write failed; here + /// the message then goes without a ticket, as it does while `state.db` + /// could not be opened, because the recipient's replies would stop + /// validating after a restart. pub fn generate_ticket( &mut self, destination_hash: [u8; 16], expiry_secs: Option, - ) -> [u8; 16] { - use rand::RngCore; - let mut token = [0u8; TICKET_LENGTH]; - rand::thread_rng().fill_bytes(&mut token); - let expires = now_f64() + expiry_secs.unwrap_or(TICKET_EXPIRY) as f64; - self.ticket_store - .add_inbound(Ticket::new(token, destination_hash, expires)); - token + ) -> Option { + let now = now_f64(); + let expires = now + expiry_secs.unwrap_or(TICKET_EXPIRY) as f64; + let token: [u8; TICKET_LENGTH] = rand::random(); + let durable = !self.state_store.is_fallback(); + let outcome = self.state_store.call(move |s| { + // A failed read counts as no row, as `LXMFStore` returns `None`. + if let Ok(Some(last)) = s.get_last_ticket_delivery(&destination_hash) + && now - last < TICKET_INTERVAL as f64 + { + return Ok(None); + } + if let Ok(Some(reusable)) = + s.get_reusable_inbound_ticket(&destination_hash, TICKET_RENEW as f64) + { + return Ok(Some(reusable)); + } + if !durable { + return Ok(None); + } + let mut stored = Ok(()); + s.synced(&mut |s| stored = s.store_inbound_ticket(&destination_hash, &token, expires))?; + stored.map(|()| Some((expires, token))) + }); + match outcome { + Ok(ticket) => { + ticket.map(|(expires, token)| Ticket::new(token, destination_hash, expires)) + } + Err(error) => { + tracing::error!(%error, "could not save inbound ticket in the LXMF state store; sending without a ticket"); + None + } + } } - /// Record an externally-provided outbound ticket so the router can use it when sending. + /// Record a ticket received from `destination_hash` for stamping messages to it. /// /// Python reference: `LXMRouter.remember_ticket`. pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) { - self.ticket_store - .remember_outbound(Ticket::new(token, destination_hash, expires)); + self.state_store.write("remember ticket", move |s| { + s.remember_ticket(&destination_hash, expires, &token) + }); } /// Return the currently stored valid outbound ticket for `destination_hash`. /// /// Python reference: `LXMRouter.get_outbound_ticket`. pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> { - let now = now_f64(); - self.ticket_store - .find_outbound(destination_hash, now) - .map(|t| t.token) + let destination = *destination_hash; + self.store_read("recall outbound ticket", move |s| { + s.get_outbound_ticket(&destination) + }) } /// Returns the expiry (Unix epoch seconds) of the valid ticket for `destination_hash`. /// /// Python reference: `LXMRouter.get_outbound_ticket_expiry`. pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option { - let now = now_f64(); - self.ticket_store - .find_outbound(destination_hash, now) - .map(|t| t.expires) + let destination = *destination_hash; + self.store_read("recall outbound ticket expiry", move |s| { + s.get_outbound_ticket_expiry(&destination) + }) } - /// Borrow all locally issued inbound tickets, across destinations. Expired - /// entries remain visible until culled. This does not include learned outbound tickets. - pub fn get_inbound_tickets(&self) -> &[Ticket] { - self.ticket_store.inbound() + /// The unexpired tickets issued to `destination_hash`, against which its + /// stamps are checked; `None` when there are none. + /// + /// Python reference: `LXMRouter.get_inbound_tickets`. + pub fn get_inbound_tickets(&self, destination_hash: &[u8; 16]) -> Option> { + let destination = *destination_hash; + self.store_read("recall inbound tickets", move |s| { + s.get_inbound_tickets(&destination) + }) + } + + /// A store read on behalf of the caller. A failure is logged and reads as + /// no row, as `LXMFStore`'s getters return `None`. + fn store_read( + &self, + what: &'static str, + job: impl FnOnce(&mut dyn crate::state_store::Backend) -> Result, StateStoreError> + + Send + + 'static, + ) -> Option { + self.state_store + .call(job) + .inspect_err( + |error| tracing::error!(%error, "could not {what} from the LXMF state store"), + ) + .ok() + .flatten() } /// Cancel a message in the router's outbound or deferred-stamp queue @@ -1143,8 +1116,11 @@ impl LxmRouter { /// ticket-delivery accounting and callbacks reflect the observable result. pub fn complete_outbound_message(&mut self, mut msg: LxMessage) { if msg.fields().contains(FIELD_TICKET) { - self.ticket_store - .mark_ticket_delivered(msg.destination_hash(), now_f64()); + let (destination, now) = (msg.destination_hash(), now_f64()); + self.state_store + .write("record last ticket delivery", move |s| { + s.mark_last_ticket_delivery(&destination, now) + }); } let destination = msg.destination_hash(); if !self.destination_retains.contains(&destination) { @@ -1214,15 +1190,11 @@ impl LxmRouter { }) } - /// Get the cached required stamp cost for a destination (delivery). - /// - /// Returns the cached entry unchanged, without an expiry check. Use - /// [`Self::get_stamp_cost`] to exclude expired entries. Unlike Python's - /// same-named message-ID lookup, this API takes a destination hash. + /// The stored stamp cost for a destination; the same read as + /// [`Self::get_stamp_cost`]. Unlike Python's same-named message-ID + /// lookup, this API takes a destination hash. pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option { - self.outbound_stamp_costs - .get(destination_hash) - .and_then(|e| e.cost) + self.get_stamp_cost(destination_hash) } /// Return the recipient stamp cost recorded on a deferred message. @@ -1234,18 +1206,22 @@ impl LxmRouter { .and_then(|m| m.stamp_cost()) } - /// Check the local-delivery dedupe cache for a message or transient ID. - /// Durable discard/deletion decisions can also populate it; presence does - /// not prove a message file exists. This lookup does not check expiry. + /// Whether a message or transient ID is recorded as delivered + /// (`LXMRouter.has_message`). Durable discard/deletion decisions can also + /// record one; presence does not prove a message file exists. pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool { - self.propagation_store.is_locally_delivered(transient_id) + let id = *transient_id; + self.state_store + .call(move |s| s.has_delivered(&id)) + .inspect_err(|error| tracing::error!(%error, "could not query delivered transient ID in the LXMF state store")) + .unwrap_or(false) } - /// Mark a message ID delivered in memory and invoke the registered callback. + /// Record a message ID as delivered and invoke the registered callback. /// A message from an ignored source returns `false` and is not recorded /// (Python `lxmf_delivery`). With `allow_duplicate = false`, an ID already - /// in the local-delivery cache returns `false`; with `true`, repeated calls - /// may invoke the callback again. + /// delivered returns `false`; with `true`, repeated calls may invoke the + /// callback again. /// This compatibility helper does not verify the message, persist local /// effects or record a distinct ciphertext transient ID. Use the reservation /// and durable-receipt commit path for application admission. @@ -1254,36 +1230,70 @@ impl LxmRouter { if self.is_ignored(&message.source_hash()) { return false; } - let message_id = message.message_id(); - if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) { + if !self.claim_delivered(message.message_id(), allow_duplicate) { return false; } - self.claim_locally_delivered(message_id); if let Some(ref callback) = self.delivery_callback { callback(message); } true } - /// Record a delivered ID, durably first when state is loaded from a directory - /// (Python `conditionally_claim_delivered`). A failed write is logged and the - /// message still counts as new, as Python's store does. - fn claim_locally_delivered(&mut self, id: PropagationTransientId) { - self.propagation_store.mark_locally_delivered(id); - self.append_claim(&id, false); + /// Claim a delivered ID before the delivery is acted on, as `lxmf_delivery` + /// does: `conditionally_claim_delivered`, or `mark_locally_delivered` when + /// duplicates are allowed. The write is awaited and flushed, so the claim + /// is on disk before any callback runs. Returns `false` only for an ID the + /// store already holds; a failed write is logged and the message counts as + /// new, as `LXMFStore._claim` treats it. + fn claim_delivered(&mut self, id: PropagationTransientId, allow_duplicate: bool) -> bool { + let now = now_f64(); + self.state_store + .call_synced(move |s| { + if allow_duplicate { + s.mark_locally_delivered(&id, now).map(|()| true) + } else { + s.conditionally_claim_delivered(&id, now) + } + }) + .unwrap_or_else(|error| { + tracing::error!(%error, "could not claim delivered transient ID in the LXMF state store, treating as claimed"); + true + }) } - fn claim_locally_processed(&mut self, id: PropagationTransientId) { - self.propagation_store.mark_locally_processed(id); - self.append_claim(&id, true); + /// Claim a processed ID as `lxmf_propagation` does: + /// `conditionally_claim_processed`, or `unconditionally_mark_processed` when + /// duplicates are allowed. Awaited and flushed, and a failed write counts + /// as new, like [`Self::claim_delivered`]. The ID also enters the in-memory + /// index the propagation node shares. + fn claim_processed(&mut self, id: PropagationTransientId, allow_duplicate: bool) -> bool { + let now = now_f64(); + self.propagation_store.claim_processed(id, now); + self.state_store + .call_synced(move |s| { + if allow_duplicate { + s.unconditionally_mark_processed(&id, now).map(|()| true) + } else { + s.conditionally_claim_processed(&id, now) + } + }) + .unwrap_or_else(|error| { + tracing::error!(%error, "could not claim processed transient ID in the LXMF state store, treating as claimed"); + true + }) } - fn append_claim(&self, id: &PropagationTransientId, processed: bool) { - if let Some(dir) = &self.claims_dir - && let Err(error) = crate::persist::append_delivery_claim(dir, id, processed, now_f64()) - { - tracing::error!(%error, "could not claim transient id in the router state directory"); - } + /// Write processed IDs that propagation intake stored + /// (`unconditionally_mark_processed` in `lxmf_propagation`). The intake has + /// already made its duplicate decision, so nothing waits for the write, and + /// it is committed at upstream's level. + pub fn record_processed_claims(&mut self, ids: &[(PropagationTransientId, f64)]) { + let ids = ids.to_vec(); + self.state_store + .write("mark processed transient IDs", move |s| { + ids.iter() + .try_for_each(|(id, at)| s.unconditionally_mark_processed(id, *at)) + }); } /// Reserve a message ID before local disk/DB work. An existing reservation @@ -1338,16 +1348,27 @@ impl LxmRouter { { self.learn_ticket_from_inbound(verified); } - self.claim_locally_delivered(receipt.record().scope.transient_id); - self.claim_locally_processed(receipt.record().scope.transient_id); + let (transient_id, message_id) = + (receipt.record().scope.transient_id, message.message_id()); // Python lxmf_delivery drops ignored sources before claiming the message id. - if self.is_ignored(&message.source_hash()) { - return false; - } - let new_message = !self - .propagation_store - .is_locally_delivered(&message.message_id()); - self.claim_locally_delivered(message.message_id()); + let ignored = self.is_ignored(&message.source_hash()); + let now = now_f64(); + self.propagation_store.claim_processed(transient_id, now); + // The claims of `lxmf_propagation` and `lxmf_delivery`, in one flushed transaction. + let new_message = self + .state_store + .call_synced(move |s| { + s.mark_locally_delivered(&transient_id, now)?; + s.unconditionally_mark_processed(&transient_id, now)?; + if ignored { + return Ok(false); + } + s.conditionally_claim_delivered(&message_id, now) + }) + .unwrap_or_else(|error| { + tracing::error!(%error, "could not claim an admitted message in the LXMF state store, treating as claimed"); + !ignored + }); if new_message && receipt.record().disposition == crate::admission::DurableDisposition::Committed { @@ -1370,7 +1391,7 @@ impl LxmRouter { else { return false; }; - self.ticket_store.remember_outbound(ticket); + self.remember_ticket(ticket.destination_hash, ticket.token, ticket.expires); true } @@ -1397,25 +1418,28 @@ impl LxmRouter { let transient_id = rns_crypto::sha::full_hash(&lxmf_data); if !allow_duplicate && (self.propagation_store.contains(&transient_id) - || self.propagation_store.is_locally_processed(&transient_id)) + || !self.claim_processed(transient_id, false)) { return Ok(PaperIngest::Duplicate); } - self.claim_locally_processed(transient_id); + if allow_duplicate { + self.claim_processed(transient_id, true); + } let mut packed = destination_hash.to_vec(); packed.extend_from_slice(&decrypt_fn(&encrypted)?); - // Python records the transient id as delivered even when the decrypted - // bytes do not unpack (LXMRouter.py). - let unpacked = LxMessage::unpack(&packed); - self.claim_locally_delivered(transient_id); - let mut message = unpacked?; - message.method = DeliveryMethod::Propagated; - message.representation = DeliveryRepresentation::Paper; - message.transport_encrypted = true; - message.transport_encryption = Some(rns_identity::identity::CURVE.to_string()); - self.deliver_inbound(&message, allow_duplicate); - Ok(PaperIngest::Delivered(Box::new(message))) + let delivered = LxMessage::unpack(&packed).map(|mut message| { + message.method = DeliveryMethod::Propagated; + message.representation = DeliveryRepresentation::Paper; + message.transport_encrypted = true; + message.transport_encryption = Some(rns_identity::identity::CURVE.to_string()); + self.deliver_inbound(&message, allow_duplicate); + message + }); + // `lxmf_propagation` marks the transient ID after the delivery attempt, + // also when the decrypted bytes did not unpack. + self.claim_delivered(transient_id, true); + Ok(PaperIngest::Delivered(Box::new(delivered?))) } /// Replace the router-wide callback used by inbound delivery/commit helpers. @@ -1430,63 +1454,197 @@ impl LxmRouter { self.delivery_callback = Some(Box::new(callback)); } - /// Load persisted runtime state (stamp costs, tickets, dedup sets) from - /// `state_dir`. Missing files are treated as empty state; other load errors - /// propagate after any earlier fields have already been replaced. Dedup-cache - /// timestamps are restored so age-based expiry survives restarts. + /// Open the router's storage in `state_dir`: the LXMF 1.3.0 store + /// `state_dir/state.db` and the node statistics file. + /// + /// The msgpack caches the store replaced (`local_deliveries`, + /// `locally_processed`, `outbound_stamp_costs`, `available_tickets`) are + /// imported in that order, each in one transaction, and renamed to + /// `.imported` after its commit (`LXMRouter.__import_legacy_storage`). + /// Expired rows are then cleaned as upstream cleans them at start-up. + /// + /// A store that cannot be opened, is corrupt, or carries a newer version + /// never fails this call: the state is kept in memory for the session, the + /// old caches stay where they are, and one error line names the file and + /// the remedy. Only an unreadable node statistics file is an error. pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> { - use crate::persist; - self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?; - let (snapshot, legacy) = persist::load_tickets(state_dir)?; - if let Some(legacy) = legacy { - self.ticket_store.replace_legacy(legacy); - } else { - self.ticket_store.replace_snapshot(snapshot); + use crate::state_store::legacy::{self, Source}; + + self.state_store = Self::open_state_store(state_dir); + let durable = self.state_store.is_file_backed(); + + for source in Source::ALL { + let name = source.file_name(); + let file = state_dir.join(name); + if !file.is_file() { + continue; + } + let outcome = self.state_store.call(move |s| { + Ok(if durable { + legacy::import(s, source, &file) + } else { + // The session's memory gets the rows; the file stays for a later import. + legacy::read_rows(source, &file).and_then(|rows| { + s.apply_imported(&rows).map_err(legacy::ImportError::Store) + }) + }) + }); + match outcome { + Ok(Ok(rows)) => { + tracing::debug!( + rows, + file = name, + "imported legacy cache into the LXMF state store" + ) + } + Ok(Err(error)) => { + tracing::error!( + file = name, + "legacy cache not imported into the LXMF state store: {error}" + ) + } + Err(error) => { + tracing::error!(%error, file = name, "legacy cache not imported into the LXMF state store") + } + } } - self.propagation_store - .replace_locally_delivered(persist::load_local_deliveries(state_dir)?); - self.propagation_store - .replace_locally_processed(persist::load_locally_processed(state_dir)?); - let (delivered, processed) = persist::load_delivery_claims(state_dir)?; - for (id, at) in delivered { - self.propagation_store.restore_locally_delivered(id, at); + self.import_delivery_claims(state_dir, durable); + + // `LXMRouter.__import_legacy_storage` ends with these four. + self.clean_transient_id_caches(); + self.cull_stamp_costs(); + self.clean_available_tickets(); + self.state_store.write("run incremental vacuum", |s| { + s.incremental_vacuum(STORE_VACUUM_PAGES).map(|_| ()) + }); + + // The propagation node dedupes its intake against the processed IDs. + match self.state_store.call(|s| s.processed_ids()) { + Ok(processed) => self + .propagation_store + .replace_locally_processed(processed.into_iter().collect()), + Err(error) => { + tracing::error!(%error, "could not read processed transient IDs from the LXMF state store") + } } - for (id, at) in processed { - self.propagation_store.restore_locally_processed(id, at); - } - self.claims_dir = Some(state_dir.to_path_buf()); - let stats = persist::load_node_stats(state_dir)?; + + let stats = crate::persist::load_node_stats(state_dir)?; self.client_propagation_messages_received = stats.client_propagation_messages_received; self.client_propagation_messages_served = stats.client_propagation_messages_served; self.unpeered_propagation_incoming = stats.unpeered_propagation_incoming; self.unpeered_propagation_rx_bytes = stats.unpeered_propagation_rx_bytes; - // Python cleans transient IDs, tickets and stamp costs at load (LXMRouter.py). - let now = now_f64(); - self.propagation_store.clean_transient_caches(now); - self.ticket_store.cull(now); - self.outbound_stamp_costs - .retain(|_, e| now - e.recorded_at < STAMP_COST_EXPIRY as f64); Ok(()) } - /// Clone all runtime state written by [`Self::save_state`] into one owned - /// value. Embedders can take this snapshot while holding the router lock, + /// `state_dir/state.db`, or the in-memory store when it cannot be used + /// (`LXMRouter.__init__` falls back to the old files instead). + fn open_state_store(state_dir: &std::path::Path) -> StateStoreHandle { + #[cfg(feature = "sqlite-store")] + { + let path = state_dir.join(crate::state_store::FILE_NAME); + let opened = std::fs::create_dir_all(state_dir) + .map_err(|e| StateStoreError::Open(e.to_string())) + .and_then(|()| StateStoreHandle::open_file(&path)); + match opened { + Ok(store) => store, + Err(error) => { + tracing::error!( + "LXMF state store {} cannot be used ({error}). Stamp costs, tickets, and \ + message deduplication are kept in memory until this process exits. To \ + start a new store, stop this program and remove state.db, state.db-wal, \ + and state.db-shm there; if the file was written by a newer version, \ + update instead", + path.display() + ); + StateStoreHandle::fallback() + } + } + } + #[cfg(not(feature = "sqlite-store"))] + { + let _ = state_dir; + StateStoreHandle::in_memory() + } + } + + /// Fold the `delivery_claims` journal of earlier releases into the store. + /// It has no upstream counterpart: every claim is now written to the store + /// before its delivery, so the file is removed once its records commit. + fn import_delivery_claims(&mut self, state_dir: &std::path::Path, durable: bool) { + use crate::state_store::ImportRow; + + let (delivered, processed) = match crate::persist::load_delivery_claims(state_dir) { + Ok(claims) => claims, + Err(error) => { + tracing::error!(%error, "could not read delivery claims"); + return; + } + }; + if delivered.is_empty() && processed.is_empty() { + return; + } + let rows: Vec = delivered + .into_iter() + .map(|(id, at)| ImportRow::Delivered(id, at)) + .chain( + processed + .into_iter() + .map(|(id, at)| ImportRow::Processed(id, at)), + ) + .collect(); + match self.state_store.call(move |s| s.apply_imported(&rows)) { + Ok(_) if durable => { + if let Err(error) = crate::persist::clear_delivery_claims(state_dir) { + tracing::warn!(%error, "could not remove imported delivery claims"); + } + } + Ok(_) => {} + Err(error) => tracing::error!(%error, "delivery claims not imported"), + } + } + + /// Run `cull` up to [`STORE_CULL_CHUNKS`] times, stopping at the first + /// empty pass; `LXMRouter.__cull_store`. + fn cull_store( + store: &mut dyn crate::state_store::Backend, + mut cull: impl FnMut(&mut dyn crate::state_store::Backend) -> Result, + ) -> Result<(), StateStoreError> { + for _ in 0..STORE_CULL_CHUNKS { + if cull(store)? == 0 { + break; + } + } + Ok(()) + } + + /// `LXMRouter.clean_transient_id_caches`. + fn clean_transient_id_caches(&mut self) { + let now = now_f64(); + self.propagation_store.clean_transient_caches(now); + let cutoff = now - MESSAGE_EXPIRY as f64 * 6.0; + self.state_store.write("cull transient IDs", move |s| { + Self::cull_store(s, |s| s.cull_delivered(cutoff, STORE_CULL_ROWS))?; + Self::cull_store(s, |s| s.cull_processed(cutoff, STORE_CULL_ROWS)) + }); + } + + /// `LXMRouter.clean_available_tickets`. + fn clean_available_tickets(&mut self) { + let now = now_f64(); + self.state_store.write("cull tickets", move |s| { + Self::cull_store(s, |s| s.cull_tickets_outbound(now, STORE_CULL_ROWS))?; + Self::cull_store(s, |s| { + s.cull_tickets_inbound(now - TICKET_GRACE as f64, STORE_CULL_ROWS) + }) + }); + } + + /// Clone the state written by [`Self::save_state`] into one owned value. + /// Embedders can take this snapshot while holding the router lock, /// release the lock, and perform persistence through /// [`RouterStateSnapshot::save_state`]. pub fn state_snapshot(&self) -> RouterStateSnapshot { - let claims_dir = self.claims_dir.as_ref().filter(|dir| { - crate::persist::rotate_delivery_claims(dir) - .inspect_err(|error| tracing::warn!(%error, "could not rotate delivery claims")) - .is_ok() - }); RouterStateSnapshot { - claims_dir: claims_dir.cloned(), - outbound_stamp_costs: self.outbound_stamp_costs.clone(), - tickets: crate::persist::TicketPersistenceSnapshot::capture( - self.ticket_store.snapshot(), - ), - local_deliveries: self.propagation_store.locally_delivered_ids().clone(), - locally_processed: self.propagation_store.locally_processed_ids().clone(), node_stats: crate::persist::PersistedNodeStats { client_propagation_messages_received: self.client_propagation_messages_received, client_propagation_messages_served: self.client_propagation_messages_served, @@ -1496,9 +1654,8 @@ impl LxmRouter { } } - /// Persist runtime state to `state_dir` using MessagePack. Each file is - /// replaced atomically; the set is not a single transaction. Serialize writes - /// so an older snapshot cannot overwrite newer state. + /// Write the node statistics to `state_dir`. Everything else + /// [`Self::load_state`] restores is already in `state.db`. pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> { self.state_snapshot().save_state(state_dir) } @@ -1657,16 +1814,15 @@ impl LxmRouter { self.static_peers.retain(|h| h != destination_hash); } - /// Get a cached outbound stamp cost, or `None` if missing, expired or - /// announced without a cost. + /// The stamp cost a destination's latest announce carried, or `None` if + /// none is stored or it announced without one + /// (`LXMRouter.get_outbound_stamp_cost`). Entries leave the store when + /// [`Self::cull_stamp_costs`] next runs after [`STAMP_COST_EXPIRY`]. pub fn get_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option { - let entry = self.outbound_stamp_costs.get(destination_hash)?; - let now = now_f64(); - if now - entry.recorded_at < STAMP_COST_EXPIRY as f64 { - entry.cost - } else { - None - } + let destination = *destination_hash; + self.store_read("recall outbound stamp cost", move |s| { + s.get_outbound_stamp_cost(&destination) + }) } pub fn set_stamp_cost(&mut self, destination_hash: [u8; 16], cost: f64) { @@ -1677,14 +1833,10 @@ impl LxmRouter { /// announce carried. `None` keeps an entry that makes later messages /// unstamped until the next announce. pub fn update_stamp_cost(&mut self, destination_hash: [u8; 16], cost: Option) { - let now = now_f64(); - self.outbound_stamp_costs.insert( - destination_hash, - StampCostEntry { - cost, - recorded_at: now, - }, - ); + self.state_store + .write("update outbound stamp cost", move |s| { + s.update_stamp_cost(&destination_hash, cost) + }); } pub fn set_propagation_enabled(&mut self, enabled: bool) { @@ -1829,8 +1981,10 @@ impl LxmRouter { required_cost: f64, destination_hash: &[u8; 16], ) -> bool { - let now = now_f64(); - for token in self.ticket_store.inbound_tokens(destination_hash, now) { + for token in self + .get_inbound_tickets(destination_hash) + .unwrap_or_default() + { let mut material = Vec::with_capacity(16 + 32); material.extend_from_slice(&token); material.extend_from_slice(message_id); @@ -2522,10 +2676,14 @@ impl LxmRouter { std::mem::take(&mut self.outbound_kick) } + /// Remove stamp costs last updated more than [`STAMP_COST_EXPIRY`] ago + /// (`LXMRouter.clean_outbound_stamp_costs`). pub fn cull_stamp_costs(&mut self) { - let now = now_f64(); - self.outbound_stamp_costs - .retain(|_, e| now - e.recorded_at < STAMP_COST_EXPIRY as f64); + let cutoff = now_f64() - STAMP_COST_EXPIRY as f64; + self.state_store + .write("cull outbound stamp costs", move |s| { + Self::cull_store(s, |s| s.cull_stamp_costs(cutoff, STORE_CULL_ROWS)) + }); } pub fn cull_propagation(&mut self) { @@ -2690,7 +2848,7 @@ impl LxmRouter { fn run_periodic_jobs(&mut self) { // Job cadences match the Python LXMRouter jobloop. if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) { - self.propagation_store.clean_transient_caches(now_f64()); + self.clean_transient_id_caches(); } if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL) && self.config.propagation_enabled @@ -2707,7 +2865,10 @@ impl LxmRouter { } if self.processing_count.is_multiple_of(JOB_STAMPCOST_INTERVAL) { self.cull_stamp_costs(); - self.ticket_store.cull(now_f64()); + self.clean_available_tickets(); + self.state_store.write("run incremental vacuum", |s| { + s.incremental_vacuum(STORE_VACUUM_PAGES).map(|_| ()) + }); } } @@ -2719,7 +2880,6 @@ impl LxmRouter { peers: self.peers.len(), propagation_entries: self.propagation_store.len(), propagation_size: self.propagation_store.total_size(), - stamp_costs_cached: self.outbound_stamp_costs.len(), } } } @@ -2773,7 +2933,6 @@ pub struct RouterStats { pub peers: usize, pub propagation_entries: usize, pub propagation_size: usize, - pub stamp_costs_cached: usize, } /// Outcome of one [`LxmRouter::sync_peers`] pass. @@ -2850,11 +3009,11 @@ mod tests { fn run_jobs_tick_cleans_transient_caches_at_job_interval() { let mut router = LxmRouter::new(RouterConfig::default()); let ancient = 1.0; // far older than MESSAGE_EXPIRY * 6 - let mut delivered = std::collections::HashMap::new(); - delivered.insert([0xAB; 32], ancient); router - .propagation_store - .replace_locally_delivered(delivered); + .state_store + .call(move |s| s.mark_locally_delivered(&[0xAB; 32], ancient)) + .unwrap(); + assert!(router.has_message(&[0xAB; 32])); // Land exactly on the transient-cache job multiple. router.processing_count = JOB_TRANSIENT_INTERVAL - 1; @@ -2862,10 +3021,7 @@ mod tests { router.run_jobs_tick(); assert!( - !router - .propagation_store - .locally_delivered_ids() - .contains_key(&[0xAB; 32]), + !router.has_message(&[0xAB; 32]), "expired dedup id must be aged out by the jobloop" ); } @@ -2962,23 +3118,16 @@ mod tests { let dest = [0xAA; 16]; router.set_stamp_cost(dest, 8.5); router.update_stamp_cost(dest, None); - assert!(router.outbound_stamp_costs.contains_key(&dest)); assert_eq!(router.get_stamp_cost(&dest), None); let mut draft = crate::message::LxMessageDraft::new(dest, [0xBB; 16], "", "x", DeliveryMethod::Direct) .unwrap(); router.prepare_outbound(&mut draft).unwrap(); assert_eq!(draft.stamp_cost, None); - - let tmp = tempfile::TempDir::new().unwrap(); - router.save_state(tmp.path()).unwrap(); - let mut restored = LxmRouter::new(RouterConfig::default()); - restored.load_state(tmp.path()).unwrap(); - assert!(restored.outbound_stamp_costs[&dest].cost.is_none()); } #[test] - fn integer_stamp_costs_stored_by_older_versions_still_load() { + fn stamp_costs_stored_by_older_versions_are_imported_once() { #[derive(serde::Serialize)] struct OldEntry { cost: u8, @@ -2992,14 +3141,13 @@ mod tests { recorded_at: now_f64(), }, )]); - std::fs::write( - tmp.path().join(crate::persist::STAMP_COSTS_FILE), - rmp_serde::to_vec(&old).unwrap(), - ) - .unwrap(); + let file = tmp.path().join("outbound_stamp_costs"); + std::fs::write(&file, rmp_serde::to_vec(&old).unwrap()).unwrap(); let mut router = LxmRouter::new(RouterConfig::default()); router.load_state(tmp.path()).unwrap(); assert_eq!(router.get_stamp_cost(&[0xAA; 16]), Some(12.0)); + assert!(!file.exists()); + assert!(tmp.path().join("outbound_stamp_costs.imported").exists()); } #[test] @@ -3076,22 +3224,22 @@ mod tests { fn prepare_outbound_issues_native_reply_ticket_before_signing() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); - let dir = tempfile::tempdir().unwrap(); let dest = [0xAA; 16]; let mut msg = LxMessageDraft::new(dest, [0xBB; 16], "ticket", "reply", DeliveryMethod::Direct) .unwrap(); msg.include_ticket = true; - let intent = router.prepare_outbound(&mut msg).unwrap(); - assert!(intent.requires_persistence()); + router.prepare_outbound(&mut msg).unwrap(); let crate::message::FieldValue::MessagePack(field) = msg.get_field(FIELD_TICKET).unwrap() else { panic!("native ticket field required") }; let value = rmpv::decode::read_value(&mut field.encoded()).unwrap(); - assert_eq!(value.as_array().unwrap().len(), 2); - assert!(msg.clone().sign(&key).is_err()); - intent.persist(dir.path(), &mut msg).unwrap(); + let issued = value.as_array().unwrap()[1].as_slice().unwrap().to_vec(); + assert_eq!( + router.get_inbound_tickets(&dest), + Some(vec![issued.try_into().unwrap()]) + ); router.submit_signed(msg.sign(&key).unwrap()).unwrap(); let hash = router.pending_outbound[0].message_id(); assert!(router.mark_outbound_delivered(&hash)); @@ -3099,16 +3247,14 @@ mod tests { LxMessageDraft::new(dest, [0xBB; 16], "ticket", "later", DeliveryMethod::Direct) .unwrap(); next.include_ticket = true; - let intent = router.prepare_outbound(&mut next).unwrap(); + router.prepare_outbound(&mut next).unwrap(); assert!(!next.fields().contains_key(&FIELD_TICKET.into())); - assert!(!intent.requires_persistence()); } #[test] fn externally_retained_message_updates_ticket_only_when_completed() { let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); let mut router = LxmRouter::new(RouterConfig::default()); - let dir = tempfile::tempdir().unwrap(); let dest = [0xAC; 16]; let mut in_flight = LxMessageDraft::new( dest, @@ -3119,52 +3265,21 @@ mod tests { ) .unwrap(); in_flight.include_ticket = true; - router - .prepare_outbound(&mut in_flight) - .unwrap() - .persist(dir.path(), &mut in_flight) - .unwrap(); + router.prepare_outbound(&mut in_flight).unwrap(); let in_flight = in_flight.sign(&key).unwrap().finalize(None).unwrap(); let mut before_proof = LxMessageDraft::new(dest, [0xBD; 16], "ticket", "before", DeliveryMethod::Direct) .unwrap(); before_proof.include_ticket = true; - router - .prepare_outbound(&mut before_proof) - .unwrap() - .persist(dir.path(), &mut before_proof) - .unwrap(); + router.prepare_outbound(&mut before_proof).unwrap(); assert!(before_proof.get_field(FIELD_TICKET).is_some()); router.complete_outbound_message(in_flight); let mut after_proof = LxMessageDraft::new(dest, [0xBD; 16], "ticket", "after", DeliveryMethod::Direct) .unwrap(); after_proof.include_ticket = true; - let intent = router.prepare_outbound(&mut after_proof).unwrap(); + router.prepare_outbound(&mut after_proof).unwrap(); assert!(after_proof.get_field(FIELD_TICKET).is_none()); - assert!(!intent.requires_persistence()); - } - - #[test] - fn signed_message_requesting_ticket_fails_instead_of_invalidating_signature() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let mut router = LxmRouter::new(RouterConfig::default()); - let mut draft = LxMessageDraft::new( - [0xAA; 16], - [0xBB; 16], - "ticket", - "pending", - DeliveryMethod::Direct, - ) - .unwrap(); - draft.include_ticket = true; - let intent = router.prepare_outbound(&mut draft).unwrap(); - assert!(intent.requires_persistence()); - assert!(matches!( - draft.sign(&key), - Err(MessageError::TicketNotCommitted) - )); - assert!(router.pending_outbound.is_empty()); } #[test] @@ -3176,7 +3291,6 @@ mod tests { Some(&identity.hash), ); let mut sender = LxmRouter::new(RouterConfig::default()); - let dir = tempfile::tempdir().unwrap(); let mut draft = LxMessageDraft::new( [0xAA; 16], source, @@ -3186,11 +3300,7 @@ mod tests { ) .unwrap(); draft.include_ticket = true; - sender - .prepare_outbound(&mut draft) - .unwrap() - .persist(dir.path(), &mut draft) - .unwrap(); + sender.prepare_outbound(&mut draft).unwrap(); let message = draft.sign(&key).unwrap().finalize(None).unwrap(); let mut receiver = LxmRouter::new(RouterConfig::default()); assert!(receiver.deliver_inbound(&message, false)); @@ -3390,32 +3500,33 @@ mod tests { assert!(router.get_outbound_ticket(&dest).is_none()); assert!(router.get_outbound_ticket_expiry(&dest).is_none()); - assert!(router.get_inbound_tickets().is_empty()); + assert!(router.get_inbound_tickets(&dest).is_none()); - let token = router.generate_ticket(dest, None); + let ticket = router.generate_ticket(dest, None).unwrap(); assert!(router.get_outbound_ticket(&dest).is_none()); - assert_eq!(router.get_inbound_tickets().len(), 1); - assert_eq!(router.get_inbound_tickets()[0].token, token); + assert_eq!(router.get_inbound_tickets(&dest), Some(vec![ticket.token])); + // A ticket with enough validity left is reused, as upstream reuses it. + assert_eq!(router.generate_ticket(dest, None), Some(ticket.clone())); // A remembered peer ticket is outbound and does not alter the // locally-issued inbound set. router.remember_ticket(dest, [0x55; 16], now_f64() + 1000.0); - assert_eq!(router.get_inbound_tickets().len(), 1); + assert_eq!(router.get_inbound_tickets(&dest), Some(vec![ticket.token])); assert_eq!(router.get_outbound_ticket(&dest), Some([0x55; 16])); assert!(router.get_outbound_ticket_expiry(&dest).unwrap() > now_f64()); } #[test] fn test_validate_stamp_checks_all_tickets() { - let mut router = LxmRouter::new(RouterConfig::default()); + let router = LxmRouter::new(RouterConfig::default()); let dest = [0xAA; 16]; let expires = now_f64() + 1000.0; - router - .ticket_store - .add_inbound(Ticket::new([0x01; 16], dest, expires)); - router - .ticket_store - .add_inbound(Ticket::new([0x02; 16], dest, expires)); + for token in [[0x01; 16], [0x02; 16]] { + router + .state_store + .call(move |s| s.store_inbound_ticket(&dest, &token, expires)) + .unwrap(); + } // Stamp derived from the SECOND ticket must still validate. let message_id = [0x33u8; 32]; @@ -3640,168 +3751,210 @@ mod tests { assert!(fired.load(Ordering::Relaxed)); } + #[cfg(feature = "sqlite-store")] + fn inbound(content: &str) -> LxMessage { + crate::message::test_message([0xAA; 16], [0xBB; 16], "t", content, DeliveryMethod::Direct) + } + #[test] - fn test_save_and_load_state_roundtrip() { + #[cfg(feature = "sqlite-store")] + fn state_is_resumed_from_the_storage_directory() { let tmp = tempfile::TempDir::new().unwrap(); let dest_a = [0xAA; 16]; let transient_a = [0x11; 32]; + let message = inbound("resumed"); let mut r1 = LxmRouter::new(RouterConfig::default()); + r1.load_state(tmp.path()).unwrap(); r1.set_stamp_cost(dest_a, 8.0); - // Far-future expiry so get_outbound_ticket (which uses wall-clock now) matches. r1.remember_ticket(dest_a, [0x01; 16], 4_102_444_800.0); - r1.propagation_store.mark_locally_delivered(transient_a); - r1.propagation_store.mark_locally_processed(transient_a); + let issued = r1.generate_ticket(dest_a, None).unwrap(); + assert!(r1.deliver_inbound(&message, false)); + assert!(r1.claim_processed(transient_a, false)); r1.client_propagation_messages_received = 10; r1.client_propagation_messages_served = 11; r1.unpeered_propagation_incoming = 12; r1.unpeered_propagation_rx_bytes = 13; r1.save_state(tmp.path()).unwrap(); + drop(r1); let mut r2 = LxmRouter::new(RouterConfig::default()); r2.load_state(tmp.path()).unwrap(); - assert_eq!( - r2.outbound_stamp_costs.get(&dest_a).and_then(|e| e.cost), - Some(8.0) - ); + assert_eq!(r2.get_stamp_cost(&dest_a), Some(8.0)); assert_eq!(r2.get_outbound_ticket(&dest_a), Some([0x01; 16])); - assert!(r2.propagation_store.is_locally_delivered(&transient_a)); + assert_eq!(r2.get_inbound_tickets(&dest_a), Some(vec![issued.token])); + assert!(r2.has_message(&message.message_id())); + assert!(!r2.deliver_inbound(&message, false)); assert!(r2.propagation_store.is_locally_processed(&transient_a)); + assert!(!r2.claim_processed(transient_a, false)); assert_eq!(r2.client_propagation_messages_received, 10); assert_eq!(r2.client_propagation_messages_served, 11); assert_eq!(r2.unpeered_propagation_incoming, 12); assert_eq!(r2.unpeered_propagation_rx_bytes, 13); + // Nothing is written back in the old format. + for name in [ + "local_deliveries", + "locally_processed", + "outbound_stamp_costs", + "available_tickets", + "delivery_claims", + ] { + assert!(!tmp.path().join(name).exists(), "{name} was written"); + } } #[test] - fn test_state_snapshot_is_an_owned_coherent_copy() { - let dest = [0xA1; 16]; - let transient = [0xB2; 32]; - - let mut router = LxmRouter::new(RouterConfig::default()); - router.set_stamp_cost(dest, 8.0); - router.remember_ticket(dest, [0xC3; 16], 4_102_444_800.0); - router.propagation_store.mark_locally_delivered(transient); - router.propagation_store.mark_locally_processed(transient); - router.client_propagation_messages_received = 10; - router.client_propagation_messages_served = 11; - router.unpeered_propagation_incoming = 12; - router.unpeered_propagation_rx_bytes = 13; - - let snapshot = router.state_snapshot(); - - // Mutating every persisted router dataset after capture must not alter - // the snapshot that a background persistence task owns. - router.set_stamp_cost(dest, 42.0); - router.remember_ticket(dest, [0xD4; 16], 4_102_444_800.0); - router - .propagation_store - .replace_locally_delivered(HashMap::new()); - router - .propagation_store - .replace_locally_processed(HashMap::new()); - router.client_propagation_messages_received = 20; - router.client_propagation_messages_served = 21; - router.unpeered_propagation_incoming = 22; - router.unpeered_propagation_rx_bytes = 23; - - assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, Some(8.0)); - let dir = tempfile::tempdir().unwrap(); - snapshot.tickets.save(dir.path(), None).unwrap(); - let (tickets, _) = crate::persist::load_tickets(dir.path()).unwrap(); - assert_eq!(tickets.outbound.len(), 1); - assert_eq!(tickets.outbound[0].token, [0xC3; 16]); - assert!(snapshot.local_deliveries.contains_key(&transient)); - assert!(snapshot.locally_processed.contains_key(&transient)); - assert_eq!(snapshot.node_stats.client_propagation_messages_received, 10); - assert_eq!(snapshot.node_stats.client_propagation_messages_served, 11); - assert_eq!(snapshot.node_stats.unpeered_propagation_incoming, 12); - assert_eq!(snapshot.node_stats.unpeered_propagation_rx_bytes, 13); - } - - #[test] - fn test_state_snapshot_persists_after_router_is_dropped() { + fn state_snapshot_is_an_owned_copy_that_outlives_the_router() { let tmp = tempfile::TempDir::new().unwrap(); - let dest = [0xA5; 16]; - let transient = [0xB6; 32]; - let snapshot = { let mut router = LxmRouter::new(RouterConfig::default()); - router.set_stamp_cost(dest, 9.0); - router.remember_ticket(dest, [0xC7; 16], 4_102_444_800.0); - router.propagation_store.mark_locally_delivered(transient); - router.propagation_store.mark_locally_processed(transient); - router.client_propagation_messages_received = 30; - router.client_propagation_messages_served = 31; - router.unpeered_propagation_incoming = 32; - router.unpeered_propagation_rx_bytes = 33; - router.state_snapshot() + router.client_propagation_messages_received = 10; + router.client_propagation_messages_served = 11; + router.unpeered_propagation_incoming = 12; + router.unpeered_propagation_rx_bytes = 13; + let snapshot = router.state_snapshot(); + router.client_propagation_messages_received = 20; + snapshot }; - snapshot.save_state(tmp.path()).unwrap(); let mut restored = LxmRouter::new(RouterConfig::default()); restored.load_state(tmp.path()).unwrap(); - assert_eq!(restored.outbound_stamp_costs[&dest].cost, Some(9.0)); - assert_eq!(restored.get_outbound_ticket(&dest), Some([0xC7; 16])); - assert!(restored.propagation_store.is_locally_delivered(&transient)); - assert!(restored.propagation_store.is_locally_processed(&transient)); - assert_eq!(restored.client_propagation_messages_received, 30); - assert_eq!(restored.client_propagation_messages_served, 31); - assert_eq!(restored.unpeered_propagation_incoming, 32); - assert_eq!(restored.unpeered_propagation_rx_bytes, 33); + assert_eq!(restored.client_propagation_messages_received, 10); + assert_eq!(restored.client_propagation_messages_served, 11); + assert_eq!(restored.unpeered_propagation_incoming, 12); + assert_eq!(restored.unpeered_propagation_rx_bytes, 13); } - /// T1-10: persisted dedup timestamps are the REAL first-seen times — - /// restored on load (not reset to save-time), so age-based expiry is - /// stable across arbitrarily many save/load cycles. #[test] - fn test_dedup_cache_timestamps_survive_save_load_cycles() { + #[cfg(feature = "sqlite-store")] + fn expired_rows_are_cleaned_when_the_store_is_opened() { + use crate::state_store::{FILE_NAME, SqliteStateStore, StateStore}; let tmp = tempfile::TempDir::new().unwrap(); - let transient = [0x42; 32]; + let now = now_f64(); + let expired = now - MESSAGE_EXPIRY as f64 * 6.0 - 60.0; + let (old, kept) = ([0x01; 32], [0x02; 32]); + let dest = [0xAA; 16]; + { + let mut file = SqliteStateStore::open(&tmp.path().join(FILE_NAME)).unwrap(); + file.mark_locally_delivered(&old, expired).unwrap(); + file.mark_locally_delivered(&kept, now).unwrap(); + file.unconditionally_mark_processed(&old, expired).unwrap(); + file.remember_ticket(&dest, now - 1.0, &[0x05; 16]).unwrap(); + // Inbound tickets stay for `TICKET_GRACE` after they expire. + file.store_inbound_ticket(&dest, &[0x06; 16], now - 1.0) + .unwrap(); + file.store_inbound_ticket(&dest, &[0x07; 16], now - TICKET_GRACE as f64 - 60.0) + .unwrap(); + } + let mut router = LxmRouter::new(RouterConfig::default()); + router.load_state(tmp.path()).unwrap(); + assert!(!router.has_message(&old)); + assert!(router.has_message(&kept)); + assert!(!router.propagation_store.is_locally_processed(&old)); + drop(router); + + let count = |table: &str| -> i64 { + rusqlite::Connection::open(tmp.path().join(FILE_NAME)) + .unwrap() + .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0)) + .unwrap() + }; + assert_eq!(count("processed_transient_ids"), 0); + assert_eq!(count("tickets_outbound"), 0); + assert_eq!(count("tickets_inbound"), 1); + } + + #[test] + #[cfg(feature = "sqlite-store")] + fn an_unusable_store_file_leaves_the_router_running_in_memory() { + use crate::state_store::FILE_NAME; + let newer = |path: &std::path::Path| { + rusqlite::Connection::open(path) + .unwrap() + .execute_batch("CREATE TABLE later (x); PRAGMA user_version = 2") + .unwrap() + }; + let corrupt = |path: &std::path::Path| std::fs::write(path, [0x5A; 4096]).unwrap(); + let directory = |path: &std::path::Path| std::fs::create_dir(path).unwrap(); + for spoil in [&newer as &dyn Fn(&std::path::Path), &corrupt, &directory] { + let tmp = tempfile::TempDir::new().unwrap(); + let db = tmp.path().join(FILE_NAME); + spoil(&db); + let before = std::fs::read(&db).ok(); + let costs = HashMap::from([([0xAA_u8; 16], (Some(12.0_f64), now_f64()))]); + let legacy = tmp.path().join("outbound_stamp_costs"); + std::fs::write(&legacy, rmp_serde::to_vec(&costs).unwrap()).unwrap(); + + let mut router = LxmRouter::new(RouterConfig::default()); + router.load_state(tmp.path()).unwrap(); + // The old cache is read for the session and left for a later import. + assert_eq!(router.get_stamp_cost(&[0xAA; 16]), Some(12.0)); + assert!(legacy.exists()); + let message = inbound("fall-back"); + assert!(router.deliver_inbound(&message, false)); + assert!(!router.deliver_inbound(&message, false)); + router.set_stamp_cost([0xBB; 16], 4.0); + assert_eq!(router.get_stamp_cost(&[0xBB; 16]), Some(4.0)); + // A ticket that would not survive a restart is not handed out. + assert_eq!(router.generate_ticket([0xCC; 16], None), None); + router.save_state(tmp.path()).unwrap(); + drop(router); + assert_eq!(std::fs::read(&db).ok(), before); + } + } + + #[test] + #[cfg(feature = "sqlite-store")] + fn a_failing_store_never_turns_a_new_message_into_a_duplicate() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut router = LxmRouter::new(RouterConfig::default()); + router.load_state(tmp.path()).unwrap(); + rusqlite::Connection::open(tmp.path().join(crate::state_store::FILE_NAME)) + .unwrap() + .execute_batch( + "DROP TABLE delivered_transient_ids; DROP TABLE processed_transient_ids; \ + DROP TABLE tickets_inbound", + ) + .unwrap(); + assert!(router.deliver_inbound(&inbound("store failed"), false)); + assert!(router.claim_processed([0x21; 32], false)); + assert_eq!(router.generate_ticket([0xCC; 16], None), None); + } + + #[test] + #[cfg(feature = "sqlite-store")] + fn delivery_claims_of_earlier_releases_are_imported_and_removed() { + let tmp = tempfile::TempDir::new().unwrap(); + let (delivered, processed) = ([0x31; 32], [0x32; 32]); + let record = |kind: u8, id: [u8; 32]| { + let mut bytes = vec![kind]; + bytes.extend_from_slice(&id); + bytes.extend_from_slice(&now_f64().to_le_bytes()); + bytes + }; + let claims = tmp.path().join("delivery_claims"); + std::fs::write(&claims, record(0, delivered)).unwrap(); + std::fs::write( + tmp.path().join("delivery_claims.saving"), + record(1, processed), + ) + .unwrap(); let mut router = LxmRouter::new(RouterConfig::default()); - router.propagation_store.mark_locally_delivered(transient); - let original_ts = *router - .propagation_store - .locally_delivered_ids() - .get(&transient) - .unwrap(); - - // Multiple save/load cycles must not refresh the timestamp. - for _ in 0..3 { - router.save_state(tmp.path()).unwrap(); - let mut reloaded = LxmRouter::new(RouterConfig::default()); - reloaded.load_state(tmp.path()).unwrap(); - let loaded_ts = *reloaded - .propagation_store - .locally_delivered_ids() - .get(&transient) - .unwrap(); - assert_eq!(loaded_ts, original_ts, "timestamp must survive reload"); - router = reloaded; - } - assert_eq!(router.propagation_store.locally_delivered_ids().len(), 1); - - // An aged-out entry is gone after the periodic clean, and stays gone - // through persistence (growth bounded). - let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0; - router - .propagation_store - .clean_transient_caches(original_ts + expiry + 1.0); - assert!(!router.propagation_store.is_locally_delivered(&transient)); - router.save_state(tmp.path()).unwrap(); - let mut fresh = LxmRouter::new(RouterConfig::default()); - fresh.load_state(tmp.path()).unwrap(); - assert!(fresh.propagation_store.locally_delivered_ids().is_empty()); + router.load_state(tmp.path()).unwrap(); + assert!(router.has_message(&delivered)); + assert!(router.propagation_store.is_locally_processed(&processed)); + assert!(!claims.exists()); + assert!(!tmp.path().join("delivery_claims.saving").exists()); } #[test] fn test_load_state_missing_dir_is_ok() { let tmp = tempfile::TempDir::new().unwrap(); let mut r = LxmRouter::new(RouterConfig::default()); - r.load_state(tmp.path()).unwrap(); - assert!(r.outbound_stamp_costs.is_empty()); + r.load_state(&tmp.path().join("lxmf")).unwrap(); + assert_eq!(r.get_stamp_cost(&[0xAA; 16]), None); } #[test] diff --git a/crates/lxmf-core/src/state_store.rs b/crates/lxmf-core/src/state_store.rs new file mode 100644 index 0000000..cf5554e --- /dev/null +++ b/crates/lxmf-core/src/state_store.rs @@ -0,0 +1,1659 @@ +//! Router state in `/lxmf/state.db`, as LXMF 1.3.0 keeps it +//! (`LXMF/Storage.py`, class `LXMFStore`). Schema, pragmas, and version +//! handling follow that file; each [`StateStore`] method is one of its +//! operations. Timestamps are Unix seconds, and the store reads the system +//! clock where upstream calls `time.time()`. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; + +use crate::types::PropagationTransientId; + +/// File name inside the router's `lxmf` storage directory. +pub const FILE_NAME: &str = "state.db"; + +/// Highest `user_version` this module writes and reads; `LXMFStore.CURRENT_VERSION`. +#[cfg(feature = "sqlite-store")] +const USER_VERSION: i64 = 1; + +/// Rows per `IN (...)` query; `LXMFStore.IN_CHUNK`. +#[cfg(feature = "sqlite-store")] +const IN_CHUNK: usize = 512; + +/// Pragma list and order of `LXMFStore.__init__`. +#[cfg(feature = "sqlite-store")] +const PRAGMAS: &str = " +PRAGMA auto_vacuum=INCREMENTAL; +PRAGMA journal_mode=WAL; +PRAGMA synchronous=NORMAL; +PRAGMA journal_size_limit=8388608; +PRAGMA busy_timeout=1500;"; + +#[cfg(feature = "sqlite-store")] +const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS stamp_costs ( + destination_hash BLOB PRIMARY KEY, + updated REAL NOT NULL, + used REAL, + cost REAL); +CREATE TABLE IF NOT EXISTS delivered_transient_ids ( + transient_id BLOB PRIMARY KEY, + received REAL NOT NULL); +CREATE TABLE IF NOT EXISTS processed_transient_ids ( + transient_id BLOB PRIMARY KEY, + received REAL NOT NULL); +CREATE TABLE IF NOT EXISTS tickets_outbound ( + destination_hash BLOB PRIMARY KEY, + expires REAL NOT NULL, + ticket BLOB NOT NULL); +CREATE TABLE IF NOT EXISTS tickets_inbound ( + ticket BLOB PRIMARY KEY, + destination_hash BLOB NOT NULL, + expires REAL NOT NULL); +CREATE TABLE IF NOT EXISTS ticket_deliveries ( + destination_hash BLOB PRIMARY KEY, + timestamp REAL NOT NULL); +CREATE INDEX IF NOT EXISTS idx_delivered_received ON delivered_transient_ids (received); +CREATE INDEX IF NOT EXISTS idx_processed_received ON processed_transient_ids (received); +CREATE INDEX IF NOT EXISTS idx_stampcost_updated ON stamp_costs (updated); +CREATE INDEX IF NOT EXISTS idx_tickets_in_dest ON tickets_inbound (destination_hash);"; + +/// Failure of a state-store call. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum StateStoreError { + /// The file's `user_version` is newer than this module supports. + #[error("state store user_version {found} is newer than supported {supported}")] + NewerVersion { + /// Version found in the file. + found: i64, + /// Highest version this module supports. + supported: i64, + }, + /// The file could not be opened, configured, or given its schema. + #[error("state store could not be opened: {0}")] + Open(String), + /// A statement failed on an open store. + #[error("state store operation failed: {0}")] + Operation(String), + /// A stored value does not have the shape the schema promises. + #[error("invalid value in {table}: {reason}")] + InvalidRow { + /// Table holding the value. + table: &'static str, + /// What is wrong with it. + reason: String, + }, +} + +/// One validated row of a legacy file, ready for [`Backend::apply_imported`]. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum ImportRow { + Delivered(PropagationTransientId, f64), + Processed(PropagationTransientId, f64), + /// Destination, last heard, cost. + StampCost([u8; 16], f64, Option), + /// Destination, expires, ticket. + TicketOutbound([u8; 16], f64, [u8; 16]), + /// Ticket, destination, expires. + TicketInbound([u8; 16], [u8; 16], f64), + /// Destination, timestamp. + TicketDelivery([u8; 16], f64), +} + +mod sealed { + pub trait Sealed {} +} + +/// The operations of upstream's `LXMFStore`, one method each, under its names. +/// Implemented only in this module, so operations can be added. +pub trait StateStore: Send + sealed::Sealed { + /// Insert or update a destination's stamp cost (`update_stamp_cost`). + fn update_stamp_cost( + &mut self, + destination: &[u8; 16], + cost: Option, + ) -> Result<(), StateStoreError>; + + /// Stored cost, `None` if absent or recorded without a cost. Sets the usage time. + fn get_outbound_stamp_cost( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError>; + + /// Delete up to `max_entries` stamp costs last updated before `cutoff`. + fn cull_stamp_costs( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result; + + /// Whether a transient ID is in the delivered table. + fn has_delivered(&mut self, id: &PropagationTransientId) -> Result; + + /// The subset of `ids` present in the delivered table. + fn known_delivered( + &mut self, + ids: &[PropagationTransientId], + ) -> Result, StateStoreError>; + + /// Insert or refresh a delivered transient ID. + fn mark_locally_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError>; + + /// Insert or refresh a processed transient ID. + fn unconditionally_mark_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError>; + + /// Insert a delivered ID unless present; `true` if it was inserted. + fn conditionally_claim_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result; + + /// Insert a processed ID unless present; `true` if it was inserted. + fn conditionally_claim_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result; + + /// Delete up to `max_entries` processed IDs received before `cutoff`. + fn cull_processed(&mut self, cutoff: f64, max_entries: usize) + -> Result; + + /// Delete up to `max_entries` delivered IDs received before `cutoff`. + fn cull_delivered(&mut self, cutoff: f64, max_entries: usize) + -> Result; + + /// Store the outbound ticket for a destination, replacing any previous one. + fn remember_ticket( + &mut self, + destination: &[u8; 16], + expires: f64, + ticket: &[u8; 16], + ) -> Result<(), StateStoreError>; + + /// Unexpired outbound ticket for a destination. + fn get_outbound_ticket( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError>; + + /// Expiry of the unexpired outbound ticket for a destination. + fn get_outbound_ticket_expiry( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError>; + + /// The unexpired inbound ticket expiring latest, provided it stays valid + /// for at least `renew_before` more seconds; returned as `(expires, ticket)`. + fn get_reusable_inbound_ticket( + &mut self, + destination: &[u8; 16], + renew_before: f64, + ) -> Result, StateStoreError>; + + /// Store a locally issued inbound ticket. + fn store_inbound_ticket( + &mut self, + destination: &[u8; 16], + ticket: &[u8; 16], + expires: f64, + ) -> Result<(), StateStoreError>; + + /// Unexpired inbound tickets for a destination; `None` when there are none. + fn get_inbound_tickets( + &mut self, + destination: &[u8; 16], + ) -> Result>, StateStoreError>; + + /// Time of the last ticket delivered to a destination. + fn get_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError>; + + /// Record the time of the last ticket delivered to a destination. + fn mark_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + timestamp: f64, + ) -> Result<(), StateStoreError>; + + /// Delete up to `max_entries` outbound tickets expiring before `cutoff`. + fn cull_tickets_outbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result; + + /// Delete up to `max_entries` inbound tickets expiring before `cutoff`. + fn cull_tickets_inbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result; + + /// Return up to `max_pages` free pages to the file system; returns pages freed. + fn incremental_vacuum(&mut self, max_pages: usize) -> Result; +} + +/// What the router needs beyond upstream's operations: the legacy import, +/// the processed IDs the propagation node shares, and writes that are on disk +/// when they return. +pub(crate) trait Backend: StateStore { + /// Run `job` as one transaction that is flushed to disk before this + /// returns. The claim a delivery follows and the ticket a signed message + /// carries were fsynced by this crate's earlier files, and stay so: + /// a claim lost to a power cut delivers a message twice, a lost ticket + /// leaves the recipient's replies failing their stamp check. + fn synced(&mut self, job: &mut dyn FnMut(&mut dyn StateStore)) -> Result<(), StateStoreError>; + + /// Insert imported rows in one transaction; rows already present are kept + /// (`INSERT OR IGNORE` in `LXMFStore.import_legacy_*`). + fn apply_imported(&mut self, rows: &[ImportRow]) -> Result; + + /// Every processed transient ID with its timestamp. + fn processed_ids(&mut self) -> Result, StateStoreError>; +} + +/// Unix time as f64 seconds. +fn clock() -> f64 { + crate::now_f64() +} + +#[cfg(feature = "sqlite-store")] +mod sqlite_impl { + use super::*; + use rusqlite::{Connection, OptionalExtension, params}; + + fn op(error: rusqlite::Error) -> StateStoreError { + StateStoreError::Operation(error.to_string()) + } + + fn fixed( + bytes: Vec, + table: &'static str, + ) -> Result<[u8; N], StateStoreError> { + bytes + .try_into() + .map_err(|v: Vec| StateStoreError::InvalidRow { + table, + reason: format!("expected {N} bytes, found {}", v.len()), + }) + } + + /// The `state.db` file on one connection. + #[derive(Debug)] + pub struct SqliteStateStore { + conn: Connection, + } + + impl SqliteStateStore { + /// Open or create `path` with upstream's pragmas, schema, and + /// `user_version`; a file with a newer version is refused. + pub fn open(path: &Path) -> Result { + let open = |e: rusqlite::Error| StateStoreError::Open(e.to_string()); + let conn = Connection::open(path).map_err(open)?; + // Read before any pragma, so a newer file is refused as it was found; + // `LXMFStore.__init__` switches it to WAL first. + let found: i64 = conn + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .map_err(open)?; + if found > USER_VERSION { + return Err(StateStoreError::NewerVersion { + found, + supported: USER_VERSION, + }); + } + conn.execute_batch(PRAGMAS).map_err(open)?; + let migrate = || -> rusqlite::Result<()> { + conn.execute_batch("BEGIN")?; + conn.execute_batch(SCHEMA)?; + conn.execute_batch(&format!("PRAGMA user_version = {USER_VERSION}"))?; + conn.execute_batch("COMMIT") + }; + if let Err(error) = migrate() { + let _ = conn.execute_batch("ROLLBACK"); + return Err(StateStoreError::Open(error.to_string())); + } + Ok(Self { conn }) + } + + fn cull( + &self, + table: &'static str, + column: &'static str, + cutoff: f64, + max_entries: usize, + ) -> Result { + let sql = format!( + "DELETE FROM {table} WHERE rowid IN (SELECT rowid FROM {table} WHERE {column} < ?1 LIMIT {max_entries})" + ); + self.conn.execute(&sql, params![cutoff]).map_err(op) + } + + fn claim( + &self, + table: &'static str, + id: &PropagationTransientId, + received: f64, + ) -> Result { + let sql = format!( + "INSERT INTO {table} (transient_id, received) VALUES (?1, ?2) ON CONFLICT(transient_id) DO NOTHING" + ); + Ok(self + .conn + .execute(&sql, params![id.as_slice(), received]) + .map_err(op)? + == 1) + } + + fn upsert_received( + &self, + table: &'static str, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError> { + let sql = format!( + "INSERT INTO {table} (transient_id, received) VALUES (?1, ?2) ON CONFLICT(transient_id) DO UPDATE SET received=excluded.received" + ); + self.conn + .execute(&sql, params![id.as_slice(), received]) + .map(|_| ()) + .map_err(op) + } + } + + impl sealed::Sealed for SqliteStateStore {} + + impl StateStore for SqliteStateStore { + fn update_stamp_cost( + &mut self, + destination: &[u8; 16], + cost: Option, + ) -> Result<(), StateStoreError> { + self.conn + .execute( + "INSERT INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?1, ?2, NULL, ?3) ON CONFLICT(destination_hash) DO UPDATE SET updated=excluded.updated, cost=excluded.cost", + params![destination.as_slice(), clock(), cost], + ) + .map(|_| ()) + .map_err(op) + } + + fn get_outbound_stamp_cost( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + let cost: Option> = self + .conn + .query_row( + "SELECT cost FROM stamp_costs WHERE destination_hash=?1", + params![destination.as_slice()], + |row| row.get(0), + ) + .optional() + .map_err(op)?; + let Some(cost) = cost else { + return Ok(None); + }; + // Usage time is advisory; a failed update keeps the cost, as upstream does. + let _ = self.conn.execute( + "UPDATE stamp_costs SET used=?1 WHERE destination_hash=?2", + params![clock(), destination.as_slice()], + ); + Ok(cost) + } + + fn cull_stamp_costs( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + self.cull("stamp_costs", "updated", cutoff, max_entries) + } + + fn has_delivered(&mut self, id: &PropagationTransientId) -> Result { + let row: Option> = self + .conn + .query_row( + "SELECT transient_id FROM delivered_transient_ids WHERE transient_id=?1", + params![id.as_slice()], + |row| row.get(0), + ) + .optional() + .map_err(op)?; + Ok(row.is_some()) + } + + fn known_delivered( + &mut self, + ids: &[PropagationTransientId], + ) -> Result, StateStoreError> { + let mut known = HashSet::new(); + for chunk in ids.chunks(IN_CHUNK) { + let marks = vec!["?"; chunk.len()].join(","); + let sql = format!( + "SELECT transient_id FROM delivered_transient_ids WHERE transient_id IN ({marks})" + ); + let mut stmt = self.conn.prepare(&sql).map_err(op)?; + let params = rusqlite::params_from_iter(chunk.iter().map(|id| id.as_slice())); + let rows = stmt + .query_map(params, |row| row.get::<_, Vec>(0)) + .map_err(op)?; + for row in rows { + known.insert(fixed(row.map_err(op)?, "delivered_transient_ids")?); + } + } + Ok(known) + } + + fn mark_locally_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError> { + self.upsert_received("delivered_transient_ids", id, received) + } + + fn unconditionally_mark_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError> { + self.upsert_received("processed_transient_ids", id, received) + } + + fn conditionally_claim_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result { + self.claim("delivered_transient_ids", id, received) + } + + fn conditionally_claim_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result { + self.claim("processed_transient_ids", id, received) + } + + fn cull_processed( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + self.cull("processed_transient_ids", "received", cutoff, max_entries) + } + + fn cull_delivered( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + self.cull("delivered_transient_ids", "received", cutoff, max_entries) + } + + fn remember_ticket( + &mut self, + destination: &[u8; 16], + expires: f64, + ticket: &[u8; 16], + ) -> Result<(), StateStoreError> { + self.conn + .execute( + "INSERT INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?1, ?2, ?3) ON CONFLICT(destination_hash) DO UPDATE SET expires=excluded.expires, ticket=excluded.ticket", + params![destination.as_slice(), expires, ticket.as_slice()], + ) + .map(|_| ()) + .map_err(op) + } + + fn get_outbound_ticket( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + let row: Option> = self + .conn + .query_row( + "SELECT ticket FROM tickets_outbound WHERE destination_hash=?1 AND expires > ?2", + params![destination.as_slice(), clock()], + |row| row.get(0), + ) + .optional() + .map_err(op)?; + row.map(|bytes| fixed(bytes, "tickets_outbound")) + .transpose() + } + + fn get_outbound_ticket_expiry( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + self.conn + .query_row( + "SELECT expires FROM tickets_outbound WHERE destination_hash=?1 AND expires > ?2", + params![destination.as_slice(), clock()], + |row| row.get(0), + ) + .optional() + .map_err(op) + } + + fn get_reusable_inbound_ticket( + &mut self, + destination: &[u8; 16], + renew_before: f64, + ) -> Result, StateStoreError> { + let row: Option<(f64, Vec)> = self + .conn + .query_row( + "SELECT expires, ticket FROM tickets_inbound WHERE destination_hash=?1 AND expires > ?2 ORDER BY expires DESC LIMIT 1", + params![destination.as_slice(), clock() + renew_before], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(op)?; + row.map(|(expires, bytes)| Ok((expires, fixed(bytes, "tickets_inbound")?))) + .transpose() + } + + fn store_inbound_ticket( + &mut self, + destination: &[u8; 16], + ticket: &[u8; 16], + expires: f64, + ) -> Result<(), StateStoreError> { + self.conn + .execute( + "INSERT INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?1, ?2, ?3) ON CONFLICT(ticket) DO UPDATE SET destination_hash=excluded.destination_hash, expires=excluded.expires", + params![ticket.as_slice(), destination.as_slice(), expires], + ) + .map(|_| ()) + .map_err(op) + } + + fn get_inbound_tickets( + &mut self, + destination: &[u8; 16], + ) -> Result>, StateStoreError> { + let mut stmt = self + .conn + .prepare_cached( + "SELECT ticket FROM tickets_inbound WHERE destination_hash=?1 AND expires > ?2", + ) + .map_err(op)?; + let rows = stmt + .query_map(params![destination.as_slice(), clock()], |row| { + row.get::<_, Vec>(0) + }) + .map_err(op)?; + let mut tickets = Vec::new(); + for row in rows { + tickets.push(fixed(row.map_err(op)?, "tickets_inbound")?); + } + Ok((!tickets.is_empty()).then_some(tickets)) + } + + fn get_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + self.conn + .query_row( + "SELECT timestamp FROM ticket_deliveries WHERE destination_hash=?1", + params![destination.as_slice()], + |row| row.get(0), + ) + .optional() + .map_err(op) + } + + fn mark_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + timestamp: f64, + ) -> Result<(), StateStoreError> { + self.conn + .execute( + "INSERT INTO ticket_deliveries (destination_hash, timestamp) VALUES (?1, ?2) ON CONFLICT(destination_hash) DO UPDATE SET timestamp=excluded.timestamp", + params![destination.as_slice(), timestamp], + ) + .map(|_| ()) + .map_err(op) + } + + fn cull_tickets_outbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + self.cull("tickets_outbound", "expires", cutoff, max_entries) + } + + fn cull_tickets_inbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + self.cull("tickets_inbound", "expires", cutoff, max_entries) + } + + fn incremental_vacuum(&mut self, max_pages: usize) -> Result { + let freelist = |conn: &Connection| -> Result { + conn.query_row("PRAGMA freelist_count", [], |row| row.get(0)) + .map_err(op) + }; + let mut freed: i64 = 0; + while freed < max_pages as i64 { + let before = freelist(&self.conn)?; + let budget = max_pages as i64 - freed; + self.conn + .execute_batch(&format!("PRAGMA incremental_vacuum({budget})")) + .map_err(op)?; + let after = freelist(&self.conn)?; + if after >= before { + break; + } + freed += before - after; + } + Ok(freed as usize) + } + } + + impl Backend for SqliteStateStore { + fn synced( + &mut self, + job: &mut dyn FnMut(&mut dyn StateStore), + ) -> Result<(), StateStoreError> { + // Upstream commits every write at `synchronous=NORMAL`, which leaves + // the WAL unflushed. `fullfsync` makes the flush reach the disk on + // Apple systems and does nothing elsewhere. Both are restored after. + let committed = self + .conn + .execute_batch("PRAGMA fullfsync=ON; PRAGMA synchronous=FULL; BEGIN") + .map_err(op) + .and_then(|()| { + job(self); + self.conn.execute_batch("COMMIT").map_err(op) + }); + if committed.is_err() { + let _ = self.conn.execute_batch("ROLLBACK"); + } + if let Err(error) = self + .conn + .execute_batch("PRAGMA synchronous=NORMAL; PRAGMA fullfsync=OFF") + { + tracing::warn!(%error, "could not restore the LXMF state store's synchronous level"); + } + committed + } + + fn apply_imported(&mut self, rows: &[ImportRow]) -> Result { + let tx = self.conn.transaction().map_err(op)?; + for row in rows { + match row { + ImportRow::Delivered(id, at) => tx + .prepare_cached("INSERT OR IGNORE INTO delivered_transient_ids (transient_id, received) VALUES (?1, ?2)") + .and_then(|mut s| s.execute(params![id.as_slice(), at])), + ImportRow::Processed(id, at) => tx + .prepare_cached("INSERT OR IGNORE INTO processed_transient_ids (transient_id, received) VALUES (?1, ?2)") + .and_then(|mut s| s.execute(params![id.as_slice(), at])), + ImportRow::StampCost(dest, updated, cost) => tx + .prepare_cached("INSERT OR IGNORE INTO stamp_costs (destination_hash, updated, used, cost) VALUES (?1, ?2, NULL, ?3)") + .and_then(|mut s| s.execute(params![dest.as_slice(), updated, cost])), + ImportRow::TicketOutbound(dest, expires, ticket) => tx + .prepare_cached("INSERT OR IGNORE INTO tickets_outbound (destination_hash, expires, ticket) VALUES (?1, ?2, ?3)") + .and_then(|mut s| s.execute(params![dest.as_slice(), expires, ticket.as_slice()])), + ImportRow::TicketInbound(ticket, dest, expires) => tx + .prepare_cached("INSERT OR IGNORE INTO tickets_inbound (ticket, destination_hash, expires) VALUES (?1, ?2, ?3)") + .and_then(|mut s| s.execute(params![ticket.as_slice(), dest.as_slice(), expires])), + ImportRow::TicketDelivery(dest, at) => tx + .prepare_cached("INSERT OR IGNORE INTO ticket_deliveries (destination_hash, timestamp) VALUES (?1, ?2)") + .and_then(|mut s| s.execute(params![dest.as_slice(), at])), + } + .map_err(op)?; + } + tx.commit().map_err(op)?; + Ok(rows.len()) + } + + fn processed_ids(&mut self) -> Result, StateStoreError> { + let mut stmt = self + .conn + .prepare("SELECT transient_id, received FROM processed_transient_ids") + .map_err(op)?; + let rows = stmt + .query_map([], |r| Ok((r.get::<_, Vec>(0)?, r.get::<_, f64>(1)?))) + .map_err(op)?; + let mut out = Vec::new(); + for row in rows { + let (id, at) = row.map_err(op)?; + out.push((fixed(id, "processed_transient_ids")?, at)); + } + Ok(out) + } + } + + impl Drop for SqliteStateStore { + fn drop(&mut self) { + // `LXMFStore.close`. + let _ = self.conn.execute_batch("PRAGMA optimize"); + } + } +} +#[cfg(feature = "sqlite-store")] +pub use sqlite_impl::SqliteStateStore; + +/// The same operations in memory, for a router without a storage directory +/// and for a session whose `state.db` could not be opened. +#[derive(Debug, Default)] +pub(crate) struct MemoryStateStore { + stamp_costs: HashMap<[u8; 16], (f64, Option)>, + delivered: HashMap, + processed: HashMap, + tickets_outbound: HashMap<[u8; 16], (f64, [u8; 16])>, + tickets_inbound: HashMap<[u8; 16], ([u8; 16], f64)>, + last_deliveries: HashMap<[u8; 16], f64>, +} + +impl MemoryStateStore { + fn cull_map( + map: &mut HashMap, + max_entries: usize, + before: impl Fn(&V) -> bool, + ) -> usize { + let doomed: Vec = map + .iter() + .filter(|(_, v)| before(v)) + .take(max_entries) + .map(|(k, _)| k.clone()) + .collect(); + for key in &doomed { + map.remove(key); + } + doomed.len() + } +} + +impl sealed::Sealed for MemoryStateStore {} + +impl StateStore for MemoryStateStore { + fn update_stamp_cost( + &mut self, + destination: &[u8; 16], + cost: Option, + ) -> Result<(), StateStoreError> { + self.stamp_costs.insert(*destination, (clock(), cost)); + Ok(()) + } + + fn get_outbound_stamp_cost( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + Ok(self + .stamp_costs + .get(destination) + .and_then(|(_, cost)| *cost)) + } + + fn cull_stamp_costs( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + Ok(Self::cull_map( + &mut self.stamp_costs, + max_entries, + |(updated, _)| *updated < cutoff, + )) + } + + fn has_delivered(&mut self, id: &PropagationTransientId) -> Result { + Ok(self.delivered.contains_key(id)) + } + + fn known_delivered( + &mut self, + ids: &[PropagationTransientId], + ) -> Result, StateStoreError> { + Ok(ids + .iter() + .filter(|id| self.delivered.contains_key(*id)) + .copied() + .collect()) + } + + fn mark_locally_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError> { + self.delivered.insert(*id, received); + Ok(()) + } + + fn unconditionally_mark_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result<(), StateStoreError> { + self.processed.insert(*id, received); + Ok(()) + } + + fn conditionally_claim_delivered( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result { + Ok(match self.delivered.entry(*id) { + std::collections::hash_map::Entry::Occupied(_) => false, + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(received); + true + } + }) + } + + fn conditionally_claim_processed( + &mut self, + id: &PropagationTransientId, + received: f64, + ) -> Result { + Ok(match self.processed.entry(*id) { + std::collections::hash_map::Entry::Occupied(_) => false, + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(received); + true + } + }) + } + + fn cull_processed( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + Ok(Self::cull_map(&mut self.processed, max_entries, |t| { + *t < cutoff + })) + } + + fn cull_delivered( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + Ok(Self::cull_map(&mut self.delivered, max_entries, |t| { + *t < cutoff + })) + } + + fn remember_ticket( + &mut self, + destination: &[u8; 16], + expires: f64, + ticket: &[u8; 16], + ) -> Result<(), StateStoreError> { + self.tickets_outbound + .insert(*destination, (expires, *ticket)); + Ok(()) + } + + fn get_outbound_ticket( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + let now = clock(); + Ok(self + .tickets_outbound + .get(destination) + .filter(|(expires, _)| *expires > now) + .map(|(_, ticket)| *ticket)) + } + + fn get_outbound_ticket_expiry( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + let now = clock(); + Ok(self + .tickets_outbound + .get(destination) + .filter(|(expires, _)| *expires > now) + .map(|(expires, _)| *expires)) + } + + fn get_reusable_inbound_ticket( + &mut self, + destination: &[u8; 16], + renew_before: f64, + ) -> Result, StateStoreError> { + let threshold = clock() + renew_before; + Ok(self + .tickets_inbound + .iter() + .filter(|(_, (dest, expires))| dest == destination && *expires > threshold) + .max_by(|a, b| (a.1).1.total_cmp(&(b.1).1)) + .map(|(ticket, (_, expires))| (*expires, *ticket))) + } + + fn store_inbound_ticket( + &mut self, + destination: &[u8; 16], + ticket: &[u8; 16], + expires: f64, + ) -> Result<(), StateStoreError> { + self.tickets_inbound + .insert(*ticket, (*destination, expires)); + Ok(()) + } + + fn get_inbound_tickets( + &mut self, + destination: &[u8; 16], + ) -> Result>, StateStoreError> { + let now = clock(); + let tickets: Vec<[u8; 16]> = self + .tickets_inbound + .iter() + .filter(|(_, (dest, expires))| dest == destination && *expires > now) + .map(|(ticket, _)| *ticket) + .collect(); + Ok((!tickets.is_empty()).then_some(tickets)) + } + + fn get_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + ) -> Result, StateStoreError> { + Ok(self.last_deliveries.get(destination).copied()) + } + + fn mark_last_ticket_delivery( + &mut self, + destination: &[u8; 16], + timestamp: f64, + ) -> Result<(), StateStoreError> { + self.last_deliveries.insert(*destination, timestamp); + Ok(()) + } + + fn cull_tickets_outbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + Ok(Self::cull_map( + &mut self.tickets_outbound, + max_entries, + |(e, _)| *e < cutoff, + )) + } + + fn cull_tickets_inbound( + &mut self, + cutoff: f64, + max_entries: usize, + ) -> Result { + Ok(Self::cull_map( + &mut self.tickets_inbound, + max_entries, + |(_, e)| *e < cutoff, + )) + } + + fn incremental_vacuum(&mut self, _max_pages: usize) -> Result { + Ok(0) + } +} + +impl Backend for MemoryStateStore { + fn synced(&mut self, job: &mut dyn FnMut(&mut dyn StateStore)) -> Result<(), StateStoreError> { + job(self); + Ok(()) + } + + fn apply_imported(&mut self, rows: &[ImportRow]) -> Result { + for row in rows { + match *row { + ImportRow::Delivered(id, at) => { + self.delivered.entry(id).or_insert(at); + } + ImportRow::Processed(id, at) => { + self.processed.entry(id).or_insert(at); + } + ImportRow::StampCost(dest, updated, cost) => { + self.stamp_costs.entry(dest).or_insert((updated, cost)); + } + ImportRow::TicketOutbound(dest, expires, ticket) => { + self.tickets_outbound + .entry(dest) + .or_insert((expires, ticket)); + } + ImportRow::TicketInbound(ticket, dest, expires) => { + self.tickets_inbound + .entry(ticket) + .or_insert((dest, expires)); + } + ImportRow::TicketDelivery(dest, at) => { + self.last_deliveries.entry(dest).or_insert(at); + } + } + } + Ok(rows.len()) + } + + fn processed_ids(&mut self) -> Result, StateStoreError> { + Ok(self.processed.iter().map(|(id, at)| (*id, *at)).collect()) + } +} + +/// Import of the msgpack caches that LXMF 1.3.0 replaced, by the rules of +/// `LXMFStore.import_legacy_*`. Files written by earlier rsLXMF releases are +/// recognised by their layout and imported to the same rows. +pub(crate) mod legacy { + use super::*; + use crate::ticket::{Ticket, TicketStoreSnapshot}; + + /// The caches, in the order `LXMRouter.__import_legacy_storage` imports them. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub(crate) enum Source { + LocalDeliveries, + LocallyProcessed, + OutboundStampCosts, + AvailableTickets, + } + + impl Source { + pub(crate) const ALL: [Self; 4] = [ + Self::LocalDeliveries, + Self::LocallyProcessed, + Self::OutboundStampCosts, + Self::AvailableTickets, + ]; + + pub(crate) fn file_name(self) -> &'static str { + match self { + Self::LocalDeliveries => "local_deliveries", + Self::LocallyProcessed => "locally_processed", + Self::OutboundStampCosts => "outbound_stamp_costs", + Self::AvailableTickets => "available_tickets", + } + } + } + + /// Why a source was not imported; it stays where it is and is tried again + /// at the next start, as upstream does. + #[derive(Debug)] + pub(crate) enum ImportError { + Unreadable(String), + InvalidFormat, + Store(StateStoreError), + } + + impl std::fmt::Display for ImportError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unreadable(error) => write!(f, "could not be read: {error}"), + Self::InvalidFormat => f.write_str("has an invalid data format"), + Self::Store(error) => write!(f, "{error}"), + } + } + } + + /// A fixed-length key. Upstream writes `bin`; rsLXMF wrote `[u8; N]` as an + /// array of integers. + fn fixed_key(value: &rmpv::Value) -> Option<[u8; N]> { + match value { + rmpv::Value::Binary(bytes) => bytes.as_slice().try_into().ok(), + rmpv::Value::Array(items) => { + let bytes: Option> = items + .iter() + .map(|item| item.as_u64().and_then(|n| u8::try_from(n).ok())) + .collect(); + bytes?.try_into().ok() + } + _ => None, + } + } + + /// Python's `type(v) in (int, float)`. + fn number(value: &rmpv::Value) -> Option { + match value { + rmpv::Value::Integer(n) => n.as_f64(), + rmpv::Value::F32(n) => Some(f64::from(*n)), + rmpv::Value::F64(n) => Some(*n), + _ => None, + } + } + + fn field<'a>(map: &'a [(rmpv::Value, rmpv::Value)], name: &str) -> Option<&'a rmpv::Value> { + // A later duplicate key wins, as in a Python dict. + map.iter() + .rev() + .find(|(key, _)| key.as_str() == Some(name)) + .map(|(_, value)| value) + } + + #[derive(serde::Deserialize)] + #[serde(untagged)] + enum RustTickets { + Directional(TicketStoreSnapshot), + Flat(Vec), + } + + /// rsLXMF's own `available_tickets`: the directional snapshot, or the older + /// flat list whose entries served both directions. + fn rust_ticket_rows(bytes: &[u8]) -> Option> { + let outbound = + |t: &Ticket| ImportRow::TicketOutbound(t.destination_hash, t.expires, t.token); + let inbound = |t: &Ticket| ImportRow::TicketInbound(t.token, t.destination_hash, t.expires); + Some(match rmp_serde::from_slice(bytes).ok()? { + RustTickets::Directional(snapshot) => snapshot + .outbound + .iter() + .map(outbound) + .chain(snapshot.inbound.iter().map(inbound)) + .chain( + snapshot + .last_deliveries + .iter() + .map(|(dest, at)| ImportRow::TicketDelivery(*dest, *at)), + ) + .collect(), + RustTickets::Flat(tickets) => tickets + .iter() + .map(outbound) + .chain(tickets.iter().map(inbound)) + .collect(), + }) + } + + /// Decode `path` into the rows upstream's `import_legacy_*` would insert. + pub(crate) fn read_rows(source: Source, path: &Path) -> Result, ImportError> { + let bytes = std::fs::read(path).map_err(|e| ImportError::Unreadable(e.to_string()))?; + // Upstream's unpacker ignores bytes after the first value. + let root = rmpv::decode::read_value(&mut std::io::Cursor::new(&bytes)) + .map_err(|e| ImportError::Unreadable(e.to_string()))?; + if source == Source::AvailableTickets && root.is_array() { + return rust_ticket_rows(&bytes).ok_or(ImportError::InvalidFormat); + } + let Some(map) = root.as_map() else { + return Err(ImportError::InvalidFormat); + }; + let mut rows = Vec::new(); + match source { + Source::LocalDeliveries | Source::LocallyProcessed => { + for (key, value) in map { + let (Some(id), Some(at)) = (fixed_key::<32>(key), number(value)) else { + continue; + }; + // Written this way so NaN is skipped, as `timestamp > 0` skips it. + if at > 0.0 { + rows.push(match source { + Source::LocalDeliveries => ImportRow::Delivered(id, at), + _ => ImportRow::Processed(id, at), + }); + } + } + } + Source::OutboundStampCosts => { + for (key, value) in map { + let (Some(dest), Some(entry)) = (fixed_key::<16>(key), value.as_array()) else { + continue; + }; + if entry.len() < 2 { + continue; + } + // Upstream writes `[time, cost]` under a `bin` key + // (`LXMRouter.update_stamp_cost_legacy`). rsLXMF wrote + // `StampCostEntry` as `[cost, recorded_at]` under an array key. + let (last_heard, cost) = match key { + rmpv::Value::Binary(_) => (&entry[0], &entry[1]), + _ => (&entry[1], &entry[0]), + }; + let Some(last_heard) = number(last_heard) else { + continue; + }; + let cost = match cost { + rmpv::Value::Nil => None, + other => match number(other) { + Some(cost) => Some(cost), + None => continue, + }, + }; + rows.push(ImportRow::StampCost(dest, last_heard, cost)); + } + } + Source::AvailableTickets => { + if let Some(outbound) = field(map, "outbound").and_then(|v| v.as_map()) { + for (key, value) in outbound { + let (Some(dest), Some(entry)) = (fixed_key::<16>(key), value.as_array()) + else { + continue; + }; + if entry.len() < 2 { + continue; + } + if let (Some(expires), rmpv::Value::Binary(ticket)) = + (number(&entry[0]), &entry[1]) + && let Ok(ticket) = ticket.as_slice().try_into() + { + rows.push(ImportRow::TicketOutbound(dest, expires, ticket)); + } + } + } + if let Some(inbound) = field(map, "inbound").and_then(|v| v.as_map()) { + for (key, tickets) in inbound { + let (Some(dest), Some(tickets)) = (fixed_key::<16>(key), tickets.as_map()) + else { + continue; + }; + for (ticket, entry) in tickets { + let (Some(ticket), Some(entry)) = + (fixed_key::<16>(ticket), entry.as_array()) + else { + continue; + }; + if let Some(expires) = entry.first().and_then(number) { + rows.push(ImportRow::TicketInbound(ticket, dest, expires)); + } + } + } + } + if let Some(deliveries) = field(map, "last_deliveries").and_then(|v| v.as_map()) { + for (key, value) in deliveries { + if let (Some(dest), Some(at)) = (fixed_key::<16>(key), number(value)) { + rows.push(ImportRow::TicketDelivery(dest, at)); + } + } + } + } + } + Ok(rows) + } + + /// Import one source in one transaction, then rename it to `.imported`. + /// The rename follows the commit, so an interrupted import runs again and + /// inserts the same rows. + pub(crate) fn import( + store: &mut dyn Backend, + source: Source, + path: &Path, + ) -> Result { + let rows = read_rows(source, path)?; + let count = store.apply_imported(&rows).map_err(ImportError::Store)?; + let mut imported = path.as_os_str().to_owned(); + imported.push(".imported"); + if let Err(error) = std::fs::rename(path, &imported) { + tracing::warn!(%error, path = %path.display(), "could not mark legacy file as imported"); + } + Ok(count) + } +} + +#[cfg(feature = "sqlite-store")] +type Job = Box; + +/// The router's store. A file-backed store runs on its own thread, which owns +/// the connection: [`Self::write`] queues and returns, [`Self::call`] waits for +/// the result. Jobs run in the order they were handed over, so a read always +/// sees the writes queued before it. +pub(crate) struct StateStoreHandle { + inner: Inner, + /// `state.db` could not be opened; this session's state is not kept. + fallback: bool, +} + +enum Inner { + Memory(Box>), + #[cfg(feature = "sqlite-store")] + File { + jobs: Option>, + worker: Option>, + }, +} + +impl std::fmt::Debug for StateStoreHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match (&self.inner, self.fallback) { + (Inner::Memory(_), false) => "StateStoreHandle(memory)", + (Inner::Memory(_), true) => "StateStoreHandle(memory, fallback)", + #[cfg(feature = "sqlite-store")] + (Inner::File { .. }, _) => "StateStoreHandle(file)", + }) + } +} + +impl StateStoreHandle { + /// A store for a router without a storage directory. + pub(crate) fn in_memory() -> Self { + Self { + inner: Inner::Memory(Default::default()), + fallback: false, + } + } + + /// The in-memory store a router runs on when `state.db` cannot be opened. + #[cfg(feature = "sqlite-store")] + pub(crate) fn fallback() -> Self { + Self { + inner: Inner::Memory(Default::default()), + fallback: true, + } + } + + /// Open `path` on a dedicated thread. + #[cfg(feature = "sqlite-store")] + pub(crate) fn open_file(path: &Path) -> Result { + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (jobs, job_rx) = std::sync::mpsc::channel::(); + let path = path.to_path_buf(); + let worker = std::thread::Builder::new() + .name("lxmf-state-store".into()) + .spawn(move || match SqliteStateStore::open(&path) { + Ok(mut store) => { + let _ = ready_tx.send(Ok(())); + while let Ok(job) = job_rx.recv() { + job(&mut store); + } + } + Err(error) => { + let _ = ready_tx.send(Err(error)); + } + }) + .map_err(|e| StateStoreError::Open(e.to_string()))?; + match ready_rx.recv() { + Ok(Ok(())) => Ok(Self { + inner: Inner::File { + jobs: Some(jobs), + worker: Some(worker), + }, + fallback: false, + }), + Ok(Err(error)) => Err(error), + Err(_) => Err(StateStoreError::Open("store thread stopped".into())), + } + } + + /// Whether this is the in-memory store of a session whose file did not open. + pub(crate) fn is_fallback(&self) -> bool { + self.fallback + } + + /// Whether writes reach `state.db`. + pub(crate) fn is_file_backed(&self) -> bool { + match &self.inner { + Inner::Memory(_) => false, + #[cfg(feature = "sqlite-store")] + Inner::File { .. } => true, + } + } + + /// Run `job` and wait for its result; a file-backed store has committed + /// the job's writes when this returns. + pub(crate) fn call( + &self, + job: impl FnOnce(&mut dyn Backend) -> Result + Send + 'static, + ) -> Result { + match &self.inner { + Inner::Memory(store) => job(&mut *store.lock().unwrap_or_else(|e| e.into_inner())), + #[cfg(feature = "sqlite-store")] + Inner::File { jobs, .. } => { + let stopped = || StateStoreError::Operation("store thread stopped".into()); + let (tx, rx) = std::sync::mpsc::channel(); + jobs.as_ref() + .ok_or_else(stopped)? + .send(Box::new(move |store| { + let _ = tx.send(job(store)); + })) + .map_err(|_| stopped())?; + rx.recv().map_err(|_| stopped())? + } + } + } + + /// [`Self::call`] with `job` run as one transaction that is flushed to + /// disk before this returns ([`Backend::synced`]). + pub(crate) fn call_synced( + &self, + mut job: impl FnMut(&mut dyn StateStore) -> Result + Send + 'static, + ) -> Result { + self.call(move |store| { + let mut outcome = None; + store.synced(&mut |store| outcome = Some(job(store)))?; + outcome.expect("a synced transaction that began ran its job") + }) + } + + /// Run a write nothing waits for. A file-backed store queues it; a failure + /// is logged with `what`, as upstream logs it. + pub(crate) fn write( + &self, + what: &'static str, + job: impl FnOnce(&mut dyn Backend) -> Result<(), StateStoreError> + Send + 'static, + ) { + let logged = move |store: &mut dyn Backend| { + if let Err(error) = job(store) { + tracing::error!(%error, "could not {what} in the LXMF state store"); + } + }; + match &self.inner { + Inner::Memory(store) => logged(&mut *store.lock().unwrap_or_else(|e| e.into_inner())), + #[cfg(feature = "sqlite-store")] + Inner::File { jobs, .. } => { + if jobs + .as_ref() + .is_none_or(|jobs| jobs.send(Box::new(logged)).is_err()) + { + tracing::error!("LXMF state store thread stopped; could not {what}"); + } + } + } + } +} + +#[cfg(feature = "sqlite-store")] +impl Drop for StateStoreHandle { + fn drop(&mut self) { + // Queued writes finish and the connection closes before the router is gone. + if let Inner::File { jobs, worker } = &mut self.inner { + drop(jobs.take()); + if let Some(worker) = worker.take() { + let _ = worker.join(); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::legacy::{Source, read_rows}; + use super::*; + + fn exercise(store: &mut dyn StateStore) { + let id = [7u8; 32]; + assert!(store.conditionally_claim_delivered(&id, 1.0).unwrap()); + assert!(!store.conditionally_claim_delivered(&id, 2.0).unwrap()); + assert!(store.has_delivered(&id).unwrap()); + store.mark_locally_delivered(&id, 3.0).unwrap(); + assert!(store.conditionally_claim_processed(&id, 1.0).unwrap()); + assert_eq!(store.cull_delivered(10.0, 16).unwrap(), 1); + assert!(!store.has_delivered(&id).unwrap()); + let dest = [9u8; 16]; + store.update_stamp_cost(&dest, Some(8.0)).unwrap(); + assert_eq!(store.get_outbound_stamp_cost(&dest).unwrap(), Some(8.0)); + store.update_stamp_cost(&dest, None).unwrap(); + assert_eq!(store.get_outbound_stamp_cost(&dest).unwrap(), None); + let far = clock() + 1.0e6; + store.remember_ticket(&dest, far, &[1; 16]).unwrap(); + assert_eq!(store.get_outbound_ticket(&dest).unwrap(), Some([1; 16])); + store.store_inbound_ticket(&dest, &[2; 16], far).unwrap(); + assert_eq!( + store.get_reusable_inbound_ticket(&dest, 60.0).unwrap(), + Some((far, [2; 16])) + ); + assert_eq!( + store.get_inbound_tickets(&dest).unwrap(), + Some(vec![[2; 16]]) + ); + assert_eq!(store.cull_tickets_inbound(clock(), 16).unwrap(), 0); + } + + #[test] + fn memory_store_follows_the_operation_contract() { + exercise(&mut MemoryStateStore::default()); + } + + #[test] + #[cfg(feature = "sqlite-store")] + fn sqlite_store_follows_the_operation_contract() { + let dir = tempfile::TempDir::new().unwrap(); + let mut store = SqliteStateStore::open(&dir.path().join(FILE_NAME)).unwrap(); + exercise(&mut store); + } + + #[test] + #[cfg(feature = "sqlite-store")] + fn a_newer_user_version_is_refused_and_the_file_keeps_its_bytes() { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join(FILE_NAME); + rusqlite::Connection::open(&path) + .unwrap() + .execute_batch("CREATE TABLE later (x); PRAGMA user_version = 2") + .unwrap(); + let before = std::fs::read(&path).unwrap(); + assert!(matches!( + SqliteStateStore::open(&path), + Err(StateStoreError::NewerVersion { + found: 2, + supported: 1 + }) + )); + assert_eq!(std::fs::read(&path).unwrap(), before); + } + + fn rows_of(source: Source, bytes: Vec) -> Vec { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join(source.file_name()); + std::fs::write(&path, bytes).unwrap(); + read_rows(source, &path).unwrap() + } + + // Every rsLXMF release up to 1.4.0 wrote `{[u8; 16]: [cost: u8, recorded_at]}`. + #[test] + fn stamp_costs_written_with_integer_costs_import() { + #[derive(serde::Serialize)] + struct Entry { + cost: u8, + recorded_at: f64, + } + let file = HashMap::from([( + [0xAA; 16], + Entry { + cost: 12, + recorded_at: 1_700_000_000.0, + }, + )]); + assert_eq!( + rows_of( + Source::OutboundStampCosts, + rmp_serde::to_vec(&file).unwrap() + ), + vec![ImportRow::StampCost( + [0xAA; 16], + 1_700_000_000.0, + Some(12.0) + )] + ); + } + + // Later rsLXMF wrote `{[u8; 16]: [cost: Option, recorded_at]}`. + #[test] + fn stamp_costs_written_with_optional_fractional_costs_import() { + #[derive(serde::Serialize)] + struct Entry { + cost: Option, + recorded_at: f64, + } + let entry = |cost| Entry { + cost, + recorded_at: 1_700_000_000.0, + }; + let file = HashMap::from([([0xAA; 16], entry(Some(8.5))), ([0xBB; 16], entry(None))]); + let mut rows = rows_of( + Source::OutboundStampCosts, + rmp_serde::to_vec(&file).unwrap(), + ); + rows.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); + assert_eq!( + rows, + vec![ + ImportRow::StampCost([0xAA; 16], 1_700_000_000.0, Some(8.5)), + ImportRow::StampCost([0xBB; 16], 1_700_000_000.0, None), + ] + ); + } + + #[test] + fn transient_ids_written_by_rslxmf_import() { + let file = HashMap::from([([0x11u8; 32], 1_700_000_000.0f64)]); + assert_eq!( + rows_of(Source::LocalDeliveries, rmp_serde::to_vec(&file).unwrap()), + vec![ImportRow::Delivered([0x11; 32], 1_700_000_000.0)] + ); + assert_eq!( + rows_of(Source::LocallyProcessed, rmp_serde::to_vec(&file).unwrap()), + vec![ImportRow::Processed([0x11; 32], 1_700_000_000.0)] + ); + } + + #[test] + fn tickets_written_by_rslxmf_import_in_both_of_its_layouts() { + use crate::ticket::{Ticket, TicketStoreSnapshot}; + let learned = Ticket::new([0x01; 16], [0x02; 16], 9_999.0); + let issued = Ticket::new([0x03; 16], [0x04; 16], 8_888.0); + let directional = TicketStoreSnapshot { + version: 1, + outbound: vec![learned.clone()], + inbound: vec![issued], + last_deliveries: HashMap::from([([0x04; 16], 7_777.0)]), + }; + assert_eq!( + rows_of( + Source::AvailableTickets, + rmp_serde::to_vec(&directional).unwrap() + ), + vec![ + ImportRow::TicketOutbound([0x02; 16], 9_999.0, [0x01; 16]), + ImportRow::TicketInbound([0x03; 16], [0x04; 16], 8_888.0), + ImportRow::TicketDelivery([0x04; 16], 7_777.0), + ] + ); + // The flat list served both directions. + assert_eq!( + rows_of( + Source::AvailableTickets, + rmp_serde::to_vec(&vec![learned]).unwrap() + ), + vec![ + ImportRow::TicketOutbound([0x02; 16], 9_999.0, [0x01; 16]), + ImportRow::TicketInbound([0x01; 16], [0x02; 16], 9_999.0), + ] + ); + } +} diff --git a/crates/lxmf-core/tests/durable_delivery.rs b/crates/lxmf-core/tests/durable_delivery.rs index 9e38822..4c098e4 100644 --- a/crates/lxmf-core/tests/durable_delivery.rs +++ b/crates/lxmf-core/tests/durable_delivery.rs @@ -263,28 +263,23 @@ fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() { assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok()); } #[test] -fn reply_ticket_cannot_sign_before_its_exact_durable_intent() { +#[cfg(feature = "sqlite-store")] +fn tickets_and_delivered_claims_are_in_the_state_store_before_they_are_acted_on() { + use lxmf_core::state_store::{FILE_NAME, SqliteStateStore, StateStore}; let temp = tempfile::tempdir().unwrap(); let mut router = lxmf_core::router::LxmRouter::new(Default::default()); + router.load_state(temp.path()).unwrap(); + let stale = router.state_snapshot(); let mut draft = LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap(); draft.include_ticket = true; - let intent = router.prepare_outbound(&mut draft).unwrap(); - assert!(intent.requires_persistence()); - assert!( - draft - .clone() - .sign(&Ed25519PrivateKey::from_bytes(&[3; 32])) - .is_err() - ); - let mut other = - LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap(); - other.include_ticket = true; - assert!(matches!( - router.prepare_outbound(&mut other), - Err(lxmf_core::router::TicketPreparationError::PendingPersistence) - )); - intent.persist(temp.path(), &mut draft).unwrap(); + router.prepare_outbound(&mut draft).unwrap(); + // A second connection reads the committed ticket while the router still runs. + let issued = SqliteStateStore::open(&temp.path().join(FILE_NAME)) + .unwrap() + .get_inbound_tickets(&[1; 16]) + .unwrap() + .expect("ticket committed before prepare_outbound returned"); let msg = draft .sign(&Ed25519PrivateKey::from_bytes(&[3; 32])) .unwrap() @@ -295,9 +290,25 @@ fn reply_ticket_cannot_sign_before_its_exact_durable_intent() { .get(lxmf_core::constants::FIELD_TICKET) .is_some() ); - let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap(); - assert!(!loaded.0.inbound.is_empty()); - assert!(router.prepare_outbound(&mut other).is_ok()); + // The delivered claim is in the file before the delivery callback runs. + let db = temp.path().join(FILE_NAME); + let claimed_first = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = claimed_first.clone(); + router.register_delivery_callback(move |delivered| { + let claimed = SqliteStateStore::open(&db) + .unwrap() + .has_delivered(&delivered.message_id()) + .unwrap(); + seen.store(claimed, std::sync::atomic::Ordering::Relaxed); + }); + assert!(router.deliver_inbound(&msg, false)); + assert!(claimed_first.load(std::sync::atomic::Ordering::Relaxed)); + // An older checkpoint written afterwards cannot take the ticket away. + stale.save_state(temp.path()).unwrap(); + drop(router); + let mut restarted = lxmf_core::router::LxmRouter::new(Default::default()); + restarted.load_state(temp.path()).unwrap(); + assert_eq!(restarted.get_inbound_tickets(&[1; 16]), Some(issued)); } #[test] @@ -452,132 +463,3 @@ fn canceled_download_closes_exact_request_admission_reply() { } assert!(found); } - -#[test] -fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() { - let temp = tempfile::tempdir().unwrap(); - let mut router = lxmf_core::router::LxmRouter::new(Default::default()); - let stale = router.state_snapshot(); - let mut draft = - LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap(); - draft.include_ticket = true; - let intent = router.prepare_outbound(&mut draft).unwrap(); - intent.persist(temp.path(), &mut draft).unwrap(); - let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0; - assert_eq!(committed.inbound.len(), 1); - stale.save_state(temp.path()).unwrap(); - assert_eq!( - lxmf_core::persist::load_tickets(temp.path()).unwrap().0, - committed - ); - // A newer checkpoint can commit while a draft is waiting for its exact - // intent. The old intent verifies that its ticket is still present. - drop(draft); - let mut next = - LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap(); - next.include_ticket = true; - let intent = router.prepare_outbound(&mut next).unwrap(); - router.state_snapshot().save_state(temp.path()).unwrap(); - intent.persist(temp.path(), &mut next).unwrap(); - assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok()); - assert_eq!( - lxmf_core::persist::load_tickets(temp.path()) - .unwrap() - .0 - .inbound - .len(), - 2 - ); -} - -#[test] -fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() { - let temp = tempfile::tempdir().unwrap(); - let mut ledger = SuppressionLedger::default(); - ledger - .record_failure( - scope(1), - SuppressionReason::Malformed, - AdmissionEpochs::default(), - 100, - ) - .unwrap(); - lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap(); - assert_eq!( - lxmf_core::persist::load_suppression(temp.path()) - .unwrap() - .records() - .count(), - 1 - ); - let path = temp.path().join("propagation_suppression_v1"); - let bytes = std::fs::read(&path).unwrap(); - let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap(); - let rmpv::Value::Array(fields) = &mut value else { - panic!("ledger wrapper") - }; - let rmpv::Value::Map(rows) = &mut fields[0] else { - panic!("ledger records") - }; - rows.push(rows[0].clone()); - let mut duplicate = Vec::new(); - rmpv::encode::write_value(&mut duplicate, &value).unwrap(); - std::fs::write(&path, duplicate).unwrap(); - assert!(lxmf_core::persist::load_suppression(temp.path()).is_err()); - std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap(); - assert!(lxmf_core::persist::load_suppression(temp.path()).is_err()); -} - -#[test] -fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() { - use rns_identity::{ - announce_state::RatchetControlState, - identity::Identity, - ratchet::{RatchetRing, ReceivedRatchet}, - }; - let temp = tempfile::tempdir().unwrap(); - let identity = Identity::new(); - let mut ring = RatchetRing::new(); - let public = ring.rotate_at(100.); - let ring_path = temp.path().join("ring"); - ring.save_verified_durable(&ring_path, &identity).unwrap(); - assert_eq!( - RatchetRing::load_verified(&ring_path, &identity) - .unwrap() - .ring() - .current_public_key(), - Some(public) - ); - let control = RatchetControlState::new(identity.hash, [2; 16]) - .prepare_announce(100) - .unwrap() - .unwrap(); - let control_path = temp.path().join("control"); - control - .save_verified_durable(&control_path, &identity) - .unwrap(); - assert_eq!( - RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(), - control - ); - let received = ReceivedRatchet::new_at(public, 100.); - let received_path = temp.path().join("received"); - received.save_durable(&received_path).unwrap(); - assert_eq!( - ReceivedRatchet::load(&received_path).unwrap().ratchet_pub, - public - ); - let blocker = temp.path().join("not-a-directory"); - std::fs::write(&blocker, b"preserve").unwrap(); - assert!( - ring.save_verified_durable(&blocker.join("ring"), &identity) - .is_err() - ); - assert!( - control - .save_verified_durable(&blocker.join("control"), &identity) - .is_err() - ); - assert!(received.save_durable(&blocker.join("received")).is_err()); - assert_eq!(std::fs::read(blocker).unwrap(), b"preserve"); -} diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index dea1368..f467548 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -364,9 +364,12 @@ fn apply_propagation_store_commit( }; // LXMRouter keeps one processed-ID store; stored entries are claimed there at once. let now = now_f64(); + let mut claims = Vec::with_capacity(result.committed.len()); for (transient_id, _) in &result.committed { router.propagation_store.claim_processed(*transient_id, now); + claims.push((*transient_id, now)); } + router.record_processed_claims(&claims); distribution.extend( result .committed @@ -1794,9 +1797,17 @@ impl LxmdRunner { return; }; node.merge_processed_ids(self.router.propagation_store.locally_processed_ids()); - for (id, seen) in node.processed_ids() { + let claimed_by_node: Vec<_> = node + .processed_ids() + .iter() + .filter(|(id, _)| !self.router.propagation_store.is_locally_processed(id)) + .map(|(id, seen)| (*id, *seen)) + .collect(); + drop(node); + for (id, seen) in &claimed_by_node { self.router.propagation_store.claim_processed(*id, *seen); } + self.router.record_processed_claims(&claimed_by_node); } /// A transient ID claimed by local delivery is a duplicate for propagation intake. @@ -5247,8 +5258,8 @@ impl LxmdRunner { .copied(); let tickets = self .router - .ticket_store - .inbound_tokens(&msg.source_hash(), now_f64()); + .get_inbound_tickets(&msg.source_hash()) + .unwrap_or_default(); let cost = if self.config.enforce_stamps { self.config.stamp_cost.unwrap_or(0.0) } else { @@ -6905,13 +6916,8 @@ pub(crate) async fn main() { } } msg.include_ticket = true; - let prepared = runner.router.prepare_outbound(&mut msg).and_then(|intent| { - intent.persist(&runner.data_dir, &mut msg).map_err(|e| { - lxmf_core::router::TicketPreparationError::Encode(e.to_string()) - }) - }); - if let Err(error) = prepared { - tracing::error!(%error,"reply ticket persistence failed"); + if let Err(error) = runner.router.prepare_outbound(&mut msg) { + tracing::error!(%error, "reply ticket preparation failed"); break 'one_shot; } let Some(signing_key) = runner.identity.get_signing_key() else { @@ -7558,6 +7564,8 @@ mod tests { let (tx, _rx) = mpsc::channel(64); initialize_storage_namespace(temp.path()).unwrap(); let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap(); + let data_dir = runner.data_dir.clone(); + runner.router.load_state(&data_dir).unwrap(); let deliveries = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let observed = deliveries.clone(); runner.router.register_delivery_callback(move |_| { @@ -7661,46 +7669,6 @@ mod tests { .unwrap() } - #[tokio::test] - async fn control_unpeer_leaves_claims_rotated_by_a_running_checkpoint() { - let temp = tempfile::tempdir().unwrap(); - let (tx, _rx) = mpsc::channel::(64); - initialize_storage_namespace(temp.path()).unwrap(); - let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap(); - let data_dir = runner.data_dir.clone(); - runner.router.load_state(&data_dir).unwrap(); - let message = signed_fixture( - runner.lxmf_dest_hash, - [0xCD; 16], - "", - "claimed", - DeliveryMethod::Direct, - ); - assert!(runner.router.deliver_inbound(&message, false)); - let checkpoint = runner.router.state_snapshot(); - let saving = data_dir.join(format!( - "{}.saving", - lxmf_core::persist::DELIVERY_CLAIMS_FILE - )); - assert!(saving.exists()); - - let peer_hash = [0x44; 16]; - runner - .router - .peers - .insert(peer_hash, LxmPeer::new(peer_hash)); - let (command_tx, command_rx) = mpsc::unbounded_channel(); - runner.control_command_rx = command_rx; - command_tx.send(ControlCommand::Unpeer(peer_hash)).unwrap(); - runner.drain_control_commands(); - - assert!(!runner.router.peers.contains_key(&peer_hash)); - // The checkpoint that rotated the claims still owns them until it commits. - assert!(saving.exists()); - checkpoint.save_state(&data_dir).unwrap(); - assert!(!saving.exists()); - } - #[tokio::test] async fn a_directly_connected_peer_keeps_its_zero_hop_distance() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/lxmf-tools/src/lxmd_runtime.rs b/crates/lxmf-tools/src/lxmd_runtime.rs index 0a42a0a..b59e437 100644 --- a/crates/lxmf-tools/src/lxmd_runtime.rs +++ b/crates/lxmf-tools/src/lxmd_runtime.rs @@ -88,7 +88,6 @@ pub struct LocalStatusView { pub propagation_size: usize, pub pending_outbound: usize, pub pending_deferred_stamps: usize, - pub stamp_costs_cached: usize, } impl LocalStatusView { @@ -105,7 +104,6 @@ impl LocalStatusView { propagation_size: stats.propagation_size, pending_outbound: stats.pending_outbound, pending_deferred_stamps: stats.pending_deferred_stamps, - stamp_costs_cached: stats.stamp_costs_cached, } } } @@ -118,8 +116,7 @@ pub fn format_local_status(status: &LocalStatusView) -> String { Propagation messages: {}\n\ Propagation storage bytes: {}\n\ Pending outbound: {}\n\ - Pending deferred stamps: {}\n\ - Cached stamp costs: {}\n", + Pending deferred stamps: {}\n", hex::encode(status.lxmf_dest_hash), if status.propagation_enabled { "enabled" @@ -131,7 +128,6 @@ pub fn format_local_status(status: &LocalStatusView) -> String { status.propagation_size, status.pending_outbound, status.pending_deferred_stamps, - status.stamp_costs_cached, ) } @@ -427,7 +423,6 @@ mod tests { propagation_size: 4096, pending_outbound: 4, pending_deferred_stamps: 5, - stamp_costs_cached: 6, }; assert_eq!( @@ -438,8 +433,7 @@ mod tests { Propagation messages: 3\n\ Propagation storage bytes: 4096\n\ Pending outbound: 4\n\ - Pending deferred stamps: 5\n\ - Cached stamp costs: 6\n" + Pending deferred stamps: 5\n" ); }