From 5fe094c83ed9ef56af3a9e6de8f9cd18154a3509 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:12:29 -0600 Subject: [PATCH] propagation: transfer oversized requests as bounded Resources --- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 4 +- CHANGELOG.md | 8 +- Cargo.lock | 16 +- Cargo.toml | 16 +- api/fixtures/Cargo.lock | 12 +- api/snapshots/manifest-contract.json | 22 +- crates/lxmf-core/src/propagation_client.rs | 989 ++++++++++++++---- .../lxmf-core/src/propagation_client_tests.rs | 968 +++++++++++++++++ 9 files changed, 1791 insertions(+), 246 deletions(-) create mode 100644 crates/lxmf-core/src/propagation_client_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ba0a27..a456254 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ permissions: contents: read env: - RSLXMF_RSRETICULUM_COMMIT: 0f8731bb5b13e7f60e2d4bb38022480210009690 + RSLXMF_RSRETICULUM_COMMIT: 1ff0134979292fa8fc04c2e3db2bf483f31d7656 jobs: api-compat: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5fe823e..f4c683a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,8 +17,8 @@ env: RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }} PACKAGE_ROOT: rsLXMF LXMF_BINS: lxmd-rs - RSLXMF_RSRETICULUM_VERSION: 1.3.0 - RSLXMF_RSRETICULUM_COMMIT: 5edb8f22f5d8e6b2bd7392dc06e255ead96576fb + RSLXMF_RSRETICULUM_VERSION: 1.4.0 + RSLXMF_RSRETICULUM_COMMIT: 1ff0134979292fa8fc04c2e3db2bf483f31d7656 jobs: verify: diff --git a/CHANGELOG.md b/CHANGELOG.md index b37d880..d8027a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,11 @@ ### Fixed and improved +- Send oversized propagation `/get` and purge requests as request Resources, + with sequential bounded chunks for larger inboxes. Match responses and + Resource completion to the owning request, preserve partial downloads on + failure, and keep healthy transfers alive beyond the former whole-phase + timeout. Resource receipt alone is not successful purge completion. - Kept active attachment transfers alive while data is moving and reduced delays between delivery steps. - Corrected progress reporting for transfers split across multiple Resources by weighting each part by its payload size. - Fixed intermittent propagation-node sync and unpeer failures caused by incorrectly encoded peer addresses. @@ -17,7 +22,8 @@ - Raised the host source-build minimum to Rust 1.89 and qualified the corresponding protocol dependency update. -- Restricted rsReticulum compatibility to the 1.3 patch line so a later breaking minor release requires an explicit update. +- Migrated rsReticulum compatibility to the explicit `~1.4.0` line, including + nullable interface discovery and bounded RNode announce admission. - Updated the Python interoperability baseline to Reticulum 1.4.2 and LXMF 1.0.1, with separate LXMF 1.1.0 checks. diff --git a/Cargo.lock b/Cargo.lock index 8e54474..52b2fb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1052,7 +1052,7 @@ dependencies = [ [[package]] name = "rns-crypto" -version = "1.3.0" +version = "1.4.0" dependencies = [ "aes", "cbc", @@ -1070,7 +1070,7 @@ dependencies = [ [[package]] name = "rns-identity" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand 0.8.5", @@ -1088,7 +1088,7 @@ dependencies = [ [[package]] name = "rns-interface" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1117,7 +1117,7 @@ dependencies = [ [[package]] name = "rns-link" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand 0.8.5", @@ -1132,7 +1132,7 @@ dependencies = [ [[package]] name = "rns-protocol" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bzip2", "hex", @@ -1148,7 +1148,7 @@ dependencies = [ [[package]] name = "rns-runtime" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1175,7 +1175,7 @@ dependencies = [ [[package]] name = "rns-transport" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -1194,7 +1194,7 @@ dependencies = [ [[package]] name = "rns-wire" -version = "1.3.0" +version = "1.4.0" dependencies = [ "rns-crypto", "sha2", diff --git a/Cargo.toml b/Cargo.toml index e8cbfdb..2e12181 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,14 +13,14 @@ rust-version = "1.89" [workspace.dependencies] # Reticulum crates from a sibling rsReticulum checkout during development. -rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" } -rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" } -rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" } -rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" } -rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" } -rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" } -rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" } -rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" } +rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.4.0" } +rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.4.0" } +rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.4.0" } +rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.4.0" } +rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.4.0" } +rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.4.0" } +rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.4.0" } +rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.4.0" } # Workspace LXMF crates lxmf-core = { path = "crates/lxmf-core", version = "1.2.0" } diff --git a/api/fixtures/Cargo.lock b/api/fixtures/Cargo.lock index 6d6ceac..c9b351d 100644 --- a/api/fixtures/Cargo.lock +++ b/api/fixtures/Cargo.lock @@ -478,7 +478,7 @@ dependencies = [ [[package]] name = "rns-crypto" -version = "1.3.0" +version = "1.4.0" dependencies = [ "aes", "cbc", @@ -496,7 +496,7 @@ dependencies = [ [[package]] name = "rns-identity" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand", @@ -514,7 +514,7 @@ dependencies = [ [[package]] name = "rns-link" -version = "1.3.0" +version = "1.4.0" dependencies = [ "hex", "rand", @@ -529,7 +529,7 @@ dependencies = [ [[package]] name = "rns-protocol" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bzip2", "hex", @@ -545,7 +545,7 @@ dependencies = [ [[package]] name = "rns-transport" -version = "1.3.0" +version = "1.4.0" dependencies = [ "bytes", "hex", @@ -564,7 +564,7 @@ dependencies = [ [[package]] name = "rns-wire" -version = "1.3.0" +version = "1.4.0" dependencies = [ "rns-crypto", "sha2", diff --git a/api/snapshots/manifest-contract.json b/api/snapshots/manifest-contract.json index 9e138be..181fb8d 100644 --- a/api/snapshots/manifest-contract.json +++ b/api/snapshots/manifest-contract.json @@ -103,7 +103,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -114,7 +114,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -125,7 +125,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -136,7 +136,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -147,7 +147,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -158,7 +158,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -328,7 +328,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -339,7 +339,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -350,7 +350,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [ @@ -363,7 +363,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], @@ -374,7 +374,7 @@ "rename": null, "kind": null, "target": null, - "requirement": "~1.3.0", + "requirement": "~1.4.0", "optional": false, "defaultFeatures": true, "features": [], diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index 9eb89e7..ca1d7a4 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -7,10 +7,10 @@ //! 2. Identify on the link (LinkIdentify). //! 3. Request `/get` with `[None, None]` -- server returns available transient IDs. //! 4. Client sorts into wants/haves. -//! 5. Request `/get` with `[wants, haves, delivery_limit]`. +//! 5. Purge known haves, then request bounded wants chunks with a per-transfer limit. //! 6. Server returns `[lxmf_data_1, lxmf_data_2, ...]`. //! 7. Client processes received messages. -//! 8. Final `/get` with `[None, received_ids]` purges them from the server. +//! 8. `/get` with `[None, received_ids]` purges each downloaded batch before the next chunk. use std::collections::{HashMap, HashSet, VecDeque}; use std::time::{Duration, Instant}; @@ -19,8 +19,8 @@ use bytes::Bytes; use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use rns_link::link::{CloseReason, Link, LinkAction}; use rns_protocol::resource::{ - InboundTransfer, MAX_SEGMENTS, MultiSegmentInbound, RANDOM_HASH_SIZE, ResourceError, - TransferAction, + InboundTransfer, MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, MultiSegmentInbound, + OutboundTransfer, RANDOM_HASH_SIZE, ResourceError, TransferAction, }; use rns_protocol::resource_adv::ResourceAdvertisement; use rns_transport::link_messages::DestinationEvent; @@ -78,6 +78,55 @@ struct SegmentRoute { segment_index: usize, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RequestKind { + List, + Haves(usize), + Get(usize), + Purge(usize), +} + +impl RequestKind { + fn state(self) -> PropagationClientState { + match self { + Self::List => PropagationClientState::ListRequested, + Self::Get(_) => PropagationClientState::GetRequested, + Self::Haves(_) | Self::Purge(_) => PropagationClientState::PurgeRequested, + } + } +} + +struct ResponseResource { + logical_hash: [u8; 32], + total_segments: usize, + next_segment: usize, + data_size: usize, + assembled_bytes: usize, + waiting_since: Instant, + current_segment: Option<[u8; 32]>, +} + +/// Exactly one logical request owns the phase, independently of Link's receipt +/// reaper. Resource watchdogs own transfer time; only response waiting uses the +/// request deadline. Generation matching also scopes deferred endpoint results. +struct PendingRequest { + link_id: [u8; 16], + generation: u64, + id: [u8; 16], + kind: RequestKind, + sender_active: bool, + outbound: Option, + response: Option, + waiting_since: Option, + timeout: Duration, +} + +#[derive(Clone, Copy)] +struct EndpointRequestOwner { + generation: u64, + sender: bool, +} + struct PendingEndpointBind { interface_id: InterfaceId, rtt_request: OutboundRequest, @@ -86,6 +135,7 @@ struct PendingEndpointBind { enum EndpointSendSuccess { None, + RequestPacket, ResourceProof { assembled: Vec, route: Option, @@ -97,6 +147,8 @@ struct PendingEndpointSend { link_id: [u8; 16], final_send: bool, success: EndpointSendSuccess, + owner: Option, + queued_at: Instant, result_rx: oneshot::Receiver, } @@ -132,6 +184,12 @@ pub struct PropagationClient { received_messages: Vec>, /// IDs of messages successfully received (drives the Phase 3 purge). received_ids: Vec>, + pending_haves: VecDeque>, + pending_wants: VecDeque>, + request: Option, + next_request_generation: u64, + unread_bytes: usize, + unread_limit: usize, inbound_resources: HashMap<[u8; 32], InboundTransfer>, inbound_split_resources: HashMap<[u8; 32], MultiSegmentInbound>, segment_routing: HashMap<[u8; 32], SegmentRoute>, @@ -177,6 +235,12 @@ impl PropagationClient { local_messages: HashSet::new(), received_messages: Vec::new(), received_ids: Vec::new(), + pending_haves: VecDeque::new(), + pending_wants: VecDeque::new(), + request: None, + next_request_generation: 0, + unread_bytes: 0, + unread_limit: MAX_RESOURCE_SIZE, inbound_resources: HashMap::new(), inbound_split_resources: HashMap::new(), segment_routing: HashMap::new(), @@ -223,6 +287,7 @@ impl PropagationClient { } pub fn take_received_messages(&mut self) -> Vec> { + self.unread_bytes = 0; std::mem::take(&mut self.received_messages) } @@ -254,7 +319,12 @@ impl PropagationClient { /// Start a propagation download, limiting newly requested messages. /// `None` and zero mirror Python's `PR_ALL_MESSAGES`. + /// Drain previously received messages before restarting, including after a + /// failed purge or cancellation. A refused start never discards results. pub fn start_download_with_limit(&mut self, max_messages: Option) -> bool { + if !self.received_messages.is_empty() { + return false; + } let node_hash = match self.outbound_propagation_node { Some(h) => h, None => return false, @@ -332,6 +402,9 @@ impl PropagationClient { self.available_messages.clear(); self.received_messages.clear(); self.received_ids.clear(); + self.pending_haves.clear(); + self.pending_wants.clear(); + self.unread_bytes = 0; self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); @@ -382,7 +455,15 @@ impl PropagationClient { } fn queue_link_endpoint(&mut self, request: OutboundRequest) -> bool { - self.queue_link_endpoint_with_success(request, EndpointSendSuccess::None) + let success = if self.request.is_some() + && rns_wire::header::PacketHeader::unpack(&request.raw).is_ok_and(|(header, _)| { + header.context == rns_wire::context::PacketContext::Request + }) { + EndpointSendSuccess::RequestPacket + } else { + EndpointSendSuccess::None + }; + self.queue_link_endpoint_with_success(request, success) } fn queue_link_endpoint_with_success( @@ -393,6 +474,27 @@ impl PropagationClient { let Some(link_id) = self.link_id else { return false; }; + let owner = self.request.as_ref().and_then(|pending| { + let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).ok()?; + use rns_wire::context::PacketContext; + if matches!( + header.context, + PacketContext::Keepalive | PacketContext::LinkClose + ) { + return None; + } + Some(EndpointRequestOwner { + generation: pending.generation, + sender: matches!( + header.context, + PacketContext::Request + | PacketContext::ResourceAdv + | PacketContext::Resource + | PacketContext::ResourceHmu + | PacketContext::ResourceIcl + ), + }) + }); let (result_tx, result_rx) = oneshot::channel(); if !self.queue_transport(TransportMessage::SendLinkEndpoint { link_id, @@ -406,6 +508,8 @@ impl PropagationClient { link_id, final_send: false, success, + owner, + queued_at: Instant::now(), result_rx, }); true @@ -428,6 +532,8 @@ impl PropagationClient { link_id, final_send: true, success: EndpointSendSuccess::None, + owner: None, + queued_at: Instant::now(), result_rx, }); true @@ -449,13 +555,23 @@ impl PropagationClient { let mut still_pending = Vec::new(); let mut endpoint_sends = std::mem::take(&mut self.pending_endpoint_sends); for mut pending in endpoint_sends.drain(..) { + let current = self.link_id == Some(pending.link_id) + && pending.owner.is_none_or(|owner| { + self.request.as_ref().is_some_and(|request| { + request.generation == owner.generation + && (!owner.sender || request.sender_active) + }) + }); match pending.result_rx.try_recv() { Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => { - if self.link_id == Some(pending.link_id) - && self.status.state != PropagationClientState::Failed - { + if current && self.status.state != PropagationClientState::Failed { match pending.success { EndpointSendSuccess::None => {} + EndpointSendSuccess::RequestPacket => { + if let Some(request) = self.request.as_mut() { + request.waiting_since.get_or_insert_with(Instant::now); + } + } EndpointSendSuccess::ResourceProof { assembled, route, @@ -471,7 +587,7 @@ impl PropagationClient { final_send = pending.final_send, "propagation client Link endpoint send rejected" ); - if self.link_id == Some(pending.link_id) { + if current { self.status.state = PropagationClientState::Failed; } if pending.final_send { @@ -479,11 +595,17 @@ impl PropagationClient { } } Err(oneshot::error::TryRecvError::Closed) => { - if self.link_id == Some(pending.link_id) { + if current { self.status.state = PropagationClientState::Failed; } } - Err(oneshot::error::TryRecvError::Empty) => still_pending.push(pending), + Err(oneshot::error::TryRecvError::Empty) => { + if current && pending.queued_at.elapsed() >= Duration::from_secs(120) { + self.status.state = PropagationClientState::Failed; + } else if current || pending.final_send { + still_pending.push(pending); + } + } } } still_pending.append(&mut self.pending_endpoint_sends); @@ -564,6 +686,9 @@ impl PropagationClient { } for event in events { + if self.status.state == PropagationClientState::Failed { + break; + } match event { DestinationEvent::LinkClosed { link_id } => { self.handle_link_closed(link_id, None); @@ -638,12 +763,18 @@ impl PropagationClient { } } rns_wire::context::PacketContext::Response => { - if let Some(ref mut link) = self.link - && let Ok((_request_id, response_data)) = link.handle_response(data) + if let Some(plaintext) = + self.link.as_ref().and_then(|link| link.decrypt(data).ok()) { - self.handle_response_data(&response_data); + self.handle_response_plaintext(&plaintext); } } + rns_wire::context::PacketContext::ResourceReq => { + self.handle_outbound_request(data) + } + rns_wire::context::PacketContext::ResourcePrf => { + self.handle_outbound_proof(data) + } rns_wire::context::PacketContext::ResourceAdv => { self.handle_resource_advertisement(data); } @@ -655,7 +786,7 @@ impl PropagationClient { } rns_wire::context::PacketContext::ResourceIcl | rns_wire::context::PacketContext::ResourceRcl => { - self.handle_resource_cancel(data); + self.handle_resource_cancel(data, header.context); } rns_wire::context::PacketContext::LinkClose => { self.handle_link_closed(header.destination_hash, Some(data)); @@ -752,9 +883,10 @@ impl PropagationClient { } fn handle_response_data(&mut self, response_data: &[u8]) { - let response_phase = if self.status.state == PropagationClientState::Receiving { + let response_phase = if let Some(request) = self.request.as_ref() { + request.kind.state() + } else if self.status.state == PropagationClientState::Receiving { let Some(phase) = self.receiving_for.take() else { - self.status.state = PropagationClientState::Failed; return; }; phase @@ -770,7 +902,7 @@ impl PropagationClient { self.handle_get_response(response_data); } PropagationClientState::PurgeRequested => { - self.handle_purge_response(); + self.handle_purge_response(response_data); } _ => {} } @@ -781,15 +913,57 @@ impl PropagationClient { return; }; let Ok(plaintext) = link.decrypt(data) else { - self.status.state = PropagationClientState::Failed; return; }; let Ok(adv) = ResourceAdvertisement::unpack(&plaintext) else { - self.status.state = PropagationClientState::Failed; return; }; - if !adv.flags.is_response { + let Some(request) = self.request.as_ref() else { + return; + }; + if !adv.flags.is_response || adv.request_id.as_deref() != Some(request.id.as_slice()) { + return; + } + + if adv.flags.is_request + || !adv.flags.encrypted + || adv.flags.has_metadata + || adv.data_size > MAX_RESOURCE_SIZE + || adv.total_segments == 0 + || adv.total_segments > MAX_SEGMENTS + || adv.segment_index == 0 + || adv.segment_index > adv.total_segments + || (adv.total_segments > 1 && !adv.flags.split) + || adv.random_hash.len() != RANDOM_HASH_SIZE + { + self.status.state = PropagationClientState::Failed; + return; + } + let logical_hash = if adv.flags.split { + adv.original_hash + } else { + adv.resource_hash + }; + if let Some(response) = request.response.as_ref() { + if response.logical_hash != logical_hash + || response.total_segments != adv.total_segments + || response.data_size != adv.data_size + { + self.status.state = PropagationClientState::Failed; + return; + } + if adv.segment_index < response.next_segment + || response.current_segment == Some(adv.resource_hash) + { + return; + } + if adv.segment_index != response.next_segment || response.current_segment.is_some() { + self.status.state = PropagationClientState::Failed; + return; + } + } else if adv.segment_index != 1 { + self.status.state = PropagationClientState::Failed; return; } @@ -860,6 +1034,24 @@ impl PropagationClient { return; }; + self.retire_request_sender(); + let request = self + .request + .as_mut() + .expect("response matched request above"); + request.waiting_since = None; + let response = request.response.get_or_insert_with(|| ResponseResource { + logical_hash, + total_segments: adv.total_segments, + next_segment: 1, + data_size: adv.data_size, + assembled_bytes: 0, + waiting_since: Instant::now(), + current_segment: None, + }); + response.current_segment = Some(adv.resource_hash); + response.waiting_since = Instant::now(); + if let TransferAction::SendRequest(req_data) = transfer.request_next() { self.send_encrypted_resource_control( rns_wire::context::PacketContext::ResourceReq, @@ -980,18 +1172,34 @@ impl PropagationClient { } } - fn handle_resource_cancel(&mut self, data: &[u8]) { + fn handle_resource_cancel(&mut self, data: &[u8], context: rns_wire::context::PacketContext) { let Some(link) = self.link.as_ref() else { return; }; let Ok(plaintext) = link.decrypt(data) else { return; }; - if plaintext.len() < 32 { + if plaintext.len() != 32 { return; } let mut resource_hash = [0u8; 32]; resource_hash.copy_from_slice(&plaintext[..32]); + let matches = self.request.as_ref().is_some_and(|request| { + if context == rns_wire::context::PacketContext::ResourceRcl { + request + .outbound + .as_ref() + .is_some_and(|transfer| transfer.resource.resource_hash == resource_hash) + } else { + request + .response + .as_ref() + .is_some_and(|response| response.current_segment == Some(resource_hash)) + } + }); + if !matches { + return; + } self.inbound_resources.remove(&resource_hash); if let Some(route) = self.segment_routing.remove(&resource_hash) { self.inbound_split_resources.remove(&route.original_hash); @@ -1035,6 +1243,15 @@ impl PropagationClient { .get(&resource_hash) .and_then(|transfer| transfer.resource.metadata.clone()); self.inbound_resources.remove(&resource_hash); + // Transfer duration does not consume the transport-result/intersegment + // wait. In particular, a healthy slow segment can exceed this timeout. + if let Some(response) = self + .request + .as_mut() + .and_then(|request| request.response.as_mut()) + { + response.waiting_since = Instant::now(); + } let Some(pending) = self.pending_endpoint_sends.last_mut() else { self.status.state = PropagationClientState::Failed; @@ -1053,6 +1270,29 @@ impl PropagationClient { route: Option, metadata: Option>, ) { + let Some(response) = self + .request + .as_mut() + .and_then(|request| request.response.as_mut()) + else { + return; + }; + let Some(total) = response + .assembled_bytes + .checked_add(assembled.len()) + .filter(|total| *total <= MAX_RESOURCE_SIZE && *total <= response.data_size) + else { + self.status.state = PropagationClientState::Failed; + return; + }; + response.assembled_bytes = total; + response.current_segment = None; + response.next_segment += 1; + response.waiting_since = Instant::now(); + if response.next_segment > response.total_segments && total != response.data_size { + self.status.state = PropagationClientState::Failed; + return; + } if let Some(route) = route { let mut complete_payload = None; if let Some(coord) = self.inbound_split_resources.get_mut(&route.original_hash) { @@ -1086,19 +1326,18 @@ impl PropagationClient { } fn handle_resource_response_payload(&mut self, payload: &[u8]) { - let response_data = { - let Some(link) = self.link.as_mut() else { - return; - }; - match link.handle_response_plaintext(payload) { - Ok((_request_id, response_data)) => response_data, - Err(_) => { - self.status.state = PropagationClientState::Failed; - return; - } - } - }; - self.handle_response_data(&response_data); + if !Link::parse_response_plaintext(payload) + .ok() + .is_some_and(|(id, _)| { + self.request + .as_ref() + .is_some_and(|request| request.id == id) + }) + { + self.status.state = PropagationClientState::Failed; + return; + } + self.handle_response_plaintext(payload); } fn send_encrypted_resource_control( @@ -1132,6 +1371,27 @@ impl PropagationClient { let Some(link_id) = self.link_id else { return false; }; + let raw = Self::link_packet_bytes(link_id, context, packet_type, payload); + if !self.queue_link_endpoint(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + }) { + self.status.state = PropagationClientState::Failed; + false + } else if let Some(link) = self.link.as_mut() { + link.record_tx(payload.len()); + true + } else { + false + } + } + + fn link_packet_bytes( + link_id: [u8; 16], + context: rns_wire::context::PacketContext, + packet_type: rns_wire::flags::PacketType, + payload: &[u8], + ) -> Vec { let header = rns_wire::header::PacketHeader { flags: rns_wire::flags::PacketFlags { header_type: rns_wire::flags::HeaderType::Header1, @@ -1147,18 +1407,7 @@ impl PropagationClient { }; let mut raw = header.pack(); raw.extend_from_slice(payload); - if !self.queue_link_endpoint(OutboundRequest { - raw: Bytes::from(raw), - destination_hash: link_id, - }) { - self.status.state = PropagationClientState::Failed; - false - } else if let Some(link) = self.link.as_mut() { - link.record_tx(payload.len()); - true - } else { - false - } + raw } fn send_final_link_packet( @@ -1193,7 +1442,7 @@ impl PropagationClient { /// Phase 1: parse available transient IDs from the server. fn handle_list_response(&mut self, response_data: &[u8]) { - let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) { + let value: rmpv::Value = match Self::decode_response_value(response_data) { Ok(v) => v, Err(_) => { self.status.state = PropagationClientState::Failed; @@ -1202,6 +1451,7 @@ impl PropagationClient { }; if let Some(arr) = value.as_array() { + self.finish_request(response_data); self.available_messages.clear(); for item in arr { if let Some(id_bytes) = item.as_slice() @@ -1223,43 +1473,88 @@ impl PropagationClient { } } - /// Phase 2: parse received message data. + /// Validate and reserve the complete batch before publishing any result or + /// purge ID. A node may return a subset (or nothing) for a requested chunk. fn handle_get_response(&mut self, response_data: &[u8]) { - let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) { - Ok(v) => v, - Err(_) => { + let Ok(rmpv::Value::Array(items)) = Self::decode_response_value(response_data) else { + self.status.state = PropagationClientState::Failed; + return; + }; + let count = match self.request.as_ref().map(|request| request.kind) { + Some(RequestKind::Get(count)) => count, + _ => 0, + }; + if count > 0 && items.len() > count { + self.status.state = PropagationClientState::Failed; + return; + } + let mut batch_bytes = 0usize; + for item in &items { + let rmpv::Value::Binary(data) = item else { self.status.state = PropagationClientState::Failed; return; - } - }; - - if let Some(arr) = value.as_array() { - let mut received = 0usize; - for item in arr { - if let Some(msg_data) = item.as_slice() { - let tid = rns_crypto::sha::full_hash(msg_data); - self.received_ids.push(tid.to_vec()); - self.received_messages.push(msg_data.to_vec()); - received += 1; - } - } - self.status.progress = 1.0; - self.status.result = Some(received); - - if !self.received_ids.is_empty() { - self.send_purge_request(); - } else { - self.status.state = PropagationClientState::Complete; - } - } else { - self.status.state = PropagationClientState::Failed; + }; + let Some(bytes) = batch_bytes.checked_add(data.len()) else { + self.status.state = PropagationClientState::Failed; + return; + }; + batch_bytes = bytes; } + let Some(unread_bytes) = self + .unread_bytes + .checked_add(batch_bytes) + .filter(|bytes| *bytes <= self.unread_limit) + else { + tracing::warn!( + reason = "result_capacity", + "propagation downloaded batch exceeds unread result capacity" + ); + self.status.state = PropagationClientState::Failed; + return; + }; + self.unread_bytes = unread_bytes; + self.finish_request(response_data); + self.pending_wants.drain(..count); + self.status.result = Some(self.status.result.unwrap_or(0).saturating_add(items.len())); + for item in items { + let rmpv::Value::Binary(data) = item else { + unreachable!("batch validated above") + }; + self.received_ids + .push(rns_crypto::sha::full_hash(&data).to_vec()); + self.received_messages.push(data); + } + self.status.progress = 1.0; + self.send_next_chunk(); } - /// Phase 3: mark the download complete. - fn handle_purge_response(&mut self) { - self.status.state = PropagationClientState::Complete; - self.status.progress = 1.0; + fn decode_response_value(data: &[u8]) -> Result { + let mut remaining = data; + let value = rmpv::decode::read_value(&mut remaining).map_err(|_| ())?; + if !remaining.is_empty() { + return Err(()); + } + Ok(value) + } + + /// A successful purge is the empty array returned by Rust and Python + /// nodes. In particular a peer error code or nil must not advance a cursor. + fn handle_purge_response(&mut self, response_data: &[u8]) { + if !matches!(Self::decode_response_value(response_data), Ok(rmpv::Value::Array(items)) if items.is_empty()) + { + self.status.state = PropagationClientState::Failed; + return; + } + match self.finish_request(response_data) { + Some(RequestKind::Haves(count)) => { + self.pending_haves.drain(..count); + } + Some(RequestKind::Purge(count)) => { + self.received_ids.drain(..count); + } + _ => {} + } + self.send_next_chunk(); } pub fn tick(&mut self) { @@ -1272,19 +1567,27 @@ impl PropagationClient { if let Some(started) = self.started_at && started.elapsed() > self.timeout - && matches!( - self.status.state, - PropagationClientState::LinkEstablishing - | PropagationClientState::ListRequested - | PropagationClientState::GetRequested - | PropagationClientState::PurgeRequested - ) + && self.status.state == PropagationClientState::LinkEstablishing { self.cleanup(); self.status.state = PropagationClientState::Failed; return; } + if self.request.as_ref().is_some_and(|request| { + request + .waiting_since + .is_some_and(|started| started.elapsed() > request.timeout) + || request.response.as_ref().is_some_and(|response| { + self.inbound_resources.is_empty() + && response.waiting_since.elapsed() > request.timeout + }) + }) { + self.status.state = PropagationClientState::Failed; + self.cleanup(); + return; + } + let link_action = self.link.as_mut().map(Link::tick); match link_action { Some(LinkAction::SendKeepalive) | Some(LinkAction::TransitionedToStale) => { @@ -1306,6 +1609,10 @@ impl PropagationClient { Some(LinkAction::None) | None => {} } + if self.status.state != PropagationClientState::Failed { + self.drive_outbound_request(); + } + if self.status.state == PropagationClientState::Receiving { let mut retry_requests = Vec::new(); for transfer in self.inbound_resources.values_mut() { @@ -1390,151 +1697,375 @@ impl PropagationClient { /// Phase 1: `/get` with `[None, None]`. fn send_list_request(&mut self) { - use rmpv::Value; - - self.receiving_for = None; - let request_data = { - let array = Value::Array(vec![Value::Nil, Value::Nil]); - crate::encode_value(&array) - }; - - if self.send_get_path_request(&request_data) { - self.status.state = PropagationClientState::ListRequested; - self.started_at = Some(Instant::now()); - } else { - self.status.state = PropagationClientState::Failed; - } + let data = crate::encode_value(&rmpv::Value::Array(vec![rmpv::Value::Nil; 2])); + self.send_get_path_request(&data, RequestKind::List); } - /// Phase 2: `/get` with `[wants, haves, delivery_limit]`. + /// Snapshot selection once per cycle. Haves are purged before any wants; + /// the configured message count limits the entire cycle, not each chunk. fn send_get_request(&mut self) { + self.pending_haves.clear(); + self.pending_wants.clear(); + let mut seen = HashSet::new(); + for id in &self.available_messages { + if !seen.insert(id.clone()) { + continue; + } + if self.local_messages.contains(id) { + if !self.retain_synced_on_node { + self.pending_haves.push_back(id.clone()); + } + } else if self.pending_wants.len() < self.max_messages.unwrap_or(usize::MAX) { + self.pending_wants.push_back(id.clone()); + } + } + self.status.result = Some(0); + self.send_next_chunk(); + } + + fn chunk_body(&self, ids: &[Vec], get: bool) -> Vec { use rmpv::Value; + let ids = Value::Array(ids.iter().cloned().map(Value::Binary).collect()); + let mut fields = if get { + vec![ids, Value::Array(Vec::new())] + } else { + vec![Value::Nil, ids] + }; + if get && let Some(limit) = self.delivery_limit { + fields.push(Value::F64(limit)); + } + crate::encode_value(&Value::Array(fields)) + } - self.status.progress = 0.0; - self.status.data_size = None; - self.status.result = None; - self.receiving_for = None; - - let wants: Vec = self - .available_messages - .iter() - .filter(|id| !self.local_messages.contains(*id)) - .take(self.max_messages.unwrap_or(usize::MAX)) - .map(|id| Value::Binary(id.clone())) - .collect(); - - // haves are messages we already hold; sending them lets the server purge. - let haves: Vec = self - .available_messages - .iter() - .filter(|id| !self.retain_synced_on_node && self.local_messages.contains(*id)) - .map(|id| Value::Binary(id.clone())) - .collect(); - - if wants.is_empty() { - if haves.is_empty() { - self.status.state = PropagationClientState::Complete; - self.status.progress = 1.0; - self.status.result = Some(0); - return; - } - let array = Value::Array(vec![Value::Nil, Value::Array(haves)]); - let buf = crate::encode_value(&array); - if self.send_get_path_request(&buf) { - self.status.state = PropagationClientState::PurgeRequested; - self.started_at = Some(Instant::now()); + /// Fit the complete canonical request, not an assumed ID count. The + /// timestamp/path portion is encoded with the same Value types as Link's + /// prepare_request; its timestamp value does not change its wire length. + fn bounded_chunk(&self, ids: &[Vec], get: bool) -> (usize, Vec) { + use rmpv::Value; + let overhead = crate::encode_value(&Value::Array(vec![ + Value::F64(0.0), + Value::Binary(vec![0; 16]), + Value::Nil, + ])) + .len() + - 1; + let mut low = 0; + // Every valid transient ID consumes at least its 32 payload bytes. + let mut high = ids.len().min(MAX_EFFICIENT_SIZE / 32); + while low < high { + let count = low + (high - low).div_ceil(2); + if self.chunk_body(&ids[..count], get).len() <= MAX_EFFICIENT_SIZE - overhead { + low = count; } else { - self.status.state = PropagationClientState::Failed; + high = count - 1; } + } + (low, self.chunk_body(&ids[..low], get)) + } + + fn send_next_chunk(&mut self) { + if self.request.is_some() || self.status.state == PropagationClientState::Failed { return; } - - let mut elements = vec![Value::Array(wants), Value::Array(haves)]; - if let Some(limit) = self.delivery_limit { - elements.push(Value::F64(limit)); - } - - let array = Value::Array(elements); - let buf = crate::encode_value(&array); - - if self.send_get_path_request(&buf) { - self.status.state = PropagationClientState::GetRequested; - self.started_at = Some(Instant::now()); + if !self.received_ids.is_empty() { + self.send_purge_request(); + } else if !self.pending_haves.is_empty() { + let ids: Vec<_> = self + .pending_haves + .iter() + .take(MAX_EFFICIENT_SIZE / 32) + .cloned() + .collect(); + let (count, data) = self.bounded_chunk(&ids, false); + self.send_get_path_request(&data, RequestKind::Haves(count)); + } else if !self.pending_wants.is_empty() { + let ids: Vec<_> = self + .pending_wants + .iter() + .take(MAX_EFFICIENT_SIZE / 32) + .cloned() + .collect(); + let (count, data) = self.bounded_chunk(&ids, true); + self.status.progress = 0.0; + self.status.data_size = None; + self.send_get_path_request(&data, RequestKind::Get(count)); } else { - self.status.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Complete; + self.status.progress = 1.0; + self.status.result.get_or_insert(0); } } - /// Phase 3: `/get` with `[None, received_ids]`. fn send_purge_request(&mut self) { - use rmpv::Value; - - self.receiving_for = None; - let received: Vec = self - .received_ids - .iter() - .map(|id| Value::Binary(id.clone())) - .collect(); - - let array = Value::Array(vec![Value::Nil, Value::Array(received)]); - let buf = crate::encode_value(&array); - - if self.send_get_path_request(&buf) { - self.status.state = PropagationClientState::PurgeRequested; - self.started_at = Some(Instant::now()); - } else { - self.status.state = PropagationClientState::Failed; - } + let (count, data) = self.bounded_chunk(&self.received_ids, false); + self.send_get_path_request(&data, RequestKind::Purge(count)); } - /// Send a msgpack request to the `MESSAGE_GET_PATH` endpoint; returns `true` - /// if the request was dispatched successfully. - fn send_get_path_request(&mut self, request_data: &[u8]) -> bool { - let outbound = if let Some(ref mut link) = self.link { - match link.request( - MESSAGE_GET_PATH, - Some(request_data), - Duration::from_secs(60), - ) { - Ok((encrypted, _request_id)) => { - if let Some(link_id) = self.link_id { - let req_header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Data, - }, - hops: 0, - transport_id: None, - destination_hash: link_id, - context: rns_wire::context::PacketContext::Request, - }; - let mut req_raw = req_header.pack(); - req_raw.extend_from_slice(&encrypted); - let packet_request_id = rns_wire::hash::truncated_packet_hash( - &req_raw, - rns_wire::flags::HeaderType::Header1, - ); - link.update_pending_request_id(&_request_id, packet_request_id); - Some(OutboundRequest { - raw: Bytes::from(req_raw), - destination_hash: link_id, - }) - } else { - None - } + fn send_get_path_request(&mut self, request_data: &[u8], kind: RequestKind) -> bool { + if self.request.is_some() { + self.status.state = PropagationClientState::Failed; + return false; + } + let Some(link) = self.link.as_mut() else { + self.status.state = PropagationClientState::Failed; + return false; + }; + let timeout = link.default_request_timeout().max(Duration::from_secs(60)); + let Ok((packed, id)) = link.prepare_request(MESSAGE_GET_PATH, Some(request_data), timeout) + else { + self.status.state = PropagationClientState::Failed; + return false; + }; + if packed.len() > MAX_EFFICIENT_SIZE { + link.fail_pending_request(&id); + self.status.state = PropagationClientState::Failed; + return false; + } + let Some(generation) = self.next_request_generation.checked_add(1) else { + link.fail_pending_request(&id); + self.status.state = PropagationClientState::Failed; + return false; + }; + self.next_request_generation = generation; + let resource = packed.len() > link.mdu; + let mut packed = Some(packed); + let outbound = if resource { + let Some(keys) = link.session_keys() else { + link.fail_pending_request(&id); + self.status.state = PropagationClientState::Failed; + return false; + }; + let Ok(mut transfer) = OutboundTransfer::new_encrypted( + packed.take().unwrap(), + true, + link.rtt.unwrap_or(Duration::from_millis(500)), + keys, + ) else { + link.fail_pending_request(&id); + self.status.state = PropagationClientState::Failed; + return false; + }; + transfer.resource.flags.is_request = true; + transfer.resource.request_id = Some(id.to_vec()); + link.mark_request_resource_sending(&id); + link.track_outgoing_resource(transfer.resource.resource_hash); + Some(transfer) + } else { + None + }; + // Packet encryption is deliberately separate from prepare_request so + // the size decision precedes ciphertext construction and MTU admission. + let packet = if !resource { + let body = packed.take().unwrap(); + match link.encrypt(&body) { + Ok(data) => Some(data), + Err(_) => { + link.fail_pending_request(&id); + self.status.state = PropagationClientState::Failed; + return false; } - Err(_) => None, } } else { None }; - outbound.is_some_and(|request| self.queue_link_endpoint(request)) + self.request = Some(PendingRequest { + link_id: link.link_id, + generation, + id, + kind, + sender_active: true, + outbound, + response: None, + waiting_since: None, + timeout, + }); + self.receiving_for = None; + self.status.state = kind.state(); + if let Some(packet) = packet { + // Hash the exact header/ciphertext that send_link_packet emits. + let raw = Self::link_packet_bytes( + link.link_id, + rns_wire::context::PacketContext::Request, + rns_wire::flags::PacketType::Data, + &packet, + ); + let packet_id = + rns_wire::hash::truncated_packet_hash(&raw, rns_wire::flags::HeaderType::Header1); + link.update_pending_request_id(&id, packet_id); + self.request.as_mut().unwrap().id = packet_id; + self.send_link_packet( + rns_wire::context::PacketContext::Request, + rns_wire::flags::PacketType::Data, + &packet, + ); + } else { + self.drive_outbound_request(); + } + self.status.state != PropagationClientState::Failed + } + + fn drive_outbound_request(&mut self) { + let action = self + .request + .as_mut() + .and_then(|request| request.outbound.as_mut()) + .map(OutboundTransfer::tick); + match action { + Some(TransferAction::SendAdvertisement(data)) => { + self.send_encrypted_resource_control( + rns_wire::context::PacketContext::ResourceAdv, + &data, + ); + } + Some(TransferAction::Failed(_)) => self.status.state = PropagationClientState::Failed, + _ => {} + } + } + + fn handle_outbound_request(&mut self, data: &[u8]) { + let Some(plaintext) = self.link.as_ref().and_then(|link| link.decrypt(data).ok()) else { + return; + }; + let offset = if plaintext.first() == Some(&rns_protocol::resource::HASHMAP_IS_EXHAUSTED) { + 1 + rns_protocol::resource::MAPHASH_LEN + } else if plaintext.first() == Some(&rns_protocol::resource::HASHMAP_IS_NOT_EXHAUSTED) { + 1 + } else { + return; + }; + let Some(transfer) = self + .request + .as_mut() + .and_then(|request| request.outbound.as_mut()) + else { + return; + }; + if plaintext.get(offset..offset + 32) != Some(transfer.resource.resource_hash.as_slice()) { + return; + } + for action in transfer.handle_request(&plaintext) { + match action { + TransferAction::SendPart(_, data) => { + self.send_link_packet( + rns_wire::context::PacketContext::Resource, + rns_wire::flags::PacketType::Data, + &data, + ); + } + TransferAction::SendHmu(data) => self.send_encrypted_resource_control( + rns_wire::context::PacketContext::ResourceHmu, + &data, + ), + TransferAction::SendCancel(_, hash) => { + self.send_encrypted_resource_control( + rns_wire::context::PacketContext::ResourceIcl, + &hash, + ); + self.status.state = PropagationClientState::Failed; + } + TransferAction::Failed(_) => self.status.state = PropagationClientState::Failed, + _ => {} + } + if self.status.state == PropagationClientState::Failed { + break; + } + } + } + + fn handle_outbound_proof(&mut self, proof: &[u8]) { + if self + .request + .as_mut() + .and_then(|request| request.outbound.as_mut()) + .is_some_and(|transfer| transfer.handle_proof(proof)) + { + self.retire_request_sender(); + if let Some(request) = self.request.as_mut() { + request.waiting_since = Some(Instant::now()); + if let Some(link) = self.link.as_mut() { + link.mark_request_resource_sent(&request.id); + } + } + } + } + + fn retire_request_sender(&mut self) { + let Some(request) = self.request.as_mut() else { + return; + }; + request.sender_active = false; + if let Some(transfer) = request.outbound.take() + && let Some(link) = self.link.as_mut() + { + link.untrack_resource(&transfer.resource.resource_hash); + } + let link_id = request.link_id; + // Remove bytes still owned by our local staging queue. Actor/driver + // admitted bytes are non-recallable; generation-scoped outcomes below + // cannot settle a different phase. + self.pending_transport.retain(|message| { + let TransportMessage::SendLinkEndpoint { request, .. } = message else { + return true; + }; + let Ok((header, _)) = rns_wire::header::PacketHeader::unpack(&request.raw) else { + return true; + }; + use rns_wire::context::PacketContext; + header.destination_hash != link_id + || !matches!( + header.context, + PacketContext::Request + | PacketContext::ResourceAdv + | PacketContext::Resource + | PacketContext::ResourceHmu + | PacketContext::ResourceIcl + ) + }); + } + + fn finish_request(&mut self, data: &[u8]) -> Option { + self.retire_request_sender(); + let request = self.request.take()?; + if let Some(link) = self.link.as_mut() { + link.deliver_response_data(&request.id, data.to_vec()); + for hash in self.inbound_resources.keys() { + link.untrack_resource(hash); + } + } + self.inbound_resources.clear(); + self.inbound_split_resources.clear(); + self.segment_routing.clear(); + self.receiving_for = None; + Some(request.kind) + } + + fn handle_response_plaintext(&mut self, data: &[u8]) { + let Ok((id, response)) = Link::parse_response_plaintext(data) else { + return; + }; + if !self + .request + .as_ref() + .is_some_and(|request| request.id == id && Some(request.link_id) == self.link_id) + { + return; + } + if !matches!(Self::decode_response_value(data), Ok(rmpv::Value::Array(fields)) if fields.len() == 2 && matches!(&fields[0], rmpv::Value::Binary(_)) && fields[1].is_array()) + { + self.status.state = PropagationClientState::Failed; + return; + } + self.handle_response_data(&response); } fn cleanup(&mut self) { + self.request = None; + if let Some(link_id) = self.link_id { + self.pending_transport.retain(|message| { + !matches!(message, + TransportMessage::SendLinkEndpoint { link_id: id, .. } if *id == link_id) + }); + } let graceful_release = self.endpoint_release_queued || self.send_teardown(); if let Some(link_id) = self.link_id.take() && !graceful_release @@ -1993,6 +2524,17 @@ mod tests { client.link_id = Some(initiator.link_id); client.link = Some(initiator); client.status.state = PropagationClientState::GetRequested; + client.request = Some(PendingRequest { + link_id: client.link_id.unwrap(), + generation: 1, + id: [0x44; 16], + kind: RequestKind::Get(0), + sender_active: false, + outbound: None, + response: None, + waiting_since: Some(Instant::now()), + timeout: Duration::from_secs(60), + }); let payload = vec![0xAB; 3_000]; let mut sender = OutboundTransfer::new_encrypted( @@ -2003,6 +2545,7 @@ mod tests { ) .unwrap(); sender.resource.flags.is_response = true; + sender.resource.request_id = Some(vec![0x44; 16]); let advertisement = match sender.tick() { TransferAction::SendAdvertisement(data) => data, other => panic!("expected Resource advertisement, got {other:?}"), @@ -2046,6 +2589,17 @@ mod tests { client.link = Some(initiator); client.attached_interface = Some(0); client.status.state = PropagationClientState::GetRequested; + client.request = Some(PendingRequest { + link_id: client.link_id.unwrap(), + generation: 1, + id: [0x44; 16], + kind: RequestKind::Get(0), + sender_active: false, + outbound: None, + response: None, + waiting_since: Some(Instant::now()), + timeout: Duration::from_secs(60), + }); let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAB; 32])]); let payload = crate::encode_value(&response); @@ -2057,6 +2611,7 @@ mod tests { ) .unwrap(); sender.resource.flags.is_response = true; + sender.resource.request_id = Some(vec![0x44; 16]); let advertisement = match sender.tick() { TransferAction::SendAdvertisement(data) => data, other => panic!("expected Resource advertisement, got {other:?}"), @@ -2091,6 +2646,17 @@ mod tests { client.link = Some(initiator); client.attached_interface = Some(0); client.status.state = PropagationClientState::GetRequested; + client.request = Some(PendingRequest { + link_id: client.link_id.unwrap(), + generation: 1, + id: [0x44; 16], + kind: RequestKind::Get(0), + sender_active: false, + outbound: None, + response: None, + waiting_since: Some(Instant::now()), + timeout: Duration::from_secs(60), + }); let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAC; 32])]); let mut sender = OutboundTransfer::new_encrypted( @@ -2101,6 +2667,7 @@ mod tests { ) .unwrap(); sender.resource.flags.is_response = true; + sender.resource.request_id = Some(vec![0x44; 16]); let advertisement = match sender.tick() { TransferAction::SendAdvertisement(data) => data, other => panic!("expected Resource advertisement, got {other:?}"), @@ -2141,7 +2708,7 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.status.state = PropagationClientState::PurgeRequested; - client.handle_purge_response(); + client.handle_purge_response(&[0x90]); assert_eq!(client.status.state, PropagationClientState::Complete); } @@ -2338,3 +2905,7 @@ mod tests { assert!(client.link.as_ref().is_some_and(Link::is_active)); } } + +#[cfg(test)] +#[path = "propagation_client_tests.rs"] +mod lifecycle_tests; diff --git a/crates/lxmf-core/src/propagation_client_tests.rs b/crates/lxmf-core/src/propagation_client_tests.rs new file mode 100644 index 0000000..02e6349 --- /dev/null +++ b/crates/lxmf-core/src/propagation_client_tests.rs @@ -0,0 +1,968 @@ +//! In-process encrypted peers: every emitted packet is checked at the real MTU. +use super::*; +use rmpv::Value; +use rns_wire::{context::PacketContext as Context, flags::PacketType}; + +struct Peer { + client: PropagationClient, + link: Link, + rx: mpsc::Receiver, + held: Vec>, + hold_advertisement: bool, + resource_requests: usize, + hmus: usize, + drop_part: bool, + drop_hmu: bool, + drop_request: bool, + retries: usize, +} + +impl Peer { + fn new() -> Self { + let key = Ed25519PrivateKey::generate(); + let (mut initiator, request) = Link::new_initiator([0xe8; 16], 1); + let (mut responder, proof) = Link::new_responder(&request, &key, [0xe8; 16], 1).unwrap(); + let rtt = initiator + .validate_proof(&proof, &key.public_key(), &key.public_key().to_bytes()) + .unwrap(); + responder.receive_rtt_packet(&rtt).unwrap(); + let (tx, rx) = mpsc::channel(256); + let mut client = PropagationClient::new(tx, None, None); + client.link_id = Some(initiator.link_id); + client.link = Some(initiator); + client.attached_interface = Some(7); + client.set_propagation_node([0xe8; 16]); + Self { + client, + link: responder, + rx, + held: Vec::new(), + hold_advertisement: false, + resource_requests: 0, + hmus: 0, + drop_part: false, + drop_hmu: false, + drop_request: false, + retries: 0, + } + } + + fn inject(&mut self, context: Context, payload: &[u8]) { + let raw = PropagationClient::link_packet_bytes( + self.link.link_id, + context, + if context == Context::ResourcePrf { + PacketType::Proof + } else { + PacketType::Data + }, + payload, + ); + assert!( + raw.len() <= rns_wire::constants::MTU, + "peer packet exceeds MTU" + ); + self.client + .event_tx + .try_send(DestinationEvent::InboundPacket { + raw: raw.into(), + interface_id: 7, + metrics: Default::default(), + }) + .unwrap(); + self.client.drain_events(&HashMap::new()); + } + + fn packet(&mut self) -> (Context, Vec, Vec) { + let TransportMessage::SendLinkEndpoint { + request, + result_tx, + role, + .. + } = self.rx.try_recv().expect("client packet") + else { + panic!("request must use typed Link endpoint"); + }; + assert_eq!(role, LinkEndpointRole::Initiator); + assert!( + request.raw.len() <= rns_wire::constants::MTU, + "client packet exceeds MTU: {}", + request.raw.len() + ); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + if self.hold_advertisement && header.context == Context::ResourceAdv { + self.held.push(result_tx); + self.hold_advertisement = false; + } else { + result_tx.send(LinkEndpointSendResult::Sent).unwrap(); + } + self.client.poll_endpoint_control(); + ( + header.context, + request.raw[offset..].to_vec(), + request.raw.to_vec(), + ) + } + + /// Receive the exact client's next request, optionally withholding its + /// Resource proof to exercise response-before-proof ordering. + fn request(&mut self, prove: bool) -> ([u8; 16], Value, Option>) { + let (context, payload, raw) = self.packet(); + if context == Context::Request { + let (_, _, _, data) = self.link.handle_request(&payload).unwrap(); + let id = + rns_wire::hash::truncated_packet_hash(&raw, rns_wire::flags::HeaderType::Header1); + assert_eq!(self.client.request.as_ref().unwrap().id, id); + return ( + id, + PropagationClient::decode_response_value(&data).unwrap(), + None, + ); + } + assert_eq!(context, Context::ResourceAdv); + self.resource_requests += 1; + let adv = ResourceAdvertisement::unpack(&self.link.decrypt(&payload).unwrap()).unwrap(); + assert!(adv.flags.encrypted && adv.flags.is_request && !adv.flags.is_response); + assert_eq!(adv.total_segments, 1); + let mut receiver = InboundTransfer::from_advertisement( + adv.num_parts, + adv.transfer_size, + adv.data_size, + adv.random_hash.as_slice().try_into().unwrap(), + adv.resource_hash, + adv.flags, + adv.get_map_hashes(), + Duration::from_millis(10), + ) + .unwrap(); + if let TransferAction::SendRequest(request) = receiver.request_next() { + if !self.drop_request { + self.inject(Context::ResourceReq, &self.link.encrypt(&request).unwrap()); + } + self.drop_request = false; + } + let mut packets = 0; + while !receiver.resource.is_complete() { + packets += 1; + assert!(packets < 20_000, "bounded request peer loop"); + if self.rx.is_empty() { + receiver.last_activity = Instant::now() - Duration::from_secs(1000); + receiver.req_sent = Some(receiver.last_activity); + let TransferAction::SendRequest(request) = receiver.check_timeout() else { + panic!("receiver should retry its missing window"); + }; + self.retries += 1; + self.inject(Context::ResourceReq, &self.link.encrypt(&request).unwrap()); + } + let (context, body, _) = self.packet(); + if context == Context::Resource && self.drop_part { + self.drop_part = false; + continue; + } + if context == Context::ResourceHmu && self.drop_hmu { + self.drop_hmu = false; + continue; + } + let action = match context { + Context::Resource => receiver.receive_part(body), + Context::ResourceHmu => { + self.hmus += 1; + let plaintext = self.link.decrypt(&body).unwrap(); + assert_eq!(&plaintext[..32], &adv.resource_hash); + let fields = + PropagationClient::decode_response_value(&plaintext[32..]).unwrap(); + let fields = fields.as_array().unwrap(); + receiver.hashmap_update( + fields[0].as_u64().unwrap() as usize, + fields[1].as_slice().unwrap(), + ) + } + other => panic!("unexpected client Resource context {other:?}"), + }; + if let TransferAction::SendRequest(request) = action { + self.inject(Context::ResourceReq, &self.link.encrypt(&request).unwrap()); + } + } + let decrypt = |data: &[u8]| self.link.decrypt(data).map_err(|_| ResourceError::Corrupt); + let (plaintext, proof) = receiver.complete(Some(&decrypt)).unwrap(); + let (id, path, _, data) = Link::parse_request(&plaintext).unwrap(); + assert_eq!( + path, + rns_crypto::sha::truncated_hash(MESSAGE_GET_PATH.as_bytes()) + ); + assert_eq!(adv.request_id.as_deref(), Some(id.as_slice())); + assert_eq!(self.client.request.as_ref().unwrap().id, id); + if prove { + self.inject(Context::ResourcePrf, &proof); + } + ( + id, + PropagationClient::decode_response_value(&data).unwrap(), + Some(proof), + ) + } + + fn response(&mut self, id: [u8; 16], value: Value, resource: bool) { + self.response_with_envelope(id, id, value, resource); + } + + fn response_with_envelope( + &mut self, + id: [u8; 16], + envelope_id: [u8; 16], + value: Value, + resource: bool, + ) { + if !resource { + let payload = self + .link + .create_response(&envelope_id, &crate::encode_value(&value)) + .unwrap(); + self.inject(Context::Response, &payload); + return; + } + let envelope = crate::encode_value(&Value::Array(vec![ + Value::Binary(envelope_id.to_vec()), + value, + ])); + let keys = self.link.session_keys().unwrap(); + let encrypt = |data: &[u8]| rns_link::encryption::link_encrypt(&keys, data).unwrap(); + let resources = if envelope.len() <= MAX_EFFICIENT_SIZE { + let mut transfer = + OutboundTransfer::new_encrypted(envelope, false, Duration::from_millis(10), keys) + .unwrap(); + transfer.resource.flags.is_response = true; + transfer.resource.request_id = Some(id.to_vec()); + vec![transfer] + } else { + rns_protocol::resource::MultiSegmentOutbound::with_options( + envelope, + false, + None, + Some(id.to_vec()), + true, + Some(&encrypt), + ) + .unwrap() + .segments + .into_iter() + .map(|segment| OutboundTransfer::from_prebuilt(segment, Duration::from_millis(10))) + .collect() + }; + for mut sender in resources { + let TransferAction::SendAdvertisement(adv) = sender.tick() else { + panic!() + }; + self.inject(Context::ResourceAdv, &self.link.encrypt(&adv).unwrap()); + let mut packets = 0; + loop { + packets += 1; + assert!(packets < 20_000, "bounded response peer loop"); + let (context, body, _) = self.packet(); + if context == Context::ResourcePrf { + assert!(sender.handle_proof(&body)); + break; + } + assert_eq!(context, Context::ResourceReq); + let request = self.link.decrypt(&body).unwrap(); + for action in sender.handle_request(&request) { + match action { + TransferAction::SendPart(_, data) => self.inject(Context::Resource, &data), + TransferAction::SendHmu(data) => { + self.inject(Context::ResourceHmu, &self.link.encrypt(&data).unwrap()) + } + other => panic!("unexpected response action {other:?}"), + } + } + } + } + } +} + +fn ids(n: usize) -> Vec> { + (0..n) + .map(|i| rns_crypto::sha::full_hash(&(i as u64).to_be_bytes()).to_vec()) + .collect() +} +fn blobs(n: usize) -> Vec> { + (0..n) + .map(|i| { + let mut data = ids(5).concat(); + data[..8].copy_from_slice(&(i as u64).to_be_bytes()); + data + }) + .collect() +} +fn binary_list(items: &[Vec]) -> Value { + Value::Array(items.iter().cloned().map(Value::Binary).collect()) +} +fn empty() -> Value { + Value::Array(Vec::new()) +} + +#[test] +fn full_encoded_mdu_boundary_selects_packet_or_resource() { + for delta in [-1isize, 0, 1] { + let mut peer = Peer::new(); + let len = peer + .client + .link + .as_ref() + .unwrap() + .mdu + .wrapping_add_signed(delta); + let body = crate::encode_value(&Value::Array(vec![Value::Binary(vec![0x42; len - 32])])); + assert!(peer.client.send_get_path_request(&body, RequestKind::List)); + let resource = peer.client.request.as_ref().unwrap().outbound.is_some(); + assert_eq!(resource, delta > 0); + let _ = peer.request(true); + } +} + +#[test] +fn fifty_haves_complete_through_encrypted_request_resource() { + let mut peer = Peer::new(); + let haves = ids(50); + peer.client.available_messages = haves.clone(); + peer.client.replace_local_message_ids(haves.clone()); + peer.client.send_get_request(); + let (id, data, _) = peer.request(true); + assert_eq!(data, Value::Array(vec![Value::Nil, binary_list(&haves)])); + assert_eq!( + peer.client.state(), + PropagationClientState::PurgeRequested, + "proof is not purge success" + ); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert_eq!(peer.resource_requests, 1); + assert!(peer.client.pending_haves.is_empty()); +} + +#[test] +fn fifty_downloaded_messages_survive_get_and_purge_resource_round_trip() { + let mut peer = Peer::new(); + let messages = blobs(50); + let wants: Vec<_> = messages + .iter() + .map(|data| rns_crypto::sha::full_hash(data).to_vec()) + .collect(); + peer.client.available_messages = wants.clone(); + peer.client.send_get_request(); + let (get_id, request, _) = peer.request(true); + assert_eq!(request.as_array().unwrap()[0], binary_list(&wants)); + peer.response(get_id, binary_list(&messages), true); + assert_eq!(peer.client.received_count(), 50); + let (purge_id, request, _) = peer.request(true); + assert_eq!(request, Value::Array(vec![Value::Nil, binary_list(&wants)])); + peer.response(purge_id, empty(), true); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert_eq!(peer.client.transfer_status().result, Some(50)); + assert_eq!(peer.client.take_received_messages(), messages); + assert_eq!(peer.resource_requests, 2); + assert_eq!(peer.client.unread_bytes, 0); +} + +#[test] +fn early_response_retires_sender_and_ignores_late_proof_cancel_and_receipt() { + let mut peer = Peer::new(); + peer.hold_advertisement = true; + peer.client.available_messages = ids(50); + peer.client.send_get_request(); + let (old_id, _, proof) = peer.request(false); + let old_hash = peer + .client + .request + .as_ref() + .unwrap() + .outbound + .as_ref() + .unwrap() + .resource + .resource_hash; + peer.response(old_id, binary_list(&blobs(1)), false); + let new_request = peer.client.request.as_ref().unwrap(); + assert_ne!(old_id, new_request.id); + let generation = new_request.generation; + let wait = new_request.waiting_since; + assert!(new_request.outbound.is_none()); + peer.inject(Context::ResourcePrf, &proof.unwrap()); + peer.inject(Context::ResourceRcl, &peer.link.encrypt(&old_hash).unwrap()); + for receipt in peer.held.drain(..) { + let _ = receipt.send(LinkEndpointSendResult::InvalidPacket); + } + peer.client.poll_endpoint_control(); + assert_eq!(peer.client.request.as_ref().unwrap().generation, generation); + assert_eq!(peer.client.request.as_ref().unwrap().waiting_since, wait); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + let (purge, _, _) = peer.request(true); + peer.response(purge, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); +} + +#[test] +fn foreign_responses_and_cancels_cannot_advance_or_fail_request() { + let mut peer = Peer::new(); + peer.client.available_messages = ids(50); + peer.client.send_get_request(); + let id = peer.client.request.as_ref().unwrap().id; + peer.response([0xaa; 16], empty(), false); + peer.inject( + Context::ResourceRcl, + &peer.link.encrypt(&[0xbb; 32]).unwrap(), + ); + peer.inject(Context::ResourcePrf, &[0xcc; 64]); + let hash = peer + .client + .request + .as_ref() + .unwrap() + .outbound + .as_ref() + .unwrap() + .resource + .resource_hash; + peer.inject(Context::ResourceIcl, &peer.link.encrypt(&hash).unwrap()); + assert_eq!(peer.client.request.as_ref().unwrap().id, id); + assert_eq!(peer.client.state(), PropagationClientState::GetRequested); + peer.inject(Context::ResourceRcl, &peer.link.encrypt(&hash).unwrap()); + assert_eq!(peer.client.state(), PropagationClientState::Failed); +} + +#[test] +fn purge_errors_never_complete_or_advance_chunk() { + for value in [ + Value::Nil, + Value::from(0xf0), + Value::Array(vec![Value::Nil]), + Value::Binary(vec![0x90]), + ] { + let mut peer = Peer::new(); + peer.client.received_ids = ids(12); + peer.client.send_purge_request(); + let (id, _, _) = peer.request(true); + peer.response(id, value, false); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.received_ids.len(), 12); + } +} + +#[test] +fn capacity_failure_precedes_publication_purge_and_cursor_advance() { + let mut peer = Peer::new(); + peer.client.unread_limit = 100; + peer.client.received_messages.push(vec![1; 20]); + peer.client.unread_bytes = 20; + peer.client.available_messages = ids(2); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + peer.response(id, binary_list(&[vec![2; 60], vec![3; 30]]), false); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.pending_wants.len(), 2); + assert!(peer.client.received_ids.is_empty()); + assert_eq!(peer.client.received_messages, vec![vec![1; 20]]); + assert_eq!(peer.client.unread_bytes, 20); + assert!(peer.rx.try_recv().is_err(), "overflow must not queue purge"); + assert!(!peer.client.start_download()); + peer.client.cancel_download(); + assert!(!peer.client.start_download()); + assert_eq!(peer.client.take_received_messages(), vec![vec![1; 20]]); +} + +#[test] +fn request_resource_progress_is_not_a_fixed_120_second_operation() { + let mut peer = Peer::new(); + peer.client.received_ids = ids(50); + peer.client.send_purge_request(); + peer.client.started_at = Some(Instant::now() - Duration::from_secs(600)); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + let (id, _, _) = peer.request(true); + let request = peer.client.request.as_mut().unwrap(); + request.waiting_since = Some(Instant::now() - request.timeout - Duration::from_secs(1)); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert!(peer.client.request.is_none()); + // No late response can resurrect a cleaned-up request. + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Failed); +} + +#[test] +fn lost_advertisement_retries_same_resource_and_eventually_fails() { + let mut peer = Peer::new(); + peer.client.received_ids = ids(50); + peer.client.send_purge_request(); + let (_, payload, _) = peer.packet(); + let original = peer.link.decrypt(&payload).unwrap(); + let mut retries = 0; + while peer.client.state() != PropagationClientState::Failed { + peer.client + .request + .as_mut() + .unwrap() + .outbound + .as_mut() + .unwrap() + .started_at = Instant::now() - Duration::from_secs(100_000); + peer.client.drive_outbound_request(); + if peer.client.state() != PropagationClientState::Failed { + let (context, payload, _) = peer.packet(); + assert_eq!(context, Context::ResourceAdv); + assert_eq!(peer.link.decrypt(&payload).unwrap(), original); + retries += 1; + assert!(retries <= rns_protocol::resource::MAX_ADV_RETRIES); + } + } + assert!(retries > 0); +} + +#[test] +fn oversized_logical_sets_advance_after_empty_and_partial_chunks() { + let mut peer = Peer::new(); + let selected = ids(30_845); + peer.client.max_messages = Some(30_840); + peer.client.available_messages = selected.clone(); + peer.client.available_messages.push(selected[0].clone()); + peer.client.send_get_request(); + let first = peer.client.request.as_ref().unwrap(); + let RequestKind::Get(first_count) = first.kind else { + panic!() + }; + assert!(first_count < 30_840); + assert!( + first + .outbound + .as_ref() + .unwrap() + .resource + .advertisement_data_size + <= MAX_EFFICIENT_SIZE + ); + let id = first.id; + // Correlated early empty response skips the complete requested chunk. + peer.response(id, empty(), false); + let RequestKind::Get(tail_count) = peer.client.request.as_ref().unwrap().kind else { + panic!() + }; + assert_eq!(first_count + tail_count, 30_840); + let tail = peer.client.request.as_ref().unwrap().id; + peer.response(tail, binary_list(&blobs(1)), false); + assert!(peer.client.pending_wants.is_empty()); + assert_eq!(peer.client.received_ids.len(), 1); + let purge = peer.client.request.as_ref().unwrap().id; + peer.response(purge, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert_eq!(peer.client.transfer_status().result, Some(1)); +} + +#[test] +fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() { + let mut peer = Peer::new(); + let selected = ids(30_840); + peer.client.available_messages = selected.clone(); + peer.client.replace_local_message_ids(selected); + peer.client.send_get_request(); + let RequestKind::Haves(first) = peer.client.request.as_ref().unwrap().kind else { + panic!() + }; + assert!(first < 30_840); + let id = peer.client.request.as_ref().unwrap().id; + peer.response(id, empty(), false); + assert_eq!(peer.client.pending_haves.len(), 30_840 - first); + let id = peer.client.request.as_ref().unwrap().id; + peer.response(id, empty(), false); + assert!(peer.client.pending_haves.is_empty()); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + + let mut peer = Peer::new(); + peer.client.available_messages = ids(2); + peer.client.replace_local_message_ids(ids(1)); + peer.client.set_retain_synced_on_node(true); + peer.client.send_get_request(); + let (id, data, _) = peer.request(true); + assert_eq!(data.as_array().unwrap()[0], binary_list(&ids(2)[1..])); + assert_eq!(data.as_array().unwrap()[1], empty()); + peer.response(id, binary_list(&blobs(1)), false); + assert!(matches!( + peer.client.request.as_ref().unwrap().kind, + RequestKind::Purge(1) + )); +} + +#[test] +fn hashmap_updates_and_split_responses_keep_exact_request_identity() { + let mut peer = Peer::new(); + peer.client.received_ids = ids(1200); + peer.client.send_purge_request(); + let (id, _, _) = peer.request(true); + assert!( + peer.hmus > 0, + "incompressible IDs cross advertised hashmap boundary" + ); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + + let mut peer = Peer::new(); + peer.client.available_messages = ids(1); + peer.client.set_delivery_limit(2000.0); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100]; + peer.response(id, binary_list(std::slice::from_ref(&blob)), true); + assert_eq!(peer.client.received_messages, vec![blob]); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + assert!(peer.client.inbound_split_resources.is_empty()); +} + +#[test] +fn every_id_branch_switches_at_real_packet_boundary() { + for count in [11, 12, 50] { + for branch in 0..4 { + let mut peer = Peer::new(); + let selected = ids(count); + peer.client.set_delivery_limit(1000.0); + match branch { + 0 => { + peer.client.available_messages = selected.clone(); + peer.client.send_get_request(); + } + 1 | 2 => { + peer.client.available_messages = selected.clone(); + peer.client.replace_local_message_ids(selected.clone()); + if branch == 2 { + peer.client.available_messages.push(vec![0xee; 32]); + } + peer.client.send_get_request(); + } + _ => { + peer.client.received_ids = selected.clone(); + peer.client.send_purge_request(); + } + } + assert_eq!( + peer.client.request.as_ref().unwrap().outbound.is_some(), + count > 11 + ); + let (id, body, _) = peer.request(true); + let fields = body.as_array().unwrap(); + assert_eq!( + fields[if branch == 0 { 0 } else { 1 }], + binary_list(&selected) + ); + peer.response(id, empty(), false); + if branch == 2 { + let (id, body, _) = peer.request(true); + assert_eq!(body.as_array().unwrap()[0], binary_list(&[vec![0xee; 32]])); + peer.response(id, empty(), false); + } + assert_eq!(peer.client.state(), PropagationClientState::Complete); + } + } +} + +#[test] +fn list_resource_response_starts_correlated_haves_resource() { + let mut peer = Peer::new(); + let selected = ids(50); + peer.client.replace_local_message_ids(selected.clone()); + peer.client.send_list_request(); + let (id, body, _) = peer.request(true); + assert_eq!(body, Value::Array(vec![Value::Nil, Value::Nil])); + peer.response(id, binary_list(&selected), true); + let (id, body, _) = peer.request(true); + assert_eq!(body, Value::Array(vec![Value::Nil, binary_list(&selected)])); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); +} + +#[test] +fn request_resource_recovers_lost_req_part_and_hashmap_update() { + let mut peer = Peer::new(); + peer.drop_request = true; + peer.drop_part = true; + peer.drop_hmu = true; + peer.client.received_ids = ids(1200); + peer.client.send_purge_request(); + let (id, body, _) = peer.request(true); + assert_eq!(body.as_array().unwrap()[1].as_array().unwrap().len(), 1200); + assert!(peer.retries >= 3); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); +} + +#[test] +fn encoded_single_segment_ceiling_is_inclusive() { + for extra in [0, 1] { + let mut peer = Peer::new(); + // A bin32 adds five bytes, its array one byte, and the request + // envelope adds 28 bytes for the float timestamp and path hash. + let body = crate::encode_value(&Value::Array(vec![Value::Binary(vec![ + 0x42; + MAX_EFFICIENT_SIZE + - 34 + + extra + ])])); + let admitted = peer.client.send_get_path_request(&body, RequestKind::List); + assert_eq!(admitted, extra == 0); + if admitted { + let sender = peer + .client + .request + .as_ref() + .unwrap() + .outbound + .as_ref() + .unwrap(); + assert_eq!(sender.resource.advertisement_data_size, MAX_EFFICIENT_SIZE); + } else { + assert!(peer.client.request.is_none()); + assert!(peer.rx.is_empty()); + } + } +} + +#[test] +fn mismatched_resource_envelope_fails_without_publishing_or_purging() { + let mut peer = Peer::new(); + peer.client.available_messages = ids(1); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + peer.response_with_envelope(id, [0xff; 16], binary_list(&blobs(1)), true); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.received_count(), 0); + assert!(peer.client.received_ids.is_empty()); + assert_eq!(peer.client.pending_wants.len(), 1); +} + +#[test] +fn advertisement_requires_matching_request_id_and_response_direction() { + let mut peer = Peer::new(); + peer.client.received_ids = ids(12); + peer.client.send_purge_request(); + let (id, _, _) = peer.request(true); + let mut sender = OutboundTransfer::new_encrypted( + Link::pack_response(&id, &[0x90]).unwrap(), + false, + Duration::from_millis(10), + peer.link.session_keys().unwrap(), + ) + .unwrap(); + sender.resource.flags.is_response = true; + sender.resource.request_id = Some(vec![0xfe; 16]); + let TransferAction::SendAdvertisement(bytes) = sender.tick() else { + panic!() + }; + let mut adv = ResourceAdvertisement::unpack(&bytes).unwrap(); + peer.inject( + Context::ResourceAdv, + &peer.link.encrypt(&adv.pack()).unwrap(), + ); + assert!(peer.client.inbound_resources.is_empty()); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + adv.request_id = Some(id.to_vec()); + adv.flags.is_response = false; + peer.inject( + Context::ResourceAdv, + &peer.link.encrypt(&adv.pack()).unwrap(), + ); + assert!(peer.client.inbound_resources.is_empty()); + adv.flags.is_response = true; + adv.flags.is_request = true; + peer.inject( + Context::ResourceAdv, + &peer.link.encrypt(&adv.pack()).unwrap(), + ); + assert_eq!(peer.client.state(), PropagationClientState::Failed); +} + +#[test] +fn malformed_batch_is_atomic_and_preserves_prior_results() { + let mut peer = Peer::new(); + peer.client.received_messages.push(vec![0xab; 20]); + peer.client.unread_bytes = 20; + peer.client.available_messages = ids(2); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + peer.response( + id, + Value::Array(vec![Value::Binary(vec![7; 10]), Value::Nil]), + false, + ); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.received_messages, vec![vec![0xab; 20]]); + assert_eq!(peer.client.unread_bytes, 20); + assert!(peer.client.received_ids.is_empty()); + assert_eq!(peer.client.pending_wants.len(), 2); +} + +#[test] +fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained() { + for failure in 0..3 { + let mut peer = Peer::new(); + let messages = blobs(50); + peer.client.available_messages = ids(50); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + peer.response(id, binary_list(&messages), true); + assert_eq!(peer.client.received_count(), 50); + match failure { + 0 => { + let (id, _, _) = peer.request(true); + peer.response(id, Value::from(0xf0), false); + peer.client.tick(); + } + 1 => peer.client.cancel_download(), + _ => { + let teardown = peer.link.teardown(CloseReason::DestinationClosed).unwrap(); + peer.inject(Context::LinkClose, &teardown); + } + } + assert!(!peer.client.start_download()); + assert_eq!(peer.client.take_received_messages(), messages); + assert_eq!(peer.client.unread_bytes, 0); + assert!(peer.client.start_download()); + assert!(peer.client.take_received_messages().is_empty()); + } +} + +#[test] +fn transport_result_deadline_is_finite_and_retains_results() { + let mut peer = Peer::new(); + peer.client.received_messages.push(vec![0x33; 10]); + peer.client.unread_bytes = 10; + peer.client.received_ids = ids(50); + peer.client.send_purge_request(); + let pending = peer.client.pending_endpoint_sends.last_mut().unwrap(); + pending.queued_at = Instant::now() - Duration::from_secs(121); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert!(peer.client.request.is_none()); + assert!(!peer.client.start_download()); + assert_eq!(peer.client.take_received_messages(), vec![vec![0x33; 10]]); +} + +#[test] +fn packet_response_wait_begins_after_transport_admission() { + let mut peer = Peer::new(); + peer.client.send_list_request(); + assert!( + peer.client + .request + .as_ref() + .unwrap() + .waiting_since + .is_none() + ); + peer.client.started_at = Some(Instant::now() - Duration::from_secs(600)); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::ListRequested); + let (id, _, _) = peer.request(true); + assert!( + peer.client + .request + .as_ref() + .unwrap() + .waiting_since + .is_some() + ); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); +} + +#[test] +fn slow_segment_gets_a_fresh_proof_admission_deadline() { + let mut peer = Peer::new(); + peer.client.available_messages = ids(1); + peer.client.send_get_request(); + let (id, _, _) = peer.request(true); + let messages = blobs(1); + let mut sender = OutboundTransfer::new_encrypted( + Link::pack_response(&id, &crate::encode_value(&binary_list(&messages))).unwrap(), + false, + Duration::from_millis(10), + peer.link.session_keys().unwrap(), + ) + .unwrap(); + sender.resource.flags.is_response = true; + sender.resource.request_id = Some(id.to_vec()); + let TransferAction::SendAdvertisement(adv) = sender.tick() else { + panic!() + }; + peer.inject(Context::ResourceAdv, &peer.link.encrypt(&adv).unwrap()); + let (context, request, _) = peer.packet(); + assert_eq!(context, Context::ResourceReq); + peer.client.started_at = Some(Instant::now() - Duration::from_secs(600)); + peer.client + .request + .as_mut() + .unwrap() + .response + .as_mut() + .unwrap() + .waiting_since = Instant::now() - Duration::from_secs(600); + for action in sender.handle_request(&peer.link.decrypt(&request).unwrap()) { + let TransferAction::SendPart(_, data) = action else { + panic!() + }; + peer.inject(Context::Resource, &data); + } + assert!( + peer.client + .request + .as_ref() + .unwrap() + .response + .as_ref() + .unwrap() + .waiting_since + .elapsed() + < Duration::from_secs(1) + ); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::Receiving); + let (context, proof, _) = peer.packet(); + assert_eq!(context, Context::ResourcePrf); + assert!(sender.handle_proof(&proof)); + assert_eq!(peer.client.received_messages, messages); +} + +#[test] +fn response_resource_before_request_proof_retires_only_its_sender() { + let mut peer = Peer::new(); + peer.client.available_messages = ids(50); + peer.client.send_get_request(); + let (id, _, proof) = peer.request(false); + peer.response(id, binary_list(&blobs(50)), true); + let successor = peer.client.request.as_ref().unwrap().id; + let generation = peer.client.request.as_ref().unwrap().generation; + peer.inject(Context::ResourcePrf, &proof.unwrap()); + assert_eq!(peer.client.request.as_ref().unwrap().generation, generation); + assert_eq!(peer.client.request.as_ref().unwrap().id, successor); + let (id, _, _) = peer.request(true); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert_eq!(peer.client.received_count(), 50); +} + +#[test] +fn full_then_closed_transport_fails_request_without_losing_accepted_results() { + let mut peer = Peer::new(); + while peer + .client + .transport_tx + .try_send(TransportMessage::DeregisterDestination { hash: [0; 16] }) + .is_ok() + {} + peer.client.received_messages.push(vec![1; 12]); + peer.client.unread_bytes = 12; + peer.client.received_ids = ids(50); + peer.client.send_purge_request(); + assert_eq!(peer.client.pending_transport.len(), 1); + assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested); + peer.rx.close(); + peer.client.tick(); + assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert!(peer.client.request.is_none()); + assert_eq!(peer.client.take_received_messages(), vec![vec![1; 12]]); +}