From 69d9e8a5b5e92a2fc3a5e41c3323b0271e77b5ff Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Fri, 24 Jul 2026 18:44:53 -0600 Subject: [PATCH] packet: add resend and receipt controls --- crates/rns-runtime/src/lib.rs | 6 +- crates/rns-runtime/src/reticulum.rs | 219 +++++++++++++++++++++++++- crates/rns-transport/src/actor/mod.rs | 58 +++++++ crates/rns-transport/src/messages.rs | 16 ++ 4 files changed, 293 insertions(+), 6 deletions(-) diff --git a/crates/rns-runtime/src/lib.rs b/crates/rns-runtime/src/lib.rs index aa4b4e9..eeac7ff 100644 --- a/crates/rns-runtime/src/lib.rs +++ b/crates/rns-runtime/src/lib.rs @@ -40,9 +40,9 @@ pub mod prelude { pub use crate::resource_source::{ResourceOptions, ResourceSource}; pub use crate::reticulum::{ AnnounceSubscription, ControlError, InitOptions, InterfaceStats, LinkConnectError, - LinkConnectOptions, PacketReceiptHandle, PacketReceiptStatus, RecalledDestination, - ReceiptError, ReticulumError, ReticulumHandle, SendError, SendOptions, SendResult, init, - init_with_options, + LinkConnectOptions, OutboundPacket, PacketReceiptHandle, PacketReceiptStatus, + RecalledDestination, ReceiptError, ReticulumError, ReticulumHandle, SendError, SendOptions, + SendResult, init, init_with_options, }; pub use rns_identity::destination::{ AllowPolicy, DestType, Destination, Direction, ProofStrategy, diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 0fcf24a..53cdf44 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -238,6 +238,66 @@ pub struct SendResult { pub receipt: Option, } +/// Stateful non-Link application packet that can be sent and re-sent. +/// +/// Re-sending runs the normal destination encryption path again, producing +/// fresh ciphertext, a new packet hash, and a new receipt when requested. +pub struct OutboundPacket<'a> { + runtime: &'a ReticulumHandle, + destination: &'a Destination, + data: &'a [u8], + options: SendOptions, + sent: bool, +} + +impl std::fmt::Debug for OutboundPacket<'_> { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("OutboundPacket") + .field("destination_hash", &hex::encode(self.destination.hash)) + .field("data_len", &self.data.len()) + .field("sent", &self.sent) + .finish() + } +} + +impl OutboundPacket<'_> { + pub fn is_sent(&self) -> bool { + self.sent + } + + /// Send this packet for the first time. + pub async fn send(&mut self) -> Result { + if self.sent { + return Err(SendError::AlreadySent); + } + let result = self + .runtime + .send_to(self.destination, self.data, self.options.clone()) + .await?; + self.sent = true; + Ok(result) + } + + /// Re-send a previously-sent packet with fresh destination encryption. + pub async fn resend(&mut self) -> Result { + if !self.sent { + return Err(SendError::NotSent); + } + match self + .runtime + .send_to(self.destination, self.data, self.options.clone()) + .await + { + Ok(result) => Ok(result), + Err(error) => { + self.sent = false; + Err(error) + } + } + } +} + /// Current lifecycle state of a tracked packet. pub type PacketReceiptStatus = ReceiptUpdate; @@ -247,6 +307,7 @@ pub struct PacketReceiptHandle { pub packet_hash: [u8; 32], pub truncated_hash: [u8; 16], status_rx: watch::Receiver, + transport_tx: mpsc::Sender, } impl std::fmt::Debug for PacketReceiptHandle { @@ -269,6 +330,30 @@ impl PacketReceiptHandle { self.status_rx.clone() } + /// Change the timeout of this receipt while it is still pending. + /// + /// The new duration is measured from the original send time, matching + /// Python `PacketReceipt.set_timeout`. + pub async fn set_timeout(&self, timeout: Duration) -> Result<(), ReceiptError> { + if self.status() != ReceiptUpdate::Sent { + return Err(ReceiptError::NoLongerTracked); + } + let (result_tx, result_rx) = tokio::sync::oneshot::channel(); + self.transport_tx + .send(TransportMessage::SetReceiptTimeout { + truncated_hash: self.truncated_hash, + timeout, + result_tx, + }) + .await + .map_err(|_| ReceiptError::TransportClosed)?; + if result_rx.await.map_err(|_| ReceiptError::TransportClosed)? { + Ok(()) + } else { + Err(ReceiptError::NoLongerTracked) + } + } + /// Wait until the packet is delivered or reaches another terminal state. pub async fn delivered(mut self) -> Result { loop { @@ -296,6 +381,8 @@ pub enum ReceiptError { Failed, #[error("packet receipt was culled")] Culled, + #[error("packet receipt is no longer pending")] + NoLongerTracked, #[error("transport closed before the receipt concluded")] TransportClosed, } @@ -320,6 +407,10 @@ pub enum SendError { NoInterface, #[error("another in-flight receipt has the same truncated packet hash")] ReceiptCollision, + #[error("packet was already sent; use resend")] + AlreadySent, + #[error("packet has not been sent yet")] + NotSent, #[error("transport control failed: {0}")] Control(#[from] ControlError), } @@ -576,11 +667,31 @@ impl ReticulumHandle { }) } + /// Prepare one stateful non-Link application packet. + /// + /// [`OutboundPacket::send`] performs the same validated destination + /// resolution, encryption, receipt registration, and dispatch as + /// [`Self::send_to`]. [`OutboundPacket::resend`] repeats that complete + /// path so each attempt receives fresh ciphertext and receipt state. + pub fn outbound_packet<'a>( + &'a self, + destination: &'a Destination, + data: &'a [u8], + options: SendOptions, + ) -> OutboundPacket<'a> { + OutboundPacket { + runtime: self, + destination, + data, + options, + sent: false, + } + } + /// Encrypt and dispatch one non-Link application packet. /// - /// SINGLE destinations are resolved from the validated announce cache so - /// callers do not need to manually compose packet headers, encryption, - /// receipt registration, and proof correlation. + /// Call [`Self::outbound_packet`] when the same logical packet may need + /// to be re-sent with fresh ciphertext. pub async fn send_to( &self, destination: &Destination, @@ -660,6 +771,7 @@ impl ReticulumHandle { packet_hash, truncated_hash, status_rx, + transport_tx: self.transport_tx.clone(), }), Some(TrackedReceiptRegistration { truncated_hash, @@ -5473,6 +5585,18 @@ loglevel = 7 b"hello" ); result_tx.send(OutboundDispatchResult::Sent).unwrap(); + + let TransportMessage::SetReceiptTimeout { + truncated_hash, + timeout, + result_tx, + } = transport_rx.recv().await.expect("receipt timeout update") + else { + panic!("expected receipt timeout update"); + }; + assert_eq!(truncated_hash, receipt.truncated_hash); + assert_eq!(timeout, Duration::from_secs(3)); + result_tx.send(true).unwrap(); receipt.status_tx.send_replace(ReceiptUpdate::Delivered { rtt: Duration::from_millis(42), }); @@ -5493,6 +5617,7 @@ loglevel = 7 .unwrap(); let receipt = sent.receipt.expect("receipt requested"); assert_eq!(receipt.packet_hash, sent.packet_hash); + receipt.set_timeout(Duration::from_secs(3)).await.unwrap(); assert_eq!( receipt.delivered().await.unwrap(), Duration::from_millis(42) @@ -5500,6 +5625,94 @@ loglevel = 7 responder.await.unwrap(); } + #[tokio::test] + async fn outbound_packet_resend_uses_fresh_ciphertext_and_enforces_state() { + let (transport_tx, mut transport_rx) = mpsc::channel::(4); + let (raw_tx, mut raw_rx) = mpsc::channel::(2); + let remote_identity = Identity::new(); + let destination = Destination::new( + Some(&remote_identity), + Direction::Out, + DestType::Single, + "resend.test", + ) + .unwrap(); + let destination_hash = destination.hash; + let public_key = remote_identity.get_public_key(); + let responder = tokio::spawn(async move { + for _ in 0..2 { + let TransportMessage::Rpc { query, response_tx } = + transport_rx.recv().await.expect("recall query") + else { + panic!("expected recall query"); + }; + assert!(matches!( + query, + TransportQuery::RecallDestination { dest } if dest == destination_hash + )); + response_tx + .send(TransportQueryResponse::RecalledDestination(Some( + RecalledDestinationRpcEntry { + dest_hash: destination_hash, + public_key, + app_data: None, + ratchet: None, + hops: 1, + timestamp: 1.0, + }, + ))) + .unwrap(); + + let TransportMessage::SendPacket { + request, + receipt, + result_tx, + .. + } = transport_rx.recv().await.expect("packet send") + else { + panic!("expected packet send"); + }; + assert!(receipt.is_none()); + raw_tx.send(request.raw).await.unwrap(); + result_tx.send(OutboundDispatchResult::Sent).unwrap(); + } + }); + + let mut handle = dummy_handle(); + handle.transport_tx = transport_tx; + let options = SendOptions { + create_receipt: false, + ..SendOptions::default() + }; + let mut packet = handle.outbound_packet(&destination, b"again", options); + assert!(matches!(packet.resend().await, Err(SendError::NotSent))); + + let first = packet.send().await.unwrap(); + assert!(packet.is_sent()); + assert!(matches!(packet.send().await, Err(SendError::AlreadySent))); + let second = packet.resend().await.unwrap(); + assert_ne!(first.packet_hash, second.packet_hash); + + let first_raw = raw_rx.recv().await.unwrap(); + let second_raw = raw_rx.recv().await.unwrap(); + assert_ne!(first_raw, second_raw); + let inbound = Destination::new( + Some(&remote_identity), + Direction::In, + DestType::Single, + "resend.test", + ) + .unwrap(); + for raw in [first_raw, second_raw] { + let packed = rns_wire::packet::Packet::from_raw(&raw).unwrap(); + assert_eq!( + inbound.decrypt(packed.data(), &remote_identity).unwrap(), + b"again" + ); + } + responder.await.unwrap(); + } + #[tokio::test] async fn send_to_reports_no_interface_without_returning_a_receipt() { let (transport_tx, mut transport_rx) = mpsc::channel::(2); diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 41da2b4..e8718fd 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -443,6 +443,24 @@ impl TransportActor { let _ = result_tx.send(result); } } + TransportMessage::SetReceiptTimeout { + truncated_hash, + timeout, + result_tx, + } => { + let updated = self + .receipt_table + .get_mut(&truncated_hash) + .is_some_and(|receipt| { + if receipt.status == ReceiptStatus::Sent { + receipt.timeout = Some(timeout); + true + } else { + false + } + }); + let _ = result_tx.send(updated); + } TransportMessage::Tick(_) => { self.on_tick(); } @@ -7701,6 +7719,46 @@ mod tests { assert!(!actor.receipt_msg_ids.contains_key(&proof_hash)); } + #[test] + fn set_receipt_timeout_updates_only_pending_receipts() { + let (mut actor, _tx) = TransportActor::new(); + let packet_hash = [0x62; 32]; + let truncated_hash = [0x62; 16]; + actor.receipt_table.insert( + truncated_hash, + PacketReceipt::new(packet_hash, truncated_hash, Some(Duration::from_secs(180))), + ); + + let (result_tx, result_rx) = tokio::sync::oneshot::channel(); + actor.handle_message(TransportMessage::SetReceiptTimeout { + truncated_hash, + timeout: Duration::from_secs(7), + result_tx, + }); + assert!(result_rx.blocking_recv().unwrap()); + assert_eq!( + actor.receipt_table[&truncated_hash].timeout, + Some(Duration::from_secs(7)) + ); + + actor + .receipt_table + .get_mut(&truncated_hash) + .unwrap() + .deliver(); + let (result_tx, result_rx) = tokio::sync::oneshot::channel(); + actor.handle_message(TransportMessage::SetReceiptTimeout { + truncated_hash, + timeout: Duration::from_secs(1), + result_tx, + }); + assert!(!result_rx.blocking_recv().unwrap()); + assert_eq!( + actor.receipt_table[&truncated_hash].timeout, + Some(Duration::from_secs(7)) + ); + } + #[test] fn outbound_destination_binding_survives_receipt_registration_order() { let destination = rns_identity::identity::Identity::new(); diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs index 5d57ade..cf939b0 100644 --- a/crates/rns-transport/src/messages.rs +++ b/crates/rns-transport/src/messages.rs @@ -310,6 +310,12 @@ pub enum TransportMessage { receipt: Option, result_tx: tokio::sync::oneshot::Sender, }, + /// Change the timeout of one still-pending tracked packet. + SetReceiptTimeout { + truncated_hash: [u8; 16], + timeout: std::time::Duration, + result_tx: tokio::sync::oneshot::Sender, + }, Tick(TimerTick), /// Read-only query paired with a oneshot reply channel — used for all /// RPC and introspection so callers don't need direct state access. @@ -441,6 +447,7 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str { TransportMessage::Outbound(_) => "Outbound", TransportMessage::OutboundAttached { .. } => "OutboundAttached", TransportMessage::SendPacket { .. } => "SendPacket", + TransportMessage::SetReceiptTimeout { .. } => "SetReceiptTimeout", TransportMessage::Tick(_) => "Tick", TransportMessage::Rpc { .. } => "Rpc", TransportMessage::RegisterDestination { .. } => "RegisterDestination", @@ -793,6 +800,15 @@ impl std::fmt::Debug for TransportMessage { .field("attached_interface", attached_interface) .field("receipt", receipt) .finish(), + Self::SetReceiptTimeout { + truncated_hash, + timeout, + .. + } => f + .debug_struct("SetReceiptTimeout") + .field("truncated_hash", truncated_hash) + .field("timeout", timeout) + .finish_non_exhaustive(), Self::Tick(t) => f.debug_tuple("Tick").field(t).finish(), Self::Rpc { query, .. } => f.debug_struct("Rpc").field("query", query).finish(), Self::RegisterDestination { hash, app_name, .. } => f