diff --git a/crates/lxmf-core/src/message.rs b/crates/lxmf-core/src/message.rs index 589097c..5235beb 100644 --- a/crates/lxmf-core/src/message.rs +++ b/crates/lxmf-core/src/message.rs @@ -12,7 +12,7 @@ //! ```text //! encrypted_data = destination.encrypt(packed[16..]) //! lxmf_data = packed[..16] + encrypted_data -//! transient_id = full_hash(lxmf_data)[..16] +//! transient_id = full_hash(lxmf_data) //! lxmf_data += ?propagation_stamp //! propagation_packed = msgpack([timestamp, [lxmf_data]]) //! ``` @@ -28,6 +28,7 @@ use rns_crypto::sha::{full_hash, sha256, truncated_hash}; use serde::{Deserialize, Serialize}; use crate::constants::*; +use crate::types::PropagationTransientId; /// Shared handler invoked on per-message state transitions. pub type MessageCallback = Arc; @@ -88,8 +89,8 @@ pub struct LxMessage { pub hash: Option<[u8; 32]>, /// Alias for [`hash`](Self::hash) set after packing. pub message_id: Option<[u8; 32]>, - /// Truncated hash used by the propagation offer/get protocol. - pub transient_id: Option<[u8; 16]>, + /// Full hash used by the propagation offer/get protocol. + pub transient_id: Option, /// Destination-required stamp cost for outbound stamp generation. pub stamp_cost: Option, /// Outbound ticket for stamp bypass (16 bytes). @@ -307,7 +308,7 @@ impl LxMessage { pub fn pack_propagated_encrypted( &mut self, encrypt_fn: F, - ) -> Result<(Vec, [u8; 16]), MessageError> + ) -> Result<(Vec, PropagationTransientId), MessageError> where F: FnOnce(&[u8]) -> Result, MessageError>, { @@ -325,7 +326,7 @@ impl LxMessage { &mut self, encrypt_fn: F, target_cost: u8, - ) -> Result<(Vec, [u8; 16], u32), MessageError> + ) -> Result<(Vec, PropagationTransientId, u32), MessageError> where F: FnOnce(&[u8]) -> Result, MessageError>, { @@ -336,7 +337,7 @@ impl LxMessage { &mut self, encrypt_fn: F, propagation_stamp_cost: Option, - ) -> Result<(Vec, [u8; 16], u32), MessageError> + ) -> Result<(Vec, PropagationTransientId, u32), MessageError> where F: FnOnce(&[u8]) -> Result, MessageError>, { @@ -349,9 +350,7 @@ impl LxMessage { lxmf_data.extend_from_slice(&encrypted_data); // transient_id is computed before the propagation stamp is appended. - let full = full_hash(&lxmf_data); - let mut tid = [0u8; 16]; - tid.copy_from_slice(&full[..16]); + let tid = full_hash(&lxmf_data); self.transient_id = Some(tid); let mut stamp_value = 0; @@ -359,7 +358,7 @@ impl LxMessage { && self.propagation_stamp.is_none() { let (stamp, value) = crate::stamper::generate_stamp_raw( - &full, + &tid, target_cost, crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, ) @@ -373,7 +372,7 @@ impl LxMessage { if let Some(ref prop_stamp) = self.propagation_stamp { if stamp_value == 0 { let workblock = crate::stamper::stamp_workblock_raw( - &full, + &tid, crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN, ); stamp_value = crate::stamper::stamp_value_raw(&workblock, prop_stamp); @@ -414,16 +413,13 @@ impl LxMessage { Ok(wrapper) } - /// Compute `transient_id = full_hash(lxmf_data)[..16]` for a propagation blob. + /// Compute `transient_id = full_hash(lxmf_data)` for a propagation blob. /// /// The input must be `dest_hash + encrypted_data` without the propagation stamp; callers must /// strip the trailing 32-byte stamp first if present. Python computes the transient ID /// before the stamp is appended. - pub fn compute_propagation_transient_id(lxmf_data: &[u8]) -> [u8; 16] { - let full = full_hash(lxmf_data); - let mut tid = [0u8; 16]; - tid.copy_from_slice(&full[..16]); - tid + pub fn compute_propagation_transient_id(lxmf_data: &[u8]) -> PropagationTransientId { + full_hash(lxmf_data) } /// Unpack a wire message: `dest_hash(16) + src_hash(16) + signature(64) + msgpack_payload`. @@ -481,11 +477,9 @@ impl LxMessage { callbacks: MessageCallbacks::default(), }; - // Default to truncated-message-hash transient_id for direct messages. Propagation - // callers should overwrite via [`compute_propagation_transient_id`]. - let mut tid = [0u8; 16]; - tid.copy_from_slice(&hash[..16]); - msg.transient_id = Some(tid); + // Default to the message hash for direct messages. Propagation callers + // overwrite via [`compute_propagation_transient_id`]. + msg.transient_id = Some(hash); Ok(msg) } @@ -608,9 +602,7 @@ impl LxMessage { Self::message_id_from_payload(&self.destination_hash, &self.source_hash, &payload); self.hash = Some(hash); self.message_id = Some(hash); - let mut tid = [0u8; 16]; - tid.copy_from_slice(&hash[..16]); - self.transient_id = Some(tid); + self.transient_id = Some(hash); Ok(hash) } @@ -634,6 +626,7 @@ impl LxMessage { self.signature = Some(signing_key.sign(&signed_data)); self.hash = Some(message_hash); self.message_id = Some(message_hash); + self.transient_id = Some(message_hash); self.state = MessageState::Outbound; Ok(()) } @@ -661,6 +654,7 @@ impl LxMessage { self.signature = Some(signature); self.hash = Some(message_hash); self.message_id = Some(message_hash); + self.transient_id = Some(message_hash); self.state = MessageState::Outbound; Ok(()) } @@ -2003,7 +1997,7 @@ mod tests { assert!(!propagation_packed.is_empty()); assert_eq!(msg.transient_id, Some(tid)); - assert_ne!(tid, [0u8; 16]); + assert_ne!(tid, [0u8; 32]); let (ts, entries) = LxMessage::unpack_propagation_wrapper(&propagation_packed).unwrap(); assert!(ts > 0.0); @@ -2029,7 +2023,7 @@ mod tests { fn test_propagation_transient_id() { let lxmf_data = vec![0xAA; 100]; let tid = LxMessage::compute_propagation_transient_id(&lxmf_data); - assert_eq!(tid.len(), 16); + assert_eq!(tid.len(), 32); let tid2 = LxMessage::compute_propagation_transient_id(&lxmf_data); assert_eq!(tid, tid2); @@ -2046,7 +2040,7 @@ mod tests { let lxmf_data = vec![0x42; 200]; let tid = LxMessage::compute_propagation_transient_id(&lxmf_data); let expected_full = full_hash(&lxmf_data); - assert_eq!(&tid[..], &expected_full[..16]); + assert_eq!(tid, expected_full); } #[test] diff --git a/crates/lxmf-core/src/peer.rs b/crates/lxmf-core/src/peer.rs index d5e4c88..a7fe119 100644 --- a/crates/lxmf-core/src/peer.rs +++ b/crates/lxmf-core/src/peer.rs @@ -5,6 +5,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use crate::constants::*; +use crate::types::PropagationTransientId; type StoredPeer = ( Vec, @@ -39,7 +40,7 @@ pub struct LxmPeer { pub propagation_transfer_limit: Option, /// Per-sync propagation limit in KB. pub propagation_sync_limit: Option, - pub currently_transferring_messages: Option>, + pub currently_transferring_messages: Option>, pub link_alive: bool, pub created_at: f64, pub last_heard: f64, @@ -61,7 +62,7 @@ pub struct LxmPeer { /// Static peers are operator-configured; autopeered peers come from announces. pub is_static: bool, /// Message hashes already handled by this peer, for sync filtering. - pub handled_messages: std::collections::HashSet<[u8; 16]>, + pub handled_messages: std::collections::HashSet, } impl LxmPeer { @@ -162,11 +163,11 @@ impl LxmPeer { self.sync_backoff = 0.0; } - pub fn add_handled_message(&mut self, hash: &[u8; 16]) { + pub fn add_handled_message(&mut self, hash: &PropagationTransientId) { self.handled_messages.insert(*hash); } - pub fn has_handled(&self, hash: &[u8; 16]) -> bool { + pub fn has_handled(&self, hash: &PropagationTransientId) -> bool { self.handled_messages.contains(hash) } @@ -218,8 +219,8 @@ impl LxmPeer { peer.handled_messages = handled_vec .into_iter() .filter_map(|v| { - if v.len() == 16 { - let mut arr = [0u8; 16]; + if v.len() == 32 { + let mut arr = [0u8; 32]; arr.copy_from_slice(&v); Some(arr) } else { @@ -440,6 +441,10 @@ fn now_f64() -> f64 { mod tests { use super::*; + fn tid(byte: u8) -> PropagationTransientId { + [byte; 32] + } + #[test] fn test_new_peer() { let peer = LxmPeer::new([0xAA; 16]); @@ -509,7 +514,7 @@ mod tests { let mut peer = LxmPeer::new([0; 16]); assert!(peer.currently_transferring_messages.is_none()); - peer.currently_transferring_messages = Some(vec![[0xAA; 16], [0xBB; 16]]); + peer.currently_transferring_messages = Some(vec![tid(0xAA), tid(0xBB)]); assert_eq!( peer.currently_transferring_messages.as_ref().unwrap().len(), 2 @@ -658,7 +663,7 @@ mod tests { let mut peer = LxmPeer::new([0xAA; 16]); peer.begin_sync(); peer.link_established([0xBB; 16], Some(10.0)); - peer.currently_transferring_messages = Some(vec![[0x01; 16], [0x02; 16]]); + peer.currently_transferring_messages = Some(vec![tid(0x01), tid(0x02)]); peer.link_closed(); diff --git a/crates/lxmf-core/src/persist.rs b/crates/lxmf-core/src/persist.rs index beea7aa..5fe6c6c 100644 --- a/crates/lxmf-core/src/persist.rs +++ b/crates/lxmf-core/src/persist.rs @@ -17,6 +17,7 @@ use std::path::Path; use crate::router::StampCostEntry; use crate::ticket::Ticket; +use crate::types::PropagationTransientId; pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs"; pub const TICKETS_FILE: &str = "available_tickets"; @@ -63,19 +64,25 @@ pub fn load_tickets(dir: &Path) -> io::Result> { Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default()) } -pub fn save_local_deliveries(dir: &Path, ids: &HashMap<[u8; 16], f64>) -> io::Result<()> { +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> { +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<[u8; 16], f64>) -> io::Result<()> { +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> { +pub fn load_locally_processed(dir: &Path) -> io::Result> { Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default()) } @@ -116,7 +123,7 @@ mod tests { fn local_deliveries_roundtrip() { let tmp = TempDir::new().unwrap(); let mut ids = HashMap::new(); - ids.insert([0x03; 16], 1_700_000_000.0); + 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); diff --git a/crates/lxmf-core/src/propagation.rs b/crates/lxmf-core/src/propagation.rs index bd514c8..7bdade1 100644 --- a/crates/lxmf-core/src/propagation.rs +++ b/crates/lxmf-core/src/propagation.rs @@ -5,10 +5,12 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::time::{SystemTime, UNIX_EPOCH}; +use crate::types::PropagationTransientId; + /// A stored propagation entry awaiting collection by peers. #[derive(Debug, Clone)] pub struct PropagationEntry { - pub transient_id: [u8; 16], + pub transient_id: PropagationTransientId, pub message_hash: [u8; 32], pub destination_hash: [u8; 16], pub stored_at: f64, @@ -19,7 +21,7 @@ pub struct PropagationEntry { impl PropagationEntry { pub fn new( - transient_id: [u8; 16], + transient_id: PropagationTransientId, message_hash: [u8; 32], destination_hash: [u8; 16], size: usize, @@ -48,17 +50,17 @@ impl PropagationEntry { /// Accepts both the 3-component format and the legacy 2-component /// `{transient_id}_{timestamp}` form (stamp_value defaults to 0). - pub fn parse_filename(filename: &str) -> Option<([u8; 16], f64, u8)> { + pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> { let parts: Vec<&str> = filename.split('_').collect(); match parts.len() { 3 => { - let tid = hex_decode_16(parts[0])?; + let tid = hex_decode_32(parts[0])?; let ts: f64 = parts[1].parse().ok()?; let sv: u8 = parts[2].parse().ok()?; Some((tid, ts, sv)) } 2 => { - let tid = hex_decode_16(parts[0])?; + let tid = hex_decode_32(parts[0])?; let ts: f64 = parts[1].parse().ok()?; Some((tid, ts, 0)) } @@ -70,14 +72,14 @@ impl PropagationEntry { /// Owned by the router actor; no shared access. #[derive(Debug, Default)] pub struct PropagationStore { - entries: HashMap<[u8; 16], PropagationEntry>, + entries: HashMap, total_size: usize, - locally_delivered_ids: HashSet<[u8; 16]>, - locally_processed_ids: HashSet<[u8; 16]>, + locally_delivered_ids: HashSet, + locally_processed_ids: HashSet, ignored_destinations: HashSet<[u8; 16]>, /// Prioritised destinations receive a 0.1x weight multiplier during culling. prioritised_destinations: HashSet<[u8; 16]>, - peer_distribution_queue: VecDeque<([u8; 16], Option<[u8; 16]>)>, + peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>, /// `None` disables the byte-size cap. pub storage_limit: Option, } @@ -97,15 +99,15 @@ impl PropagationStore { true } - pub fn get(&self, transient_id: &[u8; 16]) -> Option<&PropagationEntry> { + pub fn get(&self, transient_id: &PropagationTransientId) -> Option<&PropagationEntry> { self.entries.get(transient_id) } - pub fn contains(&self, transient_id: &[u8; 16]) -> bool { + pub fn contains(&self, transient_id: &PropagationTransientId) -> bool { self.entries.contains_key(transient_id) } - pub fn remove(&mut self, transient_id: &[u8; 16]) -> Option { + pub fn remove(&mut self, transient_id: &PropagationTransientId) -> Option { if let Some(entry) = self.entries.remove(transient_id) { self.total_size = self.total_size.saturating_sub(entry.size); Some(entry) @@ -114,7 +116,7 @@ impl PropagationStore { } } - pub fn transient_ids(&self) -> Vec<[u8; 16]> { + pub fn transient_ids(&self) -> Vec { self.entries.keys().copied().collect() } @@ -132,7 +134,7 @@ impl PropagationStore { pub fn cull_expired(&mut self, max_age_secs: u64) { let now = now_f64(); let cutoff = now - max_age_secs as f64; - let removed: Vec<[u8; 16]> = self + let removed: Vec = self .entries .iter() .filter(|(_, e)| e.stored_at < cutoff) @@ -156,7 +158,7 @@ impl PropagationStore { let bytes_needed = self.total_size - limit_bytes; let now = now_f64(); - let mut weighted: Vec<([u8; 16], f64)> = self + let mut weighted: Vec<(PropagationTransientId, f64)> = self .entries .iter() .map(|(tid, entry)| { @@ -205,7 +207,7 @@ impl PropagationStore { priority_weight * age_weight * entry.size as f64 } - pub fn get_stamp_value(&self, transient_id: &[u8; 16]) -> Option { + pub fn get_stamp_value(&self, transient_id: &PropagationTransientId) -> Option { self.entries.get(transient_id).map(|e| e.stamp_value) } @@ -229,35 +231,35 @@ impl PropagationStore { self.prioritised_destinations.remove(dest_hash); } - pub fn mark_locally_delivered(&mut self, transient_id: [u8; 16]) { + pub fn mark_locally_delivered(&mut self, transient_id: PropagationTransientId) { self.locally_delivered_ids.insert(transient_id); } - pub fn is_locally_delivered(&self, transient_id: &[u8; 16]) -> bool { + pub fn is_locally_delivered(&self, transient_id: &PropagationTransientId) -> bool { self.locally_delivered_ids.contains(transient_id) } - pub fn mark_locally_processed(&mut self, transient_id: [u8; 16]) { + pub fn mark_locally_processed(&mut self, transient_id: PropagationTransientId) { self.locally_processed_ids.insert(transient_id); } - pub fn is_locally_processed(&self, transient_id: &[u8; 16]) -> bool { + pub fn is_locally_processed(&self, transient_id: &PropagationTransientId) -> bool { self.locally_processed_ids.contains(transient_id) } - pub fn locally_delivered_ids(&self) -> &HashSet<[u8; 16]> { + pub fn locally_delivered_ids(&self) -> &HashSet { &self.locally_delivered_ids } - pub fn locally_processed_ids(&self) -> &HashSet<[u8; 16]> { + pub fn locally_processed_ids(&self) -> &HashSet { &self.locally_processed_ids } - pub fn replace_locally_delivered(&mut self, ids: HashSet<[u8; 16]>) { + pub fn replace_locally_delivered(&mut self, ids: HashSet) { self.locally_delivered_ids = ids; } - pub fn replace_locally_processed(&mut self, ids: HashSet<[u8; 16]>) { + pub fn replace_locally_processed(&mut self, ids: HashSet) { self.locally_processed_ids = ids; } @@ -273,12 +275,18 @@ impl PropagationStore { /// `from_peer` is the peer we received this message from, or `None` if it /// originated locally. - pub fn enqueue_distribution(&mut self, transient_id: [u8; 16], from_peer: Option<[u8; 16]>) { + pub fn enqueue_distribution( + &mut self, + transient_id: PropagationTransientId, + from_peer: Option<[u8; 16]>, + ) { self.peer_distribution_queue .push_back((transient_id, from_peer)); } - pub fn drain_distribution_queue(&mut self) -> Vec<([u8; 16], Option<[u8; 16]>)> { + pub fn drain_distribution_queue( + &mut self, + ) -> Vec<(PropagationTransientId, Option<[u8; 16]>)> { self.peer_distribution_queue.drain(..).collect() } @@ -298,7 +306,7 @@ impl PropagationStore { self.total_size } - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator { self.entries.iter() } } @@ -312,8 +320,8 @@ fn now_f64() -> f64 { pub use rns_crypto::hex_encode; -fn hex_decode_16(s: &str) -> Option<[u8; 16]> { - if s.len() != 32 { +fn hex_decode_32(s: &str) -> Option { + if s.len() != 64 { return None; } let bytes: Option> = (0..s.len()) @@ -321,7 +329,7 @@ fn hex_decode_16(s: &str) -> Option<[u8; 16]> { .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok()) .collect(); let bytes = bytes?; - let mut arr = [0u8; 16]; + let mut arr = [0u8; 32]; arr.copy_from_slice(&bytes); Some(arr) } @@ -330,10 +338,14 @@ fn hex_decode_16(s: &str) -> Option<[u8; 16]> { mod tests { use super::*; + fn tid(byte: u8) -> PropagationTransientId { + [byte; 32] + } + #[test] fn test_entry_filename() { let entry = PropagationEntry { - transient_id: [0xAA; 16], + transient_id: tid(0xAA), message_hash: [0xBB; 32], destination_hash: [0xCC; 16], stored_at: 1234567890.0, @@ -342,7 +354,9 @@ mod tests { collected: false, }; let fname = entry.filename(); - assert!(fname.starts_with("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); + assert!(fname.starts_with( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + )); let parts: Vec<&str> = fname.split('_').collect(); assert_eq!(parts.len(), 3); assert_eq!(parts[2], "8"); @@ -350,7 +364,8 @@ mod tests { #[test] fn test_parse_filename_3_component() { - let fname = "aabbccddaabbccddaabbccddaabbccdd_1234567890_16"; + let fname = + "aabbccddaabbccddaabbccddaabbccddaabbccddaabbccddaabbccddaabbccdd_1234567890_16"; let (tid, ts, sv) = PropagationEntry::parse_filename(fname).unwrap(); assert_eq!(tid[0], 0xaa); assert_eq!(ts, 1234567890.0); @@ -359,8 +374,8 @@ mod tests { #[test] fn test_parse_filename_2_component_legacy() { - let fname = "aabbccddaabbccddaabbccddaabbccdd_1234567890"; - let (tid, ts, sv) = PropagationEntry::parse_filename(fname).unwrap(); + let fname = format!("{}_1234567890", "aa".repeat(32)); + let (tid, ts, sv) = PropagationEntry::parse_filename(&fname).unwrap(); assert_eq!(tid[0], 0xaa); assert_eq!(ts, 1234567890.0); assert_eq!(sv, 0); @@ -371,28 +386,36 @@ mod tests { let mut store = PropagationStore::new(); assert!(store.is_empty()); - let entry = PropagationEntry::new([0xAA; 16], [0xBB; 32], [0xCC; 16], 500, 8); + let entry = PropagationEntry::new(tid(0xAA), [0xBB; 32], [0xCC; 16], 500, 8); store.insert(entry); assert_eq!(store.len(), 1); assert_eq!(store.total_size(), 500); - assert!(store.contains(&[0xAA; 16])); - assert!(!store.contains(&[0x00; 16])); + assert!(store.contains(&tid(0xAA))); + assert!(!store.contains(&tid(0x00))); } #[test] fn test_store_remove() { let mut store = PropagationStore::new(); store.insert(PropagationEntry::new( - [0xAA; 16], [0xBB; 32], [0xCC; 16], 500, 8, + tid(0xAA), + [0xBB; 32], + [0xCC; 16], + 500, + 8, )); store.insert(PropagationEntry::new( - [0xDD; 16], [0xEE; 32], [0xCC; 16], 300, 4, + tid(0xDD), + [0xEE; 32], + [0xCC; 16], + 300, + 4, )); assert_eq!(store.total_size(), 800); - store.remove(&[0xAA; 16]); + store.remove(&tid(0xAA)); assert_eq!(store.len(), 1); assert_eq!(store.total_size(), 300); } @@ -403,9 +426,9 @@ mod tests { let dest1 = [0xAA; 16]; let dest2 = [0xBB; 16]; - store.insert(PropagationEntry::new([0x01; 16], [0; 32], dest1, 100, 0)); - store.insert(PropagationEntry::new([0x02; 16], [0; 32], dest1, 200, 0)); - store.insert(PropagationEntry::new([0x03; 16], [0; 32], dest2, 300, 0)); + store.insert(PropagationEntry::new(tid(0x01), [0; 32], dest1, 100, 0)); + store.insert(PropagationEntry::new(tid(0x02), [0; 32], dest1, 200, 0)); + store.insert(PropagationEntry::new(tid(0x03), [0; 32], dest2, 300, 0)); assert_eq!(store.entries_for_destination(&dest1).len(), 2); assert_eq!(store.entries_for_destination(&dest2).len(), 1); @@ -414,8 +437,8 @@ mod tests { #[test] fn test_transient_ids() { let mut store = PropagationStore::new(); - store.insert(PropagationEntry::new([0x01; 16], [0; 32], [0; 16], 100, 0)); - store.insert(PropagationEntry::new([0x02; 16], [0; 32], [0; 16], 200, 0)); + store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0)); + store.insert(PropagationEntry::new(tid(0x02), [0; 32], [0; 16], 200, 0)); let ids = store.transient_ids(); assert_eq!(ids.len(), 2); @@ -429,16 +452,16 @@ mod tests { store.ignore_destination(ignored_dest); - let entry1 = PropagationEntry::new([0x01; 16], [0; 32], ignored_dest, 100, 0); + let entry1 = PropagationEntry::new(tid(0x01), [0; 32], ignored_dest, 100, 0); assert!(!store.insert(entry1)); assert_eq!(store.len(), 0); - let entry2 = PropagationEntry::new([0x02; 16], [0; 32], allowed_dest, 200, 0); + let entry2 = PropagationEntry::new(tid(0x02), [0; 32], allowed_dest, 200, 0); assert!(store.insert(entry2)); assert_eq!(store.len(), 1); store.unignore_destination(&ignored_dest); - let entry3 = PropagationEntry::new([0x03; 16], [0; 32], ignored_dest, 100, 0); + let entry3 = PropagationEntry::new(tid(0x03), [0; 32], ignored_dest, 100, 0); assert!(store.insert(entry3)); assert_eq!(store.len(), 2); } @@ -446,33 +469,33 @@ mod tests { #[test] fn test_locally_delivered_ids() { let mut store = PropagationStore::new(); - let tid = [0xAA; 16]; + let transient_id = tid(0xAA); - assert!(!store.is_locally_delivered(&tid)); - store.mark_locally_delivered(tid); - assert!(store.is_locally_delivered(&tid)); + assert!(!store.is_locally_delivered(&transient_id)); + store.mark_locally_delivered(transient_id); + assert!(store.is_locally_delivered(&transient_id)); } #[test] fn test_locally_processed_ids() { let mut store = PropagationStore::new(); - let tid = [0xBB; 16]; + let transient_id = tid(0xBB); - assert!(!store.is_locally_processed(&tid)); - store.mark_locally_processed(tid); - assert!(store.is_locally_processed(&tid)); + assert!(!store.is_locally_processed(&transient_id)); + store.mark_locally_processed(transient_id); + assert!(store.is_locally_processed(&transient_id)); } #[test] fn test_cull_by_weight() { let mut store = PropagationStore::new(); - let mut entry1 = PropagationEntry::new([0x01; 16], [0; 32], [0xAA; 16], 500, 0); + let mut entry1 = PropagationEntry::new(tid(0x01), [0; 32], [0xAA; 16], 500, 0); entry1.stored_at = 1000.0; store.entries.insert(entry1.transient_id, entry1.clone()); store.total_size += 500; - let mut entry2 = PropagationEntry::new([0x02; 16], [0; 32], [0xBB; 16], 300, 0); + let mut entry2 = PropagationEntry::new(tid(0x02), [0; 32], [0xBB; 16], 300, 0); entry2.stored_at = now_f64(); store.entries.insert(entry2.transient_id, entry2.clone()); store.total_size += 300; @@ -482,7 +505,7 @@ mod tests { store.cull_by_weight(400); assert!(store.total_size() <= 400); // Old entry evicted first (higher weight). - assert!(!store.contains(&[0x01; 16])); + assert!(!store.contains(&tid(0x01))); } #[test] @@ -491,16 +514,16 @@ mod tests { assert!(!store.has_pending_distribution()); - store.enqueue_distribution([0xAA; 16], Some([0xBB; 16])); - store.enqueue_distribution([0xCC; 16], None); + store.enqueue_distribution(tid(0xAA), Some([0xBB; 16])); + store.enqueue_distribution(tid(0xCC), None); assert!(store.has_pending_distribution()); let entries = store.drain_distribution_queue(); assert_eq!(entries.len(), 2); - assert_eq!(entries[0].0, [0xAA; 16]); + assert_eq!(entries[0].0, tid(0xAA)); assert_eq!(entries[0].1, Some([0xBB; 16])); - assert_eq!(entries[1].0, [0xCC; 16]); + assert_eq!(entries[1].0, tid(0xCC)); assert!(entries[1].1.is_none()); assert!(!store.has_pending_distribution()); @@ -512,7 +535,7 @@ mod tests { let now = now_f64(); let entry = PropagationEntry { - transient_id: [0x01; 16], + transient_id: tid(0x01), message_hash: [0; 32], destination_hash: [0xAA; 16], stored_at: now, @@ -538,9 +561,9 @@ mod tests { #[test] fn test_get_stamp_value() { let mut store = PropagationStore::new(); - store.insert(PropagationEntry::new([0xAA; 16], [0; 32], [0; 16], 100, 12)); + store.insert(PropagationEntry::new(tid(0xAA), [0; 32], [0; 16], 100, 12)); - assert_eq!(store.get_stamp_value(&[0xAA; 16]), Some(12)); - assert_eq!(store.get_stamp_value(&[0xBB; 16]), None); + assert_eq!(store.get_stamp_value(&tid(0xAA)), Some(12)); + assert_eq!(store.get_stamp_value(&tid(0xBB)), None); } } diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index 398c696..7db725b 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -29,6 +29,7 @@ use tokio::sync::mpsc; use crate::constants::*; use crate::propagation::hex_encode; +use crate::types::PropagationTransientId; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PropagationClientState { @@ -118,7 +119,7 @@ impl PropagationClient { self.delivery_limit = Some(limit_kb); } - pub fn add_local_message(&mut self, transient_id: [u8; 16]) { + pub fn add_local_message(&mut self, transient_id: PropagationTransientId) { self.local_messages.insert(transient_id.to_vec()); } @@ -693,7 +694,7 @@ impl PropagationClient { self.available_messages.clear(); for item in arr { if let Some(id_bytes) = item.as_slice() - && matches!(id_bytes.len(), 16 | 32) + && id_bytes.len() == 32 { self.available_messages.push(id_bytes.to_vec()); } @@ -1064,10 +1065,10 @@ mod tests { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.add_local_message([0xAA; 16]); - client.add_local_message([0xBB; 16]); + client.add_local_message([0xAA; 32]); + client.add_local_message([0xBB; 32]); assert_eq!(client.local_messages.len(), 2); - assert!(client.local_messages.contains(&vec![0xAA; 16])); + assert!(client.local_messages.contains(&vec![0xAA; 32])); client.add_local_message_id(vec![0xCC; 32]); assert!(client.local_messages.contains(&vec![0xCC; 32])); } diff --git a/crates/lxmf-core/src/propagation_node.rs b/crates/lxmf-core/src/propagation_node.rs index d832dcb..67167bc 100644 --- a/crates/lxmf-core/src/propagation_node.rs +++ b/crates/lxmf-core/src/propagation_node.rs @@ -13,6 +13,7 @@ use crate::message::LxMessage; use crate::peer::LxmPeer; use crate::propagation::{PropagationEntry, PropagationStore, hex_encode}; use crate::sync::{OfferResponse, SyncGet, SyncOffer, SyncSession}; +use crate::types::PropagationTransientId; #[derive(Debug, Clone)] pub struct PropagationNodeConfig { @@ -105,7 +106,7 @@ impl PropagationNode { None => return false, }; - let transient_id = rns_crypto::sha::truncated_hash(&hash); + let transient_id = message.transient_id.unwrap_or(hash); if self.store.contains(&transient_id) { return false; } @@ -174,9 +175,7 @@ impl PropagationNode { return false; } - let full = rns_crypto::sha::full_hash(lxmf_data); - let mut transient_id = [0u8; 16]; - transient_id.copy_from_slice(&full[..16]); + let transient_id = rns_crypto::sha::full_hash(lxmf_data); if self.store.contains(&transient_id) { return false; } @@ -190,12 +189,9 @@ impl PropagationNode { let mut destination_hash = [0u8; 16]; destination_hash.copy_from_slice(&lxmf_data[..DESTINATION_LENGTH]); - let mut message_hash = [0u8; 32]; - message_hash.copy_from_slice(&full); - let entry = PropagationEntry::new( transient_id, - message_hash, + transient_id, destination_hash, lxmf_data.len(), stamp_value, @@ -320,7 +316,7 @@ impl PropagationNode { &self, _peer_hash: [u8; 16], peer_min_stamp_cost: Option, - ) -> Vec<[u8; 16]> { + ) -> Vec { match peer_min_stamp_cost { Some(min_cost) if min_cost > 0 => self .store @@ -333,7 +329,10 @@ impl PropagationNode { } /// Returns only messages the peer has not already received. - pub fn create_offer_filtered(&self, handled: &HashSet<[u8; 16]>) -> Vec<[u8; 16]> { + pub fn create_offer_filtered( + &self, + handled: &HashSet, + ) -> Vec { self.store .transient_ids() .into_iter() @@ -349,7 +348,7 @@ impl PropagationNode { self.store.total_size() } - pub fn contains(&self, transient_id: &[u8; 16]) -> bool { + pub fn contains(&self, transient_id: &PropagationTransientId) -> bool { self.store.contains(transient_id) } @@ -387,9 +386,9 @@ impl PropagationNode { pub fn offer_request( &mut self, _peer_hash: [u8; 16], - offered_ids: &[[u8; 16]], - ) -> Vec<[u8; 16]> { - let peer_has: HashSet<[u8; 16]> = offered_ids.iter().copied().collect(); + offered_ids: &[PropagationTransientId], + ) -> Vec { + let peer_has: HashSet = offered_ids.iter().copied().collect(); self.store .transient_ids() @@ -411,7 +410,7 @@ impl PropagationNode { is_throttled: bool, access_allowed: bool, peering_key_valid: bool, - offered_ids: &[[u8; 16]], + offered_ids: &[PropagationTransientId], ) -> OfferResponse { if !identity_known { return OfferResponse::ErrorNoIdentity; @@ -426,7 +425,7 @@ impl PropagationNode { return OfferResponse::ErrorInvalidKey; } - let wanted: Vec<[u8; 16]> = offered_ids + let wanted: Vec = offered_ids .iter() .filter(|id| !self.store.contains(id)) .copied() @@ -530,7 +529,7 @@ impl PropagationNode { } /// Expected wire format: `[peering_key_bytes, [transient_id_1, ...]]`. - fn decode_offer_request(data: &[u8]) -> Option<(Vec, Vec<[u8; 16]>)> { + fn decode_offer_request(data: &[u8]) -> Option<(Vec, Vec)> { let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?; let arr = value.as_array()?; if arr.len() < 2 { @@ -544,14 +543,9 @@ impl PropagationNode { for id_val in ids_array { if let Some(id_bytes) = id_val.as_slice() { match id_bytes.len() { - 16 => { - let mut tid = [0u8; 16]; - tid.copy_from_slice(id_bytes); - offered_ids.push(tid); - } 32 => { - let mut tid = [0u8; 16]; - tid.copy_from_slice(&id_bytes[..16]); + let mut tid = [0u8; 32]; + tid.copy_from_slice(id_bytes); offered_ids.push(tid); } _ => {} @@ -598,17 +592,12 @@ impl PropagationNode { let wants_is_nil = arr[0].is_nil(); let haves_is_nil = arr[1].is_nil(); - fn parse_store_id(value: &rmpv::Value) -> Option<[u8; 16]> { + fn parse_store_id(value: &rmpv::Value) -> Option { let id_bytes = value.as_slice()?; match id_bytes.len() { - 16 => { - let mut tid = [0u8; 16]; - tid.copy_from_slice(id_bytes); - Some(tid) - } 32 => { - let mut tid = [0u8; 16]; - tid.copy_from_slice(&id_bytes[..16]); + let mut tid = [0u8; 32]; + tid.copy_from_slice(id_bytes); Some(tid) } _ => None, @@ -687,7 +676,10 @@ impl PropagationNode { /// Fetch raw packed message data for each requested transient ID. Python /// reference: LXMRouter.message_get_request_received(). Returns an empty /// vec when there is no disk storage configured. - pub fn message_get_request(&self, requested_ids: &[[u8; 16]]) -> Vec<([u8; 16], Vec)> { + pub fn message_get_request( + &self, + requested_ids: &[PropagationTransientId], + ) -> Vec<(PropagationTransientId, Vec)> { let dir = match &self.storage_path { Some(d) => d, None => return Vec::new(), @@ -747,10 +739,10 @@ impl PropagationNode { let mut messages = Vec::new(); for wanted_id_bytes in &get.wanted_ids { - if wanted_id_bytes.len() != 16 { + if wanted_id_bytes.len() != 32 { continue; } - let mut tid = [0u8; 16]; + let mut tid = [0u8; 32]; tid.copy_from_slice(wanted_id_bytes); if let Some(ref dir) = self.storage_path @@ -771,7 +763,11 @@ impl PropagationNode { /// the sync session. Python reference: /// LXMRouter.propagation_resource_concluded() (LXMRouter.py:2271) -- /// `peer.queue_handled_message(transient_id)`. - pub fn mark_peer_handled(&mut self, peer_hash: &[u8; 16], transient_id: &[u8; 16]) { + pub fn mark_peer_handled( + &mut self, + peer_hash: &[u8; 16], + transient_id: &PropagationTransientId, + ) { if let Some(mut peer) = self.load_peer(peer_hash) { peer.add_handled_message(transient_id); let _ = self.save_peer(&peer); @@ -843,6 +839,14 @@ mod tests { msg } + fn tid(byte: u8) -> PropagationTransientId { + [byte; 32] + } + + fn id(byte: u8) -> Vec { + vec![byte; 32] + } + #[test] fn test_new_propagation_node() { let node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); @@ -917,7 +921,7 @@ mod tests { let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg1"); let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); - let tid1 = rns_crypto::sha::truncated_hash(&msg1.hash.unwrap()); + let tid1 = msg1.transient_id.unwrap(); node.accept_message(&msg1); node.accept_message(&msg2); @@ -1059,12 +1063,12 @@ mod tests { .unwrap(); let mut peer = LxmPeer::new([0xBB; 16]); - peer.add_handled_message(&[0xCC; 16]); + peer.add_handled_message(&tid(0xCC)); node.save_peer(&peer).unwrap(); let loaded_peers = node.load_peers(); assert_eq!(loaded_peers.len(), 1); - assert!(loaded_peers[0].has_handled(&[0xCC; 16])); + assert!(loaded_peers[0].has_handled(&tid(0xCC))); let _ = std::fs::remove_dir_all(&dir); } @@ -1082,12 +1086,12 @@ mod tests { .unwrap(); let mut peer1 = LxmPeer::new([0xBB; 16]); - peer1.add_handled_message(&[0x11; 16]); + peer1.add_handled_message(&tid(0x11)); node.save_peer(&peer1).unwrap(); let mut peer2 = LxmPeer::new([0xDD; 16]); - peer2.add_handled_message(&[0x22; 16]); - peer2.add_handled_message(&[0x33; 16]); + peer2.add_handled_message(&tid(0x22)); + peer2.add_handled_message(&tid(0x33)); node.save_peer(&peer2).unwrap(); let loaded = node.load_peers(); @@ -1182,9 +1186,9 @@ mod tests { let msg2 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg2"); let msg3 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "msg3"); - let tid1 = rns_crypto::sha::truncated_hash(&msg1.hash.unwrap()); - let tid2 = rns_crypto::sha::truncated_hash(&msg2.hash.unwrap()); - let tid3 = rns_crypto::sha::truncated_hash(&msg3.hash.unwrap()); + let tid1 = msg1.transient_id.unwrap(); + let tid2 = msg2.transient_id.unwrap(); + let tid3 = msg3.transient_id.unwrap(); node.accept_message(&msg1); node.accept_message(&msg2); @@ -1213,7 +1217,7 @@ mod tests { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); let missing = node.offer_request([0xDD; 16], &[tid]); @@ -1233,7 +1237,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "get request content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); let results = node.message_get_request(&[tid]); @@ -1259,7 +1263,7 @@ mod tests { ) .unwrap(); - let results = node.message_get_request(&[[0xFF; 16]]); + let results = node.message_get_request(&[tid(0xFF)]); assert!(results.is_empty()); let _ = std::fs::remove_dir_all(&dir); @@ -1269,7 +1273,7 @@ mod tests { fn test_message_get_request_no_storage() { let node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let results = node.message_get_request(&[[0xFF; 16]]); + let results = node.message_get_request(&[tid(0xFF)]); assert!(results.is_empty()); } @@ -1294,11 +1298,11 @@ mod tests { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); let msg1 = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "has_this"); - let tid1 = rns_crypto::sha::truncated_hash(&msg1.hash.unwrap()); + let tid1 = msg1.transient_id.unwrap(); node.accept_message(&msg1); let peer_hash = [0xDD; 16]; - let tid2 = [0xEE; 16]; + let tid2 = tid(0xEE); let offer = crate::sync::SyncOffer { peering_key: Vec::new(), transient_ids: vec![tid1.to_vec(), tid2.to_vec()], @@ -1337,7 +1341,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "sync get content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); let get = crate::sync::SyncGet { @@ -1387,7 +1391,7 @@ mod tests { fn test_offer_request_checked_have_all() { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); let resp = node.offer_request_checked([0xDD; 16], true, false, true, true, &[tid]); @@ -1404,7 +1408,7 @@ mod tests { false, true, true, - &[[0x11; 16], [0x22; 16]], + &[tid(0x11), tid(0x22)], ); assert_eq!(resp, OfferResponse::WantAll); } @@ -1413,15 +1417,15 @@ mod tests { fn test_offer_request_checked_want_some() { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let stored_tid = msg.transient_id.unwrap(); node.accept_message(&msg); let resp = - node.offer_request_checked([0xDD; 16], true, false, true, true, &[tid, [0x99; 16]]); + node.offer_request_checked([0xDD; 16], true, false, true, true, &[stored_tid, tid(0x99)]); match resp { OfferResponse::WantSome(ids) => { assert_eq!(ids.len(), 1); - assert_eq!(ids[0], [0x99; 16].to_vec()); + assert_eq!(ids[0], id(0x99)); } _ => panic!("expected WantSome"), } @@ -1445,7 +1449,7 @@ mod tests { let parsed = OfferResponse::from_msgpack(&encoded); assert_eq!(parsed, OfferResponse::ErrorThrottled); - let ids = vec![vec![0xAA; 16], vec![0xBB; 16]]; + let ids = vec![id(0xAA), id(0xBB)]; let encoded = PropagationNode::encode_offer_response(&OfferResponse::WantSome(ids.clone())); let parsed = OfferResponse::from_msgpack(&encoded); match parsed { @@ -1465,8 +1469,8 @@ mod tests { let offer = Value::Array(vec![ Value::Binary(vec![]), Value::Array(vec![ - Value::Binary(vec![0x11; 16]), - Value::Binary(vec![0x22; 16]), + Value::Binary(id(0x11)), + Value::Binary(id(0x22)), ]), ]); let mut buf = Vec::new(); @@ -1507,8 +1511,8 @@ mod tests { let offer = Value::Array(vec![ Value::Binary(vec![0xAA; 32]), Value::Array(vec![ - Value::Binary(vec![0x11; 16]), - Value::Binary(vec![0x22; 16]), + Value::Binary(id(0x11)), + Value::Binary(id(0x22)), ]), ]); let mut buf = Vec::new(); @@ -1519,8 +1523,8 @@ mod tests { let (key, ids) = result.unwrap(); assert_eq!(key, vec![0xAA; 32]); assert_eq!(ids.len(), 2); - assert_eq!(ids[0], [0x11; 16]); - assert_eq!(ids[1], [0x22; 16]); + assert_eq!(ids[0], tid(0x11)); + assert_eq!(ids[1], tid(0x22)); } #[test] @@ -1531,16 +1535,15 @@ mod tests { Value::Array(vec![ Value::Binary(vec![0x11; 16]), Value::Binary(vec![0x22; 8]), - Value::Binary(vec![0x33; 32]), + Value::Binary(id(0x33)), ]), ]); let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &offer).unwrap(); let (_, ids) = PropagationNode::decode_offer_request(&buf).unwrap(); - assert_eq!(ids.len(), 2); - assert_eq!(ids[0], [0x11; 16]); - assert_eq!(ids[1], [0x33; 16]); + assert_eq!(ids.len(), 1); + assert_eq!(ids[0], tid(0x33)); } #[test] @@ -1567,7 +1570,7 @@ mod tests { let response: rmpv::Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap(); let arr = response.as_array().unwrap(); assert_eq!(arr.len(), 1); - assert_eq!(arr[0].as_slice().unwrap().len(), 16); + assert_eq!(arr[0].as_slice().unwrap().len(), 32); let _ = std::fs::remove_dir_all(&dir); } @@ -1693,7 +1696,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "purge content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); assert_eq!(node.message_count(), 1); @@ -1724,7 +1727,7 @@ mod tests { .unwrap(); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "get data content"); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); node.accept_message(&msg); use rmpv::Value; @@ -1775,7 +1778,7 @@ mod tests { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); let entry1 = crate::propagation::PropagationEntry { - transient_id: [0x01; 16], + transient_id: tid(0x01), message_hash: [0x11; 32], destination_hash: [0xCC; 16], stored_at: 1000.0, @@ -1784,7 +1787,7 @@ mod tests { collected: false, }; let entry2 = crate::propagation::PropagationEntry { - transient_id: [0x02; 16], + transient_id: tid(0x02), message_hash: [0x22; 32], destination_hash: [0xCC; 16], stored_at: 1000.0, @@ -1800,7 +1803,7 @@ mod tests { let filtered = node.create_offer([0xFF; 16], Some(10)); assert_eq!(filtered.len(), 1); - assert_eq!(filtered[0], [0x01; 16]); + assert_eq!(filtered[0], tid(0x01)); let all2 = node.create_offer([0xFF; 16], Some(0)); assert_eq!(all2.len(), 2); diff --git a/crates/lxmf-core/src/propagation_sync.rs b/crates/lxmf-core/src/propagation_sync.rs index f0f1006..b30db12 100644 --- a/crates/lxmf-core/src/propagation_sync.rs +++ b/crates/lxmf-core/src/propagation_sync.rs @@ -25,6 +25,7 @@ use crate::peer::LxmPeer; use crate::propagation::hex_encode; use crate::propagation_node::{PropagationNode, PropagationNodeConfig}; use crate::sync::OfferResponse; +use crate::types::PropagationTransientId; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncTaskState { @@ -315,11 +316,11 @@ impl PropagationSyncTask { self.state = SyncTaskState::Complete; } OfferResponse::WantSome(wanted_id_bytes) => { - let wanted_ids: Vec<[u8; 16]> = wanted_id_bytes + let wanted_ids: Vec = wanted_id_bytes .iter() .filter_map(|id| { - if id.len() == 16 { - let mut arr = [0u8; 16]; + if id.len() == 32 { + let mut arr = [0u8; 32]; arr.copy_from_slice(id); Some(arr) } else { @@ -335,7 +336,7 @@ impl PropagationSyncTask { } } - fn queue_messages_for_ids(&mut self, ids: &[[u8; 16]]) { + fn queue_messages_for_ids(&mut self, ids: &[PropagationTransientId]) { let results = self.propagation_node.message_get_request(ids); self.transfer_queue = results.into_iter().map(|(_tid, data)| data).collect(); @@ -958,7 +959,7 @@ mod tests { task.set_node([0xBB; 16]); task.state = SyncTaskState::AwaitingResponse; - let wanted = vec![vec![0x11; 16], vec![0x22; 16]]; + let wanted = vec![vec![0x11; 32], vec![0x22; 32]]; task.handle_offer_response(OfferResponse::WantSome(wanted)); assert_eq!(task.state, SyncTaskState::Complete); } @@ -982,7 +983,7 @@ mod tests { crate::constants::DeliveryMethod::Propagated, ); msg.sign(&key).unwrap(); - let tid = rns_crypto::sha::truncated_hash(&msg.hash.unwrap()); + let tid = msg.transient_id.unwrap(); task.accept_message(&msg); let wanted = vec![tid.to_vec()]; diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index 86eea69..f50701d 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -15,6 +15,7 @@ use crate::peer::LxmPeer; use crate::propagation::PropagationStore; use crate::stamper; use crate::ticket::{Ticket, TicketStore}; +use crate::types::PropagationTransientId; /// Router configuration. /// @@ -684,13 +685,13 @@ impl LxmRouter { .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs_f64(); - let delivered: std::collections::HashMap<[u8; 16], f64> = self + let delivered: std::collections::HashMap = self .propagation_store .locally_delivered_ids() .iter() .map(|id| (*id, now)) .collect(); - let processed: std::collections::HashMap<[u8; 16], f64> = self + let processed: std::collections::HashMap = self .propagation_store .locally_processed_ids() .iter() @@ -1695,7 +1696,7 @@ mod tests { fn test_save_and_load_state_roundtrip() { let tmp = tempfile::TempDir::new().unwrap(); let dest_a = [0xAA; 16]; - let transient_a = [0x11; 16]; + let transient_a = [0x11; 32]; let mut r1 = LxmRouter::new(RouterConfig::default()); r1.set_stamp_cost(dest_a, 8); @@ -2266,7 +2267,7 @@ mod tests { let mut router = LxmRouter::new(RouterConfig::default()); let peer_hash = [0xAA; 16]; let mut peer = LxmPeer::new(peer_hash); - peer.currently_transferring_messages = Some(vec![[0x01; 16], [0x02; 16]]); + peer.currently_transferring_messages = Some(vec![[0x01; 32], [0x02; 32]]); peer.state = PeerState::ResourceTransferring; router.add_peer(peer); diff --git a/crates/lxmf-core/src/sync.rs b/crates/lxmf-core/src/sync.rs index 7e17415..6df4bf1 100644 --- a/crates/lxmf-core/src/sync.rs +++ b/crates/lxmf-core/src/sync.rs @@ -18,6 +18,7 @@ use serde::{Deserialize, Serialize}; use crate::constants::PeerError; use crate::propagation::PropagationStore; +use crate::types::PropagationTransientId; pub const SYNC_MSG_OFFER: u16 = 0x0001; pub const SYNC_MSG_GET: u16 = 0x0002; @@ -191,8 +192,8 @@ impl OfferResponse { pub struct SyncSession { pub peer_hash: [u8; 16], pub state: SyncState, - pub offered_ids: Vec<[u8; 16]>, - pub wanted_ids: Vec<[u8; 16]>, + pub offered_ids: Vec, + pub wanted_ids: Vec, pub transferred: usize, } @@ -217,7 +218,11 @@ impl SyncSession { } } - pub fn prepare_offer(&mut self, our_ids: Vec<[u8; 16]>, peering_key: Vec) -> SyncOffer { + pub fn prepare_offer( + &mut self, + our_ids: Vec, + peering_key: Vec, + ) -> SyncOffer { self.offered_ids = our_ids.clone(); self.state = SyncState::OfferSent; SyncOffer { @@ -232,8 +237,8 @@ impl SyncSession { .transient_ids .iter() .filter(|id| { - if id.len() == 16 { - let mut arr = [0u8; 16]; + if id.len() == 32 { + let mut arr = [0u8; 32]; arr.copy_from_slice(id); !our_store.contains(&arr) } else { @@ -252,8 +257,8 @@ impl SyncSession { .wanted_ids .iter() .filter_map(|id| { - if id.len() == 16 { - let mut arr = [0u8; 16]; + if id.len() == 32 { + let mut arr = [0u8; 32]; arr.copy_from_slice(id); Some(arr) } else { @@ -286,11 +291,19 @@ mod tests { use super::*; use crate::propagation::{PropagationEntry, PropagationStore}; + fn tid(byte: u8) -> PropagationTransientId { + [byte; 32] + } + + fn id(byte: u8) -> Vec { + vec![byte; 32] + } + #[test] fn test_sync_offer_pack_unpack() { let offer = SyncOffer { peering_key: vec![0xDD; 32], - transient_ids: vec![vec![0xAA; 16], vec![0xBB; 16], vec![0xCC; 16]], + transient_ids: vec![id(0xAA), id(0xBB), id(0xCC)], }; let packed = offer.pack(); @@ -300,15 +313,15 @@ mod tests { unpacked.unpack(&packed).unwrap(); assert_eq!(unpacked.peering_key, vec![0xDD; 32]); assert_eq!(unpacked.transient_ids.len(), 3); - assert_eq!(unpacked.transient_ids[0], vec![0xAA; 16]); - assert_eq!(unpacked.transient_ids[1], vec![0xBB; 16]); - assert_eq!(unpacked.transient_ids[2], vec![0xCC; 16]); + assert_eq!(unpacked.transient_ids[0], id(0xAA)); + assert_eq!(unpacked.transient_ids[1], id(0xBB)); + assert_eq!(unpacked.transient_ids[2], id(0xCC)); } #[test] fn test_sync_get_pack_unpack() { let get = SyncGet { - wanted_ids: vec![vec![0x11; 16], vec![0x22; 16]], + wanted_ids: vec![id(0x11), id(0x22)], }; let packed = get.pack(); @@ -317,8 +330,8 @@ mod tests { let mut unpacked = SyncGet::new(); unpacked.unpack(&packed).unwrap(); assert_eq!(unpacked.wanted_ids.len(), 2); - assert_eq!(unpacked.wanted_ids[0], vec![0x11; 16]); - assert_eq!(unpacked.wanted_ids[1], vec![0x22; 16]); + assert_eq!(unpacked.wanted_ids[0], id(0x11)); + assert_eq!(unpacked.wanted_ids[1], id(0x22)); } #[test] @@ -339,7 +352,7 @@ mod tests { let mut session = SyncSession::new(peer_hash); assert_eq!(session.state, SyncState::Idle); - let ids = vec![[0x01; 16], [0x02; 16], [0x03; 16]]; + let ids = vec![tid(0x01), tid(0x02), tid(0x03)]; let offer = session.prepare_offer(ids.clone(), vec![0xFF; 32]); assert_eq!(session.state, SyncState::OfferSent); assert_eq!(offer.transient_ids.len(), 3); @@ -352,18 +365,18 @@ mod tests { let mut session = SyncSession::new(peer_hash); let mut store = PropagationStore::new(); - store.insert(PropagationEntry::new([0x01; 16], [0; 32], [0; 16], 100, 0)); + store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0)); let offer = SyncOffer { peering_key: vec![0xFF; 32], - transient_ids: vec![vec![0x01; 16], vec![0x02; 16], vec![0x03; 16]], + transient_ids: vec![id(0x01), id(0x02), id(0x03)], }; let get = session.process_offer(&offer, &store); assert_eq!(session.state, SyncState::Receiving); assert_eq!(get.wanted_ids.len(), 2); - assert_eq!(get.wanted_ids[0], vec![0x02; 16]); - assert_eq!(get.wanted_ids[1], vec![0x03; 16]); + assert_eq!(get.wanted_ids[0], id(0x02)); + assert_eq!(get.wanted_ids[1], id(0x03)); } #[test] @@ -373,7 +386,7 @@ mod tests { session.state = SyncState::OfferSent; let get = SyncGet { - wanted_ids: vec![vec![0x01; 16], vec![0x02; 16]], + wanted_ids: vec![id(0x01), id(0x02)], }; session.process_get(&get); @@ -442,7 +455,7 @@ mod tests { let offer = SyncOffer { peering_key: vec![0xFF; 32], - transient_ids: vec![vec![0x01; 16], vec![0x02; 16]], + transient_ids: vec![id(0x01), id(0x02)], }; let get = session.process_offer(&offer, &store); @@ -456,7 +469,7 @@ mod tests { let offer = SyncOffer { peering_key: vec![0xFF; 32], - transient_ids: vec![vec![0x01; 16], vec![0x02; 8], vec![0x03; 32]], + transient_ids: vec![vec![0x01; 16], vec![0x02; 8], id(0x03)], }; let get = session.process_offer(&offer, &store); @@ -468,7 +481,7 @@ mod tests { let mut session = SyncSession::new([0xCC; 16]); let get = SyncGet { - wanted_ids: vec![vec![0x01; 16], vec![0x02; 10]], + wanted_ids: vec![id(0x01), vec![0x02; 10]], }; session.process_get(&get); @@ -529,8 +542,8 @@ mod tests { #[test] fn test_offer_response_want_some() { - let id1 = vec![0xAA; 16]; - let id2 = vec![0xBB; 16]; + let id1 = id(0xAA); + let id2 = id(0xBB); let value = rmpv::Value::Array(vec![ rmpv::Value::Binary(id1.clone()), rmpv::Value::Binary(id2.clone()),