diff --git a/crates/lxmf-core/src/link_delivery.rs b/crates/lxmf-core/src/link_delivery.rs index 54c6d80..ee90ac7 100644 --- a/crates/lxmf-core/src/link_delivery.rs +++ b/crates/lxmf-core/src/link_delivery.rs @@ -146,7 +146,7 @@ impl LinkDeliveryStartOptions { timing, packed_override: Some(packed_payload), auto_compress, - reusable: false, + reusable: true, } } } @@ -389,9 +389,10 @@ pub struct PendingDelivery { packet_awaiting_dispatch: bool, pretransfer_identify_staged: bool, endpoint_release_queued: bool, - /// Keep successful Direct links open for additional messages. Propagation - /// deposits currently keep the old one-shot behavior. + /// Keep successful links open for additional messages. pub reusable: bool, + /// Upload link to a propagation node; never identified (LXMRouter.py:3283-3287). + propagation_upload: bool, /// Whether local Link identification was staged after a successful Direct /// delivery. Requires configured identity keys; it is not a peer acknowledgement. pub backchannel_identified: bool, @@ -801,6 +802,18 @@ pub struct DirectLinkSnapshot { pub idle_expired: bool, pub queued_deliveries: usize, pub in_flight_deliveries: usize, + /// Whether the Link ever became active. + pub link_activated: bool, +} + +impl DirectLinkSnapshot { + pub fn link_active(&self) -> bool { + self.link_state == LinkState::Active + } + + pub fn link_closed(&self) -> bool { + self.link_state == LinkState::Closed || self.delivery_state == DeliveryState::Failed + } } /// Snapshot of a message currently owned by link delivery. @@ -884,6 +897,8 @@ pub struct LinkDeliveryManager { direct_links: HashMap<[u8; 16], [u8; 16]>, /// Reusable upstream-style inbound backchannels keyed by remote LXMF delivery destination hash. backchannel_links: HashMap<[u8; 16], [u8; 16]>, + /// Reusable propagation upload links keyed by propagation node hash. + propagation_links: HashMap<[u8; 16], [u8; 16]>, pending: HashMap<[u8; 16], PendingDelivery>, backchannel_tx: Option>, backchannel_cancellation_aware: bool, @@ -942,6 +957,7 @@ impl LinkDeliveryManager { endpoint_lifecycle_rx, direct_links: HashMap::new(), backchannel_links: HashMap::new(), + propagation_links: HashMap::new(), pending: HashMap::new(), backchannel_tx: None, backchannel_cancellation_aware: false, @@ -1039,11 +1055,9 @@ impl LinkDeliveryManager { /// segments remain immutable. This never enables compression or changes the /// propagation-node envelope. New submissions still carry their own policy. pub fn disable_pending_direct_compression(&mut self, destination: [u8; 16]) { - for delivery in self - .pending - .values_mut() - .filter(|delivery| delivery.reusable && delivery.dest_hash == destination) - { + for delivery in self.pending.values_mut().filter(|delivery| { + delivery.reusable && !delivery.propagation_upload && delivery.dest_hash == destination + }) { if delivery.transfer.is_none() && delivery.remaining_segments.is_none() { delivery.message.auto_compress = false; delivery.auto_compress = false; @@ -1226,6 +1240,7 @@ impl LinkDeliveryManager { dest_hash: delivery.dest_hash, message: delivery.message, reason: reason.to_string(), + link_activated: true, }); } } @@ -1344,6 +1359,20 @@ impl LinkDeliveryManager { auto_compress: bool, timing: LinkEstablishmentTiming, ) -> Result<[u8; 16], LinkDeliveryStartFailure> { + if let Some(link_id) = self.propagation_links.get(&dest_hash).copied() { + if let Some(delivery) = self + .pending + .get_mut(&link_id) + .filter(|delivery| delivery.link.state != LinkState::Closed) + { + delivery.queue_delivery(message, Some(packed_payload), auto_compress); + if delivery.state == DeliveryState::Idle && delivery.link.is_active() { + let _ = delivery.start_queued_delivery(); + } + return Ok(link_id); + } + self.propagation_links.remove(&dest_hash); + } self.start_delivery_inner( message, dest_hash, @@ -1642,6 +1671,7 @@ impl LinkDeliveryManager { reusable, } = options; let msg_hash = Some(message.message_id()); + let packed_override_kind = packed_override.is_some(); let (mut link, request_data) = Link::new_initiator(dest_hash, hops); if link .try_extend_establishment_timeout(timing.first_hop_timeout().as_secs_f64()) @@ -1756,6 +1786,7 @@ impl LinkDeliveryManager { pretransfer_identify_staged: false, endpoint_release_queued: false, reusable, + propagation_upload: packed_override_kind, backchannel_identified: false, queued: VecDeque::new(), inbound_resources: HashMap::new(), @@ -1764,7 +1795,9 @@ impl LinkDeliveryManager { inbound_resource_lifecycles: HashMap::new(), }, ); - if reusable { + if packed_override_kind { + self.propagation_links.insert(dest_hash, link_id); + } else if reusable { self.direct_links.insert(dest_hash, link_id); } @@ -2417,7 +2450,7 @@ impl LinkDeliveryManager { }; delivery.link.record_inbound(); delivery.link.record_rx(encrypted_data.len()); - if !delivery.reusable { + if delivery.propagation_upload { let mut input = plaintext.as_slice(); let rejection = rmpv::decode::read_value(&mut input).ok(); if input.is_empty() @@ -2479,7 +2512,7 @@ impl LinkDeliveryManager { let Some(delivery) = self.pending.get_mut(link_id) else { return false; }; - if !delivery.reusable || !delivery.link.is_active() { + if !delivery.reusable || delivery.propagation_upload || !delivery.link.is_active() { return false; } @@ -2670,7 +2703,7 @@ impl LinkDeliveryManager { let Some(delivery) = self.pending.get_mut(link_id) else { return false; }; - if !delivery.reusable || !delivery.link.is_active() { + if !delivery.reusable || delivery.propagation_upload || !delivery.link.is_active() { return false; } delivery.link.record_inbound(); @@ -3046,8 +3079,6 @@ impl LinkDeliveryManager { } // Reusable Direct links follow upstream LXMF and identify // after a successful delivery, not before the transfer. - // One-shot propagation links keep the previous pre-transfer - // identify behavior for compatibility with existing callers. delivery.state = DeliveryState::Transferring; if delivery.message.progress < 0.05 { delivery.message.progress = 0.05; @@ -3395,7 +3426,9 @@ impl LinkDeliveryManager { resource_id, ); } - if delivery.reusable { + if delivery.propagation_upload { + self.propagation_links.remove(&delivery.dest_hash); + } else if delivery.reusable { self.direct_links.remove(&delivery.dest_hash); } let graceful_release = delivery.endpoint_release_queued @@ -3662,6 +3695,7 @@ impl LinkDeliveryManager { dest_hash: delivery.dest_hash, message: delivery.message, reason, + link_activated: true, }); } } @@ -4151,6 +4185,7 @@ impl LinkDeliveryManager { dest_hash: delivery.dest_hash, message: delivery.message, reason, + link_activated: true, }) } } @@ -4376,6 +4411,7 @@ impl LinkDeliveryManager { dest_hash: delivery.dest_hash, message: queued.message, reason: reason.to_string(), + link_activated: delivery.link.activated_at.is_some(), }); } break; @@ -4405,6 +4441,9 @@ impl LinkDeliveryManager { if self.direct_links.get(&dest_hash) == Some(&link_id) { self.direct_links.remove(&dest_hash); } + if self.propagation_links.get(&dest_hash) == Some(&link_id) { + self.propagation_links.remove(&dest_hash); + } } if !results.is_empty() { @@ -4460,6 +4499,7 @@ impl LinkDeliveryManager { dest_hash: delivery.dest_hash, message: delivery.message, reason: reason.to_string(), + link_activated: true, }); } @@ -4533,6 +4573,9 @@ impl LinkDeliveryManager { if self.direct_links.get(&dest_hash) == Some(&link_id) { self.direct_links.remove(&dest_hash); } + if self.propagation_links.get(&dest_hash) == Some(&link_id) { + self.propagation_links.remove(&dest_hash); + } } if cancelled { @@ -4859,6 +4902,23 @@ impl LinkDeliveryManager { idle_expired: direct_link_idle_expired(delivery), queued_deliveries: delivery.queued.len(), in_flight_deliveries: usize::from(delivery.state != DeliveryState::Idle), + link_activated: delivery.link.activated_at.is_some(), + }) + } + + /// Snapshot of the reusable upload Link to a propagation node. + pub fn propagation_link_snapshot(&self, node: [u8; 16]) -> Option { + let link_id = *self.propagation_links.get(&node)?; + let delivery = self.pending.get(&link_id)?; + Some(DirectLinkSnapshot { + link_id, + dest_hash: node, + link_state: delivery.link.state, + delivery_state: delivery.state, + idle_expired: direct_link_idle_expired(delivery), + queued_deliveries: delivery.queued.len(), + in_flight_deliveries: usize::from(delivery.state != DeliveryState::Idle), + link_activated: delivery.link.activated_at.is_some(), }) } @@ -4897,7 +4957,11 @@ impl LinkDeliveryManager { pub fn stats(&self) -> LinkDeliveryStats { let mut stats = LinkDeliveryStats { sessions: self.pending.len(), - direct_sessions: self.pending.values().filter(|d| d.reusable).count(), + direct_sessions: self + .pending + .values() + .filter(|d| d.reusable && !d.propagation_upload) + .count(), one_shot_sessions: self.pending.values().filter(|d| !d.reusable).count(), backchannel_sessions: self.backchannel_links.len(), pending_backchannel_starts: self @@ -4944,7 +5008,7 @@ fn delivery_event( ) -> LxmfDeliveryEvent { LxmfDeliveryEvent { kind, - method: if delivery.reusable { + method: if !delivery.propagation_upload { LxmfDeliveryEventMethod::Direct } else { LxmfDeliveryEventMethod::PropagationDeposit @@ -5073,6 +5137,7 @@ fn fail_backchannel_start_in_place( dest_hash: start.dest_hash, message, reason, + link_activated: true, } } @@ -5138,6 +5203,7 @@ fn finish_reusable_delivery( delivery: &mut PendingDelivery, ) { if !delivery.backchannel_identified + && !delivery.propagation_upload && let (Some(pub_key), Some(sign_key)) = (identity_pub, identity_key) { delivery.backchannel_identified = send_link_identify( @@ -5227,6 +5293,7 @@ fn push_failed_delivery_and_queue( dest_hash: delivery.dest_hash, message, reason: reason.to_string(), + link_activated: delivery.link.activated_at.is_some(), }); fail_queued_deliveries(results, events, link_id, delivery, reason); } @@ -5259,6 +5326,7 @@ fn fail_queued_deliveries( dest_hash: delivery.dest_hash, message: queued.message, reason: reason.to_string(), + link_activated: delivery.link.activated_at.is_some(), }); } } @@ -5487,6 +5555,8 @@ pub enum DeliveryResult { dest_hash: [u8; 16], message: LxMessage, reason: String, + /// Whether the Link carrying the message had become active. + link_activated: bool, }, } @@ -6519,7 +6589,7 @@ mod tests { } #[tokio::test] - async fn exact_packed_packet_preserves_rtt_identify_and_payload_order() { + async fn exact_packed_packet_sends_rtt_then_payload_without_identify() { exact_packet_driver_fixture(false, true).await; } @@ -6802,34 +6872,6 @@ mod tests { mgr.tick().is_empty(), "5ms proof floor must not run before driver admission" ); - if packed { - assert_eq!(mgr.pending[&link_id].state, DeliveryState::Identifying); - let rtt = driver_rx.recv().await.unwrap(); - let (header, offset) = rns_wire::header::PacketHeader::unpack(&rtt).unwrap(); - assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt); - responder.receive_rtt_packet(&rtt[offset..]).unwrap(); - tx.send(TransportMessage::Tick(TimerTick { - timestamp: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs_f64(), - })) - .await - .unwrap(); - tokio::time::timeout(Duration::from_secs(2), async { - loop { - assert!(mgr.tick().is_empty()); - if mgr.pending[&link_id].state == DeliveryState::AwaitingProof { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .unwrap(); - tokio::time::sleep(Duration::from_millis(30)).await; - assert!(mgr.tick().is_empty()); - } assert!(mgr.pending[&link_id].packet_awaiting_dispatch); assert_eq!( mgr.message_timeout_window(message_hash).unwrap().1, @@ -6841,19 +6883,9 @@ mod tests { } let rtt = driver_rx.recv().await.unwrap(); let (header, offset) = rns_wire::header::PacketHeader::unpack(&rtt).unwrap(); - if packed { - assert_eq!( - header.context, - rns_wire::context::PacketContext::LinkIdentify - ); - assert_eq!( - responder.handle_identification(&rtt[offset..]).unwrap(), - identity_pub - ); - } else { - assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt); - responder.receive_rtt_packet(&rtt[offset..]).unwrap(); - } + // Propagation uploads are never identified, even with identity keys. + assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt); + responder.receive_rtt_packet(&rtt[offset..]).unwrap(); tx.send(TransportMessage::Tick(TimerTick { timestamp: std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -9112,29 +9144,34 @@ mod tests { } #[test] - fn test_packed_delivery_is_one_shot_not_direct_session() { + fn packed_deliveries_share_one_propagation_link() { let (tx, _rx) = mpsc::channel(64); let mut mgr = LinkDeliveryManager::new(tx, None, None); - let dest_hash = [0xC1; 16]; - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Propagation", - "deposit", - crate::constants::DeliveryMethod::Propagated, - ); + let node = [0xC1; 16]; + let message = |content: &str| { + crate::message::test_message( + [0xAA; 16], + [0xBB; 16], + "Propagation", + content, + crate::constants::DeliveryMethod::Propagated, + ) + }; - let link_id = mgr - .start_packed_delivery(msg, dest_hash, 1, b"packed propagation".to_vec(), false) + let first = mgr + .start_packed_delivery(message("one"), node, 1, b"one".to_vec(), false) + .unwrap(); + let second = mgr + .start_packed_delivery(message("two"), node, 1, b"two".to_vec(), false) .unwrap(); - assert_eq!(mgr.pending_count(), 1); + assert_eq!(first, second, "a second upload reuses the pending link"); assert_eq!(mgr.session_count(), 1); + assert_eq!(mgr.pending_count(), 2); assert_eq!(mgr.stats().direct_sessions, 0); - assert_eq!(mgr.stats().one_shot_sessions, 1); - assert!(!mgr.delivery_link_available(&dest_hash)); - assert!(mgr.direct_link_snapshot(dest_hash).is_none()); - assert!(!mgr.pending.get(&link_id).unwrap().reusable); + assert!(mgr.direct_link_snapshot(node).is_none()); + let snapshot = mgr.propagation_link_snapshot(node).unwrap(); + assert_eq!(snapshot.queued_deliveries, 1); } #[test] diff --git a/crates/lxmf-core/src/message.rs b/crates/lxmf-core/src/message.rs index 99bc93a..5d62b19 100644 --- a/crates/lxmf-core/src/message.rs +++ b/crates/lxmf-core/src/message.rs @@ -48,6 +48,11 @@ fn bounded_lossy_text(bytes: &[u8]) -> Cow<'_, str> { } pub type MessageCallback = Arc; +fn run_isolated_callback(callback: &MessageCallback, message: &LxMessage, kind: &str) { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(message))).is_err() { + tracing::error!(callback = kind, "an external message callback panicked"); + } +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AudioField<'a> { pub mode: u8, @@ -84,6 +89,13 @@ pub struct MessageMetadata { pub progress: f64, pub auto_compress: bool, pub callbacks: MessageCallbacks, + /// Retry state owned by the outbound router; never persisted. + pub awaiting_path: bool, + pub sent_on_path: bool, + pub sent_on_slow_path: bool, + pub path_request_retried: bool, + pub max_delivery_attempts: Option, + pub receipt_timeout: Option, } impl Default for MessageMetadata { fn default() -> Self { @@ -103,6 +115,12 @@ impl Default for MessageMetadata { progress: 0., auto_compress: true, callbacks: MessageCallbacks::default(), + awaiting_path: false, + sent_on_path: false, + sent_on_slow_path: false, + path_request_retried: false, + max_delivery_attempts: None, + receipt_timeout: None, } } } @@ -479,18 +497,20 @@ impl LxMessage { } /// Invoke the delivery callback, if registered. Every call invokes it again; - /// the caller must prevent duplicate notifications when required. + /// the caller must prevent duplicate notifications when required. A + /// panicking callback is logged and contained. pub fn notify_delivered(&self) { if let Some(ref cb) = self.callbacks.on_delivered { - cb(self); + run_isolated_callback(cb, self, "delivery"); } } /// Invoke the failure callback, if registered. Every call invokes it again; - /// the caller must prevent duplicate notifications when required. + /// the caller must prevent duplicate notifications when required. A + /// panicking callback is logged and contained. pub fn notify_failed(&self) { if let Some(ref cb) = self.callbacks.on_failed { - cb(self); + run_isolated_callback(cb, self, "failed"); } } @@ -654,7 +674,11 @@ impl LxMessage { self.state = MessageState::Rejected; } + /// Mark the message delivered; repeated calls notify only once. pub fn mark_delivered(&mut self) { + if self.state == MessageState::Delivered { + return; + } self.state = MessageState::Delivered; self.notify_delivered(); } diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index f1cb6ff..4d2710b 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -28,6 +28,9 @@ use crate::stamper; use crate::ticket::{Ticket, TicketStore}; use crate::types::PropagationTransientId; +pub mod outbound; +pub use outbound::{MediumSnapshot, RouteInfo, attempt_due, attempt_limit, schedule_attempt}; + /// Outstanding inbound admission reservation. Return it to the same router /// instance that issued it; its counter is not unique across router instances. #[derive(Debug)] @@ -212,29 +215,7 @@ pub enum TicketPreparationError { Encode(String), } -/// Current route metadata for an LXMF Direct delivery destination. -#[derive(Debug, Clone, PartialEq)] -pub struct DirectRouteSnapshot { - pub destination_hash: [u8; 16], - pub hops: u8, - pub interface_name: Option, - pub learned_at: Option, - pub expires_at: Option, -} - -impl DirectRouteSnapshot { - pub fn new(destination_hash: [u8; 16], hops: u8) -> Self { - Self { - destination_hash, - hops: hops.max(1), - interface_name: None, - learned_at: None, - expires_at: None, - } - } -} - -/// Reusable Direct/backchannel Link state visible to the router-level policy. +/// Reusable Direct/backchannel or propagation Link state visible to the router. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DirectReusableLinkState { None, @@ -243,99 +224,48 @@ pub enum DirectReusableLinkState { Closed { activated: bool }, } -/// Input snapshot for core Direct-delivery planning. +/// Link work the router asks the embedder to perform for one message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkDeliveryPlan { + /// Send over the established Link to the target. + UseLink, + /// Establish a new Link to the target carrying this message. + StartLink { hops: u8 }, +} + +/// Embedder snapshot consumed by [`LxmRouter::process_outbound_with_inputs`]. #[derive(Debug, Clone, PartialEq)] -pub struct DirectDeliveryPlanInput { - pub identity_known: bool, - pub route: Option, - pub reusable_link: DirectReusableLinkState, +pub struct OutboundInputs { + pub medium: MediumSnapshot, + /// Destinations, including the propagation node, whose identity is known. + pub identities: HashSet<[u8; 16]>, + /// Reusable Direct or backchannel Link state per destination; absent means none. + pub direct_links: HashMap<[u8; 16], DirectReusableLinkState>, + /// State of the reusable Link to the outbound propagation node. + pub propagation_link: DirectReusableLinkState, + /// Propagated messages whose propagation stamp is still being generated. + /// Like Python's deferred stamp queue, they are not processed yet. + pub propagation_unready: HashSet<[u8; 32]>, + /// Messages a Link delivery already carries, from a `StartLink` plan. + pub link_owned: HashSet<[u8; 32]>, } -/// Core Direct-delivery policy decision. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum DirectDeliveryPlan { - UseReusableLink, - WaitForReusableLink, - StartNewLink { hops: u8 }, - RequestPath { drop_existing: bool }, - DeferTerminalFailure, - Fail, +impl Default for OutboundInputs { + fn default() -> Self { + Self { + medium: MediumSnapshot::default(), + identities: HashSet::new(), + direct_links: HashMap::new(), + propagation_link: DirectReusableLinkState::None, + propagation_unready: HashSet::new(), + link_owned: HashSet::new(), + } + } } -/// Plan a Direct delivery from the caller's identity, route and Link snapshot. -/// Mutates attempt, timing, progress and message state; the caller performs -/// path requests and Link operations and reports their outcomes. -pub fn plan_direct_delivery( - message: &mut LxMessage, - input: DirectDeliveryPlanInput, - now: f64, -) -> DirectDeliveryPlan { - if message.delivery_attempts > MAX_DELIVERY_ATTEMPTS { - message.mark_failed(); - return DirectDeliveryPlan::Fail; - } - - match input.reusable_link { - DirectReusableLinkState::Active => { - if message.progress < 0.05 { - message.progress = 0.05; - } - if message.state != MessageState::Sending { - message.mark_sending(); - } - return DirectDeliveryPlan::UseReusableLink; - } - DirectReusableLinkState::Pending => { - return DirectDeliveryPlan::WaitForReusableLink; - } - DirectReusableLinkState::Closed { .. } => { - message.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; - if message.progress < 0.01 { - message.progress = 0.01; - } - return DirectDeliveryPlan::RequestPath { - drop_existing: true, - }; - } - DirectReusableLinkState::None => {} - } - - if !input.identity_known { - message.delivery_attempts += 1; - message.last_delivery_attempt = now; - message.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; - if message.progress < 0.01 { - message.progress = 0.01; - } - return DirectDeliveryPlan::RequestPath { - drop_existing: false, - }; - } - - message.delivery_attempts += 1; - message.last_delivery_attempt = now; - message.next_delivery_attempt = now + DELIVERY_RETRY_WAIT as f64; - - if message.delivery_attempts >= MAX_DELIVERY_ATTEMPTS { - return DirectDeliveryPlan::DeferTerminalFailure; - } - - if let Some(route) = input.route { - if message.progress < 0.03 { - message.progress = 0.03; - } - DirectDeliveryPlan::StartNewLink { - hops: route.hops.max(1), - } - } else { - message.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; - if message.progress < 0.01 { - message.progress = 0.01; - } - DirectDeliveryPlan::RequestPath { - drop_existing: false, - } - } +enum OutboundStep { + Removed, + Kept { advanced: bool }, } /// Router-owned policy and queues. The embedding application serializes access and drives it. @@ -396,17 +326,15 @@ pub struct LxmRouter { next_inbound_reservation: u64, /// Destinations of delivered messages not yet taken by the embedder. destination_retains: VecDeque<[u8; 16]>, + /// Last router path request per destination, for debouncing. + path_request_times: HashMap<[u8; 16], f64>, + /// A slow-path message concluded; outbound processing should run again. + outbound_kick: bool, } /// Delivered destinations a router holds for the embedder to retain. const MAX_PENDING_RETAINS: usize = 256; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum DirectOutboundHandling { - EmitLegacyAction, - LeavePending, -} - /// Callback invoked when a message is delivered locally. pub type DeliveryCallback = Box; @@ -503,6 +431,8 @@ impl LxmRouter { inbound_reservations: HashMap::new(), next_inbound_reservation: 0, destination_retains: VecDeque::new(), + path_request_times: HashMap::new(), + outbound_kick: false, } } @@ -901,16 +831,21 @@ impl LxmRouter { self.allowed_control.retain(|h| h != identity_hash); } + /// Drop delivered messages whose source is `dest_hash` (Python + /// `ignore_destination`). Propagation storage is unaffected, as in Python. pub fn ignore_destination(&mut self, dest_hash: [u8; 16]) { if !self.ignored.contains(&dest_hash) { self.ignored.push(dest_hash); } - self.propagation_store.ignore_destination(dest_hash); } pub fn unignore_destination(&mut self, dest_hash: &[u8; 16]) { self.ignored.retain(|h| h != dest_hash); - self.propagation_store.unignore_destination(dest_hash); + } + + /// Whether messages from this source are ignored on delivery. + pub fn is_ignored(&self, source_hash: &[u8; 16]) -> bool { + self.ignored.contains(source_hash) } /// Mark an outbound destination as PLAIN, as a Python `LXMessage` built @@ -945,6 +880,11 @@ impl LxmRouter { !self.compression_unsupported.contains(dest_hash) } + /// Python `LXMessage.send` re-reads compression support for its recipient on every send. + fn message_compression_supported(&self, i: usize) -> bool { + self.compression_supported(&self.pending_outbound[i].destination_hash()) + } + pub fn prioritise(&mut self, identity_hash: [u8; 16], level: u8) { self.prioritized.insert(identity_hash, level); self.propagation_store.prioritise_destination(identity_hash); @@ -1115,7 +1055,8 @@ impl LxmRouter { } /// Mark a pending outbound message delivered and remove it from the - /// outbound queue. + /// outbound queue. A message that went over a slow path asks for another + /// outbound pass ([`Self::take_outbound_kick`]). pub fn mark_outbound_delivered(&mut self, message_hash: &[u8; 32]) -> bool { let Some(pos) = self .pending_outbound @@ -1126,10 +1067,38 @@ impl LxmRouter { }; let msg = self.pending_outbound.remove(pos); + self.outbound_kick |= msg.sent_on_slow_path; self.complete_outbound_message(msg); true } + /// Mark a pending propagated message accepted by the propagation node + /// (Python `__mark_propagated`) and remove it from the outbound queue. + pub fn mark_outbound_propagated(&mut self, message_hash: &[u8; 32]) -> bool { + let Some(pos) = self + .pending_outbound + .iter() + .position(|m| &m.message_id() == message_hash) + else { + return false; + }; + let mut msg = self.pending_outbound.remove(pos); + self.outbound_kick |= msg.sent_on_slow_path; + let destination = msg.destination_hash(); + if !self.destination_retains.contains(&destination) { + if self.destination_retains.len() == MAX_PENDING_RETAINS { + self.destination_retains.pop_front(); + } + self.destination_retains.push_back(destination); + } + if msg.state != MessageState::Sent { + msg.state = MessageState::Sent; + msg.progress = 1.0; + msg.notify_delivered(); + } + true + } + /// Complete an outbound message whose in-flight ownership moved from the /// router queue into an embedding runtime. /// @@ -1163,8 +1132,8 @@ impl LxmRouter { self.destination_retains.drain(..).collect() } - /// Mark a pending outbound message failed and remove it from the outbound - /// queue. + /// Fail a pending outbound message (Python `fail_message`) and remove it + /// from the outbound queue. pub fn mark_outbound_failed(&mut self, message_hash: &[u8; 32]) -> bool { let Some(pos) = self .pending_outbound @@ -1173,9 +1142,7 @@ impl LxmRouter { else { return false; }; - - let mut msg = self.pending_outbound.remove(pos); - msg.mark_failed(); + self.fail_pending(pos); true } @@ -1196,24 +1163,6 @@ impl LxmRouter { true } - /// Re-arm a pending outbound message after a path request without adding a - /// duplicate queue entry. - pub fn defer_outbound_for_path_request(&mut self, message_hash: &[u8; 32], now: f64) -> bool { - let Some(msg) = self - .pending_outbound - .iter_mut() - .find(|m| &m.message_id() == message_hash) - else { - return false; - }; - - msg.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; - if msg.progress < 0.01 { - msg.progress = 0.01; - } - true - } - /// Get the recorded progress for a queued or deferred message. The value is /// returned unchanged; caller-written metadata is not clamped here. /// @@ -1266,7 +1215,8 @@ impl LxmRouter { /// effects or record a distinct ciphertext transient ID. Use the reservation /// and durable-receipt commit path for application admission. pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool { - if self.ignored.contains(&message.source_hash()) { + // LXMRouter.py:2231-2233: ignored sources are dropped before dedup. + if self.is_ignored(&message.source_hash()) { return false; } let message_id = message.message_id(); @@ -1678,19 +1628,19 @@ impl LxmRouter { self.outbound_propagation_node = destination_hash; } - /// Mark pending messages due after a destination announce. - /// - /// Python's delivery announce handler sets `next_delivery_attempt = time.time()` - /// and triggers outbound processing. Rust tracks the previous attempt time, - /// so setting it beyond the retry window makes the message eligible on the - /// next scheduler tick. + /// Python's delivery announce handler: re-arm Direct and Opportunistic + /// messages to the destination that are awaiting a path. Returns how many. pub fn trigger_outbound_for_delivery_announce(&mut self, destination_hash: [u8; 16]) -> usize { let now = now_f64(); - let due_now = now - DELIVERY_RETRY_WAIT as f64; let mut triggered = 0; for message in &mut self.pending_outbound { - if message.destination_hash() == destination_hash { - message.last_delivery_attempt = due_now; + if message.destination_hash() == destination_hash + && matches!( + message.method, + DeliveryMethod::Direct | DeliveryMethod::Opportunistic + ) + && message.awaiting_path + { message.next_delivery_attempt = now; triggered += 1; } @@ -1698,10 +1648,8 @@ impl LxmRouter { triggered } - /// Mark pending propagated messages due after the configured propagation node announces. - /// - /// Requires the configured destination and app data accepted by - /// [`crate::handlers::pn_announce_data_is_valid`] before clearing retry backoff. + /// Python's propagation node announce handler: re-arm Propagated messages + /// awaiting a path when the configured outbound node announces valid data. /// The caller verifies the announce's identity and authenticity. pub fn trigger_outbound_for_propagation_node_announce( &mut self, @@ -1716,11 +1664,9 @@ impl LxmRouter { } let now = now_f64(); - let due_now = now - DELIVERY_RETRY_WAIT as f64; let mut triggered = 0; for message in &mut self.pending_outbound { - if message.method == DeliveryMethod::Propagated { - message.last_delivery_attempt = due_now; + if message.method == DeliveryMethod::Propagated && message.awaiting_path { message.next_delivery_attempt = now; triggered += 1; } @@ -1953,297 +1899,537 @@ impl LxmRouter { } } - /// Move eligible outbound messages into [`OutboundAction`]s, subject to - /// retry times and the per-call processing limit. Other messages remain queued. - /// The caller owns emitted deliveries, including proof tracking and retries; - /// requeue retryable failures through [`Self::try_send`] after updating attempts. + /// [`Self::process_outbound_with_inputs`] with no path, identity or Link + /// knowledge, for embedders that track none of them. + pub fn process_outbound(&mut self) -> Vec { + self.process_outbound_with_inputs(&OutboundInputs::default(), now_f64()) + } + + /// Plan outbound work as Python `LXMRouter.process_outbound` does. + /// + /// Messages stay in `pending_outbound` until the embedder reports a + /// terminal outcome ([`Self::mark_outbound_delivered`], + /// [`Self::mark_outbound_propagated`], [`Self::mark_outbound_rejected`], + /// [`Self::outbound_link_closed`]) or the router fails them. Emitted send + /// actions carry a copy of the queued message. #[tracing::instrument( level = "debug", - name = "router.process_outbound", + name = "router.process_outbound_with_inputs", skip_all, fields(pending_count = self.pending_outbound.len()), )] - pub fn process_outbound(&mut self) -> Vec { - self.process_outbound_inner(DirectOutboundHandling::EmitLegacyAction) - } - - fn process_outbound_without_direct(&mut self) -> Vec { - self.process_outbound_inner(DirectOutboundHandling::LeavePending) - } - - fn process_outbound_inner( + pub fn process_outbound_with_inputs( &mut self, - direct_handling: DirectOutboundHandling, + inputs: &OutboundInputs, + now: f64, ) -> Vec { if !self.config.ext.processing_outbound { return Vec::new(); } - let mut actions = Vec::new(); - let mut processed = 0usize; - + let mut links_started = HashSet::new(); + let mut advanced = 0usize; let mut i = 0; while i < self.pending_outbound.len() { if self .config .ext .processing_limit - .is_some_and(|limit| processed >= limit) + .is_some_and(|limit| advanced >= limit) { break; } - - let msg = &self.pending_outbound[i]; - - let now = now_f64(); - - // Python fails only when delivery_attempts > MAX (outer guard is - // `<= MAX`, LXMRouter.py:2597/2671); match that boundary exactly. - if msg.delivery_attempts > MAX_DELIVERY_ATTEMPTS { - let mut msg = self.pending_outbound.remove(i); - msg.mark_failed(); - actions.push(OutboundAction::Failed(msg)); - processed += 1; - continue; - } - - // Python LXMF gates on an absolute `next_delivery_attempt`. Honor an - // explicit deadline when set (path request -> now+7s, etc.); - // otherwise fall back to the legacy - // last_delivery_attempt + DELIVERY_RETRY_WAIT (10s) rule. - let due_at = if msg.next_delivery_attempt > 0.0 { - msg.next_delivery_attempt - } else if msg.last_delivery_attempt > 0.0 { - msg.last_delivery_attempt + DELIVERY_RETRY_WAIT as f64 - } else { - 0.0 - }; - if now < due_at { - i += 1; - continue; - } - - let age = now - msg.timestamp(); - if age > MESSAGE_EXPIRY as f64 { - let mut msg = self.pending_outbound.remove(i); - msg.mark_failed(); - actions.push(OutboundAction::Expired(msg)); - processed += 1; - continue; - } - - // State transitions match Python LXMessage.py:476-499: - // Opportunistic -> Sent immediately; the embedding runtime keeps - // receipt ownership until an authenticated packet proof arrives. - // Direct / Propagated -> Sending (multi-step). - match msg.method { - DeliveryMethod::Direct => { - match direct_handling { - DirectOutboundHandling::EmitLegacyAction => { - let mut msg = self.pending_outbound.remove(i); - msg.mark_sending(); - let dest_hash = msg.destination_hash(); - msg.auto_compress = self.compression_supported(&dest_hash); - actions.push(OutboundAction::DeliverDirect { - message: msg, - dest_hash, - }); - processed += 1; - // The next element has shifted into index i, so do not advance. - } - DirectOutboundHandling::LeavePending => { - i += 1; - } - } - } - DeliveryMethod::Propagated => { - if let Some(peer_hash) = self.outbound_propagation_node { - let mut msg = self.pending_outbound.remove(i); - msg.mark_sending(); - actions.push(OutboundAction::DeliverPropagated { - message: msg, - prop_hash: peer_hash, - }); - processed += 1; - } else { - i += 1; - } - } - DeliveryMethod::Opportunistic => { - let mut msg = self.pending_outbound.remove(i); - msg.mark_sent(); - msg.progress = 0.50; - let dest_hash = msg.destination_hash(); - msg.auto_compress = self.compression_supported(&dest_hash); - actions.push(OutboundAction::DeliverOpportunistic { - message: msg, - dest_hash, - }); - processed += 1; - } - _ => { + match self.plan_outbound(i, inputs, now, &mut links_started, &mut actions) { + OutboundStep::Removed => advanced += 1, + OutboundStep::Kept { advanced: moved } => { + advanced += usize::from(moved); i += 1; } } } - actions } - /// Plan Direct deliveries while retaining their originals in the router queue. - /// The caller executes plans, reports terminal Link results to the router and - /// handles non-Direct actions. This method does not poll a Link manager itself. - pub fn process_outbound_with_direct(&mut self, mut direct_input: F) -> Vec - where - F: FnMut(&LxMessage, f64) -> DirectDeliveryPlanInput, - { - if !self.config.ext.processing_outbound { - return Vec::new(); + fn plan_outbound( + &mut self, + i: usize, + inputs: &OutboundInputs, + now: f64, + links_started: &mut HashSet<[u8; 16]>, + actions: &mut Vec, + ) -> OutboundStep { + let message = &self.pending_outbound[i]; + match (message.state, message.method) { + (MessageState::Delivered, _) | (MessageState::Sent, DeliveryMethod::Propagated) => { + self.pending_outbound.remove(i); + return OutboundStep::Removed; + } + (MessageState::Cancelled | MessageState::Rejected, _) => { + let message = self.pending_outbound.remove(i); + message.notify_failed(); + return OutboundStep::Removed; + } + _ => {} + } + if self.pending_outbound[i].progress < 0.01 { + self.pending_outbound[i].progress = 0.01; + } + match self.pending_outbound[i].method { + DeliveryMethod::Opportunistic => self.plan_opportunistic(i, inputs, now, actions), + DeliveryMethod::Direct => self.plan_direct(i, inputs, now, links_started, actions), + DeliveryMethod::Propagated => { + self.plan_propagated(i, inputs, now, links_started, actions) + } + DeliveryMethod::Paper => OutboundStep::Kept { advanced: false }, + } + } + + fn plan_opportunistic( + &mut self, + i: usize, + inputs: &OutboundInputs, + now: f64, + actions: &mut Vec, + ) -> OutboundStep { + let medium = &inputs.medium; + let destination = self.pending_outbound[i].destination_hash(); + let has_path = medium.has_path(&destination); + let message = &self.pending_outbound[i]; + // LXMRouter.handle_outbound requests an unknown path before the first attempt. + if message.delivery_attempts == 0 + && message.next_delivery_attempt == 0.0 + && !message.awaiting_path + && !has_path + { + self.request_path_action(destination, medium, now, actions); + schedule_attempt( + &mut self.pending_outbound[i], + medium.medium_path_timeout, + true, + now, + ); + return OutboundStep::Kept { advanced: true }; + } + let held = self.slow_path_held(i, Some(destination), medium); + let message = &self.pending_outbound[i]; + let due = attempt_due(message, has_path, now); + if held || !due { + return OutboundStep::Kept { advanced: false }; + } + if message.delivery_attempts > attempt_limit(message) { + actions.push(OutboundAction::Failed(self.fail_pending(i))); + return OutboundStep::Removed; } - let mut actions = Vec::new(); - let mut processed = 0usize; - let mut i = 0; - - while i < self.pending_outbound.len() { - if self - .config - .ext - .processing_limit - .is_some_and(|limit| processed >= limit) - { - break; + self.pending_outbound[i].awaiting_path = false; + let attempts = self.pending_outbound[i].delivery_attempts; + if attempts >= MAX_PATHLESS_TRIES && !has_path { + let message = &mut self.pending_outbound[i]; + message.delivery_attempts += 1; + message.sent_on_path = false; + self.request_path_action(destination, medium, now, actions); + let message = &mut self.pending_outbound[i]; + schedule_attempt(message, medium.medium_path_timeout, true, now); + message.progress = 0.01; + } else if attempts == MAX_PATHLESS_TRIES + 1 + && has_path + && self.pending_outbound[i].sent_on_path + { + let message = &mut self.pending_outbound[i]; + message.delivery_attempts += 1; + message.sent_on_path = false; + message.awaiting_path = true; + if !self.path_request_pending(&destination, medium, now) { + self.path_request_times.insert(destination, now); + actions.push(OutboundAction::RequestPath { + destination, + drop_existing: true, + }); } + let message = &mut self.pending_outbound[i]; + message.next_delivery_attempt = now + medium.path_request_wait(); + message.progress = 0.01; + } else { + let slow = slow_path(medium, &destination); + let compress = self.compression_supported(&destination); + let message = &mut self.pending_outbound[i]; + message.delivery_attempts += 1; + message.sent_on_path = has_path; + message.sent_on_slow_path = slow; + message.auto_compress = compress; + schedule_attempt( + message, + medium.destination_round_trip(&destination), + false, + now, + ); + message.state = MessageState::Sent; + message.progress = 0.50; + actions.push(OutboundAction::SendOpportunistic { + message: message.clone(), + }); + } + OutboundStep::Kept { advanced: true } + } - let now = now_f64(); + fn plan_direct( + &mut self, + i: usize, + inputs: &OutboundInputs, + now: f64, + links_started: &mut HashSet<[u8; 16]>, + actions: &mut Vec, + ) -> OutboundStep { + let medium = &inputs.medium; + let destination = self.pending_outbound[i].destination_hash(); + let link = if links_started.contains(&destination) { + DirectReusableLinkState::Pending + } else { + inputs + .direct_links + .get(&destination) + .copied() + .unwrap_or(DirectReusableLinkState::None) + }; + let route = medium + .route(&destination) + .filter(|_| inputs.identities.contains(&destination)); + let owned = inputs + .link_owned + .contains(&self.pending_outbound[i].message_id()); + self.plan_link_delivery( + i, + destination, + link, + route, + owned, + medium, + now, + actions, + || { + links_started.insert(destination); + }, + ) + } - if self.pending_outbound[i].delivery_attempts > MAX_DELIVERY_ATTEMPTS { - let mut msg = self.pending_outbound.remove(i); - msg.mark_failed(); - actions.push(OutboundAction::Failed(msg)); - processed += 1; - continue; + fn plan_propagated( + &mut self, + i: usize, + inputs: &OutboundInputs, + now: f64, + links_started: &mut HashSet<[u8; 16]>, + actions: &mut Vec, + ) -> OutboundStep { + let Some(node) = self.outbound_propagation_node else { + actions.push(OutboundAction::Failed(self.fail_pending(i))); + return OutboundStep::Removed; + }; + if inputs + .propagation_unready + .contains(&self.pending_outbound[i].message_id()) + { + return OutboundStep::Kept { advanced: false }; + } + let link = if links_started.contains(&node) { + DirectReusableLinkState::Pending + } else { + inputs.propagation_link + }; + let medium = &inputs.medium; + let route = medium + .route(&node) + .filter(|_| inputs.identities.contains(&node)); + let owned = inputs + .link_owned + .contains(&self.pending_outbound[i].message_id()); + self.plan_link_delivery(i, node, link, route, owned, medium, now, actions, || { + links_started.insert(node); + }) + } + + /// The shared Direct and Propagated branches of Python `process_outbound`. + #[allow(clippy::too_many_arguments)] + fn plan_link_delivery( + &mut self, + i: usize, + target: [u8; 16], + link: DirectReusableLinkState, + route: Option, + owned: bool, + medium: &MediumSnapshot, + now: f64, + actions: &mut Vec, + link_started: impl FnOnce(), + ) -> OutboundStep { + let held = self.slow_path_held(i, Some(target), medium); + let has_path = medium.has_path(&target); + let message = &self.pending_outbound[i]; + if held { + return OutboundStep::Kept { advanced: false }; + } + if message.delivery_attempts > attempt_limit(message) { + if attempt_due(message, has_path, now) { + actions.push(OutboundAction::Failed(self.fail_pending(i))); + return OutboundStep::Removed; } - - let age = now - self.pending_outbound[i].timestamp(); - if age > MESSAGE_EXPIRY as f64 { - let mut msg = self.pending_outbound.remove(i); - msg.mark_failed(); - actions.push(OutboundAction::Expired(msg)); - processed += 1; - continue; + return OutboundStep::Kept { advanced: false }; + } + if owned { + // The Link was started for this message and sends it once active. + if link == DirectReusableLinkState::Active && message.state == MessageState::Outbound { + let message = &mut self.pending_outbound[i]; + message.progress = message.progress.max(0.05); + message.state = MessageState::Sending; + return OutboundStep::Kept { advanced: true }; } - - match self.pending_outbound[i].method { - DeliveryMethod::Direct => { - let input = direct_input(&self.pending_outbound[i], now); - if input.reusable_link == DirectReusableLinkState::None { - let msg = &self.pending_outbound[i]; - let due_at = if msg.next_delivery_attempt > 0.0 { - msg.next_delivery_attempt - } else if msg.last_delivery_attempt > 0.0 { - msg.last_delivery_attempt + DELIVERY_RETRY_WAIT as f64 - } else { - 0.0 - }; - if now < due_at { - i += 1; - continue; - } - } - - if self.pending_outbound[i].state != MessageState::Sending { - self.pending_outbound[i].mark_sending(); - } - // Python LXMessage.send re-reads compression support on every send. - let dest_hash = self.pending_outbound[i].destination_hash(); - self.pending_outbound[i].auto_compress = self.compression_supported(&dest_hash); - let plan = plan_direct_delivery(&mut self.pending_outbound[i], input, now); - match plan { - DirectDeliveryPlan::Fail => { - let mut msg = self.pending_outbound.remove(i); - msg.mark_failed(); - actions.push(OutboundAction::Failed(msg)); - processed += 1; - continue; - } - DirectDeliveryPlan::DeferTerminalFailure => { - processed += 1; - i += 1; - } - _ => { - let msg = self.pending_outbound[i].clone(); - let dest_hash = msg.destination_hash(); - actions.push(OutboundAction::PlanDirect { - message: msg, - dest_hash, - plan, - }); - processed += 1; - i += 1; - } - } + return OutboundStep::Kept { advanced: false }; + } + match link { + DirectReusableLinkState::Active => { + if message.state != MessageState::Outbound { + return OutboundStep::Kept { advanced: false }; } - DeliveryMethod::Propagated => { - let msg = &self.pending_outbound[i]; - let due_at = if msg.next_delivery_attempt > 0.0 { - msg.next_delivery_attempt - } else if msg.last_delivery_attempt > 0.0 { - msg.last_delivery_attempt + DELIVERY_RETRY_WAIT as f64 - } else { - 0.0 - }; - if now < due_at { - i += 1; - continue; - } - - if let Some(peer_hash) = self.outbound_propagation_node { - let mut msg = self.pending_outbound.remove(i); - msg.mark_sending(); - actions.push(OutboundAction::DeliverPropagated { - message: msg, - prop_hash: peer_hash, - }); - processed += 1; - } else { - i += 1; - } + let slow = slow_path(medium, &target); + let compress = self.message_compression_supported(i); + let message = &mut self.pending_outbound[i]; + if message.progress < 0.05 { + message.progress = 0.05; } - DeliveryMethod::Opportunistic => { - let msg = &self.pending_outbound[i]; - let due_at = if msg.next_delivery_attempt > 0.0 { - msg.next_delivery_attempt - } else if msg.last_delivery_attempt > 0.0 { - msg.last_delivery_attempt + DELIVERY_RETRY_WAIT as f64 - } else { - 0.0 - }; - if now < due_at { - i += 1; - continue; - } - - let mut msg = self.pending_outbound.remove(i); - msg.mark_sent(); - msg.progress = 0.50; - let dest_hash = msg.destination_hash(); - msg.auto_compress = self.compression_supported(&dest_hash); - actions.push(OutboundAction::DeliverOpportunistic { - message: msg, - dest_hash, + message.sent_on_slow_path = slow; + message.auto_compress = compress; + message.state = MessageState::Sending; + actions.push(OutboundAction::DeliverOverLink { + message: message.clone(), + target, + plan: LinkDeliveryPlan::UseLink, + }); + OutboundStep::Kept { advanced: true } + } + DirectReusableLinkState::Pending => OutboundStep::Kept { advanced: false }, + DirectReusableLinkState::Closed { activated } => { + self.closed_link(i, target, activated, medium, now, actions); + OutboundStep::Kept { advanced: true } + } + DirectReusableLinkState::None => { + if !attempt_due(message, has_path, now) { + return OutboundStep::Kept { advanced: false }; + } + let message = &mut self.pending_outbound[i]; + message.delivery_attempts += 1; + message.awaiting_path = false; + schedule_attempt(message, medium.destination_round_trip(&target), false, now); + if message.delivery_attempts >= attempt_limit(message) { + actions.push(OutboundAction::Failed(self.fail_pending(i))); + return OutboundStep::Removed; + } + if let Some(route) = route { + let slow = slow_path(medium, &target); + let compress = self.message_compression_supported(i); + let message = &mut self.pending_outbound[i]; + message.progress = 0.03; + message.sent_on_slow_path = slow; + message.auto_compress = compress; + actions.push(OutboundAction::DeliverOverLink { + message: message.clone(), + target, + plan: LinkDeliveryPlan::StartLink { + hops: route.hops.max(1), + }, }); - processed += 1; - } - DeliveryMethod::Paper => { - i += 1; + link_started(); + } else { + self.request_path_action(target, medium, now, actions); + let message = &mut self.pending_outbound[i]; + schedule_attempt(message, medium.medium_path_timeout, true, now); + message.progress = 0.01; } + OutboundStep::Kept { advanced: true } } } + } + /// Handle the closed Link a Direct or Propagated message was using, as + /// Python's `CLOSED` link branches do: Direct re-requests the path (once + /// only if the Link never activated) and never drops it; both reschedule + /// only while `attempts + 1 < attempt_limit`. + pub fn outbound_link_closed( + &mut self, + message_hash: &[u8; 32], + link_activated: bool, + medium: &MediumSnapshot, + now: f64, + ) -> Vec { + let mut actions = Vec::new(); + let Some(i) = self + .pending_outbound + .iter() + .position(|m| &m.message_id() == message_hash) + else { + return actions; + }; + let target = match self.outbound_target(&self.pending_outbound[i]) { + Some(target) if self.pending_outbound[i].method != DeliveryMethod::Opportunistic => { + target + } + _ => return actions, + }; + self.closed_link(i, target, link_activated, medium, now, &mut actions); actions } + fn closed_link( + &mut self, + i: usize, + target: [u8; 16], + link_activated: bool, + medium: &MediumSnapshot, + now: f64, + actions: &mut Vec, + ) { + if self.pending_outbound[i].method == DeliveryMethod::Direct { + if link_activated { + self.request_path_action(target, medium, now, actions); + } else if !self.pending_outbound[i].path_request_retried { + self.request_path_action(target, medium, now, actions); + self.pending_outbound[i].path_request_retried = true; + } + } + let message = &mut self.pending_outbound[i]; + if message.state != MessageState::Cancelled { + message.state = MessageState::Outbound; + } + if message.delivery_attempts + 1 < attempt_limit(message) { + schedule_attempt(message, medium.destination_round_trip(&target), false, now); + } + } + + /// Wait for a path before the next attempt, as after a path request. + pub fn await_outbound_path( + &mut self, + message_hash: &[u8; 32], + medium: &MediumSnapshot, + now: f64, + ) -> Vec { + let mut actions = Vec::new(); + let Some(i) = self + .pending_outbound + .iter() + .position(|m| &m.message_id() == message_hash) + else { + return actions; + }; + let destination = self.pending_outbound[i].destination_hash(); + self.request_path_action(destination, medium, now, &mut actions); + let message = &mut self.pending_outbound[i]; + message.state = MessageState::Outbound; + schedule_attempt(message, medium.medium_path_timeout, true, now); + actions + } + + /// Python `LXMRouter.request_path`: returns `false`, without requesting, + /// inside the debounce window of an earlier request for the destination. + pub fn request_path( + &mut self, + destination: [u8; 16], + medium: &MediumSnapshot, + now: f64, + ) -> bool { + let window = medium.path_request_debounce(); + if self + .path_request_times + .get(&destination) + .is_some_and(|requested| now - requested < window) + { + return false; + } + self.path_request_times + .retain(|_, requested| now - *requested < window); + self.path_request_times.insert(destination, now); + true + } + + /// Python `LXMRouter.path_request_pending`. + pub fn path_request_pending( + &self, + destination: &[u8; 16], + medium: &MediumSnapshot, + now: f64, + ) -> bool { + self.path_request_times + .get(destination) + .is_some_and(|requested| now - requested < medium.path_request_wait()) + } + + fn request_path_action( + &mut self, + destination: [u8; 16], + medium: &MediumSnapshot, + now: f64, + actions: &mut Vec, + ) { + if self.request_path(destination, medium, now) { + actions.push(OutboundAction::RequestPath { + destination, + drop_existing: false, + }); + } + } + + fn outbound_target(&self, message: &LxMessage) -> Option<[u8; 16]> { + if message.method == DeliveryMethod::Propagated { + self.outbound_propagation_node + } else { + Some(message.destination_hash()) + } + } + + /// Python `LXMRouter.slow_path_held`. + fn slow_path_held(&self, i: usize, target: Option<[u8; 16]>, medium: &MediumSnapshot) -> bool { + if self.pending_outbound[i].state != MessageState::Outbound { + return false; + } + if !target.is_some_and(|target| slow_path(medium, &target)) { + return false; + } + let mut ahead = true; + for (j, other) in self.pending_outbound.iter().enumerate() { + if j == i { + ahead = false; + } else if matches!( + other.state, + MessageState::Delivered + | MessageState::Failed + | MessageState::Cancelled + | MessageState::Rejected + ) || (other.method == DeliveryMethod::Propagated + && other.state == MessageState::Sent) + { + continue; + } else if (ahead && self.outbound_target(other) == target) || slow_path_in_flight(other) + { + return true; + } + } + false + } + + /// Python `LXMRouter.fail_message` for a queued message. + fn fail_pending(&mut self, i: usize) -> LxMessage { + let mut message = self.pending_outbound.remove(i); + message.progress = 0.0; + if message.state != MessageState::Rejected { + message.state = MessageState::Failed; + } + message.notify_failed(); + message + } + + /// Whether a slow-path message concluded since the last call. Python + /// re-runs outbound processing at once when that happens. + pub fn take_outbound_kick(&mut self) -> bool { + std::mem::take(&mut self.outbound_kick) + } + pub fn cull_stamp_costs(&mut self) { let now = now_f64(); self.outbound_stamp_costs @@ -2257,11 +2443,8 @@ impl LxmRouter { } } - /// Compatibility executor without a destination encryptor. With transport - /// configured, Opportunistic actions fail encryption and are requeued. - /// Direct/Propagated actions are consumed without delivery; without transport, - /// all supplied actions are discarded. Handle delivery actions in the embedder - /// or use [`Self::execute_actions_with_encryptor`] for Opportunistic work. + /// Compatibility executor without a destination encryptor: every + /// opportunistic send fails its message, as a raising `send()` does in Python. pub fn execute_actions(&mut self, actions: Vec) { self.execute_actions_with_encryptor(actions, |dest_hash, _plaintext| { Err(MessageError::PackFailed(format!( @@ -2271,18 +2454,13 @@ impl LxmRouter { }); } - /// Send single-packet opportunistic actions with caller-supplied - /// destination encryption. + /// Send opportunistic packets with caller-supplied destination encryption. /// /// Python encrypts Opportunistic LXMF packet payloads with the recipient - /// destination identity before handing bytes to Reticulum. Core cannot - /// infer destination keys, so embeddings must provide the encryptor. - /// - /// This consumes the action list. Direct/Propagated actions are discarded, - /// and without a configured transport all actions are discarded. Dispatch - /// those methods separately before calling. Successful packet enqueueing does - /// not retain a message for delivery-proof tracking; the embedding runtime - /// must own that lifecycle when delivery confirmation is required. + /// destination identity before handing bytes to Reticulum. An encryption + /// failure fails the message. Path requests are sent without dropping the + /// current path; Link and failure actions are left to the embedder. Without + /// a configured transport nothing is sent. pub fn execute_actions_with_encryptor( &mut self, actions: Vec, @@ -2296,101 +2474,87 @@ impl LxmRouter { }; for action in actions { - match action { - OutboundAction::DeliverOpportunistic { - mut message, - dest_hash, - } => { - let plain = self.plain_destinations.contains(&dest_hash); - let payload = if plain { - Ok(message.wire_bytes()[DESTINATION_LENGTH..].to_vec()) - } else { - message.pack_opportunistic_encrypted(|plaintext| { - encrypt_fn(dest_hash, plaintext) - }) + let message = match action { + OutboundAction::SendOpportunistic { message } => message, + OutboundAction::RequestPath { destination, .. } => { + let _ = transport_tx.try_send( + rns_transport::messages::TransportMessage::RequestPath { + destination_hash: destination, + }, + ); + continue; + } + _ => continue, + }; + let dest_hash = message.destination_hash(); + let message_id = message.message_id(); + let plain = self.plain_destinations.contains(&dest_hash); + let payload = if plain { + Ok(message.wire_bytes()[DESTINATION_LENGTH..].to_vec()) + } else { + message.pack_opportunistic_encrypted(|plaintext| encrypt_fn(dest_hash, plaintext)) + }; + match payload { + Ok(packet_payload) => { + // Python LXMessage.__as_packet strips the destination + // hash before encryption because the RNS packet + // header already carries it. + let flags = rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: if plain { + rns_wire::flags::DestinationType::Plain + } else { + rns_wire::flags::DestinationType::Single + }, + packet_type: rns_wire::flags::PacketType::Data, }; - match payload { - Ok(packet_payload) => { - // Python LXMessage.__as_packet strips the destination - // hash before encryption because the RNS packet - // header already carries it. - let flags = rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: if plain { - rns_wire::flags::DestinationType::Plain - } else { - rns_wire::flags::DestinationType::Single - }, - packet_type: rns_wire::flags::PacketType::Data, - }; - let header = rns_wire::header::PacketHeader { - flags, - hops: 0, - transport_id: None, + let header = rns_wire::header::PacketHeader { + flags, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&packet_payload); + if transport_tx + .try_send(rns_transport::messages::TransportMessage::Outbound( + rns_transport::messages::OutboundRequest { + raw: Bytes::from(raw), destination_hash: dest_hash, - context: rns_wire::context::PacketContext::None, - }; - let mut raw = header.pack(); - raw.extend_from_slice(&packet_payload); - - let dispatched = transport_tx - .try_send(rns_transport::messages::TransportMessage::Outbound( - rns_transport::messages::OutboundRequest { - raw: Bytes::from(raw), - destination_hash: dest_hash, - }, - )) - .is_ok(); - if dispatched - && matches!( - message.state, - MessageState::Sending | MessageState::Sent - ) - { - message.mark_sent(); - message.progress = 1.0; - } else { - tracing::warn!( - dest = %hex::encode(dest_hash), - "transport backpressure deferred opportunistic LXMF delivery" - ); - self.pending_outbound.push(message); - } - } - Err(err) => { - tracing::warn!( - dest = %hex::encode(dest_hash), - error = %err, - "cannot execute opportunistic LXMF action; re-queueing" - ); - self.pending_outbound.push(message); - } + }, + )) + .is_err() + { + tracing::warn!( + dest = %hex::encode(dest_hash), + "transport backpressure deferred opportunistic LXMF delivery" + ); } } - OutboundAction::DeliverDirect { .. } | OutboundAction::PlanDirect { .. } => { + Err(err) => { tracing::warn!( - "Direct LXMF delivery requires LinkDeliveryManager; action left for embedding runtime" + dest = %hex::encode(dest_hash), + error = %err, + "opportunistic LXMF send failed" ); + self.mark_outbound_failed(&message_id); } - OutboundAction::DeliverPropagated { .. } => { - // Requires a link to a propagation node; handled outside this layer. - } - OutboundAction::Failed(_) | OutboundAction::Expired(_) => {} } } } /// Advance deferred stamps and periodic jobs using the compatibility executor. - /// Direct messages stay queued; Propagated actions are consumed without delivery, - /// and Opportunistic work lacks destination encryption. This is not a complete - /// delivery driver; use explicit action processing in an embedding runtime. + /// Opportunistic sends fail for lack of destination encryption and Link work + /// is not performed. This is not a complete delivery driver; use explicit + /// action processing in an embedding runtime. pub fn tick(&mut self) { self.processing_count += 1; self.process_deferred_stamps(); - let actions = self.process_outbound_without_direct(); + let actions = self.process_outbound(); if !actions.is_empty() { self.execute_actions(actions); } @@ -2399,8 +2563,8 @@ impl LxmRouter { } /// Advance stamps, Opportunistic actions and periodic jobs with destination - /// encryption. Direct messages stay queued; Propagated actions are consumed - /// without delivery. For other methods or proof tracking, drive actions explicitly. + /// encryption. Link work is not performed and no path, identity or Link + /// knowledge is used. For those or for proof tracking, drive actions explicitly. pub fn tick_with_encryptor(&mut self, encrypt_fn: F) where F: FnMut([u8; 16], &[u8]) -> Result, MessageError>, @@ -2408,7 +2572,7 @@ impl LxmRouter { self.processing_count += 1; self.process_deferred_stamps(); - let actions = self.process_outbound_without_direct(); + let actions = self.process_outbound(); if !actions.is_empty() { self.execute_actions_with_encryptor(actions, encrypt_fn); } @@ -2464,33 +2628,44 @@ impl LxmRouter { } } -/// Action to take on an outbound message. +/// Python `LXMRouter.slow_path`. +fn slow_path(medium: &MediumSnapshot, target: &[u8; 16]) -> bool { + medium.destination_round_trip(target) > DELIVERY_RETRY_WAIT as f64 +} + +/// Python `LXMRouter.slow_path_in_flight`. +fn slow_path_in_flight(message: &LxMessage) -> bool { + if !message.sent_on_slow_path { + return false; + } + if message.method == DeliveryMethod::Opportunistic { + message.state == MessageState::Sent + } else { + message.state == MessageState::Sending + } +} + +/// Work the router asks the embedder to perform. #[derive(Debug)] pub enum OutboundAction { - /// Exhausted delivery attempts. + /// The message failed and left the queue; its failure callback has run. Failed(LxMessage), - /// Exceeded [`MESSAGE_EXPIRY`]. - Expired(LxMessage), - DeliverDirect { - message: LxMessage, - dest_hash: [u8; 16], + /// Request a path, after dropping the current one when `drop_existing` + /// (Python waits 0.5 s between the drop and the request). + RequestPath { + destination: [u8; 16], + drop_existing: bool, }, - /// Direct delivery planned without removing the message from - /// `pending_outbound`. - PlanDirect { + /// Send one opportunistic packet. The message stays queued in `Sent` + /// state; report its delivery proof with [`LxmRouter::mark_outbound_delivered`]. + /// Register the packet receipt with at least `message.receipt_timeout`. + SendOpportunistic { message: LxMessage }, + /// Deliver over a Link to `target`, the destination for Direct messages + /// or the outbound propagation node for Propagated ones. + DeliverOverLink { message: LxMessage, - dest_hash: [u8; 16], - plan: DirectDeliveryPlan, - }, - DeliverPropagated { - message: LxMessage, - prop_hash: [u8; 16], - }, - /// Opportunistic packet action. Final encryption and packet-size admission - /// remain the executor's responsibility. - DeliverOpportunistic { - message: LxMessage, - dest_hash: [u8; 16], + target: [u8; 16], + plan: LinkDeliveryPlan, }, } @@ -2543,18 +2718,6 @@ pub struct NodeStats { mod tests { use super::*; - fn direct_policy_message() -> LxMessage { - let message = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Direct", - "hello", - DeliveryMethod::Direct, - ); - message.compute_hash().unwrap(); - message - } - #[test] fn test_router_creation() { let router = LxmRouter::new(RouterConfig::default()); @@ -2614,245 +2777,6 @@ mod tests { assert!(config.ext.processing_limit.is_none()); } - #[test] - fn test_direct_delivery_plan_starts_link_with_current_path() { - let mut msg = direct_policy_message(); - let dest = msg.destination_hash(); - let now = 1000.0; - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 4)), - reusable_link: DirectReusableLinkState::None, - }, - now, - ); - - assert_eq!(plan, DirectDeliveryPlan::StartNewLink { hops: 4 }); - assert_eq!(msg.delivery_attempts, 1); - assert_eq!(msg.last_delivery_attempt, now); - assert_eq!(msg.next_delivery_attempt, now + DELIVERY_RETRY_WAIT as f64); - assert_eq!(msg.progress, 0.03); - } - - #[test] - fn test_direct_delivery_plan_requests_path_for_unknown_identity() { - let mut msg = direct_policy_message(); - let now = 1000.0; - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: false, - route: None, - reusable_link: DirectReusableLinkState::None, - }, - now, - ); - - assert_eq!( - plan, - DirectDeliveryPlan::RequestPath { - drop_existing: false - } - ); - assert_eq!(msg.delivery_attempts, 1); - assert_eq!(msg.last_delivery_attempt, now); - assert_eq!(msg.next_delivery_attempt, now + PATH_REQUEST_WAIT as f64); - assert_eq!(msg.progress, 0.01); - } - - #[test] - fn test_direct_delivery_plan_reuses_active_link_without_attempt_increment() { - let mut msg = direct_policy_message(); - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: None, - reusable_link: DirectReusableLinkState::Active, - }, - 1000.0, - ); - - assert_eq!(plan, DirectDeliveryPlan::UseReusableLink); - assert_eq!(msg.delivery_attempts, 0); - assert_eq!(msg.state, MessageState::Sending); - assert_eq!(msg.progress, 0.05); - } - - #[test] - fn test_direct_delivery_plan_waits_for_pending_link() { - let mut msg = direct_policy_message(); - let dest = msg.destination_hash(); - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 2)), - reusable_link: DirectReusableLinkState::Pending, - }, - 1000.0, - ); - - assert_eq!(plan, DirectDeliveryPlan::WaitForReusableLink); - assert_eq!(msg.delivery_attempts, 0); - assert_eq!(msg.next_delivery_attempt, 0.0); - } - - #[test] - fn test_direct_delivery_plan_defers_terminal_failure_at_attempt_boundary() { - let mut msg = direct_policy_message(); - let dest = msg.destination_hash(); - msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS - 1; - let now = 1000.0; - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 1)), - reusable_link: DirectReusableLinkState::None, - }, - now, - ); - - assert_eq!(plan, DirectDeliveryPlan::DeferTerminalFailure); - assert_eq!(msg.delivery_attempts, MAX_DELIVERY_ATTEMPTS); - assert_eq!(msg.next_delivery_attempt, now + DELIVERY_RETRY_WAIT as f64); - } - - #[test] - fn test_direct_delivery_plan_requests_rediscovery_for_closed_link() { - let mut msg = direct_policy_message(); - let dest = msg.destination_hash(); - let now = 1000.0; - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 3)), - reusable_link: DirectReusableLinkState::Closed { activated: false }, - }, - now, - ); - - assert_eq!( - plan, - DirectDeliveryPlan::RequestPath { - drop_existing: true - } - ); - assert_eq!(msg.delivery_attempts, 0); - assert_eq!(msg.next_delivery_attempt, now + PATH_REQUEST_WAIT as f64); - assert_eq!(msg.progress, 0.01); - } - - #[test] - fn test_direct_delivery_plan_fails_above_max_attempts() { - let mut msg = direct_policy_message(); - let dest = msg.destination_hash(); - msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS + 1; - let plan = plan_direct_delivery( - &mut msg, - DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 1)), - reusable_link: DirectReusableLinkState::None, - }, - 1000.0, - ); - - assert_eq!(plan, DirectDeliveryPlan::Fail); - assert_eq!(msg.state, MessageState::Failed); - } - - #[test] - fn test_process_outbound_with_direct_keeps_message_pending() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = direct_policy_message(); - let msg_hash = Some(msg.message_id()); - let dest = msg.destination_hash(); - router.try_send(msg).unwrap(); - - let actions = - router.process_outbound_with_direct(|message, _now| DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(message.destination_hash(), 4)), - reusable_link: DirectReusableLinkState::None, - }); - - assert_eq!(router.pending_outbound.len(), 1); - let pending = &router.pending_outbound[0]; - assert_eq!(Some(pending.message_id()), msg_hash); - assert_eq!(pending.state, MessageState::Sending); - assert_eq!(pending.delivery_attempts, 1); - assert_eq!(pending.progress, 0.03); - match actions.as_slice() { - [ - OutboundAction::PlanDirect { - message, - dest_hash, - plan, - }, - ] => { - assert_eq!(*dest_hash, dest); - assert_eq!(Some(message.message_id()), msg_hash); - assert_eq!(*plan, DirectDeliveryPlan::StartNewLink { hops: 4 }); - } - other => panic!("expected PlanDirect StartNewLink, got {other:?}"), - } - } - - #[test] - fn test_process_outbound_with_direct_polls_pending_link_despite_retry_deadline() { - let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = direct_policy_message(); - msg.next_delivery_attempt = now_f64() + 3600.0; - let msg_hash = Some(msg.message_id()); - router.try_send(msg).unwrap(); - - let actions = - router.process_outbound_with_direct(|_message, _now| DirectDeliveryPlanInput { - identity_known: true, - route: None, - reusable_link: DirectReusableLinkState::Pending, - }); - - assert_eq!(router.pending_outbound.len(), 1); - assert_eq!(Some(router.pending_outbound[0].message_id()), msg_hash); - assert_eq!(router.pending_outbound[0].delivery_attempts, 0); - match actions.as_slice() { - [OutboundAction::PlanDirect { plan, .. }] => { - assert_eq!(*plan, DirectDeliveryPlan::WaitForReusableLink); - } - other => panic!("expected PlanDirect WaitForReusableLink, got {other:?}"), - } - } - - #[test] - fn test_outbound_terminal_helpers_update_pending_queue() { - let mut router = LxmRouter::new(RouterConfig::default()); - let first = direct_policy_message(); - let first_hash = first.message_id(); - router.try_send(first).unwrap(); - - assert!(router.defer_outbound_for_path_request(&first_hash, 1000.0)); - assert_eq!( - router.pending_outbound[0].next_delivery_attempt, - 1000.0 + PATH_REQUEST_WAIT as f64 - ); - assert_eq!(router.pending_outbound[0].progress, 0.01); - - assert!(router.mark_outbound_delivered(&first_hash)); - assert!(router.pending_outbound.is_empty()); - - let second = direct_policy_message(); - let second_hash = second.message_id(); - router.try_send(second).unwrap(); - assert!(router.mark_outbound_failed(&second_hash)); - assert!(router.pending_outbound.is_empty()); - } - #[test] fn test_allow_disallow() { let mut router = LxmRouter::new(RouterConfig::default()); @@ -3912,28 +3836,6 @@ mod tests { assert!(router.pending_outbound.is_empty()); } - /// At exactly MAX the message is still attempted (dispatched), not failed. - #[test] - fn test_process_outbound_at_max_attempts_not_failed() { - let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Test", - "Content", - DeliveryMethod::Direct, - ); - msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS; - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - assert!( - !matches!(actions[0], OutboundAction::Failed(_)), - "at exactly MAX the message is still attempted, not failed" - ); - } - #[test] fn test_stats() { let router = LxmRouter::new(RouterConfig::default()); @@ -3968,68 +3870,6 @@ mod tests { assert!(router.transport_tx.is_some()); } - #[test] - fn test_process_outbound_direct_delivery() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Direct", - "Content", - DeliveryMethod::Direct, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - let has_direct = actions - .iter() - .any(|a| matches!(a, OutboundAction::DeliverDirect { .. })); - assert!(has_direct); - } - - #[test] - fn test_process_outbound_propagated_delivery() { - let mut router = LxmRouter::new(RouterConfig::default()); - let peer_hash = [0x11; 16]; - let peer = crate::peer::LxmPeer::new(peer_hash); - router.add_peer(peer); - router.set_outbound_propagation_node(Some(peer_hash)); - - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Propagated", - "Content", - DeliveryMethod::Propagated, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - let has_propagated = actions - .iter() - .any(|a| matches!(a, OutboundAction::DeliverPropagated { .. })); - assert!(has_propagated); - } - - #[test] - fn test_process_outbound_opportunistic_delivery() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Opportunistic", - "Content", - DeliveryMethod::Opportunistic, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - let has_opportunistic = actions - .iter() - .any(|a| matches!(a, OutboundAction::DeliverOpportunistic { .. })); - assert!(has_opportunistic); - } - #[test] fn test_process_outbound_propagated_no_node() { let mut router = LxmRouter::new(RouterConfig::default()); @@ -4051,88 +3891,6 @@ mod tests { ); } - #[test] - fn test_delivery_announce_trigger_clears_direct_retry_backoff() { - let mut router = LxmRouter::new(RouterConfig::default()); - let dest = [0xAA; 16]; - let mut msg = crate::message::test_message( - dest, - [0xBB; 16], - "Direct", - "Content", - DeliveryMethod::Direct, - ); - msg.delivery_attempts = 1; - msg.last_delivery_attempt = now_f64(); - msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64; - router.try_send(msg).unwrap(); - - assert!(router.process_outbound().is_empty()); - assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1); - assert!(matches!( - router.process_outbound().as_slice(), - [OutboundAction::DeliverDirect { .. }] - )); - } - - #[test] - fn test_delivery_announce_trigger_clears_propagated_recipient_backoff() { - let mut router = LxmRouter::new(RouterConfig::default()); - let dest = [0xAA; 16]; - let node = [0xCC; 16]; - router.set_outbound_propagation_node(Some(node)); - let mut msg = crate::message::test_message( - dest, - [0xBB; 16], - "Propagated", - "Content", - DeliveryMethod::Propagated, - ); - msg.delivery_attempts = 1; - msg.last_delivery_attempt = now_f64(); - msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64; - router.try_send(msg).unwrap(); - - assert!(router.process_outbound().is_empty()); - assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1); - assert!(matches!( - router.process_outbound().as_slice(), - [OutboundAction::DeliverPropagated { .. }] - )); - } - - #[test] - fn test_propagation_node_announce_trigger_clears_propagated_retry_backoff() { - let mut router = LxmRouter::new(RouterConfig::default()); - let node = [0xCC; 16]; - router.set_outbound_propagation_node(Some(node)); - let mut msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Propagated", - "Content", - DeliveryMethod::Propagated, - ); - msg.delivery_attempts = 1; - msg.last_delivery_attempt = now_f64(); - msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64; - router.try_send(msg).unwrap(); - - assert!(router.process_outbound().is_empty()); - - let pn_data = crate::handlers::get_propagation_node_app_data( - &crate::handlers::PropagationNodeAnnounceData::new(true, 256, 10240, 16.0, 3.0, 18.0), - ); - assert_eq!( - router.trigger_outbound_for_propagation_node_announce(node, &pn_data), - 1 - ); - assert!(matches!( - router.process_outbound().as_slice(), - [OutboundAction::DeliverPropagated { .. }] - )); - } - #[test] fn test_propagation_node_announce_trigger_requires_configured_valid_node() { let mut router = LxmRouter::new(RouterConfig::default()); @@ -4158,44 +3916,6 @@ mod tests { ); } - /// A queued message older than `MESSAGE_EXPIRY` must be flushed as - /// `Expired` on the next `process_outbound`, marked Failed, and not - /// held indefinitely. Mirrors Python LXMRouter.process_outbound where - /// the age check runs before any delivery attempt. - #[test] - fn test_process_outbound_expired_message_marked_failed() { - let mut router = LxmRouter::new(RouterConfig::default()); - let mut msg = crate::message::LxMessageDraft::new( - [0xAA; 16], - [0xBB; 16], - "Stale", - "Content", - DeliveryMethod::Direct, - ) - .unwrap(); - // Anchor the timestamp comfortably past the expiry window. - msg.set_timestamp(now_f64() - (MESSAGE_EXPIRY as f64) - 60.0) - .unwrap(); - let msg = msg - .sign(&rns_crypto::ed25519::Ed25519PrivateKey::generate()) - .unwrap() - .finalize(None) - .unwrap(); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - assert!( - matches!(&actions[0], OutboundAction::Expired(m) if m.state == MessageState::Failed), - "expired message surfaces as Expired with state=Failed, got {:?}", - actions[0] - ); - assert!( - router.pending_outbound.is_empty(), - "expired message removed from queue" - ); - } - /// A message that has attempted delivery within the last /// `DELIVERY_RETRY_WAIT` seconds must be skipped by `process_outbound` /// rather than immediately retried. Prevents tight-loop reattempt @@ -4210,9 +3930,8 @@ mod tests { "Content", DeliveryMethod::Direct, ); - // Simulate one failed attempt very recently. msg.delivery_attempts = 1; - msg.last_delivery_attempt = now_f64() - 1.0; // 1 s ago, inside the 10 s window. + msg.next_delivery_attempt = now_f64() + 5.0; router.try_send(msg).unwrap(); let actions = router.process_outbound(); @@ -4232,7 +3951,7 @@ mod tests { /// delivery attempt, but it still needs the same retry backoff to avoid /// tight request-path loops. #[test] - fn test_process_outbound_retry_backoff_uses_last_attempt_timestamp() { + fn test_process_outbound_retry_backoff_applies_to_propagated() { let mut router = LxmRouter::new(RouterConfig::default()); let mut msg = crate::message::test_message( [0xAA; 16], @@ -4241,7 +3960,7 @@ mod tests { "Content", DeliveryMethod::Propagated, ); - msg.last_delivery_attempt = now_f64() - 1.0; + msg.next_delivery_attempt = now_f64() + 5.0; router.set_outbound_propagation_node(Some([0xCC; 16])); router.try_send(msg).unwrap(); @@ -4254,37 +3973,6 @@ mod tests { assert_eq!(router.pending_outbound[0].delivery_attempts, 0); } - /// The state machine contract: a Direct message picked up by - /// `process_outbound` must be emitted as `DeliverDirect` with the - /// message state transitioned to `Sending` before it leaves the queue. - /// Complements `test_process_outbound_direct_delivery`, which only - /// covers the action variant without asserting on state. - #[test] - fn test_process_outbound_direct_transitions_to_sending() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Direct", - "Content", - DeliveryMethod::Direct, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - match &actions[0] { - OutboundAction::DeliverDirect { message, .. } => { - assert_eq!( - message.state, - MessageState::Sending, - "Direct message enters Sending on dequeue" - ); - } - other => panic!("expected DeliverDirect, got {:?}", other), - } - } - #[test] fn test_tick_sends_to_transport() { let mut router = LxmRouter::new(RouterConfig::default()); @@ -4304,181 +3992,18 @@ mod tests { router.try_send(msg).unwrap(); router.tick_with_encryptor(|_dest, plaintext| Ok(plaintext.to_vec())); - - let received = rx.try_recv(); - assert!(received.is_ok(), "expected outbound packet from tick()"); - assert!( - router.pending_outbound.is_empty(), - "a successful fire-and-forget tick must not requeue the sent packet" - ); - } - - #[test] - fn test_execute_actions_no_transport() { - let mut router = LxmRouter::new(RouterConfig::default()); - // No transport set — execute_actions must be a no-op. - let actions = vec![OutboundAction::DeliverDirect { - message: crate::message::test_message( - [0; 16], - [0; 16], - "t", - "c", - DeliveryMethod::Direct, - ), - dest_hash: [0; 16], - }]; - router.execute_actions(actions); - } - - #[test] - fn test_execute_actions_only_sends_opportunistic_packet_payload_shape() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let dest_hash = [0xAA; 16]; - let src_hash = [0xBB; 16]; - - let (tx, mut rx) = tokio::sync::mpsc::channel(2); - let mut router = LxmRouter::new(RouterConfig::default()); - router.set_transport(tx); - - let direct = crate::message::LxMessageDraft::new( - dest_hash, - src_hash, - "Direct", - "d", - DeliveryMethod::Direct, - ) - .unwrap(); - let direct = direct.sign(&key).unwrap().finalize(None).unwrap(); - - let opportunistic = crate::message::LxMessageDraft::new( - dest_hash, - src_hash, - "Opp", - "o", - DeliveryMethod::Opportunistic, - ) - .unwrap(); - let opportunistic = opportunistic.sign(&key).unwrap().finalize(None).unwrap(); - let opportunistic_packed = opportunistic.pack().unwrap(); - - router.execute_actions_with_encryptor( - vec![ - OutboundAction::DeliverDirect { - message: direct, - dest_hash, - }, - OutboundAction::DeliverOpportunistic { - message: opportunistic, - dest_hash, - }, - ], - |_dest, plaintext| { - let mut out = vec![0xEE]; - out.extend_from_slice(plaintext); - Ok(out) - }, - ); - - let opportunistic_raw = match rx.try_recv().expect("opportunistic outbound request") { - rns_transport::messages::TransportMessage::Outbound(req) => req.raw, - other => panic!("expected outbound request, got {other:?}"), - }; - let (_, opportunistic_data_offset) = - rns_wire::header::PacketHeader::unpack(&opportunistic_raw).unwrap(); - assert_eq!( - &opportunistic_raw[opportunistic_data_offset..], - [&[0xEE], &opportunistic_packed[DESTINATION_LENGTH..]].concat(), - "Opportunistic delivery encrypts the LXMF tail after the destination hash" - ); - assert!( - rx.try_recv().is_err(), - "Direct actions require LinkDeliveryManager and must not be sent as destination packets" - ); - } - - #[test] - fn opportunistic_transport_backpressure_requeues_instead_of_dropping() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let dest_hash = [0xA1; 16]; - let (tx, mut rx) = tokio::sync::mpsc::channel(1); - tx.try_send( - rns_transport::messages::TransportMessage::DeregisterDestination { hash: [0xF0; 16] }, - ) - .unwrap(); - let mut router = LxmRouter::new(RouterConfig::default()); - router.set_transport(tx); - let message = crate::message::LxMessageDraft::new( - dest_hash, - [0xB1; 16], - "defer", - "payload", - DeliveryMethod::Opportunistic, - ) - .unwrap(); - let message = message.sign(&key).unwrap().finalize(None).unwrap(); - let message_hash = Some(message.message_id()); - - router.execute_actions_with_encryptor( - vec![OutboundAction::DeliverOpportunistic { message, dest_hash }], - |_dest, plaintext| Ok(plaintext.to_vec()), - ); - assert!(matches!( - rx.try_recv().unwrap(), - rns_transport::messages::TransportMessage::DeregisterDestination { .. } + rx.try_recv(), + Ok(rns_transport::messages::TransportMessage::RequestPath { .. }) )); - assert_eq!(router.pending_outbound.len(), 1); - assert_eq!( - Some(router.pending_outbound.first().unwrap().message_id()), - message_hash - ); - } - #[test] - fn test_execute_actions_without_encryptor_does_not_send_opportunistic_plaintext() { - let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); - let dest_hash = [0xAA; 16]; - let src_hash = [0xBB; 16]; - - let (tx, mut rx) = tokio::sync::mpsc::channel(2); - let mut router = LxmRouter::new(RouterConfig::default()); - router.set_transport(tx); - - let direct = crate::message::LxMessageDraft::new( - dest_hash, - src_hash, - "Direct", - "d", - DeliveryMethod::Direct, - ) - .unwrap(); - let direct = direct.sign(&key).unwrap().finalize(None).unwrap(); - - let opportunistic = crate::message::LxMessageDraft::new( - dest_hash, - src_hash, - "Opp", - "o", - DeliveryMethod::Opportunistic, - ) - .unwrap(); - let opportunistic = opportunistic.sign(&key).unwrap().finalize(None).unwrap(); - - router.execute_actions(vec![ - OutboundAction::DeliverDirect { - message: direct, - dest_hash, - }, - OutboundAction::DeliverOpportunistic { - message: opportunistic, - dest_hash, - }, - ]); - - assert!( - rx.try_recv().is_err(), - "execute_actions without an encryptor must not send raw opportunistic payloads" - ); + router.pending_outbound[0].next_delivery_attempt = 0.0; + router.tick_with_encryptor(|_dest, plaintext| Ok(plaintext.to_vec())); + assert!(matches!( + rx.try_recv(), + Ok(rns_transport::messages::TransportMessage::Outbound(_)) + )); + assert_eq!(router.pending_outbound[0].state, MessageState::Sent); } #[test] @@ -4495,6 +4020,7 @@ mod tests { DeliveryMethod::Propagated, )) .unwrap(); + router.pending_outbound[0].awaiting_path = true; // NaN slot-5 cost: pn_announce_data_is_valid accepts it, the typed parse does not. let data = hex::decode( "97c2ce6553f100c3cd0100cd280093cb7ff800000000000003128101c407706e206e616d65", @@ -4526,14 +4052,19 @@ mod tests { DeliveryMethod::Direct, )) .unwrap(); - let actions = router.process_outbound_with_direct(|_, _| DirectDeliveryPlanInput { - identity_known: true, - route: Some(DirectRouteSnapshot::new(dest, 1)), - reusable_link: DirectReusableLinkState::None, - }); + let mut inputs = OutboundInputs::default(); + inputs.identities.insert(dest); + inputs.medium.routes.insert( + dest, + RouteInfo { + hops: 1, + first_hop_timeout: 6.0, + }, + ); + let actions = router.process_outbound_with_inputs(&inputs, now_f64()); assert!(matches!( actions.as_slice(), - [OutboundAction::PlanDirect { message, .. }] if !message.auto_compress + [OutboundAction::DeliverOverLink { message, .. }] if !message.auto_compress )); router.update_compression_support(dest, None); assert!(router.compression_supported(&dest)); @@ -4545,12 +4076,11 @@ mod tests { let dest = [0xAA; 16]; router.ignore_destination(dest); - assert!(router.ignored.contains(&dest)); - assert!(router.propagation_store.is_destination_ignored(&dest)); + assert!(router.is_ignored(&dest)); + assert!(!router.propagation_store.is_destination_ignored(&dest)); router.unignore_destination(&dest); - assert!(!router.ignored.contains(&dest)); - assert!(!router.propagation_store.is_destination_ignored(&dest)); + assert!(!router.is_ignored(&dest)); } #[test] @@ -4872,7 +4402,8 @@ mod tests { let actions = router.process_outbound(); assert_eq!(actions.len(), 1); - assert_eq!(router.pending_outbound.len(), 1); + assert_eq!(router.pending_outbound.len(), 2); + assert_eq!(router.pending_outbound[1].delivery_attempts, 0); } #[test] @@ -4901,78 +4432,6 @@ mod tests { assert_eq!(router.pending_outbound[0].method, DeliveryMethod::Direct); } - #[test] - fn test_direct_message_state_sending() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Direct", - "Content", - DeliveryMethod::Direct, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - match &actions[0] { - OutboundAction::DeliverDirect { message, .. } => { - assert_eq!(message.state, MessageState::Sending); - } - _ => panic!("expected DeliverDirect"), - } - } - - #[test] - fn test_propagated_message_state_sending() { - let mut router = LxmRouter::new(RouterConfig::default()); - let peer_hash = [0x11; 16]; - let peer = crate::peer::LxmPeer::new(peer_hash); - router.add_peer(peer); - router.set_outbound_propagation_node(Some(peer_hash)); - - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Propagated", - "Content", - DeliveryMethod::Propagated, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - match &actions[0] { - OutboundAction::DeliverPropagated { message, .. } => { - assert_eq!(message.state, MessageState::Sending); - } - _ => panic!("expected DeliverPropagated"), - } - } - - #[test] - fn test_opportunistic_message_state_sent() { - let mut router = LxmRouter::new(RouterConfig::default()); - let msg = crate::message::test_message( - [0xAA; 16], - [0xBB; 16], - "Opportunistic", - "Content", - DeliveryMethod::Opportunistic, - ); - router.try_send(msg).unwrap(); - - let actions = router.process_outbound(); - assert_eq!(actions.len(), 1); - match &actions[0] { - OutboundAction::DeliverOpportunistic { message, .. } => { - assert_eq!(message.state, MessageState::Sent); - assert_eq!(message.progress, 0.50); - } - _ => panic!("expected DeliverOpportunistic"), - } - } - #[test] fn test_direct_message_left_for_link_delivery_after_execute() { let mut router = LxmRouter::new(RouterConfig::default()); @@ -4993,6 +4452,11 @@ mod tests { router.tick(); + // Without a known path the router only asks for one (LXMRouter.py:3229-3233). + assert!(matches!( + rx.try_recv(), + Ok(rns_transport::messages::TransportMessage::RequestPath { .. }) + )); assert!( rx.try_recv().is_err(), "Direct delivery requires LinkDeliveryManager, not router.execute_actions" diff --git a/crates/lxmf-core/src/router/outbound.rs b/crates/lxmf-core/src/router/outbound.rs new file mode 100644 index 0000000..4e6f16b --- /dev/null +++ b/crates/lxmf-core/src/router/outbound.rs @@ -0,0 +1,146 @@ +//! Medium-aware outbound timing: Python `LXMRouter` path and retry model. +//! +//! The embedder supplies a [`MediumSnapshot`] of Reticulum's view (lowest +//! online bitrate, medium path timeout and per-destination routes); the router +//! derives retry waits, attempt limits and receipt timeouts from it. + +use std::collections::HashMap; +use std::time::Duration; + +use rand::Rng; + +use crate::constants::{ + DELIVERY_RETRY_WAIT, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, PROCESSING_INTERVAL, +}; +use crate::message::LxMessage; + +pub const PATH_REQUEST_DEBOUNCE: f64 = 60.0; +pub const SLOW_INTERFACE_BITRATE: u64 = 2000; +pub const AIRTIME_AWARE_MTU_TIME: f64 = 0.5; +const PER_HOP_TIMEOUT: f64 = rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT; + +/// Reticulum's current route to a destination. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RouteInfo { + pub hops: u8, + /// `Reticulum.get_first_hop_timeout` for the destination, in seconds. + pub first_hop_timeout: f64, +} + +/// Reticulum inputs to outbound planning. A destination without an entry in +/// `routes` has no known path. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MediumSnapshot { + /// `Reticulum.get_lowest_interface_bitrate`. + pub lowest_interface_bitrate: Option, + /// `Reticulum.get_medium_path_timeout`; 0 when no bitrate is known. + pub medium_path_timeout: f64, + pub routes: HashMap<[u8; 16], RouteInfo>, +} + +impl MediumSnapshot { + pub fn has_path(&self, destination: &[u8; 16]) -> bool { + self.routes.contains_key(destination) + } + + pub fn route(&self, destination: &[u8; 16]) -> Option { + self.routes.get(destination).copied() + } + + /// Python `LXMRouter.destination_round_trip`. + pub fn destination_round_trip(&self, destination: &[u8; 16]) -> f64 { + match self.routes.get(destination) { + None => self.medium_path_timeout, + Some(route) => { + 2.0 * (route.first_hop_timeout - PER_HOP_TIMEOUT).max(0.0) + PER_HOP_TIMEOUT + } + } + } + + /// Python `LXMRouter.path_request_wait`. + pub fn path_request_wait(&self) -> f64 { + (PATH_REQUEST_WAIT as f64).max(self.medium_path_timeout) + } + + /// Python `LXMRouter.slow_interface_online`. + pub fn slow_interface_online(&self) -> bool { + self.lowest_interface_bitrate + .is_some_and(|bitrate| bitrate < SLOW_INTERFACE_BITRATE) + } + + /// Window within which a repeated path request for one destination is skipped. + pub fn path_request_debounce(&self) -> f64 { + if self.slow_interface_online() { + PATH_REQUEST_DEBOUNCE + } else { + self.path_request_wait() + } + } +} + +/// Python `LXMRouter.attempt_limit`. +pub fn attempt_limit(message: &LxMessage) -> u32 { + message + .max_delivery_attempts + .unwrap_or(MAX_DELIVERY_ATTEMPTS) +} + +/// Python `LXMRouter.attempt_due`. +pub fn attempt_due(message: &LxMessage, has_path: bool, now: f64) -> bool { + now > message.next_delivery_attempt || (message.awaiting_path && has_path) +} + +/// Python `LXMRouter.schedule_attempt`, given the round trip it would use: +/// the medium path timeout for a path request, else the destination round trip. +pub fn schedule_attempt(message: &mut LxMessage, round_trip: f64, path_request: bool, now: f64) { + let wait = if path_request { + message.awaiting_path = true; + (PATH_REQUEST_WAIT as f64).max(round_trip) + } else { + (DELIVERY_RETRY_WAIT as f64).max(round_trip) + }; + message.next_delivery_attempt = now + wait; + + let limit = if round_trip > DELIVERY_RETRY_WAIT as f64 { + // Python's round() rounds half to even. + let scaled = (MAX_DELIVERY_ATTEMPTS as f64 * DELIVERY_RETRY_WAIT as f64 / round_trip) + .round_ties_even() as u32; + scaled.max(3) + } else { + MAX_DELIVERY_ATTEMPTS + }; + message.max_delivery_attempts = Some(limit); + + let mtu_time = (round_trip - PER_HOP_TIMEOUT).max(0.0) / 2.0; + if mtu_time > AIRTIME_AWARE_MTU_TIME { + message.next_delivery_attempt += rand::thread_rng().gen_range(0.0..=mtu_time); + let retry_wait = (DELIVERY_RETRY_WAIT as f64).max(round_trip) + mtu_time; + let remaining = (i64::from(limit) - i64::from(message.delivery_attempts) + 1).max(1); + message.receipt_timeout = Some(retry_wait * remaining as f64 + PROCESSING_INTERVAL as f64); + } else { + message.receipt_timeout = None; + } +} + +/// Timeout for an opportunistic delivery receipt: the RNS packet receipt +/// timeout (Packet.py:429-433), raised to the message's airtime-aware +/// `receipt_timeout` (LXMessage.py:482). Without a route Reticulum counts +/// `PATHFINDER_M` hops. +pub fn opportunistic_receipt_timeout( + route: Option, + receipt_timeout: Option, +) -> Duration { + let (first_hop, hops) = route + .map(|route| (route.first_hop_timeout, route.hops)) + .unwrap_or((PER_HOP_TIMEOUT, rns_transport::constants::PATHFINDER_M)); + let base = rns_wire::receipt::receipt_timeout_for_route( + Duration::from_secs_f64(first_hop.max(0.0)), + hops, + ); + match receipt_timeout { + Some(timeout) if timeout.is_finite() && timeout > base.as_secs_f64() => { + Duration::from_secs_f64(timeout) + } + _ => base, + } +} diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 8c463c5..3ced0b4 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -22,8 +22,7 @@ use lxmf_core::admission::{ }; use lxmf_core::admission_store::FileAdmissionStore; use lxmf_core::constants::{ - DELIVERY_LINK_COST, DELIVERY_RETRY_WAIT, DeliveryMethod, MAX_DELIVERY_ATTEMPTS, - NODE_ANNOUNCE_DELAY, PATH_REQUEST_WAIT, PROPAGATION_LINK_COST, + DELIVERY_LINK_COST, DeliveryMethod, NODE_ANNOUNCE_DELAY, PROPAGATION_LINK_COST, }; use lxmf_core::delivery_ratchet::{ DELIVERY_APP_NAME, DeliveryAnnounceKind, DeliveryRatchetError, DeliveryRatchetState, @@ -34,7 +33,6 @@ use lxmf_core::inbound_resource::{ }; use lxmf_core::link_delivery::{ BackchannelSendCommand, BackchannelSendError, BackchannelSendReceipt, DeliveryResult, - is_retryable_link_delivery_failure, }; use lxmf_core::message::{LxMessage, LxMessageDraft, MessageError}; use lxmf_core::peer::{LxmPeer, OutboundOfferPolicy}; @@ -45,8 +43,8 @@ use lxmf_core::propagation_send::{ AdvertisedNodePolicy, MissingPropagationInput, PropagationEnvelope, propagation_readiness, }; use lxmf_core::router::{ - AutopeerCandidate, DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, - DirectRouteSnapshot, LxmRouter, OutboundAction, plan_direct_delivery, + AutopeerCandidate, DirectReusableLinkState, LinkDeliveryPlan, LxmRouter, MediumSnapshot, + OutboundAction, OutboundInputs, RouteInfo, }; use lxmf_tools::daemon::{ DaemonConfig, PythonLxmdConfig, create_router_with_transport, persist_inbound_and_execute, @@ -289,12 +287,6 @@ struct PnTestTiming { store_ms: f64, } -#[derive(Debug)] -struct PendingOpportunisticDelivery { - message: LxMessage, - retry_at: f64, -} - #[derive(Debug, Clone, Copy)] enum PropagationStoreWriteOrigin { Peer([u8; 16]), @@ -1006,14 +998,6 @@ async fn wait_for_online_interface( } } -fn mark_delivery_attempt(message: &mut LxMessage) -> u32 { - let now = now_f64(); - message.delivery_attempts += 1; - message.last_delivery_attempt = now; - message.next_delivery_attempt = now + DELIVERY_RETRY_WAIT as f64; - message.delivery_attempts -} - fn queue_path_request( transport_tx: &mpsc::Sender, request_hash: [u8; 16], @@ -1067,37 +1051,20 @@ fn queue_unknown_propagation_node_path_request( true } -fn requeue_after_path_request( - router: &mut LxmRouter, - transport_tx: &mpsc::Sender, - mut message: LxMessage, - request_hash: [u8; 16], - reason: &str, - increment_attempt: bool, -) { - let now = now_f64(); - if increment_attempt { - message.delivery_attempts += 1; +fn link_snapshot_state( + snapshot: &lxmf_core::link_delivery::DirectLinkSnapshot, +) -> DirectReusableLinkState { + if snapshot.link_closed() { + // The failed session reports each carried message as a delivery result. + return DirectReusableLinkState::Pending; } - message.last_delivery_attempt = now; - message.next_delivery_attempt = now + PATH_REQUEST_WAIT as f64; - queue_path_request(transport_tx, request_hash, false, reason); - tracing::warn!( - dest = %hex::encode(message.destination_hash()), - request_dest = %hex::encode(request_hash), - attempts = message.delivery_attempts, - reason, - "re-queuing LXMF message after path request" - ); - if let Err(error) = router.try_send(message) { - tracing::warn!(%error, reason, "failed to re-queue LXMF message"); + if snapshot.link_active() { + DirectReusableLinkState::Active + } else { + DirectReusableLinkState::Pending } } -fn link_failure_retryable(reason: &str) -> bool { - is_retryable_link_delivery_failure(reason) -} - /// Python `lxmf_delivery()` receive state: the delivery method, and Curve25519 /// transport encryption for SINGLE and LINK destinations (LXMRouter.py:2174,2218-2226). fn mark_received(msg: &mut LxMessage, method: DeliveryMethod) { @@ -1121,20 +1088,6 @@ fn write_propagated_container( Ok(path) } -fn route_hops_for(route_hops: &HashMap<[u8; 16], u8>, dest_hash: [u8; 16]) -> u8 { - route_hops.get(&dest_hash).copied().unwrap_or(1).max(1) -} - -fn direct_route_snapshot( - route_hops: &HashMap<[u8; 16], u8>, - dest_hash: [u8; 16], -) -> Option { - route_hops - .get(&dest_hash) - .copied() - .map(|hops| DirectRouteSnapshot::new(dest_hash, hops)) -} - fn direct_reusable_link_state( link_delivery: Option<&lxmf_core::link_delivery::LinkDeliveryManager>, dest_hash: [u8; 16], @@ -1142,28 +1095,48 @@ fn direct_reusable_link_state( let Some(link_delivery) = link_delivery else { return DirectReusableLinkState::None; }; - if let Some(snapshot) = link_delivery.direct_link_snapshot(dest_hash) { - return match snapshot.delivery_state { - lxmf_core::link_delivery::DeliveryState::Idle => DirectReusableLinkState::Active, - lxmf_core::link_delivery::DeliveryState::Failed => { - DirectReusableLinkState::Closed { activated: false } - } - _ => DirectReusableLinkState::Pending, - }; + return link_snapshot_state(&snapshot); } - - if let Some(snapshot) = link_delivery.backchannel_link_snapshot(dest_hash) { - if snapshot.queued_deliveries > 0 || snapshot.in_flight_deliveries > 0 { - DirectReusableLinkState::Pending - } else { - DirectReusableLinkState::Active - } + if link_delivery.backchannel_link_snapshot(dest_hash).is_some() { + DirectReusableLinkState::Active } else { DirectReusableLinkState::None } } +/// Python `Transport.medium_path_timeout()` for a known bitrate (Transport.py:3550-3553). +fn medium_path_timeout(lowest_bitrate: u64) -> f64 { + let bits = (rns_wire::constants::MTU * 8) as f64; + 2.0 * (bits / lowest_bitrate.max(rns_runtime::constants::MINIMUM_BITRATE) as f64) + + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT +} + +/// Drop the current path, then request a new one 0.5 s later, as Python's +/// opportunistic rediscovery does (LXMRouter.py:3127-3133). +fn queue_path_request_after_drop( + transport_tx: &mpsc::Sender, + destination: [u8; 16], +) { + let (response_tx, _response_rx) = oneshot::channel(); + if let Err(error) = transport_tx.try_send(TransportMessage::Rpc { + query: TransportQuery::DropPath { dest: destination }, + response_tx, + }) { + tracing::warn!(dest = %hex::encode(destination), %error, "failed to queue path drop"); + } + let transport_tx = transport_tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(500)).await; + queue_path_request( + &transport_tx, + destination, + false, + "opportunistic path rediscovery", + ); + }); +} + async fn forward_backchannel_receipt( mut runtime_rx: tokio::sync::oneshot::Receiver< Result< @@ -1360,45 +1333,47 @@ fn dispatch_opportunistic_packet( raw: Vec, destination_hash: [u8; 16], destination_public_key: [u8; 64], - msg_hash: Option<[u8; 32]>, + msg_hash: [u8; 32], + timeout: Duration, ) -> Result<(), String> { - if let Some(msg_hash) = msg_hash { - let receipt_permit = transport_tx - .try_reserve() - .map_err(|error| format!("receipt reservation failed: {error}"))?; - let outbound_permit = transport_tx - .try_reserve() - .map_err(|error| format!("packet reservation failed: {error}"))?; - let (full_hash, truncated_hash) = - rns_wire::hash::packet_hash_pair(&raw, rns_wire::flags::HeaderType::Header1); - receipt_permit.send(TransportMessage::RegisterReceipt { - truncated_hash, - full_hash, + let receipt_permit = transport_tx + .try_reserve() + .map_err(|error| format!("receipt reservation failed: {error}"))?; + let outbound_permit = transport_tx + .try_reserve() + .map_err(|error| format!("packet reservation failed: {error}"))?; + let (full_hash, truncated_hash) = + rns_wire::hash::packet_hash_pair(&raw, rns_wire::flags::HeaderType::Header1); + receipt_permit.send(TransportMessage::RegisterReceipt { + truncated_hash, + full_hash, + destination_hash, + destination_public_key, + msg_id: hex::encode(msg_hash), + timeout: Some(timeout), + }); + outbound_permit.send(TransportMessage::Outbound( + rns_transport::messages::OutboundRequest { + raw: Bytes::from(raw), destination_hash, - destination_public_key, - msg_id: hex::encode(msg_hash), - timeout: Some(Duration::from_secs(15)), - }); - outbound_permit.send(TransportMessage::Outbound( - rns_transport::messages::OutboundRequest { - raw: Bytes::from(raw), - destination_hash, - }, - )); - } else { - transport_tx - .try_reserve() - .map_err(|error| format!("packet reservation failed: {error}"))? - .send(TransportMessage::Outbound( - rns_transport::messages::OutboundRequest { - raw: Bytes::from(raw), - destination_hash, - }, - )); - } + }, + )); Ok(()) } +/// `LXMessage.unpack_from_bytes` signature flags (LXMessage.py:829-842). +fn classify_signature( + msg: &LxMessage, + public_key: Option<&[u8; 64]>, +) -> Option { + use lxmf_core::constants::UnverifiedReason; + match public_key { + None => Some(UnverifiedReason::SourceUnknown), + Some(key) if msg.verify(key).is_ok() => None, + Some(_) => Some(UnverifiedReason::SignatureInvalid), + } +} + fn queue_required_transport( transport_tx: &mpsc::Sender, message: TransportMessage, @@ -1467,13 +1442,9 @@ fn decode_download_payload( /// Apply recipient policy before any durable receipt or hook can be created. fn validate_download_policy( msg: &LxMessage, - public_key: Option<[u8; 64]>, tickets: &[[u8; 16]], cost: f64, ) -> Result<(), SuppressionReason> { - if public_key.is_some_and(|key| msg.verify(&key).is_err()) { - return Err(SuppressionReason::InvalidSignature); - } if cost > 0.0 { let Some(stamp) = msg.recipient_stamp().map(|s| s.as_bytes()) else { return Err(SuppressionReason::InvalidStamp); @@ -1616,7 +1587,8 @@ struct LxmdRunner { link_resource_proof_rx: mpsc::Receiver, destination_delivery_proof_rx: mpsc::UnboundedReceiver, - opportunistic_in_flight: HashMap<[u8; 32], PendingOpportunisticDelivery>, + /// Reticulum's medium view for outbound planning, refreshed per tick. + medium: MediumSnapshot, backchannel_command_rx: Option>, backchannel_abandon_tx: mpsc::Sender, backchannel_abandon_rx: mpsc::Receiver, @@ -1900,16 +1872,6 @@ impl LxmdRunner { self.announce_subscriptions.clear(); } - fn queue_router_message(&mut self, message: LxMessage, operation: &'static str) -> bool { - match self.router.try_send(message) { - Ok(()) => true, - Err(error) => { - tracing::warn!(%error, operation, "router rejected LXMF message"); - false - } - } - } - fn new( config: DaemonConfig, config_dir: &Path, @@ -2535,7 +2497,7 @@ impl LxmdRunner { link_packet_proof_rx, link_resource_proof_rx, destination_delivery_proof_rx, - opportunistic_in_flight: HashMap::new(), + medium: MediumSnapshot::default(), backchannel_command_rx: None, backchannel_abandon_tx, backchannel_abandon_rx, @@ -3345,7 +3307,15 @@ impl LxmdRunner { if let Some(hash) = msg_hash { self.propagation_envelopes.remove(&hash); self.pending_propagation_envelopes.remove(&hash); - let _ = self.router.mark_outbound_delivered(&hash); + let propagated = + self.router.pending_outbound.iter().any(|m| { + m.message_id() == hash && m.method == DeliveryMethod::Propagated + }); + if propagated { + self.router.mark_outbound_propagated(&hash); + } else { + self.router.mark_outbound_delivered(&hash); + } tracing::info!(hash = %hex::encode(hash), "link delivery complete"); } } @@ -3370,60 +3340,36 @@ impl LxmdRunner { DeliveryResult::Failed { msg_hash, dest_hash, - message, reason, + link_activated, .. } => { tracing::warn!( dest = %hex::encode(dest_hash), reason = %reason, - attempts = message.delivery_attempts, + link_activated, "link delivery failed" ); - let router_owned = msg_hash.is_some_and(|hash| { - self.router - .pending_outbound - .iter() - .any(|pending| pending.message_id() == hash) - }); - if link_failure_retryable(&reason) - && message.delivery_attempts <= MAX_DELIVERY_ATTEMPTS + let Some(hash) = msg_hash else { + return; + }; + // A failed transfer returns the message to OUTBOUND and the Link + // is gone, as Python's CLOSED link branch handles it. + let actions = self.router.outbound_link_closed( + &hash, + link_activated, + &self.medium, + now_f64(), + ); + self.execute_outbound_actions(actions); + if !self + .router + .pending_outbound + .iter() + .any(|pending| pending.message_id() == hash) { - if let Some(hash) = msg_hash { - tracing::warn!( - hash = %hex::encode(hash), - "retrying message after link delivery failure" - ); - } - if router_owned { - queue_path_request(&self.transport_tx, dest_hash, false, &reason); - if let Some(hash) = msg_hash { - let _ = self - .router - .defer_outbound_for_path_request(&hash, now_f64()); - } - } else { - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - message, - dest_hash, - &reason, - false, - ); - } - } else { - if let Some(hash) = msg_hash { - self.propagation_envelopes.remove(&hash); - self.pending_propagation_envelopes.remove(&hash); - if router_owned { - let _ = self.router.mark_outbound_failed(&hash); - } - tracing::warn!( - hash = %hex::encode(hash), - "message delivery failed" - ); - } + self.propagation_envelopes.remove(&hash); + self.pending_propagation_envelopes.remove(&hash); self.last_delivery_failure = Some(reason); } } @@ -3642,12 +3588,10 @@ impl LxmdRunner { tracing::warn!(msg_id = %proof.msg_id, "ignored destination delivery-proof id with invalid length"); continue; }; - let Some(pending) = self.opportunistic_in_flight.remove(&message_hash) else { - tracing::debug!(msg_id = %proof.msg_id, "delivery proof does not match an in-flight opportunistic message"); + if !self.router.mark_outbound_delivered(&message_hash) { + tracing::debug!(msg_id = %proof.msg_id, "delivery proof does not match a queued opportunistic message"); continue; - }; - - self.router.complete_outbound_message(pending.message); + } tracing::info!( msg_id = %proof.msg_id, rtt_ms = proof.rtt.map(|rtt| rtt.as_secs_f64() * 1000.0), @@ -3656,27 +3600,127 @@ impl LxmdRunner { } } - fn retry_due_opportunistic_deliveries(&mut self, now: f64) { - let due = self - .opportunistic_in_flight + /// Refresh Reticulum's medium view for the destinations outbound planning + /// needs: lowest online bitrate, medium path timeout, routes and first-hop + /// timeouts (`LXMRouter.medium_path_timeout`, `destination_round_trip`). + async fn refresh_outbound_medium(&mut self) { + let mut targets: HashSet<[u8; 16]> = self + .router + .pending_outbound .iter() - .filter_map(|(hash, pending)| (pending.retry_at <= now).then_some(*hash)) - .collect::>(); - - for hash in due { - let Some(pending) = self.opportunistic_in_flight.remove(&hash) else { - continue; - }; - tracing::debug!( - msg_id = %hex::encode(hash), - attempts = pending.message.delivery_attempts, - "opportunistic delivery still awaiting proof; scheduling retry" - ); - if let Err(error) = self.router.try_send(pending.message) { - let reason = format!("failed to schedule opportunistic retry: {error}"); - tracing::warn!(msg_id = %hex::encode(hash), %reason); - self.last_delivery_failure = Some(reason); + .map(|message| message.destination_hash()) + .collect(); + if let Some(node) = self.router.outbound_propagation_node { + targets.insert(node); + } + let query = |query| { + let (response_tx, response_rx) = oneshot::channel(); + let sent = self + .transport_tx + .try_send(TransportMessage::Rpc { query, response_tx }) + .is_ok(); + async move { + if !sent { + return None; + } + tokio::time::timeout(Duration::from_millis(100), response_rx) + .await + .ok()? + .ok() } + }; + if let Some(TransportQueryResponse::InterfaceStats(interfaces)) = + query(TransportQuery::GetInterfaceStats).await + && let Some(lowest) = interfaces + .iter() + .filter(|interface| interface.online && interface.bitrate > 0) + .map(|interface| interface.bitrate) + .min() + { + // Transport keeps the last lowest bitrate when none qualifies (Transport.py:708). + self.medium.lowest_interface_bitrate = Some(lowest); + } + self.medium.medium_path_timeout = self + .medium + .lowest_interface_bitrate + .map(medium_path_timeout) + .unwrap_or(0.0); + let mut routes = HashMap::new(); + if !targets.is_empty() + && let Some(TransportQueryResponse::PathTable(entries)) = + query(TransportQuery::GetPathTable).await + { + let now = now_f64(); + for entry in entries { + if entry.expires <= now || !targets.contains(&entry.hash) { + continue; + } + let first_hop_timeout = + match query(TransportQuery::FirstHopTimeout { dest: entry.hash }).await { + Some(TransportQueryResponse::FloatResult(Some(seconds))) => seconds, + _ => rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT, + }; + routes.insert( + entry.hash, + RouteInfo { + hops: entry.hops, + first_hop_timeout, + }, + ); + } + } + self.medium.routes = routes; + } + + fn outbound_inputs(&self) -> OutboundInputs { + let mut inputs = OutboundInputs { + medium: self.medium.clone(), + ..OutboundInputs::default() + }; + for message in &self.router.pending_outbound { + let destination = message.destination_hash(); + if self + .link_delivery + .as_ref() + .is_some_and(|ld| ld.message_delivery_snapshot(message.message_id()).is_some()) + { + inputs.link_owned.insert(message.message_id()); + } + if self + .known_identities + .contains_key(&hex::encode(destination)) + { + inputs.identities.insert(destination); + } + if message.method == DeliveryMethod::Direct { + inputs.direct_links.insert( + destination, + direct_reusable_link_state(self.link_delivery.as_ref(), destination), + ); + } + } + if let Some(node) = self.router.outbound_propagation_node { + if self.known_identities.contains_key(&hex::encode(node)) { + inputs.identities.insert(node); + } + inputs.propagation_link = self + .link_delivery + .as_ref() + .and_then(|ld| ld.propagation_link_snapshot(node)) + .map(|snapshot| link_snapshot_state(&snapshot)) + .unwrap_or(DirectReusableLinkState::None); + } + inputs + } + + fn run_outbound(&mut self) { + let propagation_unready = self.prepare_propagation_envelopes(); + let mut inputs = self.outbound_inputs(); + inputs.propagation_unready = propagation_unready; + let actions = self.router.process_outbound_with_inputs(&inputs, now_f64()); + if !actions.is_empty() { + self.execute_outbound_actions(actions); + self.drain_core_backchannel_send_commands(); } } @@ -3698,7 +3742,6 @@ impl LxmdRunner { let now = now_f64(); self.drain_destination_delivery_proofs(); - self.retry_due_opportunistic_deliveries(now); self.forward_destination_retains(); self.drain_control_commands(); @@ -3709,44 +3752,7 @@ impl LxmdRunner { self.drain_backchannel_events(); self.router.process_deferred_stamps(); - // Per-destination plan inputs precomputed for pending Direct messages - // only — avoids cloning route_hops/known_identities every tick. - let direct_inputs = self - .router - .pending_outbound - .iter() - .filter(|message| message.method == DeliveryMethod::Direct) - .map(|message| message.destination_hash()) - .collect::>() - .into_iter() - .map(|dest| { - ( - dest, - DirectDeliveryPlanInput { - identity_known: self.known_identities.contains_key(&hex::encode(dest)), - route: direct_route_snapshot(&self.route_hops, dest), - reusable_link: direct_reusable_link_state( - self.link_delivery.as_ref(), - dest, - ), - }, - ) - }) - .collect::>(); - let actions = self.router.process_outbound_with_direct(|message, _now| { - direct_inputs - .get(&message.destination_hash()) - .cloned() - .unwrap_or(DirectDeliveryPlanInput { - identity_known: false, - route: None, - reusable_link: DirectReusableLinkState::None, - }) - }); - if !actions.is_empty() { - self.execute_encrypted_actions(actions); - self.drain_core_backchannel_send_commands(); - } + self.run_outbound(); // Advance the router jobloop counters (transient-cache cleaning, store // cull, peer rotation at Python cadences). `process_outbound_with_direct` // does not drive these. @@ -3760,6 +3766,9 @@ impl LxmdRunner { } } self.drain_core_backchannel_send_commands(); + if self.router.take_outbound_kick() { + self.run_outbound(); + } self.drive_propagation_sync(); @@ -4332,27 +4341,14 @@ impl LxmdRunner { }; match LxMessage::unpack(&unpack_data) { - Ok(mut msg) => { + Ok(msg) => { tracing::info!( from = %hex::encode(msg.source_hash()), title = %msg.title_text(), len = msg.content_bytes().len(), "inbound LXMF message via link" ); - msg.source_blackholed = self.source_blackholed(&msg.source_hash()); - if msg.source_blackholed { - // LXMRouter.py:1739-1741. - tracing::debug!( - from = %hex::encode(msg.source_hash()), - "Dropping LXM from blackholed identity" - ); - return; - } - if self.should_reject_for_signature(&mut msg) || self.should_reject_for_stamp(&msg) - { - return; - } - self.handle_inbound_message(msg, DeliveryMethod::Direct); + self.admit_inbound_message(msg, DeliveryMethod::Direct); } Err(e) => { tracing::debug!("link data not an LXMF message: {e}"); @@ -4682,7 +4678,11 @@ impl LxmdRunner { } else { 0.0 }; - let disposition = if self.source_blackholed(&msg.source_hash()) { + let mut msg = msg; + msg.unverified_reason = classify_signature(&msg, public_key.as_ref()); + let disposition = if self.source_blackholed(&msg.source_hash()) + || self.router.is_ignored(&msg.source_hash()) + { DurableDisposition::PolicyDiscard } else { DurableDisposition::Committed @@ -4705,7 +4705,7 @@ impl LxmdRunner { SuppressionReason::Cancelled, )); } - validate_download_policy(&msg, public_key, &tickets, cost) + validate_download_policy(&msg, &tickets, cost) .map_err(DownloadWorkerError::Rejected)?; DurableAdmissionReceipt::commit(store.prepare( record, @@ -4963,6 +4963,24 @@ impl LxmdRunner { } }; + // Python proves every delivery packet before unpacking or gating it + // (LXMRouter.py:2262-2263). + if let Some(proof_raw) = self.create_delivery_proof(raw) { + let trunc = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); + if !self.queue_runtime_transport( + TransportMessage::Outbound(rns_transport::messages::OutboundRequest { + raw: Bytes::from(proof_raw), + destination_hash: trunc, + }), + "opportunistic delivery proof", + ) { + tracing::error!( + packet = %hex::encode(trunc), + "could not stage opportunistic delivery proof" + ); + } + } + // Python strips the dest hash for opportunistic delivery; direct delivery // keeps it. Re-prepend if missing so LxMessage::unpack always sees the // [dest_hash][lxm_data] layout. @@ -4975,7 +4993,7 @@ impl LxmdRunner { }; match LxMessage::unpack(&unpack_data) { - Ok(mut msg) => { + Ok(msg) => { tracing::info!( from = %hex::encode(msg.source_hash()), title = %msg.title_text(), @@ -4983,40 +5001,7 @@ impl LxmdRunner { "inbound LXMF message received" ); - msg.source_blackholed = self.source_blackholed(&msg.source_hash()); - if msg.source_blackholed { - // LXMRouter.py:1739-1741. - tracing::debug!( - from = %hex::encode(msg.source_hash()), - "Dropping LXM from blackholed identity" - ); - return; - } - - // Reject on stamp failure BEFORE sending the delivery proof. - if self.should_reject_for_signature(&mut msg) || self.should_reject_for_stamp(&msg) - { - return; - } - - if let Some(proof_raw) = self.create_delivery_proof(raw) { - let trunc = - rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type); - if !self.queue_runtime_transport( - TransportMessage::Outbound(rns_transport::messages::OutboundRequest { - raw: Bytes::from(proof_raw), - destination_hash: trunc, - }), - "opportunistic delivery proof", - ) { - tracing::error!( - packet = %hex::encode(trunc), - "could not stage opportunistic delivery proof" - ); - } - } - - self.handle_inbound_message(msg, DeliveryMethod::Opportunistic); + self.admit_inbound_message(msg, DeliveryMethod::Opportunistic); } Err(e) => { tracing::warn!("failed to unpack LXMF message: {e}"); @@ -5024,21 +5009,33 @@ impl LxmdRunner { } } - /// Validate a recalled sender signature. Unknown senders remain deliverable - /// like Python, but can never teach the router a ticket. - fn should_reject_for_signature(&self, msg: &mut LxMessage) -> bool { - let Some(public_key) = self.known_identities.get(&hex::encode(msg.source_hash())) else { - return false; - }; - if msg.verify(public_key).is_ok() { - false - } else { - tracing::warn!( + /// Python `lxmf_delivery` gating (LXMRouter.py:2163-2257): blackholed + /// source, ticket learning from a validated signature, stamp, ignored + /// source, then delivery. Unknown or invalid signatures are delivered flagged. + fn admit_inbound_message(&mut self, mut msg: LxMessage, method: DeliveryMethod) { + msg.source_blackholed = self.source_blackholed(&msg.source_hash()); + if msg.source_blackholed { + tracing::debug!( from = %hex::encode(msg.source_hash()), - "inbound message rejected: invalid LXMF signature" + "Dropping LXM from blackholed identity" ); - true + return; } + let public_key = self + .known_identities + .get(&hex::encode(msg.source_hash())) + .copied(); + msg.unverified_reason = classify_signature(&msg, public_key.as_ref()); + if msg.unverified_reason.is_none() + && let Some(key) = public_key + && let Ok(verified) = msg.verify(&key) + { + self.router.learn_ticket_from_inbound(&verified); + } + if self.should_reject_for_stamp(&msg) { + return; + } + self.handle_inbound_message(msg, method); } /// Returns true if the message should be rejected. @@ -5089,19 +5086,10 @@ impl LxmdRunner { /// Write a received LXMF message to disk and invoke `on_inbound`. fn handle_inbound_message(&mut self, mut msg: LxMessage, method: DeliveryMethod) { - // Direct/opportunistic admission has already checked the recipient's - // policy. Ticket learning separately requires the source-bound proof; - // deliver_inbound deliberately has no authentication authority. Learn - // before deduplication so a retry after identity recall can teach its ticket. - if let Some(public_key) = self.known_identities.get(&hex::encode(msg.source_hash())) - && let Ok(verified) = msg.verify(public_key) - { - self.router.learn_ticket_from_inbound(&verified); - } if !self.router.deliver_inbound(&msg, false) { tracing::debug!( message = %hex::encode(msg.message_id()), - "ignoring already delivered inbound LXMF message" + "ignoring inbound LXMF message from an ignored source or already delivered" ); return; } @@ -5149,424 +5137,234 @@ impl LxmdRunner { ); } - fn execute_encrypted_actions(&mut self, actions: Vec) { - for action in actions { - let (mut message, dest_hash, is_opportunistic, direct_plan) = match action { - OutboundAction::DeliverDirect { message, dest_hash } => { - (message, dest_hash, false, None) - } - OutboundAction::PlanDirect { - message, - dest_hash, - plan, - } => (message, dest_hash, false, Some(plan)), - OutboundAction::DeliverOpportunistic { message, dest_hash } => { - (message, dest_hash, true, None) - } - OutboundAction::DeliverPropagated { message, prop_hash } => { - let mut message = message; - let prop_hex = hex::encode(prop_hash); - tracing::info!( - dest = %hex::encode(message.destination_hash()), - prop = %hex::encode(prop_hash), - "routing message via propagation node" - ); - match self.pack_message_for_propagation(&message, prop_hash) { - Ok(packed) => { - let attempts = mark_delivery_attempt(&mut message); - if attempts >= MAX_DELIVERY_ATTEMPTS { - tracing::warn!( - prop = %prop_hex, - attempts, - max_attempts = MAX_DELIVERY_ATTEMPTS, - "propagated delivery attempt budget reached; deferring terminal failure" - ); - self.queue_router_message(message, "propagated retry deferral"); - continue; - } - let hops = route_hops_for(&self.route_hops, prop_hash); - self.ensure_link_delivery(); - if let Some(ref mut ld) = self.link_delivery - && let Err(err) = - ld.start_packed_delivery(message, prop_hash, hops, packed, true) - { - let reason = err.error.to_string(); - tracing::warn!( - error = %reason, - prop = %hex::encode(prop_hash), - "failed to start propagated link delivery" - ); - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - *err.message, - prop_hash, - &reason, - false, - ); - } - } - Err(PropagationPreparationError::Pending) => { - message.next_delivery_attempt = now_f64() + 0.5; - self.queue_router_message(message, "propagation envelope preparation"); - } - Err(PropagationPreparationError::Missing(missing)) => { - let path = if missing == MissingPropagationInput::RecipientIdentity { - message.destination_hash() - } else { - prop_hash - }; - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - message, - path, - "propagation readiness incomplete", - true, - ); - } - Err(PropagationPreparationError::Invalid(error)) => { - self.last_delivery_failure = Some(error); - message.mark_failed(); - self.propagation_envelopes.remove(&message.message_id()); - } - } - continue; - } - OutboundAction::Failed(message) => { - self.propagation_envelopes.remove(&message.message_id()); - self.pending_propagation_envelopes - .remove(&message.message_id()); - let reason = Some(message.message_id()) - .map(|hash| { - format!("delivery attempts exhausted for {}", hex::encode(hash)) - }) - .unwrap_or_else(|| "delivery attempts exhausted".to_string()); - self.last_delivery_failure = Some(reason); - continue; - } - OutboundAction::Expired(message) => { - self.propagation_envelopes.remove(&message.message_id()); - self.pending_propagation_envelopes - .remove(&message.message_id()); - let reason = Some(message.message_id()) - .map(|hash| { - format!("message {} expired before delivery", hex::encode(hash)) - }) - .unwrap_or_else(|| "message expired before delivery".to_string()); - self.last_delivery_failure = Some(reason); - continue; - } - }; - - let dest_hex = hex::encode(dest_hash); - if !is_opportunistic { - let router_owned = direct_plan.is_some(); - let plan = direct_plan.unwrap_or_else(|| { - plan_direct_delivery( - &mut message, - DirectDeliveryPlanInput { - identity_known: self.known_identities.contains_key(&dest_hex), - route: direct_route_snapshot(&self.route_hops, dest_hash), - reusable_link: direct_reusable_link_state( - self.link_delivery.as_ref(), - dest_hash, - ), - }, - now_f64(), - ) - }); - - match plan { - DirectDeliveryPlan::RequestPath { drop_existing } => { - self.recall_identity(dest_hash); + /// Prepare propagation envelopes for queued propagated messages and return + /// those not ready yet. Python generates the propagation stamp before a + /// message enters the outbound queue, so these wait outside processing. + fn prepare_propagation_envelopes(&mut self) -> HashSet<[u8; 32]> { + let mut unready = HashSet::new(); + let Some(node) = self.router.outbound_propagation_node else { + return unready; + }; + let queued: Vec = self + .router + .pending_outbound + .iter() + .filter(|message| { + message.method == DeliveryMethod::Propagated + && message.state == lxmf_core::constants::MessageState::Outbound + }) + .cloned() + .collect(); + for message in queued { + let id = message.message_id(); + match self.pack_message_for_propagation(&message, node) { + Ok(_) => {} + Err(PropagationPreparationError::Missing( + MissingPropagationInput::NodeIdentity | MissingPropagationInput::NodePath, + )) => {} + Err(PropagationPreparationError::Missing(missing)) => { + let wanted = if missing == MissingPropagationInput::RecipientIdentity { + message.destination_hash() + } else { + node + }; + self.recall_identity(wanted); + if self.router.request_path(wanted, &self.medium, now_f64()) { queue_path_request( &self.transport_tx, - dest_hash, - drop_existing, - "direct delivery path request", - ); - tracing::warn!( - dest = %dest_hex, - attempts = message.delivery_attempts, - drop_existing, - "direct delivery waiting for path" - ); - if !router_owned { - self.queue_router_message(message, "direct path wait"); - } - } - DirectDeliveryPlan::DeferTerminalFailure => { - tracing::warn!( - dest = %dest_hex, - attempts = message.delivery_attempts, - max_attempts = MAX_DELIVERY_ATTEMPTS, - "direct delivery attempt budget reached; deferring terminal failure" - ); - if !router_owned { - self.queue_router_message(message, "direct terminal deferral"); - } - } - DirectDeliveryPlan::WaitForReusableLink => { - tracing::debug!( - dest = %dest_hex, - attempts = message.delivery_attempts, - "direct delivery waiting for reusable Link" - ); - if !router_owned { - self.queue_router_message(message, "reusable Link wait"); - } - } - DirectDeliveryPlan::UseReusableLink - | DirectDeliveryPlan::StartNewLink { .. } => { - let planned_hops = match plan { - DirectDeliveryPlan::StartNewLink { hops } => hops, - _ => route_hops_for(&self.route_hops, dest_hash), - }; - tracing::info!( - dest = %dest_hex, - hops = planned_hops, - plan = ?plan, - "routing Direct LXMF message over link delivery" - ); - self.ensure_link_delivery(); - if let Some(ref mut ld) = self.link_delivery { - if matches!(plan, DirectDeliveryPlan::UseReusableLink) - && ld.direct_link_snapshot(dest_hash).is_none() - && ld.backchannel_link_snapshot(dest_hash).is_some() - { - match ld.start_backchannel_delivery(message, dest_hash) { - Ok(_) => {} - Err(err) => { - let reason = err.error.to_string(); - let returned_message = *err.message; - tracing::warn!( - error = %reason, - dest = %dest_hex, - "failed to start daemon backchannel delivery" - ); - if router_owned { - queue_path_request( - &self.transport_tx, - dest_hash, - false, - &reason, - ); - if let Some(hash) = Some(returned_message.message_id()) - { - let _ = - self.router.defer_outbound_for_path_request( - &hash, - now_f64(), - ); - } - } else { - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - returned_message, - dest_hash, - &reason, - false, - ); - } - } - } - continue; - } - - if let Err(err) = - ld.start_delivery_with_report(message, dest_hash, planned_hops) - { - let reason = err.error.to_string(); - let returned_message = *err.message; - tracing::warn!( - error = %reason, - dest = %dest_hex, - "failed to start direct link delivery" - ); - if router_owned { - queue_path_request( - &self.transport_tx, - dest_hash, - false, - &reason, - ); - if let Some(hash) = Some(returned_message.message_id()) { - let _ = self - .router - .defer_outbound_for_path_request(&hash, now_f64()); - } - } else { - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - returned_message, - dest_hash, - &reason, - false, - ); - } - } - } - } - DirectDeliveryPlan::Fail => { - tracing::warn!( - dest = %dest_hex, - attempts = message.delivery_attempts, - "direct delivery failed before link delivery" + wanted, + false, + "propagation readiness incomplete", ); } + unready.insert(id); + } + Err(PropagationPreparationError::Pending) => { + unready.insert(id); + } + Err(PropagationPreparationError::Invalid(error)) => { + self.last_delivery_failure = Some(error); + self.propagation_envelopes.remove(&id); + self.router.mark_outbound_failed(&id); } - continue; } + } + unready + } - let destination_public_key = self.known_identities.get(&dest_hex).copied(); - let mut missing_identity = false; - let payload = match message.pack_opportunistic_encrypted(|plaintext| { - self.encrypt_for_destination(&dest_hex, plaintext) - .ok_or_else(|| { - missing_identity = true; - lxmf_core::message::MessageError::PackFailed(format!( - "no identity key for destination {dest_hex}" - )) - }) - }) { - Ok(ct) => { - tracing::info!( - dest = %dest_hex, - encrypted_len = ct.len(), - "outbound LXMF: encrypted opportunistic payload" - ); - ct + fn execute_outbound_actions(&mut self, actions: Vec) { + for action in actions { + match action { + OutboundAction::Failed(message) => { + let id = message.message_id(); + self.propagation_envelopes.remove(&id); + self.pending_propagation_envelopes.remove(&id); + tracing::warn!(hash = %hex::encode(id), "message delivery failed"); + self.last_delivery_failure = Some(format!( + "delivery attempts exhausted for {}", + hex::encode(id) + )); } - Err(err) if missing_identity => { - tracing::warn!( - dest = %dest_hex, - attempts = message.delivery_attempts, - error = %err, - "destination key unknown, re-queuing" - ); - self.recall_identity(dest_hash); - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - message, - dest_hash, - "opportunistic destination identity unknown", - true, - ); - continue; + OutboundAction::RequestPath { + destination, + drop_existing, + } => { + self.recall_identity(destination); + if drop_existing { + queue_path_request_after_drop(&self.transport_tx, destination); + } else { + queue_path_request( + &self.transport_tx, + destination, + false, + "outbound path request", + ); + } } - Err(err) => { - tracing::warn!( - dest = %dest_hex, - error = %err, - "failed to pack opportunistic LXMF message" - ); - continue; - } - }; - let Some(destination_public_key) = destination_public_key else { - tracing::error!( - dest = %dest_hex, - "opportunistic encryption succeeded without a retained destination identity" - ); - continue; - }; - let msg_hash = Some(message.message_id()); + OutboundAction::SendOpportunistic { message } => self.send_opportunistic(message), + OutboundAction::DeliverOverLink { + message, + target, + plan, + } => self.deliver_over_link(message, target, plan), + } + } + } - let flags = rns_wire::flags::PacketFlags { + fn send_opportunistic(&mut self, message: LxMessage) { + let dest_hash = message.destination_hash(); + let dest_hex = hex::encode(dest_hash); + let msg_hash = message.message_id(); + let Some(destination_public_key) = self.known_identities.get(&dest_hex).copied() else { + tracing::warn!(dest = %dest_hex, "destination key unknown, waiting for path"); + self.recall_identity(dest_hash); + let actions = self + .router + .await_outbound_path(&msg_hash, &self.medium, now_f64()); + self.execute_outbound_actions(actions); + return; + }; + let payload = match message.pack_opportunistic_encrypted(|plaintext| { + self.encrypt_for_destination(&dest_hex, plaintext) + .ok_or_else(|| MessageError::PackFailed("destination encryption failed".into())) + }) { + Ok(payload) => payload, + Err(error) => { + // A raising send() fails the message (LXMRouter.py:3143-3146). + tracing::warn!(dest = %dest_hex, %error, "opportunistic LXMF send failed"); + self.last_delivery_failure = Some(error.to_string()); + self.router.mark_outbound_failed(&msg_hash); + return; + } + }; + 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::Single, packet_type: rns_wire::flags::PacketType::Data, - }; - let header = rns_wire::header::PacketHeader { - flags, - hops: 0, - transport_id: None, - destination_hash: dest_hash, - context: rns_wire::context::PacketContext::None, - }; - let mut raw = header.pack(); - raw.extend_from_slice(&payload); - - // Escalate oversize packets to link delivery. - if raw.len() > rns_wire::constants::MTU { - tracing::info!( - dest = %dest_hex, - packet_len = raw.len(), - "packet exceeds MTU; routing to link delivery" - ); - let attempts = mark_delivery_attempt(&mut message); - if attempts >= MAX_DELIVERY_ATTEMPTS { - tracing::warn!( - dest = %dest_hex, - attempts, - max_attempts = MAX_DELIVERY_ATTEMPTS, - "oversized direct delivery attempt budget reached; deferring terminal failure" - ); - self.queue_router_message(message, "oversized direct retry deferral"); - continue; - } - let hops = route_hops_for(&self.route_hops, dest_hash); - self.ensure_link_delivery(); - if let Some(ref mut ld) = self.link_delivery - && let Err(err) = ld.start_delivery(message, dest_hash, hops) - { - let reason = err.error.to_string(); - tracing::warn!( - error = %reason, - dest = %dest_hex, - "failed to start oversized direct link delivery" - ); - requeue_after_path_request( - &mut self.router, - &self.transport_tx, - *err.message, - dest_hash, - &reason, - false, - ); - } - continue; + }, + hops: 0, + transport_id: None, + destination_hash: dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&payload); + let timeout = lxmf_core::router::outbound::opportunistic_receipt_timeout( + self.medium.route(&dest_hash), + message.receipt_timeout, + ); + match dispatch_opportunistic_packet( + &self.transport_tx, + raw, + dest_hash, + destination_public_key, + msg_hash, + timeout, + ) { + Ok(()) => { + tracing::info!(hash = %hex::encode(msg_hash), "message sent; awaiting delivery proof") } + Err(error) => tracing::warn!( + dest = %dest_hex, + %error, + "transport backpressure deferred opportunistic message" + ), + } + } - mark_delivery_attempt(&mut message); - match dispatch_opportunistic_packet( - &self.transport_tx, - raw, - dest_hash, - destination_public_key, - msg_hash, - ) { - Ok(()) => { - if let Some(hash) = msg_hash { - self.opportunistic_in_flight.insert( - hash, - PendingOpportunisticDelivery { - retry_at: message.next_delivery_attempt, - message, - }, - ); - tracing::info!(hash = %hex::encode(hash), "message sent; awaiting delivery proof"); - } else { - tracing::warn!( - dest = %dest_hex, - "opportunistic message has no message id; delivery cannot be tracked" - ); + fn deliver_over_link(&mut self, message: LxMessage, target: [u8; 16], plan: LinkDeliveryPlan) { + let msg_hash = message.message_id(); + let hops = match plan { + LinkDeliveryPlan::StartLink { hops } => hops, + LinkDeliveryPlan::UseLink => self + .medium + .route(&target) + .map(|route| route.hops.max(1)) + .unwrap_or(1), + }; + self.ensure_link_delivery(); + let propagated = message.method == DeliveryMethod::Propagated; + let packed = if propagated { + match self.pack_message_for_propagation(&message, target) { + Ok(packed) => Some(packed), + Err(PropagationPreparationError::Invalid(error)) => { + self.last_delivery_failure = Some(error); + self.router.mark_outbound_failed(&msg_hash); + return; + } + Err(_) => { + // The envelope went stale since this pass prepared it. + if let Some(queued) = self + .router + .pending_outbound + .iter_mut() + .find(|queued| queued.message_id() == msg_hash) + { + queued.state = lxmf_core::constants::MessageState::Outbound; } + return; } - Err(e) => { - tracing::warn!( - dest = %dest_hex, - error = %e, - "transport backpressure deferred opportunistic message" - ); - self.queue_router_message(message, "opportunistic transport backpressure"); - } + } + } else { + None + }; + let Some(ld) = self.link_delivery.as_mut() else { + return; + }; + let started = if let Some(packed) = packed { + ld.start_packed_delivery(message, target, hops, packed, true) + .map(|_| ()) + .map_err(|failure| failure.error.to_string()) + } else if plan == LinkDeliveryPlan::UseLink + && ld.direct_link_snapshot(target).is_none() + && ld.backchannel_link_snapshot(target).is_some() + { + ld.start_backchannel_delivery(message, target) + .map(|_| ()) + .map_err(|failure| failure.error.to_string()) + } else { + ld.start_delivery_with_report(message, target, hops) + .map(|_| ()) + .map_err(|failure| failure.error.to_string()) + }; + match started { + Ok(()) => tracing::info!( + target = %hex::encode(target), + hops, + plan = ?plan, + propagated, + "routing LXMF message over link delivery" + ), + Err(reason) => { + tracing::warn!(target = %hex::encode(target), %reason, "failed to start link delivery"); + let activated = plan == LinkDeliveryPlan::UseLink; + let actions = + self.router + .outbound_link_closed(&msg_hash, activated, &self.medium, now_f64()); + self.execute_outbound_actions(actions); } } } @@ -6250,11 +6048,6 @@ pub(crate) async fn main() { ); for destination in ignored { runner.router.ignore_destination(destination); - if let Some(ref node) = runner.propagation_node - && let Ok(mut node) = node.lock() - { - node.ignore_destination(destination); - } } } let allowed = load_hash_list(&config_dir.join("allowed")); @@ -6293,21 +6086,19 @@ pub(crate) async fn main() { runner.run_deferred_start_jobs(daemon_config.announce_at_start); 'one_shot: { let dest_hex = normalize_hash_hex(&send_args[0]); - let content = match args.send_file.as_ref() { + let contents = match args.send_file.as_ref() { Some(path) => match std::fs::read_to_string(path) { - Ok(content) => content, + Ok(content) => vec![content], Err(e) => { tracing::error!(path = %path.display(), error = %e, "failed to read --send-file"); break 'one_shot; } }, - None => match send_args.get(1) { - Some(content) => content.clone(), - None => { - tracing::error!("--send requires CONTENT unless --send-file is provided"); - break 'one_shot; - } - }, + None if send_args.len() > 1 => send_args[1..].to_vec(), + None => { + tracing::error!("--send requires CONTENT unless --send-file is provided"); + break 'one_shot; + } }; let dest_hash = match parse_destination_hash(&dest_hex) { @@ -6351,6 +6142,7 @@ pub(crate) async fn main() { } } runner.refresh_route_hops_from_transport().await; + runner.refresh_outbound_medium().await; runner.drain_link_packets(); have_key = runner.known_identities.contains_key(&dest_hex); if have_key @@ -6376,60 +6168,65 @@ pub(crate) async fn main() { ); } - let mut msg = match LxMessageDraft::new( - dest_hash, - runner.lxmf_dest_hash, - "", - &content, - args.send_method.delivery_method(), - ) { - Ok(value) => value, - Err(error) => { - tracing::error!(%error,"invalid message size"); - break 'one_shot; - } - }; - if let Some(raw) = args.send_fields_json.as_deref() { - match parse_send_fields_json(raw) { - Ok(fields) => { - tracing::info!(count = fields.len(), "attaching custom fields to --send"); - for (id, value) in fields { - if let Err(error) = msg.set_field(id, value) { - tracing::error!(%error,"invalid --send field"); - break 'one_shot; - } - } - } - Err(e) => { - tracing::error!("--send-fields-json: {e}"); + for content in &contents { + let mut msg = match LxMessageDraft::new( + dest_hash, + runner.lxmf_dest_hash, + "", + content, + args.send_method.delivery_method(), + ) { + Ok(value) => value, + Err(error) => { + tracing::error!(%error,"invalid message size"); break 'one_shot; } + }; + if let Some(raw) = args.send_fields_json.as_deref() { + match parse_send_fields_json(raw) { + Ok(fields) => { + tracing::info!( + count = fields.len(), + "attaching custom fields to --send" + ); + for (id, value) in fields { + if let Err(error) = msg.set_field(id, value) { + tracing::error!(%error,"invalid --send field"); + break 'one_shot; + } + } + } + Err(e) => { + tracing::error!("--send-fields-json: {e}"); + break 'one_shot; + } + } } - } - msg.include_ticket = true; - let prepared = runner.router.prepare_outbound(&mut msg).and_then(|intent| { - intent - .persist(&runner.data_dir, &mut msg) - .map_err(|e| lxmf_core::router::TicketPreparationError::Encode(e.to_string())) - }); - if let Err(error) = prepared { - tracing::error!(%error,"reply ticket persistence failed"); - break 'one_shot; - } - let Some(signing_key) = runner.identity.get_signing_key() else { - tracing::error!("identity has no signing key"); - break 'one_shot; - }; - let signed = match msg.sign(&signing_key) { - Ok(value) => value, - Err(error) => { - tracing::error!(%error,"failed to sign message"); + msg.include_ticket = true; + let prepared = runner.router.prepare_outbound(&mut msg).and_then(|intent| { + intent.persist(&runner.data_dir, &mut msg).map_err(|e| { + lxmf_core::router::TicketPreparationError::Encode(e.to_string()) + }) + }); + if let Err(error) = prepared { + tracing::error!(%error,"reply ticket persistence failed"); + break 'one_shot; + } + let Some(signing_key) = runner.identity.get_signing_key() else { + tracing::error!("identity has no signing key"); + break 'one_shot; + }; + let signed = match msg.sign(&signing_key) { + Ok(value) => value, + Err(error) => { + tracing::error!(%error,"failed to sign message"); + break 'one_shot; + } + }; + if let Err(error) = runner.router.submit_signed(signed) { + tracing::error!(%error,"failed to queue message"); break 'one_shot; } - }; - if let Err(error) = runner.router.submit_signed(signed) { - tracing::error!(%error,"failed to queue message"); - break 'one_shot; } // Completion phase: do not confuse queue acceptance with delivery. @@ -6440,6 +6237,7 @@ pub(crate) async fn main() { for _ in 0..args.send_timeout_secs { runner.drain_announce_events(); runner.refresh_route_hops_from_transport().await; + runner.refresh_outbound_medium().await; runner.drain_link_packets(); runner.tick(); if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await { @@ -6448,10 +6246,7 @@ pub(crate) async fn main() { } let stats = runner.router.stats(); - if stats.pending_outbound == 0 - && stats.pending_deferred_stamps == 0 - && runner.opportunistic_in_flight.is_empty() - { + if stats.pending_outbound == 0 && stats.pending_deferred_stamps == 0 { drained = true; break; } @@ -6477,6 +6272,7 @@ pub(crate) async fn main() { for _ in 0..args.send_timeout_secs { runner.drain_announce_events(); runner.refresh_route_hops_from_transport().await; + runner.refresh_outbound_medium().await; runner.drain_link_packets(); runner.tick(); if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await { @@ -6547,6 +6343,7 @@ pub(crate) async fn main() { _ = tick_timer.tick() => { runner.drain_announce_events(); runner.refresh_route_hops_from_transport().await; + runner.refresh_outbound_medium().await; runner.refresh_blackholed_identities_from_transport().await; runner.drain_link_packets(); runner.tick(); @@ -7363,8 +7160,15 @@ mod tests { let raw = vec![0x44; 64]; let (tx, mut rx) = mpsc::channel(2); - dispatch_opportunistic_packet(&tx, raw, destination_hash, public_key, Some(message_hash)) - .unwrap(); + dispatch_opportunistic_packet( + &tx, + raw, + destination_hash, + public_key, + message_hash, + Duration::from_secs(12), + ) + .unwrap(); assert!(matches!( rx.try_recv().unwrap(), @@ -7387,8 +7191,15 @@ mod tests { .unwrap(); assert!( - dispatch_opportunistic_packet(&tx, vec![0; 64], [2; 16], [3; 64], Some([4; 32])) - .is_err() + dispatch_opportunistic_packet( + &tx, + vec![0; 64], + [2; 16], + [3; 64], + [4; 32], + Duration::from_secs(12) + ) + .is_err() ); assert!(matches!( rx.try_recv().unwrap(), @@ -7718,35 +7529,6 @@ mod tests { assert_eq!(under.len(), 1); } - #[test] - fn path_request_requeue_sets_path_wait_deadline() { - let mut router = LxmRouter::new(Default::default()); - let (tx, mut rx) = mpsc::channel::(4); - let dest = [0x22; 16]; - let source = [0x11; 16]; - let message = signed_fixture(dest, source, "retry", "hello", DeliveryMethod::Direct); - let before = now_f64(); - - requeue_after_path_request(&mut router, &tx, message, dest, "test path wait", true); - - assert_eq!(router.pending_outbound.len(), 1); - let queued = &router.pending_outbound[0]; - assert_eq!(queued.delivery_attempts, 1); - assert!(queued.last_delivery_attempt >= before); - assert!( - queued.next_delivery_attempt >= before + PATH_REQUEST_WAIT as f64 - 1.0 - && queued.next_delivery_attempt <= now_f64() + PATH_REQUEST_WAIT as f64 + 1.0, - "path-request retry should wait about {PATH_REQUEST_WAIT}s" - ); - - match rx.try_recv().expect("path request") { - TransportMessage::RequestPath { destination_hash } => { - assert_eq!(destination_hash, dest); - } - other => panic!("expected RequestPath, got {other:?}"), - } - } - #[test] fn queue_path_request_can_drop_stale_path_before_requesting() { let (tx, mut rx) = mpsc::channel::(4); @@ -7805,79 +7587,6 @@ mod tests { assert_eq!(last, 1234.5); } - #[test] - fn path_request_requeue_can_preserve_attempt_count_after_link_start_failure() { - let mut router = LxmRouter::new(Default::default()); - let (tx, _rx) = mpsc::channel::(4); - let dest = [0x44; 16]; - let source = [0x33; 16]; - let mut message = signed_fixture(dest, source, "retry", "hello", DeliveryMethod::Direct); - message.delivery_attempts = 3; - - requeue_after_path_request(&mut router, &tx, message, dest, "transport full", false); - - assert_eq!(router.pending_outbound.len(), 1); - assert_eq!(router.pending_outbound[0].delivery_attempts, 3); - assert!(router.pending_outbound[0].next_delivery_attempt > now_f64()); - } - - #[test] - fn delivery_attempt_uses_delivery_retry_deadline() { - let dest = [0x66; 16]; - let source = [0x55; 16]; - let mut message = signed_fixture(dest, source, "direct", "hello", DeliveryMethod::Direct); - let before = now_f64(); - - let attempts = mark_delivery_attempt(&mut message); - - assert_eq!(attempts, 1); - assert_eq!(message.delivery_attempts, 1); - assert!(message.last_delivery_attempt >= before); - assert!( - message.next_delivery_attempt >= before + DELIVERY_RETRY_WAIT as f64 - 1.0 - && message.next_delivery_attempt <= now_f64() + DELIVERY_RETRY_WAIT as f64 + 1.0, - "delivery retry should wait about {DELIVERY_RETRY_WAIT}s" - ); - } - - #[test] - fn link_failure_retry_policy_matches_pre_establishment_failures() { - assert!(link_failure_retryable("link establishment timeout")); - assert!(link_failure_retryable("link closed")); - assert!(link_failure_retryable("transport full")); - assert!(link_failure_retryable("transport closed")); - assert!(link_failure_retryable("link is not active")); - assert!(link_failure_retryable("link not found")); - assert!(!link_failure_retryable("resource transfer failed")); - } - - #[test] - fn route_hops_for_uses_cached_announce_hops_with_one_hop_floor() { - let dest = [0x77; 16]; - let mut hops = HashMap::new(); - - assert_eq!(route_hops_for(&hops, dest), 1); - - hops.insert(dest, 4); - assert_eq!(route_hops_for(&hops, dest), 4); - - hops.insert(dest, 0); - assert_eq!(route_hops_for(&hops, dest), 1); - } - - #[test] - fn direct_route_snapshot_uses_cached_announce_hops() { - let dest = [0x88; 16]; - let mut hops = HashMap::new(); - - assert!(direct_route_snapshot(&hops, dest).is_none()); - - hops.insert(dest, 5); - let snapshot = direct_route_snapshot(&hops, dest).expect("route snapshot"); - assert_eq!(snapshot.destination_hash, dest); - assert_eq!(snapshot.hops, 5); - } - /// Real encrypted downloads pass the same decode/policy stages as workers; /// only validated bytes can create an archive, purge receipt, or hook. #[test] @@ -7929,7 +7638,7 @@ mod tests { .unwrap(); assert_eq!(decoded.wire_bytes(), missing.wire_bytes()); assert_eq!( - validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 8.0), + validate_download_policy(&decoded, &[], 8.0), Err(SuppressionReason::InvalidStamp) ); assert!(store.haves(recipient.hash, [9; 16], 101).is_empty()); @@ -7939,10 +7648,7 @@ mod tests { .join(format!("{}.lxm", hex::encode(missing.message_id()))) .exists() ); - assert_eq!( - validate_download_policy(&decoded, Some(sender.get_public_key()), &[], 0.0), - Ok(()) - ); + assert_eq!(validate_download_policy(&decoded, &[], 0.0), Ok(())); assert!(matches!( decode_download_payload( missing.wire_bytes(), @@ -7956,9 +7662,11 @@ mod tests { let mut corrupt = missing.wire_bytes().to_vec(); corrupt[32] ^= 1; let corrupt = LxMessage::unpack(&corrupt).unwrap(); + // An invalid signature is delivered flagged, as lxmf_delivery does. + assert_eq!(validate_download_policy(&corrupt, &[], 0.0), Ok(())); assert_eq!( - validate_download_policy(&corrupt, Some(sender.get_public_key()), &[], 0.0), - Err(SuppressionReason::InvalidSignature) + classify_signature(&corrupt, Some(&sender.get_public_key())), + Some(lxmf_core::constants::UnverifiedReason::SignatureInvalid) ); let ticket = [7u8; 16]; let mut material = [0u8; 48]; @@ -7978,7 +7686,7 @@ mod tests { MessageDecodeLimits::default(), ) .unwrap(); - validate_download_policy(&accepted, Some(sender.get_public_key()), &[ticket], 8.0).unwrap(); + validate_download_policy(&accepted, &[ticket], 8.0).unwrap(); let scope = AdmissionScope { identity: recipient.hash, node: [9; 16], diff --git a/crates/lxmf-tools/src/lxmd_cli.rs b/crates/lxmf-tools/src/lxmd_cli.rs index fceadde..c9fe9ea 100644 --- a/crates/lxmf-tools/src/lxmd_cli.rs +++ b/crates/lxmf-tools/src/lxmd_cli.rs @@ -112,8 +112,9 @@ pub struct Args { #[arg(long, value_name = "PATH")] pub identity: Option, - /// Send a single message and exit: `--send `. - #[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])] + /// Send messages and exit: `--send ...`, one message + /// per content, queued together. + #[arg(long, num_args = 1.., value_names = ["DEST_HASH", "CONTENT"])] pub send: Option>, /// Read outgoing `--send` content from a UTF-8 file instead of argv. diff --git a/crates/lxmf-tools/tests/lxmd_cli.rs b/crates/lxmf-tools/tests/lxmd_cli.rs index 8895dfe..2721026 100644 --- a/crates/lxmf-tools/tests/lxmd_cli.rs +++ b/crates/lxmf-tools/tests/lxmd_cli.rs @@ -280,7 +280,7 @@ fn clap_requires_send_argument() { "expected Clap usage failure, got:\n{}", combined_output(&output) ); - assert!(stderr(&output).contains("a value is required for '--send '")); + assert!(stderr(&output).contains("a value is required for '--send ...'")); } #[test]