diff --git a/crates/rns-identity/src/persistence/strict.rs b/crates/rns-identity/src/persistence/strict.rs index 1413baf..d0f51db 100644 --- a/crates/rns-identity/src/persistence/strict.rs +++ b/crates/rns-identity/src/persistence/strict.rs @@ -265,16 +265,9 @@ fn barrier_unsupported(error: &io::Error) -> bool { } } +/// On Apple targets `sync_all` is already `F_FULLFSYNC`. fn file_barrier(file: &File) -> io::Result<()> { - supported_barrier(file.sync_all())?; - #[cfg(any(target_os = "macos", target_os = "ios"))] - { - use std::os::fd::AsRawFd; - if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_FULLFSYNC) } == -1 { - supported_barrier(Err(io::Error::last_os_error()))?; - } - } - Ok(()) + supported_barrier(file.sync_all()) } fn parent_barrier(_path: &Path) -> io::Result<()> { diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index 753f5ff..ecf133a 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -1439,6 +1439,8 @@ impl TransportActor { .insert(pkt_hash, interface_id, Some(target_interface)); self.send_to_interface(target_interface, &forwarded); if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) { + // A first use is persisted: the path cull keeps used paths. + self.state_dirty |= path.used == 0.0; path.mark_used(); } trace!( @@ -1568,6 +1570,8 @@ impl TransportActor { return; } if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) { + // A first use is persisted: the path cull keeps used paths. + self.state_dirty |= path.used == 0.0; path.mark_used(); } @@ -2237,6 +2241,7 @@ impl TransportActor { } // Transport.py if let Some(path) = self.path_table.get_mut(&entry.destination_hash) { + self.state_dirty |= path.used == 0.0; path.mark_used(); } trace!( diff --git a/crates/rns-transport/src/actor/maintenance.rs b/crates/rns-transport/src/actor/maintenance.rs index 3575719..47e2cd4 100644 --- a/crates/rns-transport/src/actor/maintenance.rs +++ b/crates/rns-transport/src/actor/maintenance.rs @@ -45,7 +45,9 @@ impl TransportActor { if now - self.last_tables_cull >= TABLES_CULL_INTERVAL { self.cull_path_table(now); self.reverse_table.cull_expired(); - self.tunnel_table.cull_expired(); + if self.tunnel_table.cull_expired() > 0 { + self.state_dirty = true; + } self.cull_stale_tunnel_paths(now); self.cull_path_interface_suppressions(now); self.cull_local_link_route_attempts(now); @@ -75,12 +77,6 @@ impl TransportActor { ); } } - - // Cull may have removed path/tunnel entries — flag for save so - // the on-disk file reflects the current routing state. False - // positives (cull found nothing) cost one no-op file rewrite at - // the next periodic flush. - self.state_dirty = true; self.last_tables_cull = now; } @@ -131,8 +127,8 @@ impl TransportActor { if now - self.last_blackhole_check >= BLACKHOLE_CHECK_INTERVAL { if self.blackhole_table.cull_expired() > 0 { self.publish_blackhole_snapshot(); + self.state_dirty = true; } - self.state_dirty = true; self.last_blackhole_check = now; } @@ -266,6 +262,7 @@ impl TransportActor { } } if removed > 0 { + self.state_dirty = true; pathing!(removed, "removed stale paths"); } } diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 29e76f0..c96197f 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -318,6 +318,8 @@ pub struct TransportActor { /// decides whether a queued writer is still current. pub(crate) routing_save_lock: std::sync::Arc>, pub(crate) hashlist_save_in_flight: std::sync::Arc, + /// `packet_hashlist.revision()` as last loaded or saved. + pub(crate) hashlist_saved_revision: u64, /// Persisted path entries waiting on their interface to re-register. /// Drained by `drain_pending_for_interface` on `RegisterInterface`. @@ -608,6 +610,7 @@ impl TransportActor { routing_save_generation: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), routing_save_lock: std::sync::Arc::new(std::sync::Mutex::new(())), hashlist_save_in_flight: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + hashlist_saved_revision: 0, pending_path_entries: Vec::new(), recent_announces: HashMap::new(), startup_complete: false, diff --git a/crates/rns-transport/src/actor/outbound.rs b/crates/rns-transport/src/actor/outbound.rs index 1917505..1d1fc7f 100644 --- a/crates/rns-transport/src/actor/outbound.rs +++ b/crates/rns-transport/src/actor/outbound.rs @@ -266,6 +266,7 @@ impl TransportActor { // Transport.py: traffic marks use, never liveness. if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) { + self.state_dirty |= path.used == 0.0; path.mark_used(); } sent diff --git a/crates/rns-transport/src/actor/persistence.rs b/crates/rns-transport/src/actor/persistence.rs index 29b11ce..12f7c9d 100644 --- a/crates/rns-transport/src/actor/persistence.rs +++ b/crates/rns-transport/src/actor/persistence.rs @@ -86,35 +86,42 @@ pub(super) struct RoutingSnapshot { pub transport_identity_hash: Option<[u8; 16]>, } +fn write_encoded( + dir: &std::path::Path, + name: &str, + encoded: Result, crate::persistence::PersistenceError>, +) -> bool { + let written = + encoded.and_then(|bytes| crate::persistence::atomic_write_bytes(&dir.join(name), &bytes)); + if let Err(e) = &written { + trace!("failed to save {name}: {e}"); + } + written.is_ok() +} + /// Persist a routing snapshot. Runs on the blocking pool for periodic saves /// and inline for shutdown; must not touch the actor. pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSnapshot) { - let interface_names = &snapshot.interface_names; + use crate::persistence as p; + let keys = p::interface_keys(&snapshot.interface_names); - let path_table_path = dir.join("path_table.msgpack"); - if let Err(e) = - crate::persistence::save_path_table(&snapshot.path_table, interface_names, &path_table_path) - { - trace!("failed to save path table: {}", e); - } else { + if write_encoded( + dir, + "path_table.msgpack", + p::encode_path_table(&snapshot.path_table, &keys), + ) { debug!("saved path table ({} entries)", snapshot.path_table.len()); } - - let destination_table_path = dir.join("destination_table"); - if let Err(e) = crate::persistence::save_python_destination_table( - &snapshot.path_table, - interface_names, - &destination_table_path, + write_encoded( + dir, + "destination_table", + p::encode_python_destination_table(&snapshot.path_table, &keys), + ); + if write_encoded( + dir, + "blackhole_table.msgpack", + p::encode_blackhole_table(&snapshot.blackhole_table), ) { - trace!("failed to save Python destination_table: {}", e); - } - - let blackhole_path = dir.join("blackhole_table.msgpack"); - if let Err(e) = - crate::persistence::save_blackhole_table(&snapshot.blackhole_table, &blackhole_path) - { - trace!("failed to save blackhole table: {}", e); - } else { debug!( "saved blackhole table ({} entries)", snapshot.blackhole_table.len() @@ -123,39 +130,32 @@ pub(super) fn write_routing_snapshot(dir: &std::path::Path, snapshot: &RoutingSn // Publisher files are written only when fetched (Discovery.py). if let Some(local_identity_hash) = snapshot.transport_identity_hash { - let blackhole_dir = dir.join("blackhole"); - if let Err(e) = crate::persistence::save_local_blackhole_file( - &snapshot.blackhole_table, - local_identity_hash, - &blackhole_dir, - ) { - trace!("failed to save Python blackhole files: {}", e); + let written = + p::encode_local_blackhole_file(&snapshot.blackhole_table, local_identity_hash) + .and_then(|bytes| p::write_local_blackhole_file(&bytes, &dir.join("blackhole"))); + if let Err(e) = written { + trace!("failed to save Python blackhole files: {e}"); } } // Per-announce Python cache files are written event-driven at receive // (`cache_announce_to_disk`), not re-serialized here every cycle. - let tunnel_path = dir.join("tunnel_table.msgpack"); - if let Err(e) = - crate::persistence::save_tunnel_table(&snapshot.tunnel_table, interface_names, &tunnel_path) - { - trace!("failed to save tunnel table: {}", e); - } else { + if write_encoded( + dir, + "tunnel_table.msgpack", + p::encode_tunnel_table(&snapshot.tunnel_table, &keys), + ) { debug!( "saved tunnel table ({} entries)", snapshot.tunnel_table.len() ); } - - let python_tunnels_path = dir.join("tunnels"); - if let Err(e) = crate::persistence::save_python_tunnel_table( - &snapshot.tunnel_table, - interface_names, - &python_tunnels_path, - ) { - trace!("failed to save Python tunnels table: {}", e); - } + write_encoded( + dir, + "tunnels", + p::encode_python_tunnel_table(&snapshot.tunnel_table, &keys), + ); debug!( paths = snapshot.path_table.len(), @@ -430,6 +430,7 @@ impl TransportActor { trace!("failed to save hashlist: {}", e); } else { info!(entries = hashes.len(), "flushed hashlist"); + self.hashlist_saved_revision = self.packet_hashlist.revision(); } save_announce_rate_table(dir, &self.rate_table.to_bytes()); } @@ -438,15 +439,22 @@ impl TransportActor { /// Falling-edge (foreground→background) flush. Same coverage as /// `save_state` but entirely off-actor: on desktop the edge fires on /// every window focus loss, and the inline fsync chain (F_FULLFSYNC per - /// file on macOS) stalls routing + control queries for seconds. + /// file on macOS) stalls routing + control queries for seconds. What + /// is already on disk is not written again. pub(super) fn save_state_async(&mut self) { - self.save_routing_state_async(); + if self.state_dirty { + self.save_routing_state_async(); + } if !self.owns_persistent_hashlist() { return; } let Some(dir) = self.storage_dir.clone() else { return; }; + let revision = self.packet_hashlist.revision(); + if revision == self.hashlist_saved_revision { + return; + } if self .hashlist_save_in_flight .load(std::sync::atomic::Ordering::Acquire) @@ -456,6 +464,7 @@ impl TransportActor { } self.hashlist_save_in_flight .store(true, std::sync::atomic::Ordering::Release); + self.hashlist_saved_revision = revision; let hashes = self.packet_hashlist.current_hashes(); let rate_table = self.rate_table.to_bytes(); let in_flight = self.hashlist_save_in_flight.clone(); @@ -548,6 +557,7 @@ impl TransportActor { ); } self.packet_hashlist.load_from(loaded.hashes); + self.hashlist_saved_revision = self.packet_hashlist.revision(); debug!(count, "loaded canonical packet hashlist from disk"); } Err(e) => { @@ -575,6 +585,7 @@ impl TransportActor { self.packet_hashlist.load_from(hashes.clone()); match crate::persistence::save_raw_hashes(&hashes, &raw_path) { Ok(()) => { + self.hashlist_saved_revision = self.packet_hashlist.revision(); info!( source = %legacy_path.display(), destination = %raw_path.display(), @@ -1451,6 +1462,46 @@ mod async_save_tests { actor } + /// A cull pass that removes nothing leaves the routing state clean, so the + /// periodic save has nothing to write. + #[test] + fn empty_cull_pass_leaves_state_clean() { + let dir = temp_storage(); + let mut actor = dirty_actor(&dir); + actor.state_dirty = false; + actor.last_tables_cull = 0.0; + actor.last_blackhole_check = 0.0; + actor.on_tick(); + assert!(actor.path_table.has_path(&[0x11; 16])); + assert!(!actor.state_dirty); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A background edge writes only what changed since the last save. + #[test] + fn background_save_skips_unchanged_state() { + let dir = temp_storage(); + let mut actor = dirty_actor(&dir); + actor.is_transport_enabled = true; + actor.state_dirty = false; + actor.save_state_async(); + assert!(!dir.join("path_table.msgpack").exists()); + assert!(!dir.join("packet_hashlist.raw").exists()); + + actor.packet_hashlist.insert([0xAA; 32]); + actor.save_state_async(); + assert!(!dir.join("path_table.msgpack").exists()); + let saved = crate::persistence::load_hashlist_raw(&dir.join("packet_hashlist.raw")); + assert_eq!(saved.unwrap().hashes, vec![[0xAA; 32]]); + + std::fs::remove_file(dir.join("packet_hashlist.raw")).unwrap(); + actor.state_dirty = true; + actor.save_state_async(); + assert!(dir.join("path_table.msgpack").exists()); + assert!(!dir.join("packet_hashlist.raw").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// Pending known-destination marks are handed to the store on the 10 s cadence, /// without waiting for the routing tables' periodic save. #[test] diff --git a/crates/rns-transport/src/hashlist.rs b/crates/rns-transport/src/hashlist.rs index 73aaf1c..0a4bd67 100644 --- a/crates/rns-transport/src/hashlist.rs +++ b/crates/rns-transport/src/hashlist.rs @@ -13,6 +13,8 @@ pub struct PacketHashlist { current: HashSet<[u8; 32]>, previous: HashSet<[u8; 32]>, max_size: usize, + /// Bumped on every change to `current`, the persisted generation. + revision: u64, } impl PacketHashlist { @@ -28,6 +30,7 @@ impl PacketHashlist { current: HashSet::new(), previous: HashSet::new(), max_size, + revision: 0, } } @@ -42,6 +45,7 @@ impl PacketHashlist { return false; } self.current.insert(hash); + self.revision += 1; true } @@ -57,7 +61,9 @@ impl PacketHashlist { /// Forget a hash from both generations. pub fn remove(&mut self, hash: &[u8; 32]) { - self.current.remove(hash); + if self.current.remove(hash) { + self.revision += 1; + } self.previous.remove(hash); } @@ -65,6 +71,7 @@ impl PacketHashlist { /// begin an empty current generation. pub fn force_rotate(&mut self) { self.previous = std::mem::take(&mut self.current); + self.revision += 1; } pub fn len(&self) -> usize { @@ -78,6 +85,12 @@ impl PacketHashlist { pub fn clear(&mut self) { self.current.clear(); self.previous.clear(); + self.revision += 1; + } + + /// Changes when the current generation may have changed. + pub(crate) fn revision(&self) -> u64 { + self.revision } /// Snapshot the current generation in unspecified order for persistence. @@ -109,6 +122,7 @@ impl PacketHashlist { pub fn load_from(&mut self, hashes: Vec<[u8; 32]>) { self.current = hashes.into_iter().collect(); self.previous.clear(); + self.revision += 1; } } diff --git a/crates/rns-transport/src/persistence.rs b/crates/rns-transport/src/persistence.rs index 3aa7db6..862c43d 100644 --- a/crates/rns-transport/src/persistence.rs +++ b/crates/rns-transport/src/persistence.rs @@ -10,11 +10,12 @@ //! whole file and have no size limit; decoded metadata still needs validation //! before use. Loading a route does not establish that its peer is reachable. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::io::{BufReader, Read}; use std::path::Path; use rmpv::Value; +use serde::ser::{SerializeSeq, SerializeTuple, Serializer}; use serde::{Deserialize, Serialize}; use crate::constants::PERSIST_RANDOM_BLOBS; @@ -75,43 +76,127 @@ pub fn save_path_table( interface_names: &HashMap, path: &Path, ) -> Result<(), PersistenceError> { - let mut entries = Vec::new(); - for (hash, entry) in table.iter() { - let interface_name = interface_names.get(&entry.interface_id).cloned(); - // Skip entries whose interface has already been deregistered — we - // can't restore them safely (no name → no remap target on load). - if interface_name.is_none() { - continue; - } - let interface_hash = interface_name - .as_deref() - .map(interface_hash_from_name) - .map(|h| h.to_vec()); - entries.push(PersistedPathEntry { - destination_hash: hash.to_vec(), - timestamp: entry.timestamp, - next_hop: entry.next_hop.map(|h| h.to_vec()), - hops: entry.hops, - expires: entry.expires, - random_blobs: entry - .blobs_for_persist() - .iter() - .map(|b| b.to_vec()) - .collect(), - interface_id: entry.interface_id, - interface_name, - interface_hash, - packet_hash: entry.packet_hash.map(|h| h.to_vec()), - used: Some(entry.used), - }); + atomic_write_bytes( + path, + &encode_path_table(table, &interface_keys(interface_names))?, + ) +} + +/// Interface name and name hash by interface id, hashed once per save. +pub(crate) type InterfaceKeys<'a> = HashMap; + +pub(crate) fn interface_keys(names: &HashMap) -> InterfaceKeys<'_> { + names + .iter() + .map(|(&id, name)| (id, (name.as_str(), interface_hash_from_name(name)))) + .collect() +} + +fn encode(value: &T) -> Result, PersistenceError> { + rmp_serde::to_vec(value).map_err(|e| PersistenceError::Serialize(e.to_string())) +} + +/// msgpack bin, as `Value::Binary` encodes. +struct Bin<'a>(&'a [u8]); + +impl Serialize for Bin<'_> { + fn serialize(&self, s: S) -> Result { + s.serialize_bytes(self.0) } +} - let persisted = PersistedPathTable { - entries, +/// The newest `PERSIST_RANDOM_BLOBS` blobs, or all of them, as `Vec>` +/// (byte arrays) or, with `bin`, as `Value::Binary` rows. +struct Blobs<'a> { + blobs: &'a VecDeque<[u8; 10]>, + newest_only: bool, + bin: bool, +} + +impl Serialize for Blobs<'_> { + fn serialize(&self, s: S) -> Result { + let skip = if self.newest_only { + self.blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS) + } else { + 0 + }; + let blobs = self.blobs.iter().skip(skip); + if self.bin { + s.collect_seq(blobs.map(|b| Bin(b))) + } else { + s.collect_seq(blobs.map(|b| b.as_slice())) + } + } +} + +/// Borrowed [`PersistedPathEntry`]; serializes to the same bytes. +#[derive(Serialize)] +struct PathEntryRef<'a> { + destination_hash: &'a [u8], + timestamp: f64, + next_hop: Option<&'a [u8]>, + hops: u8, + expires: f64, + random_blobs: Blobs<'a>, + interface_id: u64, + interface_name: Option<&'a str>, + interface_hash: Option<&'a [u8]>, + packet_hash: Option<&'a [u8]>, + used: Option, +} + +struct PathRows<'a> { + table: &'a PathTable, + keys: &'a InterfaceKeys<'a>, +} + +impl Serialize for PathRows<'_> { + fn serialize(&self, s: S) -> Result { + let rows = || { + self.table.iter().filter_map(|(hash, entry)| { + let (name, name_hash) = self.keys.get(&entry.interface_id)?; + Some(PathEntryRef { + destination_hash: hash.as_bytes(), + timestamp: entry.timestamp, + next_hop: entry.next_hop.as_ref().map(|h| h.as_slice()), + hops: entry.hops, + expires: entry.expires, + random_blobs: Blobs { + blobs: &entry.random_blobs, + newest_only: true, + bin: false, + }, + interface_id: entry.interface_id, + interface_name: Some(name), + interface_hash: Some(name_hash), + packet_hash: entry.packet_hash.as_ref().map(|h| h.as_slice()), + used: Some(entry.used), + }) + }) + }; + let mut seq = s.serialize_seq(Some(rows().count()))?; + for row in rows() { + seq.serialize_element(&row)?; + } + seq.end() + } +} + +#[derive(Serialize)] +struct PathTableRef<'a> { + entries: PathRows<'a>, + version: u32, +} + +/// [`save_path_table`]'s file bytes, without an owned copy of the table. +pub(crate) fn encode_path_table( + table: &PathTable, + keys: &InterfaceKeys<'_>, +) -> Result, PersistenceError> { + encode(&PathTableRef { + entries: PathRows { table, keys }, version: PersistedPathTable::CURRENT_VERSION, - }; - - atomic_write(path, &persisted) + }) } /// Decode a Rust path snapshot with a supported version (1 through 4). @@ -191,37 +276,83 @@ pub fn save_python_destination_table( interface_names: &HashMap, path: &Path, ) -> Result<(), PersistenceError> { - let mut entries = Vec::new(); - for (hash, entry) in table.iter() { - let Some(interface_name) = interface_names.get(&entry.interface_id) else { - continue; - }; - let Some(packet_hash) = entry.packet_hash else { - continue; - }; - let received_from = entry.next_hop.unwrap_or(*hash.as_bytes()); - let random_blobs = entry - .random_blobs - .iter() - .map(|b| Value::Binary(b.to_vec())) - .collect(); - entries.push(Value::Array(vec![ - Value::Binary(hash.to_vec()), - Value::F64(entry.timestamp), - Value::Binary(received_from.to_vec()), - Value::Integer((entry.hops as u64).into()), - Value::F64(entry.expires), - Value::Array(random_blobs), - Value::Binary(interface_hash_from_name(interface_name).to_vec()), - Value::Binary(packet_hash.to_vec()), - Value::F64(entry.used), - ])); - } + atomic_write_bytes( + path, + &encode_python_destination_table(table, &interface_keys(interface_names))?, + ) +} - let mut serialized = Vec::new(); - rmpv::encode::write_value(&mut serialized, &Value::Array(entries)) - .map_err(|e| PersistenceError::Serialize(e.to_string()))?; - atomic_write_bytes(path, &serialized) +/// One Python `destination_table` row (Transport.py). +struct PythonPathRow<'a> { + destination_hash: &'a [u8], + timestamp: f64, + received_from: &'a [u8], + hops: u8, + expires: f64, + random_blobs: Blobs<'a>, + interface_hash: &'a [u8], + packet_hash: &'a [u8], + used: f64, +} + +impl Serialize for PythonPathRow<'_> { + fn serialize(&self, s: S) -> Result { + let mut row = s.serialize_tuple(9)?; + row.serialize_element(&Bin(self.destination_hash))?; + row.serialize_element(&self.timestamp)?; + row.serialize_element(&Bin(self.received_from))?; + row.serialize_element(&u64::from(self.hops))?; + row.serialize_element(&self.expires)?; + row.serialize_element(&self.random_blobs)?; + row.serialize_element(&Bin(self.interface_hash))?; + row.serialize_element(&Bin(self.packet_hash))?; + row.serialize_element(&self.used)?; + row.end() + } +} + +struct Rows(F); + +impl<'a, F, I> Serialize for Rows +where + F: Fn() -> I, + I: Iterator>, +{ + fn serialize(&self, s: S) -> Result { + let mut seq = s.serialize_seq(Some((self.0)().count()))?; + for row in (self.0)() { + seq.serialize_element(&row)?; + } + seq.end() + } +} + +/// [`save_python_destination_table`]'s file bytes, without a `Value` tree. +pub(crate) fn encode_python_destination_table( + table: &PathTable, + keys: &InterfaceKeys<'_>, +) -> Result, PersistenceError> { + encode(&Rows(|| { + table.iter().filter_map(|(hash, entry)| { + let (_, name_hash) = keys.get(&entry.interface_id)?; + let packet_hash = entry.packet_hash.as_ref()?; + Some(PythonPathRow { + destination_hash: hash.as_bytes(), + timestamp: entry.timestamp, + received_from: entry.next_hop.as_ref().unwrap_or(hash.as_bytes()), + hops: entry.hops, + expires: entry.expires, + random_blobs: Blobs { + blobs: &entry.random_blobs, + newest_only: false, + bin: true, + }, + interface_hash: name_hash, + packet_hash, + used: entry.used, + }) + }) + })) } /// Decode Python-compatible destination rows from a local file. @@ -395,12 +526,22 @@ pub fn save_python_tunnel_table( interface_names: &HashMap, path: &Path, ) -> Result<(), PersistenceError> { + atomic_write_bytes( + path, + &encode_python_tunnel_table(table, &interface_keys(interface_names))?, + ) +} + +pub(crate) fn encode_python_tunnel_table( + table: &crate::tunnel::TunnelTable, + keys: &InterfaceKeys<'_>, +) -> Result, PersistenceError> { let mut tunnel_values = Vec::new(); for (_, tunnel) in table.iter() { let interface_hash = tunnel .interface_id - .and_then(|id| interface_names.get(&id)) - .map(|name| Value::Binary(interface_hash_from_name(name).to_vec())) + .and_then(|id| keys.get(&id)) + .map(|(_, hash)| Value::Binary(hash.to_vec())) .unwrap_or(Value::Nil); let mut path_values = Vec::new(); @@ -440,10 +581,7 @@ pub fn save_python_tunnel_table( ])); } - let mut serialized = Vec::new(); - rmpv::encode::write_value(&mut serialized, &Value::Array(tunnel_values)) - .map_err(|e| PersistenceError::Serialize(e.to_string()))?; - atomic_write_bytes(path, &serialized) + encode_value(&Value::Array(tunnel_values)) } /// Decode a local Python-compatible tunnel table. Malformed tunnel or path @@ -614,14 +752,10 @@ pub fn save_hashlist_legacy( } /// Replace `path` with the supplied hashes concatenated as raw 32-byte records. -/// Input order and duplicates are preserved. The full output is allocated in -/// memory before writing through the shared atomic-file helper. +/// Input order and duplicates are preserved. The records are written in place +/// through the shared atomic-file helper. pub fn save_raw_hashes(hashes: &[[u8; 32]], path: &Path) -> Result<(), PersistenceError> { - let mut serialized = Vec::with_capacity(hashes.len().saturating_mul(32)); - for hash in hashes { - serialized.extend_from_slice(hash); - } - atomic_write_bytes(path, &serialized) + atomic_write_bytes(path, hashes.as_flattened()) } /// Load raw 32-byte hash records through a 64 KiB reader buffer. @@ -712,13 +846,14 @@ pub fn load_hashlist(path: &Path) -> Result, PersistenceError> { /// Write to a sibling `.tmp` file and rename on top of the target so a crash /// mid-write cannot leave a half-written snapshot on disk. +#[cfg(test)] fn atomic_write(path: &Path, data: &T) -> Result<(), PersistenceError> { let serialized = rmp_serde::to_vec(data).map_err(|e| PersistenceError::Serialize(e.to_string()))?; atomic_write_bytes(path, &serialized) } -fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> { +pub(crate) fn atomic_write_bytes(path: &Path, serialized: &[u8]) -> Result<(), PersistenceError> { // Single canonical atomic-write implementation (fsync + rename + dir // sync) lives in rns-identity; transport tables share it (AF-2026-04.2). rns_identity::persistence::atomic_write(path, serialized).map_err(PersistenceError::Io) @@ -753,6 +888,12 @@ pub fn save_blackhole_table( table: &crate::blackhole::BlackholeTable, path: &Path, ) -> Result<(), PersistenceError> { + atomic_write_bytes(path, &encode_blackhole_table(table)?) +} + +pub(crate) fn encode_blackhole_table( + table: &crate::blackhole::BlackholeTable, +) -> Result, PersistenceError> { let mut entries = Vec::new(); for (hash, entry) in table.iter_entries() { if entry.source.is_some() { @@ -767,12 +908,10 @@ pub fn save_blackhole_table( }); } - let persisted = PersistedBlackholeTable { + encode(&PersistedBlackholeTable { entries, version: PersistedBlackholeTable::CURRENT_VERSION, - }; - - atomic_write(path, &persisted) + }) } /// Decode a version-1 or version-2 Rust blackhole snapshot. Stored hash lengths, @@ -848,8 +987,25 @@ pub fn save_local_blackhole_file( table: &crate::blackhole::BlackholeTable, local_identity_hash: [u8; 16], blackhole_dir: &Path, +) -> Result<(), PersistenceError> { + write_local_blackhole_file( + &encode_local_blackhole_file(table, local_identity_hash)?, + blackhole_dir, + ) +} + +pub(crate) fn write_local_blackhole_file( + bytes: &[u8], + blackhole_dir: &Path, ) -> Result<(), PersistenceError> { std::fs::create_dir_all(blackhole_dir).map_err(PersistenceError::Io)?; + atomic_write_bytes(&blackhole_dir.join("local"), bytes) +} + +pub(crate) fn encode_local_blackhole_file( + table: &crate::blackhole::BlackholeTable, + local_identity_hash: [u8; 16], +) -> Result, PersistenceError> { let local_entries = table .iter_entries() .filter(|(_, entry)| { @@ -865,7 +1021,7 @@ pub fn save_local_blackhole_file( ) }) .collect(); - write_value_file(&blackhole_dir.join("local"), &Value::Map(local_entries)) + encode_value(&Value::Map(local_entries)) } /// Store a publisher's fetched `/list` reply as `blackhole_dir/`, @@ -1005,11 +1161,15 @@ fn blackhole_entry_value(source: [u8; 16], until: Option, reason: Option<&s ]) } -fn write_value_file(path: &Path, value: &Value) -> Result<(), PersistenceError> { +fn encode_value(value: &Value) -> Result, PersistenceError> { let mut serialized = Vec::new(); rmpv::encode::write_value(&mut serialized, value) .map_err(|e| PersistenceError::Serialize(e.to_string()))?; - atomic_write_bytes(path, &serialized) + Ok(serialized) +} + +fn write_value_file(path: &Path, value: &Value) -> Result<(), PersistenceError> { + atomic_write_bytes(path, &encode_value(value)?) } fn map_get<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a Value> { @@ -1266,13 +1426,20 @@ pub fn save_tunnel_table( interface_names: &HashMap, path: &Path, ) -> Result<(), PersistenceError> { + atomic_write_bytes( + path, + &encode_tunnel_table(table, &interface_keys(interface_names))?, + ) +} + +pub(crate) fn encode_tunnel_table( + table: &crate::tunnel::TunnelTable, + keys: &InterfaceKeys<'_>, +) -> Result, PersistenceError> { let entries: Vec = table .iter() .map(|(_, entry)| { - let interface_name = entry - .interface_id - .and_then(|id| interface_names.get(&id)) - .cloned(); + let interface = entry.interface_id.and_then(|id| keys.get(&id)); let paths: Vec = entry .tunnel_paths .iter() @@ -1299,20 +1466,16 @@ pub fn save_tunnel_table( interface_id: entry.interface_id.unwrap_or_default(), expires: entry.expires, paths, - interface_hash: interface_name - .as_deref() - .map(|name| interface_hash_from_name(name).to_vec()), - interface_name, + interface_hash: interface.map(|(_, hash)| hash.to_vec()), + interface_name: interface.map(|(name, _)| name.to_string()), } }) .collect(); - let persisted = PersistedTunnelTable { + encode(&PersistedTunnelTable { entries, version: PersistedTunnelTable::CURRENT_VERSION, - }; - - atomic_write(path, &persisted) + }) } /// Decode a supported Rust tunnel snapshot (versions 1 through 3). This returns @@ -1364,6 +1527,101 @@ mod tests { dir } + fn varied_path_table() -> (PathTable, HashMap) { + let mut table = PathTable::new(); + for i in 0..40u8 { + let mut entry = PathEntry::new( + (i % 3 != 0).then_some([i; 16]), + i % 9, + u64::from(i % 4), + InterfaceMode::Full, + ); + entry.timestamp = 1_700_000_000.25 + f64::from(i); + entry.expires = entry.timestamp + 604_800.5; + entry.used = if i % 2 == 0 { + 0.0 + } else { + entry.timestamp + 3.5 + }; + entry.packet_hash = (i % 5 != 0).then_some([i.wrapping_mul(7); 32]); + for b in 0..u16::from(i) { + entry.add_random_blob([(b % 251) as u8; 10]); + } + table.insert([i.wrapping_add(100); 16], entry); + } + let names = (0..3u64) + .map(|id| (id, format!("Interface[{id}]"))) + .collect(); + (table, names) + } + + /// The borrowed encoders write the bytes the owned-copy encoders did. + #[test] + fn path_table_encoders_match_owned_reference() { + let (table, names) = varied_path_table(); + let keys = interface_keys(&names); + + let entries: Vec = table + .iter() + .filter_map(|(hash, entry)| { + let name = names.get(&entry.interface_id)?; + Some(PersistedPathEntry { + destination_hash: hash.to_vec(), + timestamp: entry.timestamp, + next_hop: entry.next_hop.map(|h| h.to_vec()), + hops: entry.hops, + expires: entry.expires, + random_blobs: entry + .blobs_for_persist() + .iter() + .map(|b| b.to_vec()) + .collect(), + interface_id: entry.interface_id, + interface_name: Some(name.clone()), + interface_hash: Some(interface_hash_from_name(name).to_vec()), + packet_hash: entry.packet_hash.map(|h| h.to_vec()), + used: Some(entry.used), + }) + }) + .collect(); + let reference = rmp_serde::to_vec(&PersistedPathTable { + entries, + version: PersistedPathTable::CURRENT_VERSION, + }) + .unwrap(); + assert_eq!(encode_path_table(&table, &keys).unwrap(), reference); + + let rows: Vec = table + .iter() + .filter_map(|(hash, entry)| { + let name = names.get(&entry.interface_id)?; + let packet_hash = entry.packet_hash?; + Some(Value::Array(vec![ + Value::Binary(hash.to_vec()), + Value::F64(entry.timestamp), + Value::Binary(entry.next_hop.unwrap_or(*hash.as_bytes()).to_vec()), + Value::Integer((entry.hops as u64).into()), + Value::F64(entry.expires), + Value::Array( + entry + .random_blobs + .iter() + .map(|b| Value::Binary(b.to_vec())) + .collect(), + ), + Value::Binary(interface_hash_from_name(name).to_vec()), + Value::Binary(packet_hash.to_vec()), + Value::F64(entry.used), + ])) + }) + .collect(); + assert!(rows.len() > 10); + assert_eq!( + encode_python_destination_table(&table, &keys).unwrap(), + encode_value(&Value::Array(rows)).unwrap() + ); + } + #[test] fn test_save_load_path_table() { let mut table = PathTable::new();