diff --git a/Cargo.lock b/Cargo.lock index 1dbc90b..898699f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1613,6 +1613,7 @@ dependencies = [ "rns-crypto", "rns-wire", "serde", + "serde_bytes", "thiserror 2.0.18", "tracing", "zeroize", diff --git a/Cargo.toml b/Cargo.toml index 7415a7d..3476169 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ base64 = "0.22" rmp-serde = "1" rmpv = "1" serde = { version = "1", features = ["derive"] } +serde_bytes = "0.11" serde_json = "1" # Async diff --git a/crates/rns-identity/Cargo.toml b/crates/rns-identity/Cargo.toml index 95b3d10..dd323d0 100644 --- a/crates/rns-identity/Cargo.toml +++ b/crates/rns-identity/Cargo.toml @@ -13,6 +13,7 @@ thiserror = { workspace = true } rmp-serde = { workspace = true } rmpv = { workspace = true } serde = { workspace = true } +serde_bytes = { workspace = true } rand = { workspace = true } tracing = { workspace = true } hex = { workspace = true } diff --git a/crates/rns-identity/src/announce.rs b/crates/rns-identity/src/announce.rs index 60afb80..38b3ad9 100644 --- a/crates/rns-identity/src/announce.rs +++ b/crates/rns-identity/src/announce.rs @@ -12,6 +12,9 @@ const RANDOM_HASH_SIZE: usize = 10; const SIGNATURE_SIZE: usize = 64; const RATCHET_SIZE: usize = 32; +/// Maximum value carried in the low five bytes of an announce random hash. +pub const ANNOUNCE_TIME_MAX: u64 = (1u64 << 40) - 1; + const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE; #[derive(Debug, Error)] @@ -28,6 +31,8 @@ pub enum AnnounceError { InvalidPublicKey, #[error("hash collision detected for destination")] HashCollision, + #[error("announce wire time exceeds 40-bit field: {0}")] + InvalidWireTime(u64), } /// Parsed announce data. @@ -52,18 +57,33 @@ impl AnnounceData { app_data: Option<&[u8]>, ratchet_pub: Option<&[u8; 32]>, ) -> Result { - let public_key = identity.get_public_key(); - let nh = name_hash(app_name); - - let random_bytes = rns_crypto::random::random_bytes(5); let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); - let ts_bytes = ts.to_be_bytes(); + Self::create_at(identity, app_name, app_data, ratchet_pub, ts) + } + + /// Create and sign an announce with an explicit persisted 40-bit ordering + /// value. Rotation and expiry clocks must be managed separately. + pub fn create_at( + identity: &Identity, + app_name: &str, + app_data: Option<&[u8]>, + ratchet_pub: Option<&[u8; 32]>, + wire_time: u64, + ) -> Result { + if wire_time > ANNOUNCE_TIME_MAX { + return Err(AnnounceError::InvalidWireTime(wire_time)); + } + + let public_key = identity.get_public_key(); + let nh = name_hash(app_name); + let random_bytes = rns_crypto::random::random_bytes(5); + let ts_bytes = wire_time.to_be_bytes(); let mut random_hash = [0u8; 10]; random_hash[..5].copy_from_slice(&random_bytes); - // Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years. + // The value was range checked, so these are the complete 40 bits. random_hash[5..].copy_from_slice(&ts_bytes[3..8]); let dest_hash = crate::destination::Destination::hash_from_name_and_identity( @@ -302,6 +322,21 @@ mod tests { assert_eq!(validated_id.hash, id.hash); } + #[test] + fn explicit_wire_time_uses_exact_40_bit_value() { + let id = Identity::new(); + let wire_time = 0x12_3456_789Au64; + let announce = AnnounceData::create_at(&id, "test.time", None, None, wire_time).unwrap(); + assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]); + + let maximum = AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX); + assert!(maximum.is_ok()); + assert!(matches!( + AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX + 1,), + Err(AnnounceError::InvalidWireTime(_)) + )); + } + #[test] fn test_create_and_validate_with_ratchet() { let id = Identity::new(); diff --git a/crates/rns-identity/src/announce_state.rs b/crates/rns-identity/src/announce_state.rs new file mode 100644 index 0000000..059cf0b --- /dev/null +++ b/crates/rns-identity/src/announce_state.rs @@ -0,0 +1,303 @@ +//! Durable control-plane state for ratcheted announces. +//! +//! The signed Python-compatible ratchet ring contains only private keys. This +//! sidecar deliberately keeps local policy metadata separate: the last wall +//! time used for rotation and the last 40-bit value emitted on the wire. + +use std::path::Path; + +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +use crate::announce::ANNOUNCE_TIME_MAX; +use crate::identity::Identity; +use crate::persistence; + +const CONTROL_STATE_VERSION: u8 = 1; +const CONTROL_STATE_MAX_BYTES: usize = 4096; + +fn invalid_data(message: impl Into) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, message.into()) +} + +/// Signed, identity- and destination-bound state used to plan a ratcheted +/// announce without mutating live state before persistence succeeds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RatchetControlState { + identity_hash: [u8; 16], + destination_hash: [u8; 16], + last_rotation_wall: Option, + last_announce_wire: Option, +} + +impl RatchetControlState { + pub fn new(identity_hash: [u8; 16], destination_hash: [u8; 16]) -> Self { + Self { + identity_hash, + destination_hash, + last_rotation_wall: None, + last_announce_wire: None, + } + } + + pub fn identity_hash(&self) -> [u8; 16] { + self.identity_hash + } + + pub fn destination_hash(&self) -> [u8; 16] { + self.destination_hash + } + + pub fn last_rotation_wall(&self) -> Option { + self.last_rotation_wall + } + + pub fn last_announce_wire(&self) -> Option { + self.last_announce_wire + } + + /// Anchor unknown rotation age at the current wall time. Existing age is + /// never overwritten by this operation. + pub fn anchor_rotation_if_unknown(&mut self, wall_now: u64) { + if self.last_rotation_wall.is_none() { + self.last_rotation_wall = Some(wall_now); + } + } + + /// Rotation is due only when a persisted age exists and the wall clock has + /// advanced by the full interval. Clock rollback never looks elapsed. + pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool { + self.last_rotation_wall + .is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs) + } + + /// Return a cloned candidate recording a successful rotation. + pub fn with_rotation_at(&self, wall_now: u64) -> Self { + let mut candidate = self.clone(); + candidate.last_rotation_wall = Some(wall_now); + candidate + } + + /// Prepare the next wire-ordering value without mutating this live state. + /// + /// `None` means wall time has not advanced beyond the last durable value; + /// callers must coalesce/defer instead of inventing `last + 1`, which could + /// make an announce appear to come from the future. + pub fn prepare_announce(&self, wall_now: u64) -> std::io::Result> { + if wall_now > ANNOUNCE_TIME_MAX { + return Err(invalid_data(format!( + "wall time {wall_now} exceeds 40-bit announce field" + ))); + } + if self.last_announce_wire.is_some_and(|last| wall_now <= last) { + return Ok(None); + } + + let mut candidate = self.clone(); + candidate.last_announce_wire = Some(wall_now); + Ok(Some(candidate)) + } + + /// Persist this state as a signed, bounded MessagePack envelope. + pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> { + if identity.hash != self.identity_hash { + return Err(invalid_data("control state identity binding mismatch")); + } + self.validate()?; + + let body = ControlStateBody { + version: CONTROL_STATE_VERSION, + identity_hash: self.identity_hash.to_vec(), + destination_hash: self.destination_hash.to_vec(), + last_rotation_wall: self.last_rotation_wall, + last_announce_wire: self.last_announce_wire, + }; + let packed = Zeroizing::new( + rmp_serde::to_vec_named(&body).map_err(|e| std::io::Error::other(e.to_string()))?, + ); + let signature = identity.sign(&packed).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "identity cannot sign ratchet control state", + ) + })?; + let envelope = ControlStateEnvelope { + signature: signature.to_vec(), + state: packed.to_vec(), + }; + let encoded = Zeroizing::new( + rmp_serde::to_vec_named(&envelope).map_err(|e| std::io::Error::other(e.to_string()))?, + ); + if encoded.len() > CONTROL_STATE_MAX_BYTES { + return Err(invalid_data("ratchet control state exceeds size limit")); + } + persistence::atomic_write(path, &encoded) + } + + /// Load and verify state for exactly `identity` and `destination_hash`. + pub fn load_verified( + path: &Path, + identity: &Identity, + destination_hash: [u8; 16], + ) -> std::io::Result { + let encoded = Zeroizing::new( + persistence::read_file_bounded(path, CONTROL_STATE_MAX_BYTES)? + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?, + ); + let envelope: ControlStateEnvelope = + rmp_serde::from_slice(&encoded).map_err(|e| std::io::Error::other(e.to_string()))?; + if envelope.signature.len() != 64 { + return Err(invalid_data("invalid control-state signature length")); + } + let signature: [u8; 64] = envelope + .signature + .as_slice() + .try_into() + .map_err(|_| invalid_data("invalid control-state signature length"))?; + let packed = Zeroizing::new(envelope.state); + if !identity.verify(&packed, &signature) { + return Err(invalid_data("invalid ratchet control-state signature")); + } + + let body: ControlStateBody = + rmp_serde::from_slice(&packed).map_err(|e| std::io::Error::other(e.to_string()))?; + if body.version != CONTROL_STATE_VERSION { + return Err(invalid_data(format!( + "unsupported ratchet control-state version {}", + body.version + ))); + } + let identity_hash: [u8; 16] = body + .identity_hash + .as_slice() + .try_into() + .map_err(|_| invalid_data("invalid control-state identity hash"))?; + let stored_destination: [u8; 16] = body + .destination_hash + .as_slice() + .try_into() + .map_err(|_| invalid_data("invalid control-state destination hash"))?; + if identity_hash != identity.hash { + return Err(invalid_data("control state belongs to another identity")); + } + if stored_destination != destination_hash { + return Err(invalid_data("control state belongs to another destination")); + } + + let state = Self { + identity_hash, + destination_hash: stored_destination, + last_rotation_wall: body.last_rotation_wall, + last_announce_wire: body.last_announce_wire, + }; + state.validate()?; + Ok(state) + } + + fn validate(&self) -> std::io::Result<()> { + if self + .last_announce_wire + .is_some_and(|value| value > ANNOUNCE_TIME_MAX) + { + return Err(invalid_data("stored announce time exceeds 40-bit field")); + } + Ok(()) + } +} + +#[derive(Serialize, Deserialize)] +struct ControlStateBody { + version: u8, + #[serde(with = "serde_bytes")] + identity_hash: Vec, + #[serde(with = "serde_bytes")] + destination_hash: Vec, + last_rotation_wall: Option, + last_announce_wire: Option, +} + +#[derive(Serialize, Deserialize)] +struct ControlStateEnvelope { + #[serde(with = "serde_bytes")] + signature: Vec, + #[serde(with = "serde_bytes")] + state: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn announce_time_never_moves_into_the_future() { + let identity = Identity::new(); + let destination = [0x22; 16]; + let state = RatchetControlState::new(identity.hash, destination); + let state = state.prepare_announce(100).unwrap().unwrap(); + assert_eq!(state.last_announce_wire(), Some(100)); + assert!(state.prepare_announce(100).unwrap().is_none()); + assert!(state.prepare_announce(99).unwrap().is_none()); + let next = state.prepare_announce(101).unwrap().unwrap(); + assert_eq!(next.last_announce_wire(), Some(101)); + } + + #[test] + fn unknown_rotation_age_is_anchored_without_immediate_rotation() { + let identity = Identity::new(); + let mut state = RatchetControlState::new(identity.hash, [0x33; 16]); + assert!(!state.rotation_due(100, 30)); + state.anchor_rotation_if_unknown(100); + assert!(!state.rotation_due(100, 30)); + assert!(!state.rotation_due(99, 30)); + assert!(!state.rotation_due(129, 30)); + assert!(state.rotation_due(130, 30)); + } + + #[test] + fn signed_state_roundtrip_enforces_identity_and_destination_binding() { + let dir = std::env::temp_dir().join("reticulum_ratchet_control_state"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("control"); + let identity = Identity::new(); + let wrong_identity = Identity::new(); + let destination = [0x44; 16]; + let mut state = RatchetControlState::new(identity.hash, destination); + state.anchor_rotation_if_unknown(100); + let state = state.prepare_announce(101).unwrap().unwrap(); + state.save_verified(&path, &identity).unwrap(); + + assert_eq!( + RatchetControlState::load_verified(&path, &identity, destination).unwrap(), + state + ); + assert!(RatchetControlState::load_verified(&path, &wrong_identity, destination).is_err()); + assert!(RatchetControlState::load_verified(&path, &identity, [0x55; 16]).is_err()); + assert!( + path.exists(), + "rejected state remains available for recovery" + ); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn failed_candidate_persistence_cannot_mutate_live_state() { + let identity = Identity::new(); + let destination = [0x66; 16]; + let live = RatchetControlState::new(identity.hash, destination); + let candidate = live.prepare_announce(100).unwrap().unwrap(); + let missing_parent = std::env::temp_dir() + .join("reticulum_missing_control_parent") + .join("nested") + .join("state"); + let _ = std::fs::remove_dir_all( + missing_parent + .parent() + .and_then(Path::parent) + .unwrap_or_else(|| Path::new("/tmp")), + ); + + assert!(candidate.save_verified(&missing_parent, &identity).is_err()); + assert_eq!(live.last_announce_wire(), None); + } +} diff --git a/crates/rns-identity/src/destination.rs b/crates/rns-identity/src/destination.rs index 8affb6b..bd553e9 100644 --- a/crates/rns-identity/src/destination.rs +++ b/crates/rns-identity/src/destination.rs @@ -37,6 +37,23 @@ struct PathResponseCache { // Path-response dedup window (seconds). Matches upstream default. const PR_TAG_WINDOW: f64 = 30.0; +/// Separate clocks used while constructing an announce: a persisted 40-bit +/// ordering value for the wire and a local elapsed-time value for cache expiry. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct AnnounceTime { + pub wire: u64, + pub cache: f64, +} + +impl AnnounceTime { + pub fn new(wire: u64, cache: f64) -> Result { + if wire > crate::announce::ANNOUNCE_TIME_MAX || !cache.is_finite() || cache < 0.0 { + return Err(DestinationError::InvalidAnnounceTime(cache)); + } + Ok(Self { wire, cache }) + } +} + /// Destination type (matches wire format `DestinationType`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u8)] @@ -89,6 +106,8 @@ pub enum DestinationError { ProveNotSingle, #[error("identity error: {0}")] Identity(#[from] crate::identity::IdentityError), + #[error("invalid announce clock value: {0}")] + InvalidAnnounceTime(f64), } pub struct Destination { @@ -572,6 +591,28 @@ impl Destination { tag: Option<&[u8]>, now: f64, ) -> Result<(Vec, bool), DestinationError> { + if !now.is_finite() || now < 0.0 || now > crate::announce::ANNOUNCE_TIME_MAX as f64 { + return Err(DestinationError::InvalidAnnounceTime(now)); + } + self.create_announce_at( + identity, + app_data, + ratchet, + tag, + AnnounceTime::new(now as u64, now)?, + ) + } + + /// Build announce data with independent wire-ordering and cache clocks. + pub fn create_announce_at( + &mut self, + identity: &Identity, + app_data: Option<&[u8]>, + ratchet: Option<&[u8; 32]>, + tag: Option<&[u8]>, + time: AnnounceTime, + ) -> Result<(Vec, bool), DestinationError> { + let time = AnnounceTime::new(time.wire, time.cache)?; if self.dest_type != DestType::Single { return Err(DestinationError::EncryptionUnavailable); } @@ -580,7 +621,7 @@ impl Destination { } self.path_responses - .retain(|_, v| now <= v.timestamp + PR_TAG_WINDOW); + .retain(|_, v| time.cache <= v.timestamp + PR_TAG_WINDOW); if let Some(tag_bytes) = tag { if let Some(cached) = self.path_responses.get(tag_bytes) { @@ -595,9 +636,7 @@ impl Destination { let public_key = identity.get_public_key(); let random_bytes: [u8; 5] = rns_crypto::random::random_bytes(5).try_into().unwrap(); - let ts_int = now as u64; - // Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years. - let ts_bytes = &ts_int.to_be_bytes()[3..8]; + let ts_bytes = &time.wire.to_be_bytes()[3..8]; let mut random_hash = [0u8; 10]; random_hash[..5].copy_from_slice(&random_bytes); random_hash[5..].copy_from_slice(ts_bytes); @@ -637,7 +676,7 @@ impl Destination { self.path_responses.insert( tag_bytes.to_vec(), PathResponseCache { - timestamp: now, + timestamp: time.cache, announce_data: announce_data.clone(), has_ratchet, }, @@ -655,9 +694,31 @@ impl Destination { path_response: bool, tag: Option<&[u8]>, now: f64, + ) -> Result, DestinationError> { + if !now.is_finite() || now < 0.0 || now > crate::announce::ANNOUNCE_TIME_MAX as f64 { + return Err(DestinationError::InvalidAnnounceTime(now)); + } + self.announce_packet_at( + identity, + app_data, + ratchet, + path_response, + tag, + AnnounceTime::new(now as u64, now)?, + ) + } + + pub fn announce_packet_at( + &mut self, + identity: &Identity, + app_data: Option<&[u8]>, + ratchet: Option<&[u8; 32]>, + path_response: bool, + tag: Option<&[u8]>, + time: AnnounceTime, ) -> Result, DestinationError> { let (announce_data, has_ratchet) = - self.create_announce(identity, app_data, ratchet, tag, now)?; + self.create_announce_at(identity, app_data, ratchet, tag, time)?; let context = if path_response { rns_wire::context::PacketContext::PathResponse @@ -927,4 +988,45 @@ mod tests { "the cached payload's ratchet flag must not depend on current caller state" ); } + + #[test] + fn announce_wire_time_is_independent_from_path_cache_time() { + let identity = Identity::new(); + let mut dest = Destination::new( + Some(&identity), + Direction::In, + DestType::Single, + "test.time", + ) + .unwrap(); + let wire_time = 0x01_0203_0405; + let raw = dest + .announce_packet_at( + &identity, + None, + None, + false, + None, + AnnounceTime::new(wire_time, 9_999_999.0).unwrap(), + ) + .unwrap(); + let (_, header_len) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + let announce = crate::announce::AnnounceData::unpack(&raw[header_len..], false).unwrap(); + assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]); + + assert!(matches!( + dest.announce_packet_at( + &identity, + None, + None, + false, + None, + AnnounceTime { + wire: crate::announce::ANNOUNCE_TIME_MAX + 1, + cache: 1.0, + }, + ), + Err(DestinationError::InvalidAnnounceTime(_)) + )); + } } diff --git a/crates/rns-identity/src/lib.rs b/crates/rns-identity/src/lib.rs index f5975ab..67581d3 100644 --- a/crates/rns-identity/src/lib.rs +++ b/crates/rns-identity/src/lib.rs @@ -3,6 +3,7 @@ //! Python reference: `RNS/Identity.py`, `RNS/Destination.py`. pub mod announce; +pub mod announce_state; pub mod destination; pub mod identity; pub mod ifac; diff --git a/crates/rns-identity/src/ratchet.rs b/crates/rns-identity/src/ratchet.rs index 46e72d0..b1cafe7 100644 --- a/crates/rns-identity/src/ratchet.rs +++ b/crates/rns-identity/src/ratchet.rs @@ -5,10 +5,104 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; -use zeroize::Zeroize; +use zeroize::{Zeroize, Zeroizing}; +use crate::identity::Identity; use crate::persistence; +const RATCHET_FILE_MAX_BYTES: usize = 64 * 1024; +const RATCHET_PACKED_MAX_BYTES: usize = 32 * 1024; +const RECEIVED_RATCHET_FILE_MAX_BYTES: usize = 1024; + +fn wall_time_secs() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs_f64() +} + +fn invalid_data(message: impl Into) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, message.into()) +} + +fn pack_ratchet_keys(keys: &[[u8; 32]]) -> std::io::Result>> { + let byte_keys: Vec<&serde_bytes::Bytes> = keys + .iter() + .map(|key| serde_bytes::Bytes::new(key)) + .collect(); + let packed = Zeroizing::new( + rmp_serde::to_vec(&byte_keys).map_err(|e| std::io::Error::other(e.to_string()))?, + ); + if packed.len() > RATCHET_PACKED_MAX_BYTES { + return Err(invalid_data("packed ratchet ring exceeds size limit")); + } + Ok(packed) +} + +fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result> { + if packed.len() > RATCHET_PACKED_MAX_BYTES { + return Err(invalid_data("packed ratchet ring exceeds size limit")); + } + let mut encoded_keys: Vec = + rmp_serde::from_slice(packed).map_err(|e| std::io::Error::other(e.to_string()))?; + if encoded_keys.len() > RATCHET_COUNT { + for key in &mut encoded_keys { + key.as_mut().zeroize(); + } + return Err(invalid_data(format!( + "ratchet ring contains {} keys; maximum is {RATCHET_COUNT}", + encoded_keys.len() + ))); + } + + if encoded_keys.iter().any(|key| key.len() != 32) { + for key in &mut encoded_keys { + key.as_mut().zeroize(); + } + return Err(invalid_data("ratchet private key must be exactly 32 bytes")); + } + + let mut keys = Vec::with_capacity(RATCHET_COUNT); + for encoded in &mut encoded_keys { + let mut key = [0u8; 32]; + key.copy_from_slice(encoded); + keys.push(key); + encoded.as_mut().zeroize(); + } + Ok(keys) +} + +/// On-disk format accepted by [`RatchetRing::load_verified`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RatchetRingFormat { + /// Python-compatible `{signature, ratchets}` with a signature over the + /// packed private-key list. + Canonical, + /// Historical Rust envelope whose signature covered only the current + /// public ratchet and whose unsigned `last_rotation` field is ignored. + LegacyRust, +} + +/// A verified ratchet ring plus the format that was read from disk. +pub struct LoadedRatchetRing { + ring: RatchetRing, + format: RatchetRingFormat, +} + +impl LoadedRatchetRing { + pub fn ring(&self) -> &RatchetRing { + &self.ring + } + + pub fn format(&self) -> RatchetRingFormat { + self.format + } + + pub fn into_ring(self) -> RatchetRing { + self.ring + } +} + /// A bounded history of X25519 private ratchet keys for forward secrecy. /// /// Index 0 is the most recent key; older keys are retained so decryption can @@ -24,7 +118,7 @@ pub struct RatchetRing { impl RatchetRing { pub fn new() -> Self { Self { - keys: Vec::new(), + keys: Vec::with_capacity(RATCHET_COUNT), last_rotation: 0.0, retained_count: RATCHET_COUNT, rotation_interval: RATCHET_INTERVAL, @@ -35,33 +129,97 @@ impl RatchetRing { /// /// Any keys evicted past `retained_count` are zeroised before drop. pub fn rotate(&mut self) -> [u8; 32] { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); + self.rotate_at(wall_time_secs()) + } + /// Generate a fresh ratchet while recording an explicit wall-clock time. + /// + /// Callers that need crash safety should use [`Self::prepare_rotation_at`], + /// persist its candidate ring, and only then call + /// [`Self::commit_prepared_rotation`]. + pub fn rotate_at(&mut self, now: f64) -> [u8; 32] { let prv = X25519PrivateKey::generate(); let pub_key = prv.public_key().to_bytes(); - self.keys.insert(0, prv.to_bytes()); - if self.keys.len() > self.retained_count { - for key in &mut self.keys[self.retained_count..] { - key.zeroize(); - } - self.keys.truncate(self.retained_count); + // Make room before insertion so a full ring never reallocates an + // uncleared backing buffer containing every retained private key. + while self.keys.len() >= self.retained_count { + let last = self.keys.len() - 1; + self.keys[last].zeroize(); + self.keys.truncate(last); } - self.last_rotation = now; + self.keys.insert(0, prv.to_bytes()); + self.last_rotation = if now.is_finite() && now >= 0.0 { + now + } else { + 0.0 + }; pub_key } /// True when at least `rotation_interval` seconds have elapsed since the last rotate. pub fn needs_rotation(&self) -> bool { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); - now - self.last_rotation >= self.rotation_interval as f64 + self.needs_rotation_at(wall_time_secs()) + } + + /// Test rotation age against an explicit wall-clock value. + /// + /// A missing age (`last_rotation == 0`) is due. A clock rollback is not: + /// callers can anchor an unknown age with [`Self::anchor_rotation_at`] and + /// wait one normal interval instead of rotating immediately. + pub fn needs_rotation_at(&self, now: f64) -> bool { + if !now.is_finite() || now < 0.0 { + return false; + } + if self.last_rotation <= 0.0 { + return true; + } + now >= self.last_rotation && now - self.last_rotation >= self.rotation_interval as f64 + } + + /// Set the age anchor without generating or discarding any key material. + pub fn anchor_rotation_at(&mut self, now: f64) -> bool { + if !now.is_finite() || now < 0.0 { + return false; + } + self.last_rotation = now; + true + } + + pub fn last_rotation(&self) -> f64 { + self.last_rotation + } + + /// Prepare a candidate rotation without changing the live ring. + pub fn prepare_rotation_at(&self, now: f64) -> PreparedRatchetRotation { + let mut candidate = self.duplicate(); + let public_key = candidate.rotate_at(now); + PreparedRatchetRotation { + candidate, + public_key, + } + } + + /// Replace the live ring with a previously persisted candidate. + pub fn commit_prepared_rotation(&mut self, prepared: PreparedRatchetRotation) -> [u8; 32] { + let PreparedRatchetRotation { + mut candidate, + public_key, + } = prepared; + std::mem::swap(self, &mut candidate); + public_key + } + + fn duplicate(&self) -> Self { + let mut keys = Vec::with_capacity(RATCHET_COUNT); + keys.extend_from_slice(&self.keys); + Self { + keys, + last_rotation: self.last_rotation, + retained_count: self.retained_count, + rotation_interval: self.rotation_interval, + } } /// Public key of the most recent ratchet, if the ring has been rotated at least once. @@ -85,9 +243,9 @@ impl RatchetRing { self.keys.is_empty() } - /// Set `retained_count`; returns `false` if `count == 0`. + /// Set `retained_count`; returns `false` outside `1..=RATCHET_COUNT`. pub fn set_retained_ratchets(&mut self, count: usize) -> bool { - if count > 0 { + if (1..=RATCHET_COUNT).contains(&count) { self.retained_count = count; self.clean(); true @@ -116,27 +274,56 @@ impl RatchetRing { fn clean(&mut self) { if self.keys.len() > self.retained_count { + for key in &mut self.keys[self.retained_count..] { + key.zeroize(); + } self.keys.truncate(self.retained_count); } } - /// Persist to `path` as a Python-compatible msgpack envelope. + /// Persist to `path` as the exact Python-compatible msgpack envelope. /// - /// Python writes `{signature, ratchets}`. Rust also includes - /// `last_rotation`, which Python ignores and Rust defaults when loading a - /// Python-written file. `ratchets` is itself the msgpack-encoded key list - /// signed by the owning identity. + /// `signature` must cover the packed `ratchets` list. Production callers + /// should prefer [`Self::save_verified`], which cannot sign the wrong data. pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> { - let ratchets_packed = - rmp_serde::to_vec(&self.keys).map_err(|e| std::io::Error::other(e.to_string()))?; + let ratchets_packed = pack_ratchet_keys(&self.keys)?; - let persisted = RatchetRingPersisted { + let persisted = Zeroizing::new(RatchetRingPersistedWrite { signature: signature.to_vec(), - ratchets: ratchets_packed, - last_rotation: self.last_rotation, - }; - let buf = - rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?; + ratchets: ratchets_packed.to_vec(), + }); + let buf = Zeroizing::new( + rmp_serde::to_vec_named(&*persisted) + .map_err(|e| std::io::Error::other(e.to_string()))?, + ); + if buf.len() > RATCHET_FILE_MAX_BYTES { + return Err(invalid_data("ratchet ring file exceeds size limit")); + } + persistence::atomic_write(path, &buf) + } + + /// Sign the packed key list with `identity`, persist it, and verify the + /// final bytes before returning. + pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> { + let ratchets_packed = pack_ratchet_keys(&self.keys)?; + let signature = identity.sign(&ratchets_packed).ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "identity cannot sign ratchet ring", + ) + })?; + + let persisted = Zeroizing::new(RatchetRingPersistedWrite { + signature: signature.to_vec(), + ratchets: ratchets_packed.to_vec(), + }); + let buf = Zeroizing::new( + rmp_serde::to_vec_named(&*persisted) + .map_err(|e| std::io::Error::other(e.to_string()))?, + ); + if buf.len() > RATCHET_FILE_MAX_BYTES { + return Err(invalid_data("ratchet ring file exceeds size limit")); + } persistence::atomic_write(path, &buf) } @@ -152,7 +339,7 @@ impl RatchetRing { } match Self::try_load(path) { - Ok(result) => return Ok(result), + Ok(decoded) => return Ok((decoded.ring, decoded.signature)), Err(e) => { if attempt < delays_ms.len() - 1 { tracing::warn!( @@ -170,10 +357,40 @@ impl RatchetRing { Err(last_err.unwrap()) } - fn try_load(path: &Path) -> std::io::Result<(Self, [u8; 64])> { - let data = std::fs::read(path)?; + /// Load a bounded ring and verify that its signature belongs to `identity`. + /// + /// Canonical files are verified over the packed key list. Historical Rust + /// files are accepted only when their old current-public-key signature is + /// valid; their unsigned rotation timestamp is deliberately ignored. + pub fn load_verified(path: &Path, identity: &Identity) -> std::io::Result { + let decoded = Self::try_load(path)?; - let persisted: RatchetRingPersisted = + let format = if identity.verify(&decoded.packed, &decoded.signature) { + RatchetRingFormat::Canonical + } else if decoded.had_legacy_rotation + && decoded + .ring + .current_public_key() + .is_some_and(|public| identity.verify(&public, &decoded.signature)) + { + RatchetRingFormat::LegacyRust + } else { + return Err(invalid_data("invalid ratchet ring signature")); + }; + + Ok(LoadedRatchetRing { + ring: decoded.ring, + format, + }) + } + + fn try_load(path: &Path) -> std::io::Result { + let data = Zeroizing::new( + persistence::read_file_bounded(path, RATCHET_FILE_MAX_BYTES)? + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?, + ); + + let persisted: RatchetRingPersistedRead = rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?; if persisted.signature.len() != 64 { @@ -186,27 +403,67 @@ impl RatchetRing { let mut signature = [0u8; 64]; signature.copy_from_slice(&persisted.signature); - let keys: Vec<[u8; 32]> = rmp_serde::from_slice(&persisted.ratchets) - .map_err(|e| std::io::Error::other(e.to_string()))?; + let packed = Zeroizing::new(persisted.ratchets); + let keys = unpack_ratchet_keys(&packed)?; + let had_legacy_rotation = persisted.last_rotation.is_some(); - Ok(( - Self { + Ok(DecodedRatchetRing { + ring: Self { keys, - last_rotation: persisted.last_rotation, + // Rotation age is control-plane metadata, not part of the + // Python ring signature. Never trust the historical unsigned + // value from disk. + last_rotation: 0.0, retained_count: RATCHET_COUNT, rotation_interval: RATCHET_INTERVAL, }, signature, - )) + had_legacy_rotation, + packed, + }) } } -#[derive(Serialize, Deserialize)] -struct RatchetRingPersisted { +struct DecodedRatchetRing { + ring: RatchetRing, + signature: [u8; 64], + had_legacy_rotation: bool, + packed: Zeroizing>, +} + +/// A rotation candidate owns a duplicate secret ring and zeroises it on drop +/// unless it is committed into the live ring. +pub struct PreparedRatchetRotation { + candidate: RatchetRing, + public_key: [u8; 32], +} + +impl PreparedRatchetRotation { + pub fn ring(&self) -> &RatchetRing { + &self.candidate + } + + pub fn public_key(&self) -> [u8; 32] { + self.public_key + } +} + +#[derive(Serialize, Zeroize)] +struct RatchetRingPersistedWrite { + #[serde(with = "serde_bytes")] signature: Vec, + #[serde(with = "serde_bytes")] + ratchets: Vec, +} + +#[derive(Deserialize)] +struct RatchetRingPersistedRead { + #[serde(with = "serde_bytes")] + signature: Vec, + #[serde(with = "serde_bytes")] ratchets: Vec, #[serde(default)] - last_rotation: f64, + last_rotation: Option, } impl Zeroize for RatchetRing { @@ -242,28 +499,33 @@ pub struct ReceivedRatchet { // On-disk shape shared with the Python reference: `{"ratchet": bytes, "received": float}`. #[derive(Serialize, Deserialize)] struct ReceivedRatchetPersisted { + #[serde(with = "serde_bytes")] ratchet: Vec, received: f64, } impl ReceivedRatchet { pub fn new(ratchet_pub: [u8; 32]) -> Self { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); + Self::new_at(ratchet_pub, wall_time_secs()) + } + + pub fn new_at(ratchet_pub: [u8; 32], received_at: f64) -> Self { Self { ratchet_pub, - received_at: now, + received_at: if received_at.is_finite() && received_at >= 0.0 { + received_at + } else { + 0.0 + }, } } pub fn is_expired(&self) -> bool { - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs_f64(); - now - self.received_at > RATCHET_EXPIRY as f64 + self.is_expired_at(wall_time_secs()) + } + + pub fn is_expired_at(&self, now: f64) -> bool { + now.is_finite() && now >= self.received_at && now - self.received_at > RATCHET_EXPIRY as f64 } pub fn ratchet_id(&self) -> Vec { @@ -276,8 +538,8 @@ impl ReceivedRatchet { ratchet: self.ratchet_pub.to_vec(), received: self.received_at, }; - let buf = - rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?; + let buf = rmp_serde::to_vec_named(&persisted) + .map_err(|e| std::io::Error::other(e.to_string()))?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; @@ -287,7 +549,8 @@ impl ReceivedRatchet { } pub fn load(path: &Path) -> std::io::Result { - let data = std::fs::read(path)?; + let data = persistence::read_file_bounded(path, RECEIVED_RATCHET_FILE_MAX_BYTES)? + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?; let persisted: ReceivedRatchetPersisted = rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?; @@ -297,6 +560,9 @@ impl ReceivedRatchet { "invalid ratchet public key length", )); } + if !persisted.received.is_finite() || persisted.received < 0.0 { + return Err(invalid_data("invalid received-ratchet timestamp")); + } let mut ratchet_pub = [0u8; 32]; ratchet_pub.copy_from_slice(&persisted.ratchet); @@ -387,13 +653,19 @@ impl ReceivedRatchetStore { /// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op; /// any other value replaces the entry and is written to disk when backed. pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) { + self.remember_at(dest_hash, ratchet_pub, wall_time_secs()); + } + + /// Record a ratchet with an explicit local receive time. Re-inserting the + /// same key remains a no-op and therefore cannot extend its lifetime. + pub fn remember_at(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32], received_at: f64) { if let Some(existing) = self.entries.get(&dest_hash) { if existing.ratchet_pub == ratchet_pub { return; } } - let received = ReceivedRatchet::new(ratchet_pub); + let received = ReceivedRatchet::new_at(ratchet_pub, received_at); if let Some(ref dir) = self.storage_dir { let hexhash = hex::encode(dest_hash); @@ -413,6 +685,10 @@ impl ReceivedRatchetStore { /// Return the current ratchet public key for `dest_hash`, loading from /// disk on miss. Yields `None` if the entry is expired or absent. pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> { + self.get_at(dest_hash, wall_time_secs()) + } + + pub fn get_at(&mut self, dest_hash: &[u8; 16], now: f64) -> Option<[u8; 32]> { if !self.entries.contains_key(dest_hash) { if let Some(ref dir) = self.storage_dir { let hexhash = hex::encode(dest_hash); @@ -420,7 +696,7 @@ impl ReceivedRatchetStore { if path.exists() { match ReceivedRatchet::load(&path) { Ok(ratchet) => { - if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 { + if !ratchet.is_expired_at(now) { self.entries.insert(*dest_hash, ratchet); } else { return None; @@ -441,7 +717,7 @@ impl ReceivedRatchetStore { self.entries .get(dest_hash) - .filter(|r| !r.is_expired()) + .filter(|r| !r.is_expired_at(now)) .map(|r| r.ratchet_pub) } @@ -476,6 +752,7 @@ impl Default for ReceivedRatchetStore { #[cfg(test)] mod tests { use super::*; + use std::io::Cursor; #[test] fn test_ratchet_ring_rotate() { @@ -491,13 +768,56 @@ mod tests { assert_ne!(pub1, pub2); } + #[test] + fn prepared_rotation_does_not_mutate_live_ring_until_commit() { + let mut ring = RatchetRing::new(); + ring.rotate_at(100.0); + let before = ring.private_keys().to_vec(); + + let abandoned = ring.prepare_rotation_at(200.0); + assert_eq!(ring.private_keys(), before); + assert_eq!(abandoned.ring().len(), 2); + drop(abandoned); + assert_eq!(ring.private_keys(), before); + + let prepared = ring.prepare_rotation_at(200.0); + let expected_public = prepared.public_key(); + let committed_public = ring.commit_prepared_rotation(prepared); + assert_eq!(committed_public, expected_public); + assert_eq!(ring.len(), 2); + assert_eq!(ring.current_public_key(), Some(expected_public)); + assert_eq!(ring.last_rotation(), 200.0); + } + + #[test] + fn rotation_clock_rollback_never_looks_elapsed() { + let mut ring = RatchetRing::new(); + ring.set_ratchet_interval(30); + assert!(ring.needs_rotation_at(100.0)); + ring.rotate_at(100.0); + assert!(!ring.needs_rotation_at(99.0)); + assert!(!ring.needs_rotation_at(129.999)); + assert!(ring.needs_rotation_at(130.0)); + + let mut unknown_age = RatchetRing::new(); + assert!(unknown_age.needs_rotation_at(100.0)); + assert!(unknown_age.anchor_rotation_at(100.0)); + assert!(!unknown_age.needs_rotation_at(100.0)); + } + #[test] fn test_ratchet_ring_max_keys() { let mut ring = RatchetRing::new(); + let initial_capacity = ring.keys.capacity(); for _ in 0..RATCHET_COUNT + 10 { ring.rotate(); } assert_eq!(ring.len(), RATCHET_COUNT); + assert_eq!( + ring.keys.capacity(), + initial_capacity, + "rotating a full secret ring must not reallocate uncleared storage" + ); } #[test] @@ -522,6 +842,142 @@ mod tests { let _ = std::fs::remove_dir(&dir); } + #[test] + fn verified_ring_file_is_python_map_of_signed_binary_keys() { + let dir = std::env::temp_dir().join("reticulum_ratchet_python_wire"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ratchets"); + let identity = Identity::new(); + let mut ring = RatchetRing::new(); + ring.rotate_at(100.0); + ring.rotate_at(200.0); + + ring.save_verified(&path, &identity).unwrap(); + let data = std::fs::read(&path).unwrap(); + let envelope = rmpv::decode::read_value(&mut Cursor::new(&data)).unwrap(); + let map = envelope.as_map().expect("Python envelope must be a map"); + assert_eq!(map.len(), 2); + let signature = map + .iter() + .find(|(key, _)| key.as_str() == Some("signature")) + .and_then(|(_, value)| value.as_slice()) + .expect("signature must be MessagePack binary"); + let packed = map + .iter() + .find(|(key, _)| key.as_str() == Some("ratchets")) + .and_then(|(_, value)| value.as_slice()) + .expect("ratchets must be MessagePack binary"); + let signature: [u8; 64] = signature.try_into().unwrap(); + assert!(identity.verify(packed, &signature)); + + let packed_value = rmpv::decode::read_value(&mut Cursor::new(packed)).unwrap(); + let keys = packed_value.as_array().expect("ratchets must be a list"); + assert_eq!(keys.len(), 2); + assert!( + keys.iter() + .all(|key| key.as_slice().is_some_and(|b| b.len() == 32)) + ); + + let loaded = RatchetRing::load_verified(&path, &identity).unwrap(); + assert_eq!(loaded.format(), RatchetRingFormat::Canonical); + assert_eq!(loaded.ring().private_keys(), ring.private_keys()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn verified_ring_rejects_wrong_identity_signature() { + let dir = std::env::temp_dir().join("reticulum_ratchet_wrong_signature"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ratchets"); + let owner = Identity::new(); + let wrong = Identity::new(); + let mut ring = RatchetRing::new(); + ring.rotate_at(100.0); + ring.save_verified(&path, &owner).unwrap(); + + let err = RatchetRing::load_verified(&path, &wrong) + .err() + .expect("wrong owner must be rejected"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + assert!( + path.exists(), + "a rejected key file must be preserved for recovery" + ); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn verified_ring_accepts_exact_legacy_rust_shape_but_ignores_age() { + #[derive(Serialize)] + struct LegacyRustRatchets { + signature: Vec, + ratchets: Vec, + last_rotation: f64, + } + + let dir = std::env::temp_dir().join("reticulum_ratchet_legacy_rust"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ratchets"); + let identity = Identity::new(); + let keys = vec![[0x11; 32], [0x22; 32]]; + // This intentionally recreates the pre-fix Rust encoding: compact + // struct, byte vectors as integer arrays, and signature over only the + // current public ratchet. + let ratchets = rmp_serde::to_vec(&keys).unwrap(); + let current_public = ratchet_public_bytes(&keys[0]); + let signature = identity.sign(¤t_public).unwrap(); + let legacy = LegacyRustRatchets { + signature: signature.to_vec(), + ratchets, + last_rotation: f64::MAX, + }; + std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap(); + + let loaded = RatchetRing::load_verified(&path, &identity).unwrap(); + assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust); + assert_eq!(loaded.ring().private_keys(), keys); + assert_eq!(loaded.ring().last_rotation(), 0.0); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn ring_load_rejects_oversize_and_overcount_without_retrying() { + let dir = std::env::temp_dir().join("reticulum_ratchet_bounds"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ratchets"); + let identity = Identity::new(); + + std::fs::write(&path, vec![0u8; RATCHET_FILE_MAX_BYTES + 1]).unwrap(); + assert_eq!( + RatchetRing::load_verified(&path, &identity) + .err() + .expect("oversize ring must fail") + .kind(), + std::io::ErrorKind::InvalidData + ); + + let keys = vec![[0x44; 32]; RATCHET_COUNT + 1]; + let packed = rmp_serde::to_vec(&keys).unwrap(); + let envelope = RatchetRingPersistedWrite { + signature: vec![0u8; 64], + ratchets: packed, + }; + std::fs::write(&path, rmp_serde::to_vec_named(&envelope).unwrap()).unwrap(); + assert_eq!( + RatchetRing::load_verified(&path, &identity) + .err() + .expect("overcount ring must fail") + .kind(), + std::io::ErrorKind::InvalidData + ); + + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn test_ratchet_ring_loads_python_shape_without_last_rotation() { #[derive(Serialize)] @@ -597,6 +1053,17 @@ mod tests { assert!((loaded.received_at - received.received_at).abs() < 0.001); assert!(!loaded.is_expired()); + let encoded = std::fs::read(&path).unwrap(); + let envelope = rmpv::decode::read_value(&mut Cursor::new(encoded)).unwrap(); + let map = envelope.as_map().expect("Python envelope must be a map"); + assert_eq!(map.len(), 2); + assert!( + map.iter() + .find(|(key, _)| key.as_str() == Some("ratchet")) + .and_then(|(_, value)| value.as_slice()) + .is_some_and(|ratchet| ratchet.len() == 32) + ); + let _ = std::fs::remove_file(&path); let _ = std::fs::remove_dir(&dir); } @@ -642,6 +1109,25 @@ mod tests { assert_eq!(store.get(&dest_hash), Some(ratchet_pub2)); } + #[test] + fn identical_received_ratchet_does_not_refresh_expiry() { + let mut store = ReceivedRatchetStore::new(); + let dest_hash = [0xBC; 16]; + let ratchet = [0xCD; 32]; + store.remember_at(dest_hash, ratchet, 10.0); + store.remember_at(dest_hash, ratchet, 20.0); + + assert_eq!( + store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64), + Some(ratchet) + ); + assert_eq!( + store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64 + 0.001), + None, + "same-key reannounce must not extend the original receive age" + ); + } + #[test] fn test_get_ratchet_id() { let pub_bytes = rns_crypto::random::random_32();