diff --git a/CHANGELOG.md b/CHANGELOG.md index f9df308..efeb1de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - `lxmd` learns the identities Reticulum validated before it subscribed to announces, and asks Reticulum for a missing identity before a propagation download, a delivery or a peer sync, as Python LXMF recalls them. - Store a signed message so its delivery can resume after a restart under the same id. A message that is already queued is no longer queued twice. - Generate deferred stamps in the order messages were sent, as Python LXMF does, so a reply no longer overtakes the message it answers. +- Keep a destination's identity in Reticulum once a message to it is delivered, as Python LXMF does. `lxmd` asks the shared instance when attached to one. ## 1.4.0 - 2026-10-12 diff --git a/api/migrations/1.4.md b/api/migrations/1.4.md index 20b2a47..69183dc 100644 --- a/api/migrations/1.4.md +++ b/api/migrations/1.4.md @@ -178,6 +178,14 @@ copy that was already delivered. stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as already sent. +## Retaining delivered destinations + +`LxmRouter::take_destination_retains()` returns the destinations whose messages +were delivered since the last call; the router keeps the newest 256. Send each +as `TransportQuery::RetainDestination` through Reticulum's control plane +(`ReticulumHandle::query_control`), which forwards to a shared instance, so the +destination's identity outlives its path, as in Python LXMF. + The API ledger retains its original compatibility floor and lists exact removed rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary field access through Deref; duplicate `message_api` snapshot paths describe the diff --git a/api/snapshots/lxmf-core.txt b/api/snapshots/lxmf-core.txt index 693c71d..81b39b1 100644 --- a/api/snapshots/lxmf-core.txt +++ b/api/snapshots/lxmf-core.txt @@ -2013,6 +2013,7 @@ pub fn lxmf_core::router::LxmRouter::stats(&self) -> lxmf_core::router::RouterSt pub fn lxmf_core::router::LxmRouter::submit_signed(&mut self, lxmf_core::message::SignedLxMessage) -> core::result::Result<(), lxmf_core::message::MessageError> pub fn lxmf_core::router::LxmRouter::sync_peer_policies_for_store(&self, u64) -> alloc::vec::Vec pub fn lxmf_core::router::LxmRouter::sync_peers(&mut self) -> alloc::vec::Vec<[u8; 16]> +pub fn lxmf_core::router::LxmRouter::take_destination_retains(&mut self) -> alloc::vec::Vec<[u8; 16]> pub fn lxmf_core::router::LxmRouter::throttle_peer(&mut self, [u8; 16]) pub fn lxmf_core::router::LxmRouter::tick(&mut self) pub fn lxmf_core::router::LxmRouter::tick_with_encryptor(&mut self, F) where F: core::ops::function::FnMut([u8; 16], &[u8]) -> core::result::Result, lxmf_core::message::MessageError> diff --git a/api/stability.json b/api/stability.json index 8c25303..345945e 100644 --- a/api/stability.json +++ b/api/stability.json @@ -24,8 +24,8 @@ "tier": "candidate-stable", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/lxmf-core.txt", - "itemCount": 2226, - "sha256": "67e48ebcad7cdc46b04dd04ec2f38e153bf55f119c6b0ccb914d442ccd67fcdc" + "itemCount": 2227, + "sha256": "30d1006f3149b0e812c3d772f226467887cbba036beb23d686ae79d3c50860ee" }, { "name": "lxmf-tools", diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index 3b13c19..87de33f 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -365,8 +365,13 @@ pub struct LxmRouter { inbound_resource_tracker: InboundResourceTracker, inbound_reservations: HashMap<[u8; 32], u64>, next_inbound_reservation: u64, + /// Destinations of delivered messages not yet taken by the embedder. + destination_retains: VecDeque<[u8; 16]>, } +/// 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, @@ -464,6 +469,7 @@ impl LxmRouter { inbound_resource_tracker: InboundResourceTracker::default(), inbound_reservations: HashMap::new(), next_inbound_reservation: 0, + destination_retains: VecDeque::new(), } } @@ -1030,9 +1036,27 @@ impl LxmRouter { self.ticket_store .mark_ticket_delivered(msg.destination_hash(), now_f64()); } + 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); + } msg.mark_delivered(); } + /// Destinations that received a delivered message since the last call. + /// + /// Python's router retains each one's announce data in Reticulum so its + /// identity outlives its path (LXMRouter.py:2761). Send each as + /// `TransportQuery::RetainDestination` through the control plane, which + /// forwards to a shared instance. At most the newest 256 are kept between + /// calls. + pub fn take_destination_retains(&mut self) -> Vec<[u8; 16]> { + self.destination_retains.drain(..).collect() + } + /// Mark a pending outbound message failed and remove it from the outbound /// queue. pub fn mark_outbound_failed(&mut self, message_hash: &[u8; 32]) -> bool { @@ -4858,4 +4882,52 @@ mod tests { .collect(); assert_eq!(stamped, submitted); } + + fn delivered_to(destination: [u8; 16], content: &str) -> LxMessage { + crate::message::test_message( + destination, + [0xB0; 16], + "retain", + content, + DeliveryMethod::Direct, + ) + } + + /// Python retains a destination's announce data once a message to it is + /// delivered (LXMRouter.py:2761). + #[test] + fn delivered_messages_ask_to_retain_their_destination() { + let mut router = LxmRouter::new(RouterConfig::default()); + let direct = delivered_to([0xD1; 16], "direct"); + let direct_id = direct.message_id(); + router.try_send(direct).unwrap(); + let failed = delivered_to([0xD3; 16], "failed"); + let failed_id = failed.message_id(); + router.try_send(failed).unwrap(); + + assert!(router.mark_outbound_delivered(&direct_id)); + router.complete_outbound_message(delivered_to([0xD2; 16], "opportunistic")); + router.complete_outbound_message(delivered_to([0xD1; 16], "again")); + assert!(router.mark_outbound_failed(&failed_id)); + + assert_eq!( + router.take_destination_retains(), + vec![[0xD1; 16], [0xD2; 16]] + ); + assert!(router.take_destination_retains().is_empty()); + } + + #[test] + fn untaken_retains_keep_only_the_newest_destinations() { + let mut router = LxmRouter::new(RouterConfig::default()); + for n in 0..300u16 { + let mut destination = [0; 16]; + destination[..2].copy_from_slice(&n.to_be_bytes()); + router.complete_outbound_message(delivered_to(destination, "bounded")); + } + let retains = router.take_destination_retains(); + assert_eq!(retains.len(), 256); + assert_eq!(retains[0][..2], 44u16.to_be_bytes()); + assert_eq!(retains[255][..2], 299u16.to_be_bytes()); + } } diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 6603d86..3767f8c 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -1619,6 +1619,9 @@ struct LxmdRunner { known_identities: HashMap, /// Identities asked of Transport's validated announce cache. identity_recalls: HashMap<[u8; 16], oneshot::Receiver>, + /// Reaches the shared instance when attached to one. + control_plane: Option, + retain_task: Option>, route_hops: HashMap<[u8; 16], u8>, /// Transport blackhole table snapshot, refreshed per tick. Used to drop /// inbound LXMs from blackholed identities (LXMRouter.py:1739-1741). @@ -1820,6 +1823,40 @@ impl LxmdRunner { } } + /// Retain delivered destinations in Reticulum, through the shared + /// instance when attached to one, as Python's router does + /// (LXMRouter.py:2761, Reticulum.py:1449-1461). + fn forward_destination_retains(&mut self) { + let Some(control_plane) = self.control_plane.clone() else { + return; + }; + if self + .retain_task + .as_ref() + .is_some_and(|task| !task.is_finished()) + { + return; + } + let retains = self.router.take_destination_retains(); + if retains.is_empty() { + return; + } + self.retain_task = Some(tokio::spawn(async move { + for dest in retains { + if control_plane + .query_control(TransportQuery::RetainDestination { dest }) + .await + .is_none() + { + tracing::debug!( + dest = %hex::encode(dest), + "Reticulum did not retain a delivered destination" + ); + } + } + })); + } + /// Record an announced identity key and ratchet, persisting only a /// changed ratchet (Python `Identity._remember_ratchet`), off the daemon /// loop. Identity keys stay on the periodic and shutdown saves. @@ -2508,6 +2545,8 @@ impl LxmdRunner { received_ratchets, known_identities, identity_recalls: HashMap::new(), + control_plane: None, + retain_task: None, route_hops: HashMap::new(), blackholed_identities: HashSet::new(), link_delivery: None, @@ -3585,6 +3624,7 @@ impl LxmdRunner { self.drain_destination_delivery_proofs(); self.retry_due_opportunistic_deliveries(now); + self.forward_destination_retains(); self.drain_control_commands(); self.drain_identity_recalls(); @@ -6043,6 +6083,7 @@ pub(crate) async fn main() { std::process::exit(1); } }; + runner.control_plane = Some(rns_handle.clone()); if let Err(error) = runner.install_announce_subscriptions(&rns_handle).await { if shutdown.is_triggered() { tracing::info!("Startup announce cancelled by shutdown"); @@ -6574,12 +6615,12 @@ pub(crate) async fn main() { mod tests { use super::*; - /// A transport that validated `announce` before any daemon subscribed. - async fn transport_that_heard( + /// Feed `announce` to `transport` as heard on a new interface `id`. + async fn hear( + transport: &mpsc::Sender, + id: u64, announce: &[u8], - ) -> (mpsc::Sender, mpsc::Receiver) { - let (actor, tx) = rns_transport::actor::TransportActor::new(); - tokio::spawn(actor.run()); + ) -> mpsc::Receiver { let (driver_tx, driver_rx) = mpsc::channel(64); let entry = rns_transport::messages::InterfaceEntry::new( "heard".into(), @@ -6590,41 +6631,140 @@ mod tests { driver_tx, ); let owner = entry.owner.clone(); - tx.send(TransportMessage::RegisterInterface { id: 1, entry }) + transport + .send(TransportMessage::RegisterInterface { id, entry }) .await .unwrap(); - tx.send(TransportMessage::InterfaceEvent { - interface_id: 1, - owner, - message: Box::new(TransportMessage::Inbound( - rns_transport::messages::InboundPacket { - raw: Bytes::copy_from_slice(announce), - interface_id: 1, - rssi: None, - snr: None, - q: None, - }, - )), - }) - .await - .unwrap(); + transport + .send(TransportMessage::InterfaceEvent { + interface_id: id, + owner, + message: Box::new(TransportMessage::Inbound( + rns_transport::messages::InboundPacket { + raw: Bytes::copy_from_slice(announce), + interface_id: id, + rssi: None, + snr: None, + q: None, + }, + )), + }) + .await + .unwrap(); + driver_rx + } + + /// A transport that validated `announce` before any daemon subscribed. + async fn transport_that_heard( + announce: &[u8], + ) -> (mpsc::Sender, mpsc::Receiver) { + let (actor, tx) = rns_transport::actor::TransportActor::new(); + tokio::spawn(actor.run()); + let driver_rx = hear(&tx, 1, announce).await; (tx, driver_rx) } - fn propagation_node_announce(node: &Identity) -> (Vec, String) { + fn lxmf_announce( + identity: &Identity, + aspect: &str, + app_data: Option<&[u8]>, + ) -> (Vec, String) { let mut destination = Destination::new( - Some(node), + Some(identity), rns_identity::destination::Direction::In, rns_identity::destination::DestType::Single, - "lxmf.propagation", + aspect, ) .unwrap(); let raw = destination - .announce_packet(node, None, None, false, None, now_f64()) + .announce_packet(identity, app_data, None, false, None, now_f64()) .unwrap(); (raw, hex::encode(destination.hash)) } + fn propagation_node_announce(node: &Identity) -> (Vec, String) { + lxmf_announce(node, "lxmf.propagation", None) + } + + /// A standalone Reticulum with no interfaces, whose control plane is its + /// own transport. + async fn standalone_reticulum(dir: &Path) -> (ReticulumHandle, ShutdownSignal) { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write( + dir.join("config"), + "[reticulum]\nshare_instance = No\nenable_transport = No\n\ + respond_to_probes = No\npanic_on_interface_error = No\n\ + discover_interfaces = No\n\n[interfaces]\n", + ) + .unwrap(); + let shutdown = ShutdownSignal::new(); + let handle = rns_runtime::reticulum::init( + Some(dir.to_str().unwrap()), + None, + shutdown.clone(), + Arc::new(std::sync::atomic::AtomicBool::new(true)), + ) + .await + .unwrap(); + (handle, shutdown) + } + + /// Python's router retains a destination's announce data once a message + /// to it is delivered (LXMRouter.py:2761), on the shared instance when + /// attached to one (Reticulum.py:1449-1461). + #[tokio::test] + async fn delivered_destinations_are_retained_through_the_control_plane() { + let temp = tempfile::tempdir().unwrap(); + let (reticulum, shutdown) = standalone_reticulum(&temp.path().join("rns")).await; + let recipient = Identity::new(); + let (announce, recipient_hex) = lxmf_announce(&recipient, DELIVERY_APP_NAME, None); + let _driver = hear(&reticulum.transport_tx, 9001, &announce).await; + let recipient_hash: [u8; 16] = hex::decode(&recipient_hex).unwrap().try_into().unwrap(); + let lxmf_dir = temp.path().join("lxmf"); + initialize_storage_namespace(&lxmf_dir).unwrap(); + let mut runner = LxmdRunner::new( + DaemonConfig::default(), + &lxmf_dir, + reticulum.transport_tx.clone(), + None, + ) + .unwrap(); + runner.control_plane = Some(reticulum.clone()); + let delivered = LxMessageDraft::new( + recipient_hash, + runner.lxmf_dest_hash, + "", + "delivered", + DeliveryMethod::Opportunistic, + ) + .unwrap() + .sign(&runner.identity.get_signing_key().unwrap()) + .unwrap() + .finalize(None) + .unwrap(); + runner.router.complete_outbound_message(delivered); + + let deadline = Instant::now() + Duration::from_secs(5); + loop { + runner.tick(); + tokio::time::sleep(Duration::from_millis(20)).await; + let retained = match reticulum + .query_transport(TransportQuery::GetRecentAnnounces) + .await + { + Some(TransportQueryResponse::Announces(announces)) => announces + .iter() + .any(|entry| entry.dest_hash == recipient_hash && entry.retained), + _ => false, + }; + if retained { + break; + } + assert!(Instant::now() < deadline, "the recipient is retained"); + } + shutdown.trigger(); + } + /// Python's LXMF recalls identities that Transport validated before the /// router registered its handlers (Transport.py:2172, Identity.recall). #[tokio::test]