diff --git a/crates/rns-identity/src/announce.rs b/crates/rns-identity/src/announce.rs index eb8cf45..60afb80 100644 --- a/crates/rns-identity/src/announce.rs +++ b/crates/rns-identity/src/announce.rs @@ -198,6 +198,19 @@ impl AnnounceData { packet_dest_hash: &[u8; 16], known_public_key: Option<&[u8; 64]>, ) -> Result { + let identity = self.verify_signature(packet_dest_hash)?; + self.validate_destination_binding(packet_dest_hash, &identity, known_public_key)?; + Ok(identity) + } + + /// Verify the announce signature without checking destination-hash + /// binding or first-seen key continuity. + /// + /// Reticulum transport performs this lightweight precheck before announce + /// ingress limiting, then runs full binding validation before learning the + /// path. Keeping this as a distinct step lets transport match that order + /// without duplicating announce wire-format logic. + pub fn verify_signature(&self, packet_dest_hash: &[u8; 16]) -> Result { let identity = Identity::from_public_key(&self.public_key) .map_err(|_| AnnounceError::InvalidPublicKey)?; @@ -224,6 +237,17 @@ impl AnnounceData { return Err(AnnounceError::SignatureInvalid); } + Ok(identity) + } + + /// Validate destination-hash binding and first-seen public-key continuity + /// after [`verify_signature`] has succeeded. + pub fn validate_destination_binding( + &self, + packet_dest_hash: &[u8; 16], + identity: &Identity, + known_public_key: Option<&[u8; 64]>, + ) -> Result<(), AnnounceError> { // Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes. let expected_hash = { let mut material = Vec::with_capacity(26); @@ -256,7 +280,7 @@ impl AnnounceData { } } - Ok(identity) + Ok(()) } } diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index 06c99ea..72ba1b4 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -135,13 +135,73 @@ impl TransportActor { return; } - // Per-interface ingress control. Record the announce and, if the - // interface is burst-limiting, hold it for later release by the - // maintenance tick rather than processing now. - // - // Bypass the hold when the announce answers an outstanding path - // request: the announce *is* the resolution, and delaying it there - // would stall the requester for no gain. + let (announce_data, validated_identity) = { + if data_offset >= raw.len() { + tracing::warn!( + dest = hex::encode(header.destination_hash), + "announce missing payload, dropping" + ); + return; + } + + let payload = &raw[data_offset..]; + let has_ratchet = header.flags.context_flag; + tracing::debug!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + has_ratchet = has_ratchet, + header_type = ?header.flags.header_type, + "announce payload received" + ); + match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) { + Ok(announce_data) => { + tracing::debug!( + dest = hex::encode(header.destination_hash), + app_data_len = announce_data.app_data.as_ref().map(|d| d.len()), + has_ratchet_key = announce_data.ratchet.is_some(), + "announce unpacked" + ); + match announce_data.verify_signature(&header.destination_hash) { + Ok(validated_identity) => { + if self.blackhole_table.is_blackholed(&validated_identity.hash) { + trace!( + identity = hex::encode(validated_identity.hash), + dest = hex::encode(header.destination_hash), + "announce from blackholed identity, dropping" + ); + return; + } + (announce_data, validated_identity) + } + Err(e) => { + tracing::warn!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + error = %e, + "announce validation failed, dropping" + ); + return; + } + } + } + Err(e) => { + tracing::warn!( + dest = hex::encode(header.destination_hash), + payload_len = payload.len(), + has_ratchet = has_ratchet, + error = %e, + "announce unpack failed, dropping" + ); + return; + } + } + }; + + // Python validates the announce signature before ingress accounting, + // and only holds still-unknown destinations. Known re-announces and + // path responses for paths we already know must continue refreshing + // route state during an ingress burst. + let announced_destination_known = self.path_table.get(&header.destination_hash).is_some(); let answers_path_request = self.path_requests.contains_key(&header.destination_hash) || self .discovery_path_requests @@ -149,6 +209,7 @@ impl TransportActor { if let Some(entry) = self.interfaces.get_mut(&interface_id) { entry.ingress.received_announce(); if !is_from_local_client + && !announced_destination_known && !answers_path_request && entry.ingress.should_ingress_limit() { @@ -167,6 +228,36 @@ impl TransportActor { } } + let known_public_key = self + .recent_announces + .get(&header.destination_hash) + .and_then(|entry| entry.public_key); + if let Err(e) = announce_data.validate_destination_binding( + &header.destination_hash, + &validated_identity, + known_public_key.as_ref(), + ) { + tracing::warn!( + dest = hex::encode(header.destination_hash), + error = %e, + "announce validation failed, dropping" + ); + return; + } + + tracing::debug!( + dest = hex::encode(header.destination_hash), + app_data_present = announce_data.app_data.is_some(), + "announce validated" + ); + + let announce_app_data = announce_data.app_data.clone(); + let announce_public_key = Some(validated_identity.get_public_key()); + let announce_ratchet = announce_data.ratchet; + let announce_name_hash = announce_data.name_hash; + let announce_identity_hash = Some(validated_identity.hash); + let announce_random_hash = announce_data.random_hash; + let mut rate_blocked = false; // Per-interface rate limiting is opt-in and suppresses rebroadcast @@ -208,95 +299,6 @@ impl TransportActor { self.rate_table.record(header.destination_hash); } - let ( - announce_app_data, - announce_public_key, - announce_ratchet, - announce_name_hash, - announce_identity_hash, - announce_random_hash, - ) = { - if data_offset >= raw.len() { - tracing::warn!( - dest = hex::encode(header.destination_hash), - "announce missing payload, dropping" - ); - return; - } - - let payload = &raw[data_offset..]; - let has_ratchet = header.flags.context_flag; - tracing::debug!( - dest = hex::encode(header.destination_hash), - payload_len = payload.len(), - has_ratchet = has_ratchet, - header_type = ?header.flags.header_type, - "announce payload received" - ); - match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) { - Ok(announce_data) => { - tracing::debug!( - dest = hex::encode(header.destination_hash), - app_data_len = announce_data.app_data.as_ref().map(|d| d.len()), - has_ratchet_key = announce_data.ratchet.is_some(), - "announce unpacked" - ); - let known_public_key = self - .recent_announces - .get(&header.destination_hash) - .and_then(|entry| entry.public_key); - match announce_data.validate_with_known_key( - &header.destination_hash, - known_public_key.as_ref(), - ) { - Ok(validated_identity) => { - if self.blackhole_table.is_blackholed(&validated_identity.hash) { - trace!( - identity = hex::encode(validated_identity.hash), - dest = hex::encode(header.destination_hash), - "announce from blackholed identity, dropping" - ); - return; - } - - tracing::debug!( - dest = hex::encode(header.destination_hash), - app_data_present = announce_data.app_data.is_some(), - "announce validated" - ); - ( - announce_data.app_data.clone(), - Some(validated_identity.get_public_key()), - announce_data.ratchet, - announce_data.name_hash, - Some(validated_identity.hash), - announce_data.random_hash, - ) - } - Err(e) => { - tracing::warn!( - dest = hex::encode(header.destination_hash), - payload_len = payload.len(), - error = %e, - "announce validation failed, dropping" - ); - return; - } - } - } - Err(e) => { - tracing::warn!( - dest = hex::encode(header.destination_hash), - payload_len = payload.len(), - has_ratchet = has_ratchet, - error = %e, - "announce unpack failed, dropping" - ); - return; - } - } - }; - let iface_mode = self .interfaces .get(&interface_id) @@ -419,8 +421,23 @@ impl TransportActor { entry.random_blobs = random_blobs; // Store the announce packet hash so a later CacheRequest for this // destination can replay the exact announce bytes. - entry.packet_hash = Some(rns_wire::hash::packet_hash(raw, header.flags.header_type)); + let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + entry.packet_hash = Some(announce_packet_hash); + let tunnel_path = crate::tunnel::TunnelPath { + timestamp: entry.timestamp, + next_hop: entry.next_hop, + hops: entry.hops, + expires: entry.expires, + random_blobs: entry.random_blobs.iter().copied().collect(), + packet_hash: entry.packet_hash, + }; self.path_table.insert(header.destination_hash, entry); + if let Some(tunnel) = self.tunnel_table.get_mut_by_interface(interface_id) { + tunnel + .tunnel_paths + .insert(header.destination_hash, tunnel_path); + tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64; + } self.state_dirty = true; // Wake any callers waiting on a path for this destination. self.fire_path_waiters(&header.destination_hash); @@ -926,7 +943,9 @@ impl TransportActor { .get(&header.destination_hash) .is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface)); - if let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash) { + if header.context != rns_wire::context::PacketContext::Lrproof + && let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash) + { let rtt = receipt .get_rtt() .or_else(|| Some(receipt.sent_at.elapsed())); @@ -971,12 +990,24 @@ impl TransportActor { let expected_hops = link_entry.remaining_hops; let outbound_interface = link_entry.interface_id; let target_interface = link_entry.receiving_interface; + let destination_hash = link_entry.destination_hash; // Require that the proof arrived on the same interface we // forwarded the request to; a mismatch is either a routing // change or a spoof and must not be relayed. let hops_match = header.hops == expected_hops; if hops_match && _interface_id == outbound_interface { + if !self.validate_transit_lrproof(raw, header, link_entry) { + return; + } + let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + if !self.packet_hashlist.insert(pkt_hash) { + trace!( + link_id = hex::encode(header.destination_hash), + "duplicate LRPROOF dropped after link-table claim" + ); + return; + } let mut forwarded = raw.to_vec(); if forwarded.len() >= 2 { forwarded[1] = header.hops; @@ -985,6 +1016,9 @@ impl TransportActor { entry.validated = true; } self.send_to_interface(target_interface, &forwarded); + if !self.is_shared_instance { + self.use_destination(&destination_hash); + } debug!( link_id = hex::encode(header.destination_hash), via_interface = target_interface, @@ -1013,13 +1047,18 @@ impl TransportActor { // Fall through to local-pending-link delivery when link_table // didn't claim the proof. if let Some(tx) = self.destination_channels.get(&header.destination_hash) { - if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { - raw: raw.clone(), - interface_id: _interface_id, - }) { + let delivered = + tx.try_send(crate::link_messages::DestinationEvent::InboundPacket { + raw: raw.clone(), + interface_id: _interface_id, + }); + if let Err(e) = delivered { self.channel_drops += 1; warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e, "failed to deliver LRPROOF to local pending link (channel full)"); + } else { + let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + self.packet_hashlist.insert(pkt_hash); } } return; @@ -1162,6 +1201,25 @@ impl TransportActor { if forwarded.len() >= 2 { forwarded[1] = header.hops; } + let skip_hashlist = matches!( + header.context, + rns_wire::context::PacketContext::Keepalive + | rns_wire::context::PacketContext::Resource + | rns_wire::context::PacketContext::ResourceReq + | rns_wire::context::PacketContext::ResourcePrf + | rns_wire::context::PacketContext::CacheRequest + | rns_wire::context::PacketContext::Channel + ); + if !skip_hashlist { + let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type); + if !self.packet_hashlist.insert(pkt_hash) { + trace!( + link_id = hex::encode(header.destination_hash), + packet_kind, "duplicate link-table packet dropped after claim" + ); + return true; + } + } if let Some(entry) = self.link_table.get_mut(&header.destination_hash) { entry.timestamp = now_f64(); } @@ -1175,4 +1233,86 @@ impl TransportActor { ); true } + + fn validate_transit_lrproof( + &self, + raw: &[u8], + header: &rns_wire::header::PacketHeader, + link_entry: &crate::link_table::LinkEntry, + ) -> bool { + let payload_offset = header.size(); + if raw.len() < payload_offset { + warn!( + link_id = hex::encode(header.destination_hash), + raw_len = raw.len(), + "link proof missing payload, not transporting" + ); + return false; + } + + let proof_data = &raw[payload_offset..]; + if proof_data.len() != 96 && proof_data.len() != 99 { + warn!( + link_id = hex::encode(header.destination_hash), + proof_len = proof_data.len(), + "malformed link request proof length, not transporting" + ); + return false; + } + + let mut signature = [0u8; 64]; + signature.copy_from_slice(&proof_data[..64]); + let responder_x25519_pub = &proof_data[64..96]; + let signalling = if proof_data.len() == 99 { + &proof_data[96..99] + } else { + &[] + }; + + let Some(destination_public_key) = self + .recent_announces + .get(&link_entry.destination_hash) + .and_then(|announce| announce.public_key) + else { + warn!( + link_id = hex::encode(header.destination_hash), + destination = hex::encode(link_entry.destination_hash), + "link request proof has no known destination identity, not transporting" + ); + return false; + }; + + let mut destination_ed25519 = [0u8; 32]; + destination_ed25519.copy_from_slice(&destination_public_key[32..64]); + let verify_key = + match rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&destination_ed25519) { + Ok(key) => key, + Err(err) => { + warn!( + link_id = hex::encode(header.destination_hash), + destination = hex::encode(link_entry.destination_hash), + error = %err, + "link request proof destination identity is invalid, not transporting" + ); + return false; + } + }; + + let mut signed_data = Vec::with_capacity(16 + 32 + 32 + signalling.len()); + signed_data.extend_from_slice(&header.destination_hash); + signed_data.extend_from_slice(responder_x25519_pub); + signed_data.extend_from_slice(&destination_ed25519); + signed_data.extend_from_slice(signalling); + + if verify_key.verify(&signed_data, &signature).is_ok() { + true + } else { + warn!( + link_id = hex::encode(header.destination_hash), + destination = hex::encode(link_entry.destination_hash), + "invalid link request proof signature, not transporting" + ); + false + } + } } diff --git a/crates/rns-transport/src/actor/maintenance.rs b/crates/rns-transport/src/actor/maintenance.rs index 74d3591..04d01b4 100644 --- a/crates/rns-transport/src/actor/maintenance.rs +++ b/crates/rns-transport/src/actor/maintenance.rs @@ -30,6 +30,7 @@ impl TransportActor { self.path_table.cull_expired_batch(100); self.reverse_table.cull_expired_batch(100); self.tunnel_table.cull_expired_batch(50); + self.cull_stale_tunnel_paths(now); // Drop entries pointing to interfaces that have gone away — // those routes could never be used anyway. @@ -429,6 +430,42 @@ impl TransportActor { } } + pub(super) fn cull_stale_tunnel_paths(&mut self, now: f64) { + let mut removed = 0usize; + for (tunnel_id, tunnel) in self.tunnel_table.iter_mut() { + let stale: Vec<[u8; 16]> = tunnel + .tunnel_paths + .iter() + .filter_map(|(dest_hash, tunnel_path)| { + if now > tunnel_path.timestamp + TUNNEL_PATH_TIMEOUT as f64 { + return Some(*dest_hash); + } + + let active = self.path_table.get(dest_hash)?; + let current_timebase = + path_timebase_from_random_blobs(active.random_blobs.iter()); + let tunnel_timebase = + path_timebase_from_random_blobs(tunnel_path.random_blobs.iter()); + (current_timebase > tunnel_timebase).then_some(*dest_hash) + }) + .collect(); + + for dest_hash in stale { + tunnel.tunnel_paths.remove(&dest_hash); + removed += 1; + debug!( + dest = hex::encode(dest_hash), + tunnel = hex::encode(&tunnel_id[..16]), + "removed stale tunnel path" + ); + } + } + + if removed > 0 { + self.state_dirty = true; + } + } + /// Sweep `recent_announces`. Keep retained + pathed entries; reap the /// rest past `DESTINATION_TIMEOUT` (7 days). No count cap. pub(super) fn cleanup_known_destinations(&mut self, now: f64) { diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 6bc36d5..c6c35e6 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -1359,6 +1359,18 @@ mod tests { } fn make_link_data_packet(link_id: [u8; 16], hops: u8) -> Bytes { + make_link_data_packet_with_context( + link_id, + hops, + rns_wire::context::PacketContext::Resource, + ) + } + + fn make_link_data_packet_with_context( + link_id: [u8; 16], + hops: u8, + context: rns_wire::context::PacketContext, + ) -> Bytes { let flags = rns_wire::flags::PacketFlags { header_type: rns_wire::flags::HeaderType::Header1, context_flag: false, @@ -1371,7 +1383,7 @@ mod tests { hops, transport_id: None, destination_hash: link_id, - context: rns_wire::context::PacketContext::Resource, + context, }; let mut raw = header.pack(); raw.extend_from_slice(&[0xDA; 32]); @@ -1634,9 +1646,11 @@ mod tests { dest, crate::tunnel::TunnelPath { timestamp: now_f64(), + next_hop: None, hops: 2, expires: now_f64() + 600.0, random_blobs: vec![], + packet_hash: None, }, ); actor.tunnel_table.insert(crate::tunnel::TunnelEntry { @@ -1990,7 +2004,7 @@ mod tests { assert_eq!(forwarded_header.transport_id, None); } - fn make_lrproof_packet(link_id: [u8; 16], hops: u8) -> Bytes { + fn make_lrproof_packet_with_payload(link_id: [u8; 16], hops: u8, payload: &[u8]) -> Bytes { let flags = rns_wire::flags::PacketFlags { header_type: rns_wire::flags::HeaderType::Header1, context_flag: false, @@ -2006,11 +2020,39 @@ mod tests { context: rns_wire::context::PacketContext::Lrproof, }; let mut raw = header.pack(); - // Add fake proof data (signature + peer pubkey) - raw.extend_from_slice(&[0xAA; 96]); + raw.extend_from_slice(payload); Bytes::from(raw) } + fn make_lrproof_packet( + link_id: [u8; 16], + hops: u8, + destination_identity: &rns_identity::identity::Identity, + signalling: Option<[u8; 3]>, + ) -> Bytes { + let destination_public_key = destination_identity.get_public_key(); + let mut destination_ed25519 = [0u8; 32]; + destination_ed25519.copy_from_slice(&destination_public_key[32..64]); + let responder_x25519_pub = [0x42; 32]; + + let mut signed_data = Vec::new(); + signed_data.extend_from_slice(&link_id); + signed_data.extend_from_slice(&responder_x25519_pub); + signed_data.extend_from_slice(&destination_ed25519); + if let Some(signalling) = signalling { + signed_data.extend_from_slice(&signalling); + } + let signature = destination_identity.sign(&signed_data).unwrap(); + + let mut payload = Vec::new(); + payload.extend_from_slice(&signature); + payload.extend_from_slice(&responder_x25519_pub); + if let Some(signalling) = signalling { + payload.extend_from_slice(&signalling); + } + make_lrproof_packet_with_payload(link_id, hops, &payload) + } + #[test] fn test_lrproof_routing_through_relay() { // LRPROOF travels back up the link-table chain toward the initiator. @@ -2029,12 +2071,15 @@ mod tests { // Create a link_table entry as if the relay forwarded a LINKREQUEST // from interface 1 (initiator side) to interface 2 (destination side) let link_id = [0x77; 16]; + let destination_hash = [0xCC; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut relay, destination_hash, &destination_identity); let link_entry = crate::link_table::LinkEntry { timestamp: now_f64(), next_hop: Some([0xBB; 16]), interface_id: 2, // next-hop interface (toward destination) remaining_hops: 1, // 1 hop from relay to destination - destination_hash: [0xCC; 16], + destination_hash, established: false, validated: false, proof_timeout: now_f64() + 120.0, @@ -2045,7 +2090,7 @@ mod tests { // Destination sends LRPROOF with hops=0 (new proof, not incremented). // Proof arrives at relay on interface 2 (the destination side). - let proof = make_lrproof_packet(link_id, 0); + let proof = make_lrproof_packet(link_id, 0, &destination_identity, Some([1, 0, 0])); relay.on_inbound(InboundPacket { raw: proof, interface_id: 2, // arrived from destination side @@ -2087,6 +2132,9 @@ mod tests { relay.interfaces.insert(2, entry2); let link_id = [0x79; 16]; + let destination_hash = [0xCD; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut relay, destination_hash, &destination_identity); relay.link_table.insert( link_id, crate::link_table::LinkEntry { @@ -2094,7 +2142,7 @@ mod tests { next_hop: None, interface_id: 2, remaining_hops: 1, - destination_hash: [0xCD; 16], + destination_hash, established: false, validated: false, proof_timeout: now_f64() + 120.0, @@ -2103,7 +2151,7 @@ mod tests { }, ); - let proof = make_lrproof_packet(link_id, 0); + let proof = make_lrproof_packet(link_id, 0, &destination_identity, None); relay.on_inbound(InboundPacket { raw: proof, interface_id: 2, @@ -2122,6 +2170,150 @@ mod tests { assert!(relay.link_table.get(&link_id).unwrap().validated); } + #[test] + fn test_lrproof_transit_rejects_invalid_signature() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x7C; 16]; + let destination_hash = [0xDC; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut relay, destination_hash, &destination_identity); + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 1, + destination_hash, + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + let mut proof = + make_lrproof_packet(link_id, 0, &destination_identity, Some([4, 5, 6])).to_vec(); + let last = proof.len() - 1; + proof[last] ^= 0x01; + relay.on_inbound(InboundPacket { + raw: Bytes::from(proof), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + assert!( + rx1.try_recv().is_err(), + "invalid LRPROOF must not be forwarded" + ); + assert!( + !relay.link_table.get(&link_id).unwrap().validated, + "invalid LRPROOF must not mark link-table entry validated" + ); + } + + #[test] + fn test_lrproof_transit_requires_known_destination_identity() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x7D; 16]; + let destination_hash = [0xDD; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 1, + destination_hash, + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + relay.on_inbound(InboundPacket { + raw: make_lrproof_packet(link_id, 0, &destination_identity, None), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + assert!( + rx1.try_recv().is_err(), + "LRPROOF without known destination identity must not be forwarded" + ); + assert!(!relay.link_table.get(&link_id).unwrap().validated); + } + + #[test] + fn test_lrproof_transit_rejects_malformed_lengths() { + for (idx, payload_len) in [95usize, 97, 98, 100].into_iter().enumerate() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, mut rx1) = make_test_interface("to_initiator"); + let (entry2, _rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let mut link_id = [0x7E; 16]; + link_id[15] = idx as u8; + let destination_hash = [0xDE; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut relay, destination_hash, &destination_identity); + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 1, + destination_hash, + established: false, + validated: false, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 0, + }, + ); + + relay.on_inbound(InboundPacket { + raw: make_lrproof_packet_with_payload(link_id, 0, &vec![0xAA; payload_len]), + interface_id: 2, + rssi: None, + snr: None, + q: None, + }); + + assert!( + rx1.try_recv().is_err(), + "malformed LRPROOF length {payload_len} must not be forwarded" + ); + assert!(!relay.link_table.get(&link_id).unwrap().validated); + } + } + #[test] fn test_link_data_routes_via_link_table_both_directions() { let (mut relay, _tx) = TransportActor::new(); @@ -2174,6 +2366,67 @@ mod tests { assert_eq!(to_initiator[1], 1); } + #[test] + fn test_link_table_forwarding_inserts_hash_after_claim() { + let (mut relay, _tx) = TransportActor::new(); + relay.is_transport_enabled = true; + + let (entry1, _rx1) = make_test_interface("to_initiator"); + let (entry2, mut rx2) = make_test_interface("to_destination"); + relay.interfaces.insert(1, entry1); + relay.interfaces.insert(2, entry2); + + let link_id = [0x7F; 16]; + relay.link_table.insert( + link_id, + crate::link_table::LinkEntry { + timestamp: now_f64(), + next_hop: None, + interface_id: 2, + remaining_hops: 1, + destination_hash: [0xDF; 16], + established: true, + validated: true, + proof_timeout: now_f64() + 120.0, + receiving_interface: 1, + taken_hops: 1, + }, + ); + + let raw = + make_link_data_packet_with_context(link_id, 0, rns_wire::context::PacketContext::None); + let packet_hash = rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header1); + assert!( + !relay.packet_hashlist.contains(&packet_hash), + "link-table packets must not be inserted before routing claims them" + ); + + relay.on_inbound(InboundPacket { + raw: raw.clone(), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!( + relay.packet_hashlist.contains(&packet_hash), + "claimed link-table packet hash must be inserted after forwarding" + ); + rx2.try_recv().expect("first link packet should forward"); + + relay.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!( + rx2.try_recv().is_err(), + "duplicate link-table packet should be dropped after hash insertion" + ); + } + #[test] fn test_link_proof_routes_via_link_table() { let (mut relay, _tx) = TransportActor::new(); @@ -2230,6 +2483,9 @@ mod tests { relay_b.interfaces.insert(2, entry_b2); let link_id = [0x88; 16]; + let destination_hash = [0xEE; 16]; + let destination_identity = rns_identity::identity::Identity::new(); + insert_announce_for(&mut relay_b, destination_hash, &destination_identity); relay_b.link_table.insert( link_id, crate::link_table::LinkEntry { @@ -2237,7 +2493,7 @@ mod tests { next_hop: Some([0xDD; 16]), interface_id: 2, // toward destination remaining_hops: 1, - destination_hash: [0xEE; 16], + destination_hash, established: false, validated: false, proof_timeout: now_f64() + 120.0, @@ -2255,6 +2511,7 @@ mod tests { relay_a.interfaces.insert(1, entry_a1); relay_a.interfaces.insert(2, entry_a2); + insert_announce_for(&mut relay_a, destination_hash, &destination_identity); relay_a.link_table.insert( link_id, crate::link_table::LinkEntry { @@ -2262,7 +2519,7 @@ mod tests { next_hop: Some([0xCC; 16]), interface_id: 2, // toward RelayB remaining_hops: 2, - destination_hash: [0xEE; 16], + destination_hash, established: false, validated: false, proof_timeout: now_f64() + 120.0, @@ -2273,7 +2530,7 @@ mod tests { // Proof travels back: Destination → RelayB → RelayA. // Destination sends proof with hops=0. - let proof = make_lrproof_packet(link_id, 0); + let proof = make_lrproof_packet(link_id, 0, &destination_identity, Some([1, 2, 3])); relay_b.on_inbound(InboundPacket { raw: proof, interface_id: 2, // from destination @@ -3401,6 +3658,174 @@ mod tests { assert_eq!(path.interface_id, 1); } + #[test] + fn test_tunnel_learned_header2_announce_records_full_metadata() { + let (mut actor, _tx) = TransportActor::new(); + let (entry1, _rx1) = make_test_interface("iface1"); + actor.interfaces.insert(1, entry1); + + let tunnel_id = [0x31; 32]; + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 1, + tunnel_paths: std::collections::HashMap::new(), + expires: now_f64() + 600.0, + }); + + let transport_id = [0xAA; 16]; + let (raw, dest_hash, _identity) = + make_header2_announce(transport_id, "test.tunnel.h2announce", 2); + let expected_packet_hash = + rns_wire::hash::packet_hash(&raw, rns_wire::flags::HeaderType::Header2); + + actor.on_inbound(InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + let tunnel = actor.tunnel_table.get(&tunnel_id).unwrap(); + let tunnel_path = tunnel.tunnel_paths.get(&dest_hash).unwrap(); + assert_eq!(tunnel_path.next_hop, Some(transport_id)); + assert_eq!(tunnel_path.hops, 3); + assert_eq!(tunnel_path.packet_hash, Some(expected_packet_hash)); + assert!( + !tunnel_path.random_blobs.is_empty(), + "tunnel path must preserve announce random blobs for freshness comparisons" + ); + } + + #[test] + fn test_restore_tunnel_path_preserves_next_hop_and_packet_hash() { + let (mut actor, _tx) = TransportActor::new(); + + let tunnel_id = [0x32; 32]; + let dest_hash = [0x44; 16]; + let next_hop = [0x55; 16]; + let packet_hash = [0x66; 32]; + let random_blob = random_blob(0x77, 100); + let mut tunnel_paths = std::collections::HashMap::new(); + tunnel_paths.insert( + dest_hash, + crate::tunnel::TunnelPath { + timestamp: now_f64(), + next_hop: Some(next_hop), + hops: 4, + expires: now_f64() + 600.0, + random_blobs: vec![random_blob], + packet_hash: Some(packet_hash), + }, + ); + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 0, + tunnel_paths, + expires: now_f64() + 600.0, + }); + + actor.restore_tunnel_paths(&tunnel_id, 9); + + let restored = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(restored.next_hop, Some(next_hop)); + assert_eq!(restored.packet_hash, Some(packet_hash)); + assert_eq!(restored.interface_id, 9); + assert!(restored.has_random_blob(&random_blob)); + } + + #[test] + fn test_restore_tunnel_path_drops_older_than_active_path() { + let (mut actor, _tx) = TransportActor::new(); + + let tunnel_id = [0x33; 32]; + let dest_hash = [0x45; 16]; + let mut active = crate::path_table::PathEntry::new(None, 4, 1, InterfaceMode::Gateway); + let active_blob = random_blob(0x80, 200); + active.add_random_blob(active_blob); + actor.path_table.insert(dest_hash, active); + + let tunnel_blob = random_blob(0x81, 100); + let mut tunnel_paths = std::collections::HashMap::new(); + tunnel_paths.insert( + dest_hash, + crate::tunnel::TunnelPath { + timestamp: now_f64(), + next_hop: Some([0x99; 16]), + hops: 4, + expires: now_f64() + 600.0, + random_blobs: vec![tunnel_blob], + packet_hash: Some([0x88; 32]), + }, + ); + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 0, + tunnel_paths, + expires: now_f64() + 600.0, + }); + + actor.restore_tunnel_paths(&tunnel_id, 9); + + let active_after = actor.path_table.get(&dest_hash).unwrap(); + assert_eq!(active_after.interface_id, 1); + assert!(active_after.has_random_blob(&active_blob)); + assert!( + actor + .tunnel_table + .get(&tunnel_id) + .unwrap() + .tunnel_paths + .get(&dest_hash) + .is_none(), + "older tunnel path should be pruned after losing freshness comparison" + ); + } + + #[test] + fn test_maintenance_culls_stale_tunnel_paths() { + let (mut actor, _tx) = TransportActor::new(); + + let tunnel_id = [0x34; 32]; + let stale_dest = [0x46; 16]; + let fresh_dest = [0x47; 16]; + let mut tunnel_paths = std::collections::HashMap::new(); + tunnel_paths.insert( + stale_dest, + crate::tunnel::TunnelPath { + timestamp: now_f64() - TUNNEL_PATH_TIMEOUT as f64 - 1.0, + next_hop: None, + hops: 1, + expires: now_f64() + 600.0, + random_blobs: vec![], + packet_hash: Some([0x46; 32]), + }, + ); + tunnel_paths.insert( + fresh_dest, + crate::tunnel::TunnelPath { + timestamp: now_f64(), + next_hop: None, + hops: 1, + expires: now_f64() + 600.0, + random_blobs: vec![], + packet_hash: Some([0x47; 32]), + }, + ); + actor.tunnel_table.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 1, + tunnel_paths, + expires: now_f64() + 600.0, + }); + + actor.cull_stale_tunnel_paths(now_f64()); + + let tunnel = actor.tunnel_table.get(&tunnel_id).unwrap(); + assert!(!tunnel.tunnel_paths.contains_key(&stale_dest)); + assert!(tunnel.tunnel_paths.contains_key(&fresh_dest)); + } + #[test] fn test_header1_announce_learns_path_no_next_hop() { let (mut actor, _tx) = TransportActor::new(); @@ -4326,6 +4751,172 @@ mod tests { ); } + #[test] + fn test_invalid_announces_do_not_trip_ingress_hold() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry_in, _rx_in) = make_test_interface("invalid_flood_iface"); + actor.interfaces.insert(1, entry_in); + + for _ in 0..50 { + let (raw, _dest) = make_valid_announce("test.invalid.flood", 1); + let mut raw = raw.to_vec(); + let last = raw.len() - 1; + raw[last] ^= 0x01; + actor.on_inbound(crate::messages::InboundPacket { + raw: Bytes::from(raw), + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + + let entry = actor.interfaces.get(&1).unwrap(); + assert!( + !entry.ingress.is_burst_active(), + "signature-invalid announces must be dropped before ingress accounting" + ); + assert_eq!(entry.ingress.held_count(), 0); + assert_eq!(actor.path_table.iter().count(), 0); + } + + #[test] + fn test_known_reannounce_bypasses_ingress_hold() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry_in, _rx_in) = make_test_interface("known_reannounce_iface"); + actor.interfaces.insert(1, entry_in); + + let identity = rns_identity::identity::Identity::new(); + let old_blob = random_blob(0x91, 10); + let (first_raw, dest_hash) = + make_announce_for_with_random_blob(&identity, "test.known.ingress", 1, old_blob); + actor.on_inbound(crate::messages::InboundPacket { + raw: first_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!(actor.path_table.has_path(&dest_hash)); + + for _ in 0..50 { + let (raw, _dest) = make_valid_announce("test.known.flood", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + let held_before = actor.interfaces.get(&1).unwrap().ingress.held_count(); + assert!(actor.interfaces.get(&1).unwrap().ingress.is_burst_active()); + + let new_blob = random_blob(0x92, 11); + let (reannounce_raw, _) = + make_announce_for_with_random_blob(&identity, "test.known.ingress", 1, new_blob); + actor.on_inbound(crate::messages::InboundPacket { + raw: reannounce_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + + assert_eq!( + actor.interfaces.get(&1).unwrap().ingress.held_count(), + held_before, + "known re-announces must not be held during ingress burst" + ); + assert!( + actor + .path_table + .get(&dest_hash) + .unwrap() + .has_random_blob(&new_blob), + "known re-announce must refresh the active path" + ); + } + + #[test] + fn test_known_path_response_bypasses_ingress_hold_but_unknown_is_held() { + let (mut actor, _tx) = TransportActor::new(); + actor.is_transport_enabled = true; + + let (entry_in, _rx_in) = make_test_interface("path_response_ingress_iface"); + actor.interfaces.insert(1, entry_in); + + let identity = rns_identity::identity::Identity::new(); + let (first_raw, known_dest) = make_announce_for(&identity, "test.known.path_response", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw: first_raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!(actor.path_table.has_path(&known_dest)); + + for _ in 0..50 { + let (raw, _dest) = make_valid_announce("test.path_response.flood", 1); + actor.on_inbound(crate::messages::InboundPacket { + raw, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + } + assert!(actor.interfaces.get(&1).unwrap().ingress.is_burst_active()); + let held_before = actor.interfaces.get(&1).unwrap().ingress.held_count(); + + let (known_response, _) = make_announce_for_context( + &identity, + "test.known.path_response", + 1, + rns_wire::context::PacketContext::PathResponse, + ); + actor.on_inbound(crate::messages::InboundPacket { + raw: known_response, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert_eq!( + actor.interfaces.get(&1).unwrap().ingress.held_count(), + held_before, + "known path responses must not be held during ingress burst" + ); + + let other_identity = rns_identity::identity::Identity::new(); + let (unknown_response, unknown_dest) = make_announce_for_context( + &other_identity, + "test.unknown.path_response", + 1, + rns_wire::context::PacketContext::PathResponse, + ); + actor.on_inbound(crate::messages::InboundPacket { + raw: unknown_response, + interface_id: 1, + rssi: None, + snr: None, + q: None, + }); + assert!( + actor.interfaces.get(&1).unwrap().ingress.held_count() > held_before, + "unsolicited unknown path responses remain subject to ingress hold" + ); + assert!( + !actor.path_table.has_path(&unknown_dest), + "held unknown path response must not install a route immediately" + ); + } + /// `broadcast_announce_on_interfaces` must enqueue rather than send /// directly, and `process_announce_queues` must drain one entry per /// gate-open while pushing `announce_allowed_at` forward by the @@ -4548,9 +5139,11 @@ mod tests { dest_hash, crate::tunnel::TunnelPath { timestamp: now_f64(), + next_hop: None, hops: 2, expires: now_f64() + 600.0, random_blobs: vec![], + packet_hash: None, }, ); diff --git a/crates/rns-transport/src/actor/outbound.rs b/crates/rns-transport/src/actor/outbound.rs index d2f1389..a6e11e8 100644 --- a/crates/rns-transport/src/actor/outbound.rs +++ b/crates/rns-transport/src/actor/outbound.rs @@ -650,10 +650,19 @@ impl TransportActor { if let Some(existing) = self.path_table.get(dest_hash) { let old_hops = existing.hops; let old_expires = existing.expires; - // Only overwrite a live path if the tunnel copy is at least - // as short, or the live entry is already stale. if tunnel_path.hops <= old_hops || now > old_expires { - should_add = true; + let current_timebase = + path_timebase_from_random_blobs(existing.random_blobs.iter()); + let tunnel_timebase = + path_timebase_from_random_blobs(tunnel_path.random_blobs.iter()); + if tunnel_timebase >= current_timebase { + should_add = true; + } else { + debug!( + dest = hex::encode(dest_hash), + "did not restore tunnel path: existing path is more recent" + ); + } } else { debug!( dest = hex::encode(dest_hash), @@ -672,12 +681,12 @@ impl TransportActor { if should_add { let entry = crate::path_table::PathEntry { timestamp: now, - next_hop: None, + next_hop: tunnel_path.next_hop, hops: tunnel_path.hops, expires: tunnel_path.expires, random_blobs: tunnel_path.random_blobs.iter().copied().collect(), interface_id, - packet_hash: None, + packet_hash: tunnel_path.packet_hash, }; self.path_table.insert(*dest_hash, entry); self.state_dirty = true; @@ -703,6 +712,7 @@ impl TransportActor { ); } } + self.state_dirty = true; } } } diff --git a/crates/rns-transport/src/actor/persistence.rs b/crates/rns-transport/src/actor/persistence.rs index 186bceb..3ff4243 100644 --- a/crates/rns-transport/src/actor/persistence.rs +++ b/crates/rns-transport/src/actor/persistence.rs @@ -10,6 +10,42 @@ fn now() -> f64 { .unwrap_or(0.0) } +fn recent_announce_from_cached_packet( + dest_hash: [u8; 16], + hops: u8, + timestamp: f64, + raw_packet: Vec, +) -> RecentAnnounce { + let mut recent = RecentAnnounce { + dest_hash, + hops, + app_data: None, + timestamp, + public_key: None, + ratchet: None, + raw_packet, + retained: false, + name_hash: [0u8; 10], + }; + + if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&recent.raw_packet) + && header.flags.packet_type == rns_wire::flags::PacketType::Announce + && header.destination_hash == dest_hash + && recent.raw_packet.len() >= offset + && let Ok(announce) = rns_identity::announce::AnnounceData::unpack( + &recent.raw_packet[offset..], + header.flags.context_flag, + ) + { + recent.app_data = announce.app_data; + recent.public_key = Some(announce.public_key); + recent.ratchet = announce.ratchet; + recent.name_hash = announce.name_hash; + } + + recent +} + impl TransportActor { /// Flush the small/critical routing-state files: path_table, /// announce_cache, blackhole_table, tunnel_table. Hashlist is excluded — @@ -84,8 +120,9 @@ impl TransportActor { } let announce_cache_dir = dir.join("cache").join("announces"); - if let Err(e) = crate::persistence::save_python_announce_cache_for_paths( + if let Err(e) = crate::persistence::save_python_announce_cache_for_paths_and_tunnels( &self.path_table, + Some(&self.tunnel_table), self.recent_announces.values(), &interface_names, &announce_cache_dir, @@ -104,6 +141,15 @@ impl TransportActor { debug!("saved tunnel table ({} entries)", self.tunnel_table.len()); } + let python_tunnels_path = dir.join("tunnels"); + if let Err(e) = crate::persistence::save_python_tunnel_table( + &self.tunnel_table, + &interface_names, + &python_tunnels_path, + ) { + trace!("failed to save Python tunnels table: {}", e); + } + // Single-line summary for diagnosing periodic routing-state saves // without surfacing normal flushes at default log levels. debug!( @@ -229,16 +275,13 @@ impl TransportActor { }); self.recent_announces .entry(pe.destination_hash) - .or_insert_with(|| RecentAnnounce { - dest_hash: pe.destination_hash, - hops: pe.hops, - app_data: None, - timestamp: pe.timestamp, - public_key: None, - ratchet: None, - raw_packet: cached.raw_packet, - retained: false, - name_hash: [0u8; 10], + .or_insert_with(|| { + recent_announce_from_cached_packet( + pe.destination_hash, + pe.hops, + pe.timestamp, + cached.raw_packet, + ) }); pending += 1; } @@ -323,9 +366,119 @@ impl TransportActor { } self.load_python_blackhole_if_ready(); - // tunnel_table — defer remap. + // Python tunnels — canonical interop shape. Each path is only staged + // when its cached announce packet is present, mirroring upstream's + // dependency between tunnel paths and the announce cache. + let python_tunnels_path = dir.join("tunnels"); + let loaded_python_tunnel_table = if python_tunnels_path.exists() { + match crate::persistence::load_python_tunnel_table(&python_tunnels_path) { + Ok(entries) => { + let total = entries.len(); + let mut expired = 0usize; + let mut missing_cache = 0usize; + let mut legacy = 0usize; + let mut pending = 0usize; + let announce_cache_dir = dir.join("cache").join("announces"); + for te in entries { + if te.expires <= now_ts { + expired += 1; + continue; + } + + let mut paths = Vec::new(); + let mut interface_name = None; + let mut interface_hash = + te.interface_hash.as_ref().map(|hash| hash.to_vec()); + + for tp in te.paths { + if tp.expires <= now_ts { + expired += 1; + continue; + } + if interface_hash.is_none() { + interface_hash = + tp.interface_hash.as_ref().map(|hash| hash.to_vec()); + } + let cached = match crate::persistence::load_python_cached_announce( + &announce_cache_dir, + &tp.packet_hash, + ) { + Ok(Some(cached)) => cached, + Ok(None) | Err(_) => { + missing_cache += 1; + continue; + } + }; + if interface_name.is_none() { + interface_name = cached.interface_reference.clone(); + } + let next_hop = if tp.received_from == tp.destination_hash { + None + } else { + Some(tp.received_from.to_vec()) + }; + paths.push(crate::persistence::PersistedTunnelPath { + destination_hash: tp.destination_hash.to_vec(), + next_hop, + hops: tp.hops, + expires: tp.expires, + timestamp: tp.timestamp, + random_blobs: tp + .random_blobs + .iter() + .map(|blob| blob.to_vec()) + .collect(), + packet_hash: Some(tp.packet_hash.to_vec()), + }); + self.recent_announces + .entry(tp.destination_hash) + .or_insert_with(|| { + recent_announce_from_cached_packet( + tp.destination_hash, + tp.hops, + tp.timestamp, + cached.raw_packet, + ) + }); + } + + if paths.is_empty() { + continue; + } + if interface_name.is_none() && interface_hash.is_none() { + legacy += 1; + continue; + } + self.pending_tunnel_entries.push( + crate::persistence::PersistedTunnelEntry { + tunnel_id: te.tunnel_id.to_vec(), + interface_id: 0, + expires: te.expires, + paths, + interface_name, + interface_hash, + }, + ); + pending += 1; + } + debug!( + total, + pending, expired, missing_cache, legacy, "staged Python tunnel entries" + ); + pending > 0 + } + Err(e) => { + trace!("failed to load Python tunnels table: {}", e); + false + } + } + } else { + false + }; + + // tunnel_table — legacy Rust sidecar fallback, defer remap. let tunnel_path = dir.join("tunnel_table.msgpack"); - if tunnel_path.exists() { + if !loaded_python_tunnel_table && tunnel_path.exists() { match crate::persistence::load_tunnel_table(&tunnel_path) { Ok(entries) => { let total = entries.len(); @@ -340,7 +493,7 @@ impl TransportActor { expired += 1; continue; } - if te.interface_name.is_none() { + if te.interface_name.is_none() && te.interface_hash.is_none() { legacy += 1; continue; } @@ -535,7 +688,11 @@ impl TransportActor { if !self.pending_tunnel_entries.is_empty() { let mut promoted = 0usize; self.pending_tunnel_entries.retain(|te| { - if te.interface_name.as_deref() != Some(name) { + let name_matches = te.interface_name.as_deref() == Some(name); + let hash_matches = te.interface_hash.as_deref().is_some_and(|hash| { + hash == crate::persistence::interface_hash_from_name(name).as_slice() + }); + if !name_matches && !hash_matches { return true; } if te.tunnel_id.len() != 32 { @@ -548,13 +705,46 @@ impl TransportActor { if tp.destination_hash.len() == 16 { let mut dest = [0u8; 16]; dest.copy_from_slice(&tp.destination_hash); + let next_hop = tp.next_hop.as_ref().and_then(|next_hop| { + if next_hop.len() == 16 { + let mut arr = [0u8; 16]; + arr.copy_from_slice(next_hop); + Some(arr) + } else { + None + } + }); + let packet_hash = tp.packet_hash.as_ref().and_then(|packet_hash| { + if packet_hash.len() == 32 { + let mut arr = [0u8; 32]; + arr.copy_from_slice(packet_hash); + Some(arr) + } else { + None + } + }); + let random_blobs = tp + .random_blobs + .iter() + .filter_map(|blob| { + if blob.len() == 10 { + let mut arr = [0u8; 10]; + arr.copy_from_slice(blob); + Some(arr) + } else { + None + } + }) + .collect(); tunnel_paths.insert( dest, crate::tunnel::TunnelPath { timestamp: tp.timestamp, + next_hop, hops: tp.hops, expires: tp.expires, - random_blobs: vec![], + random_blobs, + packet_hash, }, ); } diff --git a/crates/rns-transport/src/persistence.rs b/crates/rns-transport/src/persistence.rs index cf02f5a..1836c28 100644 --- a/crates/rns-transport/src/persistence.rs +++ b/crates/rns-transport/src/persistence.rs @@ -7,6 +7,7 @@ use std::path::Path; use rmpv::Value; use serde::{Deserialize, Serialize}; +use crate::constants::PERSIST_RANDOM_BLOBS; use crate::hashlist::PacketHashlist; use crate::path_table::PathTable; @@ -129,6 +130,26 @@ pub struct PythonCachedAnnounce { pub interface_reference: Option, } +#[derive(Debug, Clone)] +pub struct PythonTunnelEntry { + pub tunnel_id: [u8; 32], + pub interface_hash: Option<[u8; 32]>, + pub paths: Vec, + pub expires: f64, +} + +#[derive(Debug, Clone)] +pub struct PythonTunnelPath { + pub destination_hash: [u8; 16], + pub timestamp: f64, + pub received_from: [u8; 16], + pub hops: u8, + pub expires: f64, + pub random_blobs: Vec<[u8; 10]>, + pub interface_hash: Option<[u8; 32]>, + pub packet_hash: [u8; 32], +} + pub fn interface_hash_from_name(name: &str) -> [u8; 32] { rns_crypto::sha::full_hash(name.as_bytes()) } @@ -240,12 +261,32 @@ pub fn save_python_announce_cache_for_paths<'a, I>( interface_names: &HashMap, announce_cache_dir: &Path, ) -> Result<(), PersistenceError> +where + I: IntoIterator, +{ + save_python_announce_cache_for_paths_and_tunnels( + path_entries, + None, + announces, + interface_names, + announce_cache_dir, + ) +} + +pub fn save_python_announce_cache_for_paths_and_tunnels<'a, I>( + path_entries: &PathTable, + tunnel_table: Option<&crate::tunnel::TunnelTable>, + announces: I, + interface_names: &HashMap, + announce_cache_dir: &Path, +) -> Result<(), PersistenceError> where I: IntoIterator, { std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?; let announces_by_dest: HashMap<[u8; 16], &crate::actor::RecentAnnounce> = announces.into_iter().map(|a| (a.dest_hash, a)).collect(); + let mut written = std::collections::HashSet::new(); for (dest_hash, path_entry) in path_entries.iter() { let Some(packet_hash) = path_entry.packet_hash else { @@ -261,19 +302,61 @@ where .get(&path_entry.interface_id) .map(|name| Value::String(name.as_str().into())) .unwrap_or(Value::Nil); - let value = Value::Array(vec![ - Value::Binary(announce.raw_packet.clone()), + write_python_cached_announce( + announce_cache_dir, + &packet_hash, + announce.raw_packet.clone(), interface_reference, - ]); - let mut serialized = Vec::new(); - rmpv::encode::write_value(&mut serialized, &value) - .map_err(|e| PersistenceError::Serialize(e.to_string()))?; - let path = announce_cache_dir.join(hex::encode(packet_hash)); - atomic_write_bytes(&path, &serialized)?; + )?; + written.insert(packet_hash); + } + + if let Some(tunnel_table) = tunnel_table { + for tunnel in tunnel_table.iter().map(|(_, tunnel)| tunnel) { + let interface_reference = interface_names + .get(&tunnel.interface_id) + .map(|name| Value::String(name.as_str().into())) + .unwrap_or(Value::Nil); + for (dest_hash, tunnel_path) in &tunnel.tunnel_paths { + let Some(packet_hash) = tunnel_path.packet_hash else { + continue; + }; + if written.contains(&packet_hash) { + continue; + } + let Some(announce) = announces_by_dest.get(dest_hash) else { + continue; + }; + if announce.raw_packet.is_empty() { + continue; + } + write_python_cached_announce( + announce_cache_dir, + &packet_hash, + announce.raw_packet.clone(), + interface_reference.clone(), + )?; + written.insert(packet_hash); + } + } } Ok(()) } +fn write_python_cached_announce( + announce_cache_dir: &Path, + packet_hash: &[u8; 32], + raw_packet: Vec, + interface_reference: Value, +) -> Result<(), PersistenceError> { + let value = Value::Array(vec![Value::Binary(raw_packet), interface_reference]); + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, &value) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + let path = announce_cache_dir.join(hex::encode(packet_hash)); + atomic_write_bytes(&path, &serialized) +} + pub fn load_python_cached_announce( announce_cache_dir: &Path, packet_hash: &[u8; 32], @@ -312,6 +395,142 @@ pub fn load_python_cached_announce( })) } +pub fn save_python_tunnel_table( + table: &crate::tunnel::TunnelTable, + interface_names: &HashMap, + path: &Path, +) -> Result<(), PersistenceError> { + let mut tunnel_values = Vec::new(); + for (_, tunnel) in table.iter() { + let interface_hash = interface_names + .get(&tunnel.interface_id) + .map(|name| Value::Binary(interface_hash_from_name(name).to_vec())) + .unwrap_or(Value::Nil); + + let mut path_values = Vec::new(); + for (dest_hash, tunnel_path) in &tunnel.tunnel_paths { + let Some(packet_hash) = tunnel_path.packet_hash else { + continue; + }; + let received_from = tunnel_path.next_hop.unwrap_or(*dest_hash); + let random_blob_start = tunnel_path + .random_blobs + .len() + .saturating_sub(PERSIST_RANDOM_BLOBS); + let random_blobs = tunnel_path + .random_blobs + .iter() + .skip(random_blob_start) + .map(|blob| Value::Binary(blob.to_vec())) + .collect::>(); + path_values.push(Value::Array(vec![ + Value::Binary(dest_hash.to_vec()), + Value::F64(tunnel_path.timestamp), + Value::Binary(received_from.to_vec()), + Value::Integer((tunnel_path.hops as u64).into()), + Value::F64(tunnel_path.expires), + Value::Array(random_blobs), + interface_hash.clone(), + Value::Binary(packet_hash.to_vec()), + ])); + } + + tunnel_values.push(Value::Array(vec![ + Value::Binary(tunnel.tunnel_id.to_vec()), + interface_hash, + Value::Array(path_values), + Value::F64(tunnel.expires), + ])); + } + + let mut serialized = Vec::new(); + rmpv::encode::write_value(&mut serialized, &Value::Array(tunnel_values)) + .map_err(|e| PersistenceError::Serialize(e.to_string()))?; + atomic_write_bytes(path, &serialized) +} + +pub fn load_python_tunnel_table(path: &Path) -> Result, PersistenceError> { + let data = std::fs::read(path).map_err(PersistenceError::Io)?; + let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data)) + .map_err(|e| PersistenceError::Deserialize(e.to_string()))?; + let entries = match value { + Value::Array(entries) => entries, + other => { + return Err(PersistenceError::Deserialize(format!( + "expected tunnels array, got {other:?}" + ))); + } + }; + + let mut out = Vec::new(); + for entry in entries { + let fields = match entry { + Value::Array(fields) => fields, + _ => continue, + }; + if fields.len() < 4 { + continue; + } + let Some(tunnel_id) = value_bin_array::<32>(&fields[0]) else { + continue; + }; + let interface_hash = match &fields[1] { + Value::Nil => None, + value => value_bin_array::<32>(value), + }; + let paths = match &fields[2] { + Value::Array(path_entries) => path_entries + .iter() + .filter_map(|path_entry| { + let Value::Array(path_fields) = path_entry else { + return None; + }; + if path_fields.len() < 8 { + return None; + } + let destination_hash = value_bin_array::<16>(&path_fields[0])?; + let timestamp = value_f64(&path_fields[1]).unwrap_or(0.0); + let received_from = value_bin_array::<16>(&path_fields[2])?; + let hops = value_u8(&path_fields[3])?; + let expires = value_f64(&path_fields[4]).unwrap_or(0.0); + let random_blobs = match &path_fields[5] { + Value::Array(values) => values + .iter() + .filter_map(value_bin_array::<10>) + .collect::>(), + _ => Vec::new(), + }; + let interface_hash = match &path_fields[6] { + Value::Nil => None, + value => value_bin_array::<32>(value), + }; + let packet_hash = value_bin_array::<32>(&path_fields[7])?; + Some(PythonTunnelPath { + destination_hash, + timestamp, + received_from, + hops, + expires, + random_blobs, + interface_hash, + packet_hash, + }) + }) + .collect::>(), + _ => Vec::new(), + }; + let expires = value_f64(&fields[3]).unwrap_or(0.0); + out.push(PythonTunnelEntry { + tunnel_id, + interface_hash, + paths, + expires, + }); + } + + Ok(out) +} + fn value_bin_array(value: &Value) -> Option<[u8; N]> { let Value::Binary(bytes) = value else { return None; @@ -693,14 +912,24 @@ pub struct PersistedTunnelEntry { /// stale `interface_id` once the matching interface registers. #[serde(default)] pub interface_name: Option, + /// Python-compatible stable interface hash for remapping canonical + /// `tunnels` entries across restarts. + #[serde(default)] + pub interface_hash: Option>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PersistedTunnelPath { pub destination_hash: Vec, + #[serde(default)] + pub next_hop: Option>, pub hops: u8, pub expires: f64, pub timestamp: f64, + #[serde(default)] + pub random_blobs: Vec>, + #[serde(default)] + pub packet_hash: Option>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -710,8 +939,8 @@ pub struct PersistedTunnelTable { } impl PersistedTunnelTable { - pub const CURRENT_VERSION: u32 = 2; - pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2]; + pub const CURRENT_VERSION: u32 = 3; + pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2, 3]; } pub fn save_tunnel_table( @@ -729,9 +958,19 @@ pub fn save_tunnel_table( .iter() .map(|(dest, tp)| PersistedTunnelPath { destination_hash: dest.to_vec(), + next_hop: tp.next_hop.map(|h| h.to_vec()), hops: tp.hops, expires: tp.expires, timestamp: tp.timestamp, + random_blobs: { + let start = tp.random_blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS); + tp.random_blobs + .iter() + .skip(start) + .map(|b| b.to_vec()) + .collect() + }, + packet_hash: tp.packet_hash.map(|h| h.to_vec()), }) .collect(); Some(PersistedTunnelEntry { @@ -740,6 +979,9 @@ pub fn save_tunnel_table( expires: entry.expires, paths, interface_name: Some(interface_name), + interface_hash: interface_names + .get(&entry.interface_id) + .map(|name| interface_hash_from_name(name).to_vec()), }) }) .collect(); @@ -937,6 +1179,88 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn save_load_python_tunnel_table_and_tunnel_announce_cache() { + let destination_hash = [0xAB; 16]; + let next_hop = [0xBC; 16]; + let packet_hash = [0xCD; 32]; + let tunnel_id = [0xDE; 32]; + let mut paths = HashMap::new(); + paths.insert( + destination_hash, + crate::tunnel::TunnelPath { + timestamp: 1234.5, + next_hop: Some(next_hop), + hops: 3, + expires: 9876.5, + random_blobs: vec![[0x44; 10]], + packet_hash: Some(packet_hash), + }, + ); + let mut tunnels = crate::tunnel::TunnelTable::new(); + tunnels.insert(crate::tunnel::TunnelEntry { + tunnel_id, + interface_id: 7, + tunnel_paths: paths, + expires: 9999.5, + }); + let mut names = HashMap::new(); + names.insert(7, "Interface[Tunnel]".to_string()); + + let dir = std::env::temp_dir().join("reticulum_rs_test_python_tunnels"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let tunnels_path = dir.join("tunnels"); + + save_python_tunnel_table(&tunnels, &names, &tunnels_path).unwrap(); + let loaded = load_python_tunnel_table(&tunnels_path).unwrap(); + + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].tunnel_id, tunnel_id); + assert_eq!( + loaded[0].interface_hash, + Some(interface_hash_from_name("Interface[Tunnel]")) + ); + assert_eq!(loaded[0].expires, 9999.5); + assert_eq!(loaded[0].paths.len(), 1); + assert_eq!(loaded[0].paths[0].destination_hash, destination_hash); + assert_eq!(loaded[0].paths[0].received_from, next_hop); + assert_eq!(loaded[0].paths[0].hops, 3); + assert_eq!(loaded[0].paths[0].packet_hash, packet_hash); + + let announces = [crate::actor::RecentAnnounce { + dest_hash: destination_hash, + hops: 3, + app_data: None, + timestamp: 1234.5, + public_key: None, + ratchet: None, + raw_packet: vec![0xFE; 42], + retained: false, + name_hash: [0xAB; 10], + }]; + let empty_paths = PathTable::new(); + let cache_dir = dir.join("cache").join("announces"); + save_python_announce_cache_for_paths_and_tunnels( + &empty_paths, + Some(&tunnels), + announces.iter(), + &names, + &cache_dir, + ) + .unwrap(); + let cached = load_python_cached_announce(&cache_dir, &packet_hash) + .unwrap() + .unwrap(); + assert_eq!(cached.raw_packet, vec![0xFE; 42]); + assert_eq!( + cached.interface_reference.as_deref(), + Some("Interface[Tunnel]") + ); + + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn test_save_load_hashlist() { let mut hashlist = PacketHashlist::new(); diff --git a/crates/rns-transport/src/tunnel.rs b/crates/rns-transport/src/tunnel.rs index 1f42d1f..cee4767 100644 --- a/crates/rns-transport/src/tunnel.rs +++ b/crates/rns-transport/src/tunnel.rs @@ -16,9 +16,11 @@ pub struct TunnelEntry { #[derive(Debug, Clone)] pub struct TunnelPath { pub timestamp: f64, + pub next_hop: Option<[u8; 16]>, pub hops: u8, pub expires: f64, pub random_blobs: Vec<[u8; 10]>, + pub packet_hash: Option<[u8; 32]>, } pub struct TunnelTable { @@ -64,6 +66,18 @@ impl TunnelTable { self.entries.iter_mut() } + pub fn get_mut_by_interface(&mut self, interface_id: InterfaceId) -> Option<&mut TunnelEntry> { + self.entries + .values_mut() + .find(|entry| entry.interface_id == interface_id) + } + + pub fn tunnel_paths(&self) -> impl Iterator { + self.entries + .values() + .flat_map(|entry| entry.tunnel_paths.iter()) + } + pub fn cull_expired(&mut self) -> usize { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH)