transport: preserve ordered Link delivery outcomes

This commit is contained in:
DeFiDude committed 2026-08-14 13:49:37 -06:00
1 parent 6c77c9e69d
commit eb7162b1e4
7 files changed
+593 -116

No files matched your search

+101 -52
View File
@@ -14,9 +14,9 @@
//! - RX: `…28e5` (WRITE, WRITE_NO_RESPONSE)
//! - TX: `…28e4` (READ, NOTIFY, INDICATE)
//!
//! Peer identity binds only from signature-verified announces. There is no ID
//! characteristic: a statically readable identity hash was a tracking vector
//! that defeated BLE MAC rotation.
//! Peer identity binds only from directly-originated, signature-verified LXMF
//! delivery announces. There is no ID characteristic: a statically readable
//! identity hash was a tracking vector that defeated BLE MAC rotation.
//!
//! ## Fragmentation
//!
@@ -209,20 +209,26 @@ fn mobile_peripheral_fanout_allowed(anti_loop_allows: bool) -> bool {
anti_loop_allows
}
/// Returns the destination-hash hex of `raw` ONLY if it is a signed announce
/// whose Ed25519 signature verifies. Binding a peer's identity from an
/// unverified announce let an in-range attacker claim a known contact's
/// identity and mislabel its address-to-identity association; the signature
/// check means a claim can't be forged without the private key.
fn verified_announce_identity_hex(raw: &[u8]) -> Option<String> {
/// Returns the LXMF delivery destination of a directly-originated, signed
/// announce. Relayed announces cannot identify the adjacent BLE peer: on a
/// multipoint interface the same packet is deliberately fanned back out to
/// other peers, including a second central/peripheral leg to the originator.
fn verified_direct_lxmf_announce_destination_hex(raw: &[u8]) -> Option<String> {
let (header, payload_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?;
if header.flags.packet_type != rns_wire::flags::PacketType::Announce {
if header.flags.packet_type != rns_wire::flags::PacketType::Announce || header.hops != 0 {
return None;
}
let payload = raw.get(payload_offset..)?;
let announce =
rns_identity::announce::AnnounceData::unpack(payload, header.flags.context_flag).ok()?;
announce.verify_signature(&header.destination_hash).ok()?;
let identity = announce.verify_signature(&header.destination_hash).ok()?;
let delivery_destination = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
if header.destination_hash != delivery_destination {
return None;
}
Some(hex::encode(header.destination_hash))
}
@@ -482,11 +488,10 @@ pub enum BlePeerEvent {
SubscribeReady {
address: String,
},
/// Identity hash learned from the first signed Reticulum announce.
/// Used to dedup peers across central+peripheral roles where the BLE
/// address differs for the same physical device — notably on Apple,
/// where `CBPeripheral.identifier` vs `CBCentral.identifier` don't
/// match without bonding.
/// Verified LXMF delivery destination learned from a directly-originated
/// signed Reticulum announce. Repeated observations may be emitted so the
/// embedding owner can bind them to its live connection generation and
/// dedup central/peripheral views of the same device.
IdentityResolved {
address: String,
identity_hash: String,
@@ -4991,7 +4996,6 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
// Fragment reassembly buffer: maps total_count to per-sequence payload slots.
let mut reassembly: FragmentReassembly = HashMap::new();
let mut identity_announced = false;
let mut missed_keepalives: u32 = 0;
loop {
@@ -5065,18 +5069,19 @@ async fn peer_read_loop(conn: MeshPeerConnection, ctx: PeerReadLoopCtx) {
// Forward complete packet to transport
if let Some(raw) = complete_packet {
rxb.fetch_add(raw.len() as u64, Ordering::Relaxed);
if !identity_announced {
if let Some(id_hex) = verified_announce_identity_hex(&raw) {
link_registry
.write()
.await
.set_identity(conn.ble_address.clone(), id_hex.clone());
dispatch_event(BlePeerEvent::IdentityResolved {
address: conn.ble_address.clone(),
identity_hash: id_hex,
});
identity_announced = true;
}
// Emit every directly-originated delivery announce. The
// embedding owner deduplicates within its current
// connection generation; repeated emission is what lets a
// reconnect re-verify the same stable BLE address.
if let Some(id_hex) = verified_direct_lxmf_announce_destination_hex(&raw) {
link_registry
.write()
.await
.set_identity(conn.ble_address.clone(), id_hex.clone());
dispatch_event(BlePeerEvent::IdentityResolved {
address: conn.ble_address.clone(),
identity_hash: id_hex,
});
}
// Register the source so the fan-out anti-loop filter
// doesn't echo this exact payload back to the peer it
@@ -5316,11 +5321,6 @@ pub async fn spawn_ble_peer_interface(
// can no longer corrupt each other's reassembly buffers.
type PeerReassembly = FragmentReassembly;
let mut reassembly: HashMap<String, PeerReassembly> = HashMap::new();
// Identity is learned from the first signed Reticulum announce.
// Emit once per peer address so callers can dedupe
// central/peripheral views of the same device.
let mut identity_announced: std::collections::HashSet<String> =
std::collections::HashSet::new();
while let Some((peer, data)) = rx.recv().await {
if !generation_is_current(generation) {
break;
@@ -5360,24 +5360,23 @@ pub async fn spawn_ble_peer_interface(
"BLE Peer reassembly: complete packet (parse failed)"
),
}
// Identity learning: associate this peer address
// with an identity for caller-side dedup, but only
// from a signature-verified announce. Binding from
// an unverified announce let an in-range attacker
// claim a known contact's identity and poison the
// dual-role dedup registry.
if !identity_announced.contains(&peer) {
if let Some(id_hex) = verified_announce_identity_hex(&raw) {
identity_announced.insert(peer.clone());
link_registry_p
.write()
.await
.set_identity(peer.clone(), id_hex.clone());
dispatch_event(BlePeerEvent::IdentityResolved {
address: peer.clone(),
identity_hash: id_hex,
});
}
// Direct signed delivery announces are emitted on
// every observation. Address-level suppression here
// used to survive disconnect/reconnect and made a
// stable mobile address impossible to re-verify.
// The embedding owner now deduplicates only within
// its current live connection generation.
if let Some(id_hex) =
verified_direct_lxmf_announce_destination_hex(&raw)
{
link_registry_p
.write()
.await
.set_identity(peer.clone(), id_hex.clone());
dispatch_event(BlePeerEvent::IdentityResolved {
address: peer.clone(),
identity_hash: id_hex,
});
}
// Record this packet's source so the outbound
// fan-out can skip echoing it back to the same peer.
@@ -6667,6 +6666,56 @@ pub async fn spawn_ble_peer_interface(
mod tests {
use super::*;
fn signed_announce_raw(
identity: &rns_identity::identity::Identity,
app_name: &str,
hops: u8,
) -> ([u8; 16], Vec<u8>) {
let destination_hash = rns_identity::destination::Destination::hash_from_name_and_identity(
app_name,
Some(&identity.hash),
);
let announce =
rns_identity::announce::AnnounceData::create(identity, app_name, None, None).unwrap();
let mut raw = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::Announce,
},
hops,
transport_id: None,
destination_hash,
context: rns_wire::context::PacketContext::None,
}
.pack();
raw.extend_from_slice(&announce.pack());
(destination_hash, raw)
}
#[test]
fn peer_identity_accepts_only_direct_lxmf_delivery_announces() {
let identity = rns_identity::identity::Identity::new();
let (delivery_destination, direct) = signed_announce_raw(&identity, "lxmf.delivery", 0);
let expected_destination = hex::encode(delivery_destination);
assert_eq!(
verified_direct_lxmf_announce_destination_hex(&direct).as_deref(),
Some(expected_destination.as_str())
);
let (_, relayed) = signed_announce_raw(&identity, "lxmf.delivery", 1);
assert!(verified_direct_lxmf_announce_destination_hex(&relayed).is_none());
let (_, wrong_aspect) = signed_announce_raw(&identity, "lxmf.propagation", 0);
assert!(verified_direct_lxmf_announce_destination_hex(&wrong_aspect).is_none());
let mut tampered = direct;
*tampered.last_mut().unwrap() ^= 0x01;
assert!(verified_direct_lxmf_announce_destination_hex(&tampered).is_none());
}
// ── Fragmentation ──
#[test]
+26 -1
View File
@@ -1090,7 +1090,13 @@ impl Link {
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
if self.state != LinkState::Active && self.state != LinkState::Stale {
// A responder can receive ordinary Link data immediately after its
// proof, before the initiator's LRRTT activates the responder side.
// Python proves that data in HANDSHAKE, and the session keys/signing
// identity are already established at this point.
let can_prove = matches!(self.state, LinkState::Active | LinkState::Stale)
|| (!self.is_initiator && self.state == LinkState::Handshake);
if !can_prove {
return Err(LinkCryptoError::EncryptionFailed);
}
@@ -1698,6 +1704,25 @@ mod tests {
assert_eq!(pt2, msg2);
}
#[test]
fn responder_can_prove_packet_before_lrrtt_activation() {
let dest_hash = [0xAB; 16];
let identity_key = Ed25519PrivateKey::generate();
let identity_pub = identity_key.public_key();
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
let (responder, proof_data) =
Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap();
let _rtt_data = initiator
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
.unwrap();
assert_eq!(responder.state, LinkState::Handshake);
assert_eq!(initiator.state, LinkState::Active);
let packet_hash = [0xCD; 32];
let packet_proof = responder.prove_packet(&packet_hash, &identity_key).unwrap();
assert!(initiator.validate_packet_proof(&packet_hash, &packet_proof));
}
#[test]
fn test_teardown() {
let dest_hash = [0xAA; 16];
+339 -54
View File
@@ -31,6 +31,15 @@ const MAX_PENDING_DESTINATION_ANNOUNCES: usize = 256;
/// or flow-control that this manager already committed to sending.
const MAX_PENDING_LINK_CONTROL: usize = 256;
/// Legacy application channels are bounded for API compatibility, but these
/// notifications represent terminal protocol facts. Retain them across local
/// backpressure instead of silently losing a validated proof or Link close.
enum LegacyTerminalNotification {
PacketProof(LinkPacketProof),
ResourceProof(LinkResourceProof),
LinkClosed([u8; 16]),
}
struct ActiveLink {
link: Link,
_interface_id: u64,
@@ -299,15 +308,18 @@ pub struct ResourceCompletion {
/// Ordered, capacity-lossless Link accounting notifications.
///
/// This opt-in stream contains Resource starts and conclusions, ordinary
/// inbound completion payloads, and Link closure. Progress remains available
/// only through the bounded best-effort Resource event channel. Delivery is
/// This opt-in stream contains validated ordinary Link-packet proofs, Resource
/// starts and conclusions, ordinary inbound completion payloads, and Link
/// closure in manager-observation order. Progress remains available only
/// through the bounded best-effort Resource event channel. Delivery is
/// guaranteed while the unbounded receiver remains alive. Request Resources
/// retain their start and conclusion events but dispatch inline and never
/// produce a [`LinkManagerAccountingEvent::ResourceCompletion`].
#[derive(Clone)]
#[non_exhaustive]
pub enum LinkManagerAccountingEvent {
/// A validated proof for an ordinary application Link packet.
LinkPacketProof(LinkPacketProof),
/// Resource start or terminal conclusion; progress is omitted.
ResourceEvent(LinkResourceEvent),
/// Complete ordinary inbound Resource data and metadata.
@@ -319,6 +331,11 @@ pub enum LinkManagerAccountingEvent {
impl std::fmt::Debug for LinkManagerAccountingEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::LinkPacketProof(proof) => f
.debug_struct("LinkPacketProof")
.field("link_id", &hex::encode(proof.link_id))
.field("packet_hash", &hex::encode(proof.packet_hash))
.finish(),
Self::ResourceEvent(event) => f.debug_tuple("ResourceEvent").field(event).finish(),
Self::ResourceCompletion(completion) => f
.debug_struct("ResourceCompletion")
@@ -447,6 +464,7 @@ pub struct LinkManager {
link_packet_proof_tx: Option<mpsc::Sender<LinkPacketProof>>,
/// Valid proof for an application resource sent through this manager.
outbound_resource_proof_tx: Option<mpsc::Sender<LinkResourceProof>>,
pending_legacy_terminal_events: VecDeque<LegacyTerminalNotification>,
/// Valid proof for a non-Link packet registered by the owning application.
/// Unbounded because a validated terminal event must not be discarded after
/// the network has already acknowledged delivery.
@@ -511,6 +529,7 @@ impl LinkManager {
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
pending_legacy_terminal_events: VecDeque::new(),
destination_delivery_proof_tx: None,
resource_event_tx: None,
accounting_event_tx: None,
@@ -574,6 +593,7 @@ impl LinkManager {
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
pending_legacy_terminal_events: VecDeque::new(),
destination_delivery_proof_tx: None,
resource_event_tx: None,
accounting_event_tx: None,
@@ -641,6 +661,7 @@ impl LinkManager {
pub fn try_step(&mut self) -> bool {
self.flush_pending_link_control();
self.flush_pending_destination_announces();
self.flush_pending_legacy_terminal_notifications();
match self.event_rx.try_recv() {
Ok(event) => {
self.handle_event(event);
@@ -655,6 +676,7 @@ impl LinkManager {
pub async fn step(&mut self) -> bool {
self.flush_pending_link_control();
self.flush_pending_destination_announces();
self.flush_pending_legacy_terminal_notifications();
let Some(event) = self.event_rx.recv().await else {
return false;
};
@@ -665,6 +687,7 @@ impl LinkManager {
pub fn tick(&mut self) {
self.flush_pending_link_control();
self.flush_pending_destination_announces();
self.flush_pending_legacy_terminal_notifications();
self.on_tick();
}
@@ -674,6 +697,7 @@ impl LinkManager {
loop {
self.flush_pending_link_control();
self.flush_pending_destination_announces();
self.flush_pending_legacy_terminal_notifications();
tokio::select! {
event = self.event_rx.recv() => {
match event {
@@ -695,6 +719,7 @@ impl LinkManager {
'run: loop {
self.flush_pending_link_control();
self.flush_pending_destination_announces();
self.flush_pending_legacy_terminal_notifications();
while let Ok(command) = command_rx.try_recv() {
if !self.handle_command(command) {
break 'run;
@@ -1101,6 +1126,92 @@ impl LinkManager {
true
}
fn stage_legacy_terminal_notification(
packet_proof_tx: &Option<mpsc::Sender<LinkPacketProof>>,
resource_proof_tx: &Option<mpsc::Sender<LinkResourceProof>>,
link_closed_tx: &Option<mpsc::Sender<[u8; 16]>>,
pending: &mut VecDeque<LegacyTerminalNotification>,
event: LegacyTerminalNotification,
) {
pending.push_back(event);
Self::flush_legacy_terminal_notifications(
packet_proof_tx,
resource_proof_tx,
link_closed_tx,
pending,
);
}
fn flush_legacy_terminal_notifications(
packet_proof_tx: &Option<mpsc::Sender<LinkPacketProof>>,
resource_proof_tx: &Option<mpsc::Sender<LinkResourceProof>>,
link_closed_tx: &Option<mpsc::Sender<[u8; 16]>>,
pending: &mut VecDeque<LegacyTerminalNotification>,
) {
while let Some(event) = pending.pop_front() {
let retry = match event {
LegacyTerminalNotification::PacketProof(proof) => {
let Some(tx) = packet_proof_tx else {
continue;
};
match tx.try_send(proof) {
Ok(()) => None,
Err(mpsc::error::TrySendError::Full(proof)) => {
Some(LegacyTerminalNotification::PacketProof(proof))
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!("legacy Link-packet proof receiver is closed");
None
}
}
}
LegacyTerminalNotification::ResourceProof(proof) => {
let Some(tx) = resource_proof_tx else {
continue;
};
match tx.try_send(proof) {
Ok(()) => None,
Err(mpsc::error::TrySendError::Full(proof)) => {
Some(LegacyTerminalNotification::ResourceProof(proof))
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!("legacy Resource-proof receiver is closed");
None
}
}
}
LegacyTerminalNotification::LinkClosed(link_id) => {
let Some(tx) = link_closed_tx else {
continue;
};
match tx.try_send(link_id) {
Ok(()) => None,
Err(mpsc::error::TrySendError::Full(link_id)) => {
Some(LegacyTerminalNotification::LinkClosed(link_id))
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!("legacy Link-close receiver is closed");
None
}
}
}
};
if let Some(event) = retry {
pending.push_front(event);
break;
}
}
}
fn flush_pending_legacy_terminal_notifications(&mut self) {
Self::flush_legacy_terminal_notifications(
&self.link_packet_proof_tx,
&self.outbound_resource_proof_tx,
&self.link_closed_tx,
&mut self.pending_legacy_terminal_events,
);
}
fn flush_pending_link_control(&mut self) {
while let Some(message) = self.pending_link_control.pop_front() {
match self.transport_tx.try_send(message) {
@@ -1565,28 +1676,41 @@ impl LinkManager {
}
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
if let Ok(proof_data) = active.link.prove_packet_with_link_key(&pkt_hash) {
if Self::send_link_packet_proof(
&self.transport_tx,
&mut self.pending_link_control,
&link_id,
&proof_data,
rns_wire::context::PacketContext::None,
) {
// Proofs to a link count into txbytes (Link.py:388, Packet.py:291).
active.link.record_tx(proof_data.len());
tracing::debug!(
link_id = hex::encode(link_id),
proof_len = proof_data.len(),
"delivery proof queued for channel packet"
);
} else {
tracing::error!(
link_id = hex::encode(link_id),
proof_len = proof_data.len(),
"channel delivery proof could not be retained"
);
}
let proof_retained = active
.link
.prove_packet_with_link_key(&pkt_hash)
.ok()
.is_some_and(|proof_data| {
if Self::send_link_packet_proof(
&self.transport_tx,
&mut self.pending_link_control,
&link_id,
&proof_data,
rns_wire::context::PacketContext::None,
) {
// Proofs to a link count into txbytes (Link.py:388, Packet.py:291).
active.link.record_tx(proof_data.len());
tracing::debug!(
link_id = hex::encode(link_id),
proof_len = proof_data.len(),
"delivery proof queued for channel packet"
);
true
} else {
tracing::error!(
link_id = hex::encode(link_id),
proof_len = proof_data.len(),
"channel delivery proof could not be retained"
);
false
}
});
if !proof_retained {
tracing::warn!(
link_id = hex::encode(link_id),
"channel packet withheld because its delivery proof was not retained"
);
return;
}
if let Some(ref mut channel) = active.channel {
@@ -2610,12 +2734,16 @@ impl LinkManager {
}
}
if !started_next_segment && !next_segment_failed {
if let Some(ref tx) = self.outbound_resource_proof_tx {
let _ = tx.try_send(LinkResourceProof {
Self::stage_legacy_terminal_notification(
&self.link_packet_proof_tx,
&self.outbound_resource_proof_tx,
&self.link_closed_tx,
&mut self.pending_legacy_terminal_events,
LegacyTerminalNotification::ResourceProof(LinkResourceProof {
link_id,
resource_hash: completed_resource_hash,
});
}
}),
);
Self::emit_resource_event(
&self.resource_event_tx,
&self.accounting_event_tx,
@@ -2687,17 +2815,6 @@ impl LinkManager {
active.link.record_inbound();
active.link.record_rx(data.len());
if let Ok(plaintext) = active.link.decrypt(data) {
if let Some(ref cb) = active.link.packet_callback {
cb(&plaintext);
}
if let Some(ref tx) = self.link_packet_tx {
let _ = tx.send((plaintext, link_id));
}
tracing::debug!(
link_id = hex::encode(link_id),
"link data packet decrypted and forwarded"
);
// Link proofs are unencrypted (Packet.py:198-200).
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
let proof = if let Some(key_bytes) = identity_key_bytes {
@@ -2726,6 +2843,16 @@ impl LinkManager {
proof_len = proof_data.len(),
"delivery proof queued for link data packet (unencrypted)"
);
if let Some(ref cb) = active.link.packet_callback {
cb(&plaintext);
}
if let Some(ref tx) = self.link_packet_tx {
let _ = tx.send((plaintext, link_id));
}
tracing::debug!(
link_id = hex::encode(link_id),
"link data packet decrypted, proved, and forwarded"
);
} else {
tracing::error!(
link_id = hex::encode(link_id),
@@ -3066,9 +3193,13 @@ impl LinkManager {
tracing::debug!("Link accounting event receiver is closed");
}
}
if let Some(ref tx) = self.link_closed_tx {
let _ = tx.try_send(link_id);
}
Self::stage_legacy_terminal_notification(
&self.link_packet_proof_tx,
&self.outbound_resource_proof_tx,
&self.link_closed_tx,
&mut self.pending_legacy_terminal_events,
LegacyTerminalNotification::LinkClosed(link_id),
);
let failure = format!("link closed: {reason:?}");
for resource_id in inbound_resource_ids {
Self::conclude_inbound_failure(
@@ -3685,12 +3816,25 @@ impl LinkManager {
}
}
if !matched_channel_sequence {
if let Some(ref tx) = self.link_packet_proof_tx {
let _ = tx.try_send(LinkPacketProof {
link_id,
packet_hash,
});
let proof = LinkPacketProof {
link_id,
packet_hash,
};
if let Some(tx) = &self.accounting_event_tx {
if tx
.send(LinkManagerAccountingEvent::LinkPacketProof(proof.clone()))
.is_err()
{
tracing::debug!("Link accounting event receiver is closed");
}
}
Self::stage_legacy_terminal_notification(
&self.link_packet_proof_tx,
&self.outbound_resource_proof_tx,
&self.link_closed_tx,
&mut self.pending_legacy_terminal_events,
LegacyTerminalNotification::PacketProof(proof),
);
}
}
@@ -6654,6 +6798,78 @@ mod tests {
assert!(sender_link.validate_packet_proof(&packet_hash, proof_data));
}
#[test]
fn responder_handshake_data_is_proved_before_local_delivery() {
let dest_hash = [0xB7; 16];
let identity_key = Ed25519PrivateKey::generate();
let identity_pub = identity_key.public_key();
let (mut sender_link, request_data) = Link::new_initiator(dest_hash, 1);
let (receiver_link, link_proof) =
Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap();
let _rtt_data = sender_link
.validate_proof(&link_proof, &identity_pub, &identity_pub.to_bytes())
.unwrap();
assert_eq!(receiver_link.state, LinkState::Handshake);
let link_id = receiver_link.link_id;
let encrypted = sender_link.encrypt(b"early application data").unwrap();
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&encrypted);
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
let (transport_tx, mut transport_rx) = mpsc::channel(4);
let (_event_tx, event_rx) = mpsc::channel(4);
let mut manager = LinkManager::new(transport_tx, event_rx, dest_hash, Some(identity_key));
let (packet_tx, mut packet_rx) = mpsc::unbounded_channel();
manager.set_link_packet_channel(packet_tx);
manager.active_links.insert(
link_id,
ActiveLink {
link: receiver_link,
_interface_id: 1,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
manager.handle_inbound_packet(&raw, 1);
let TransportMessage::Outbound(proof_request) =
transport_rx.try_recv().expect("delivery proof queued")
else {
panic!("expected outbound delivery proof");
};
let (_, proof_offset) = rns_wire::header::PacketHeader::unpack(&proof_request.raw).unwrap();
assert!(
sender_link.validate_packet_proof(&packet_hash, &proof_request.raw[proof_offset..])
);
assert_eq!(
packet_rx.try_recv().unwrap(),
(b"early application data".to_vec(), link_id)
);
assert_eq!(
manager.active_links[&link_id].link.state,
LinkState::Handshake
);
}
#[test]
fn link_packet_delivery_proof_survives_full_transport_ingress() {
let (sender_link, receiver_link, identity_key) = handshaken_link_pair_with_identity();
@@ -7040,7 +7256,9 @@ mod tests {
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC1; 16], None);
let (proof_tx, mut proof_rx) = mpsc::channel(4);
let (accounting_tx, mut accounting_rx) = mpsc::unbounded_channel();
lm.set_link_packet_proof_channel(proof_tx);
lm.set_accounting_event_channel(accounting_tx);
lm.active_links.insert(
link_id,
ActiveLink {
@@ -7098,16 +7316,81 @@ mod tests {
let proof = proof_rx.try_recv().expect("link packet proof event");
assert_eq!(proof.link_id, link_id);
assert_eq!(proof.packet_hash, receipt.packet_hash);
assert!(matches!(
accounting_rx.try_recv(),
Ok(LinkManagerAccountingEvent::LinkPacketProof(proof))
if proof.link_id == link_id && proof.packet_hash == receipt.packet_hash
));
}
#[test]
fn inbound_link_data_delivery_is_lossless_without_draining() {
let (initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
fn legacy_terminal_notifications_retry_after_local_backpressure() {
let (packet_tx, mut packet_rx) = mpsc::channel(1);
let (resource_tx, mut resource_rx) = mpsc::channel(1);
let (closed_tx, _closed_rx) = mpsc::channel(1);
packet_tx
.try_send(LinkPacketProof {
link_id: [0x01; 16],
packet_hash: [0x02; 32],
})
.unwrap();
let packet_sender = Some(packet_tx);
let resource_sender = Some(resource_tx);
let closed_sender = Some(closed_tx);
let mut pending = VecDeque::new();
LinkManager::stage_legacy_terminal_notification(
&packet_sender,
&resource_sender,
&closed_sender,
&mut pending,
LegacyTerminalNotification::PacketProof(LinkPacketProof {
link_id: [0x03; 16],
packet_hash: [0x04; 32],
}),
);
LinkManager::stage_legacy_terminal_notification(
&packet_sender,
&resource_sender,
&closed_sender,
&mut pending,
LegacyTerminalNotification::ResourceProof(LinkResourceProof {
link_id: [0x05; 16],
resource_hash: [0x06; 32],
}),
);
assert_eq!(pending.len(), 2);
let _prefill = packet_rx.try_recv().unwrap();
let packet_is_head = matches!(&pending[0], LegacyTerminalNotification::PacketProof(_));
assert!(packet_is_head, "packet proof remains at the ordered head");
LinkManager::flush_legacy_terminal_notifications(
&packet_sender,
&resource_sender,
&closed_sender,
&mut pending,
);
assert!(matches!(
packet_rx.try_recv(),
Ok(LinkPacketProof { link_id, .. }) if link_id == [0x03; 16]
));
assert!(matches!(
resource_rx.try_recv(),
Ok(LinkResourceProof { link_id, .. }) if link_id == [0x05; 16]
));
assert!(pending.is_empty());
}
#[test]
fn inbound_link_data_is_published_only_while_its_proof_is_retained() {
let (initiator_link, responder_link, identity_key) = handshaken_link_pair_with_identity();
let link_id = responder_link.link_id;
let (transport_tx, _transport_rx) = mpsc::channel(8);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC4; 16], None);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC4; 16], Some(identity_key));
let (packet_tx, mut packet_rx) = mpsc::unbounded_channel();
lm.set_link_packet_channel(packet_tx);
lm.active_links.insert(
@@ -7138,15 +7421,17 @@ mod tests {
context: rns_wire::context::PacketContext::None,
};
// Burst far past any bounded capacity before a single receive; every
// one of these is proved to the peer, so none may drop locally.
// Burst beyond transport ingress plus retained Link-control capacity.
// Once a proof can no longer be retained, its plaintext must not be
// published locally as though sender confirmation were still possible.
for i in 0..300u16 {
let mut raw = header.pack();
raw.extend_from_slice(&initiator_link.encrypt(&i.to_be_bytes()).unwrap());
lm.handle_inbound_packet(&raw, 1);
}
for i in 0..300u16 {
let retained = 8 + MAX_PENDING_LINK_CONTROL;
for i in 0..retained as u16 {
let (payload, from) = packet_rx.try_recv().expect("lossless link data delivery");
assert_eq!(from, link_id);
assert_eq!(payload, i.to_be_bytes());
+21 -9
View File
@@ -1069,19 +1069,31 @@ impl TransportActor {
trunc = hex::encode(header.destination_hash),
"delivery proof received for outbound message"
);
// Broadcast the DeliveryProof to every destination channel —
// we don't know which local identity originated the outbound
// message, so LXMF filters by msg_id on its side.
for (dest_hash, tx) in &self.destination_channels {
if let Err(e) =
tx.try_send(crate::link_messages::DestinationEvent::DeliveryProof {
if let Some(proof_tx) = self.receipt_proof_txs.remove(&header.destination_hash) {
if proof_tx
.send(crate::link_messages::DestinationEvent::DeliveryProof {
msg_id: msg_id.clone(),
rtt,
})
.is_err()
{
self.channel_drops += 1;
error!(dest = hex::encode(dest_hash), msg_id = %msg_id, drops = self.channel_drops, err = %e,
"failed to deliver DeliveryProof; sender will not receive confirmation");
error!(msg_id = %msg_id,
"direct delivery-proof owner closed before confirmation");
}
} else {
// Legacy receipts predate direct proof ownership. Preserve
// their broadcast behavior for compatibility.
for (dest_hash, tx) in &self.destination_channels {
if let Err(e) =
tx.try_send(crate::link_messages::DestinationEvent::DeliveryProof {
msg_id: msg_id.clone(),
rtt,
})
{
self.channel_drops += 1;
error!(dest = hex::encode(dest_hash), msg_id = %msg_id, drops = self.channel_drops, err = %e,
"failed to deliver legacy DeliveryProof; sender will not receive confirmation");
}
}
}
}
@@ -162,6 +162,7 @@ impl TransportActor {
for (key, update) in concluded {
self.receipt_table.remove(&key);
self.receipt_msg_ids.remove(&key);
self.receipt_proof_txs.remove(&key);
if let Some(status_tx) = self.receipt_updates.remove(&key) {
status_tx.send_replace(update);
}
@@ -181,6 +182,7 @@ impl TransportActor {
receipt.cull();
}
self.receipt_msg_ids.remove(&key);
self.receipt_proof_txs.remove(&key);
if let Some(status_tx) = self.receipt_updates.remove(&key) {
status_tx.send_replace(crate::messages::ReceiptUpdate::Culled);
}
+81
View File
@@ -72,6 +72,10 @@ pub struct TransportActor {
/// Truncated packet hash → LXMF msg_id for pairing delivery proofs back
/// to their originating outbound message.
pub receipt_msg_ids: HashMap<[u8; 16], String>,
/// Direct application proof sinks for receipt owners that cannot tolerate
/// loss through the legacy bounded destination-event fan-out.
pub receipt_proof_txs:
HashMap<[u8; 16], mpsc::UnboundedSender<crate::link_messages::DestinationEvent>>,
/// Direct per-send receipt observers used by the high-level runtime API.
pub receipt_updates:
HashMap<[u8; 16], tokio::sync::watch::Sender<crate::messages::ReceiptUpdate>>,
@@ -321,6 +325,7 @@ impl TransportActor {
packet_metrics_order: VecDeque::new(),
receipt_table: HashMap::new(),
receipt_msg_ids: HashMap::new(),
receipt_proof_txs: HashMap::new(),
receipt_updates: HashMap::new(),
interfaces: HashMap::new(),
local_destinations: HashSet::new(),
@@ -786,11 +791,35 @@ impl TransportActor {
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
self.receipt_table.insert(truncated_hash, receipt);
self.receipt_msg_ids.insert(truncated_hash, msg_id);
self.receipt_proof_txs.remove(&truncated_hash);
debug!(
trunc = hex::encode(truncated_hash),
"registered receipt for outbound LXMF message"
);
}
TransportMessage::RegisterReceiptWithProof {
truncated_hash,
full_hash,
destination_hash,
destination_public_key,
msg_id,
timeout,
proof_tx,
} => {
let mut receipt = PacketReceipt::new(
full_hash,
truncated_hash,
Some(timeout.unwrap_or(std::time::Duration::from_secs(180))),
);
receipt.set_destination_identity(destination_hash, Some(destination_public_key));
self.receipt_table.insert(truncated_hash, receipt);
self.receipt_msg_ids.insert(truncated_hash, msg_id);
self.receipt_proof_txs.insert(truncated_hash, proof_tx);
debug!(
trunc = hex::encode(truncated_hash),
"registered receipt with direct application proof owner"
);
}
TransportMessage::RegisterLink {
link_id,
destination_hash,
@@ -981,6 +1010,7 @@ impl TransportActor {
self.path_states.clear();
self.packet_metrics.clear();
self.packet_metrics_order.clear();
self.receipt_proof_txs.clear();
self.discovery_path_requests.clear();
self.pending_local_path_requests.clear();
self.pending_discovery_prs.clear();
@@ -8223,6 +8253,57 @@ mod tests {
assert!(!actor.receipt_msg_ids.contains_key(&proof_hash));
}
#[test]
fn direct_delivery_proof_owner_bypasses_full_destination_channel() {
let (mut actor, _tx) = TransportActor::new();
let (iface, _rx) = make_test_interface("direct-proof-owner");
actor.interfaces.insert(1, iface);
let destination = rns_identity::identity::Identity::new();
let destination_hash = [0xD3; 16];
let packet_hash = [0x63; 32];
let mut proof_hash = [0u8; 16];
proof_hash.copy_from_slice(&packet_hash[..16]);
let (proof_tx, mut proof_rx) = mpsc::unbounded_channel();
actor.handle_message(TransportMessage::RegisterReceiptWithProof {
truncated_hash: proof_hash,
full_hash: packet_hash,
destination_hash,
destination_public_key: destination.get_public_key(),
msg_id: "direct-owner-message".to_string(),
timeout: Some(Duration::from_secs(180)),
proof_tx,
});
let (legacy_tx, _legacy_rx) = mpsc::channel(1);
legacy_tx
.try_send(crate::link_messages::DestinationEvent::LinkClosed {
link_id: [0x64; 16],
})
.unwrap();
actor.destination_channels.insert([0x65; 16], legacy_tx);
let signature = destination.sign(&packet_hash).unwrap();
actor.on_inbound(InboundPacket {
raw: make_proof_packet_with_payload(proof_hash, 0, &signature),
interface_id: 1,
rssi: None,
snr: None,
q: None,
});
assert!(matches!(
proof_rx.try_recv(),
Ok(crate::link_messages::DestinationEvent::DeliveryProof { msg_id, .. })
if msg_id == "direct-owner-message"
));
assert!(!actor.receipt_table.contains_key(&proof_hash));
assert!(!actor.receipt_msg_ids.contains_key(&proof_hash));
assert!(!actor.receipt_proof_txs.contains_key(&proof_hash));
assert_eq!(actor.channel_drops, 0);
}
#[test]
fn set_receipt_timeout_updates_only_pending_receipts() {
let (mut actor, _tx) = TransportActor::new();
+23
View File
@@ -462,6 +462,19 @@ pub enum TransportMessage {
/// Override default 180s timeout when `Some`.
timeout: Option<std::time::Duration>,
},
/// Register an application-owned receipt with a direct, capacity-lossless
/// proof sink. Unlike the legacy destination fan-out, a validated terminal
/// proof cannot be discarded because an unrelated destination mailbox is
/// full.
RegisterReceiptWithProof {
truncated_hash: [u8; 16],
full_hash: [u8; 32],
destination_hash: [u8; 16],
destination_public_key: [u8; 64],
msg_id: String,
timeout: Option<std::time::Duration>,
proof_tx: mpsc::UnboundedSender<crate::link_messages::DestinationEvent>,
},
/// Record a new link in the table. `initiator=true` means we started the
/// handshake, so the entry is pending until `ActivateLink` arrives.
RegisterLink {
@@ -517,6 +530,7 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str {
TransportMessage::SharedConnectionRestored { .. } => "SharedConnectionRestored",
TransportMessage::SynthesizeTunnel { .. } => "SynthesizeTunnel",
TransportMessage::RegisterReceipt { .. } => "RegisterReceipt",
TransportMessage::RegisterReceiptWithProof { .. } => "RegisterReceiptWithProof",
TransportMessage::RegisterLink { .. } => "RegisterLink",
TransportMessage::ActivateLink { .. } => "ActivateLink",
TransportMessage::AwaitPath { .. } => "AwaitPath",
@@ -951,6 +965,15 @@ impl std::fmt::Debug for TransportMessage {
.field("truncated_hash", truncated_hash)
.field("msg_id", msg_id)
.finish(),
Self::RegisterReceiptWithProof {
truncated_hash,
msg_id,
..
} => f
.debug_struct("RegisterReceiptWithProof")
.field("truncated_hash", truncated_hash)
.field("msg_id", msg_id)
.finish(),
Self::RegisterLink {
link_id,
destination_hash,