diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12ca28c..864c8b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,3 +62,8 @@ jobs: working-directory: rsLXMF - run: cargo clippy --workspace --all-targets -- -D warnings working-directory: rsLXMF + - name: Check public API documentation + env: + RUSTDOCFLAGS: "-D warnings" + run: cargo doc --workspace --no-deps + working-directory: rsLXMF diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 94c3576..d56032b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,7 +17,7 @@ env: RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }} PACKAGE_ROOT: rsLXMF LXMF_BINS: lxmd-rs - RSLXMF_RSRETICULUM_REF: v1.0.1 + RSLXMF_RSRETICULUM_REF: v1.1.0 jobs: build: diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ba6262f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## 1.1.0 - 2026-07-26 + +- Added bounded propagation-node admission, exact inbound Resource ownership, + asynchronous validation, and peer-specific throttling. +- Completed live peer offer preparation, encrypted Resource synchronization, + cancellation, and proof-gated convergence. +- Added public inbound Resource tracking and cancellation plus restart-safe + persistence and packet/Resource deduplication. +- Unified safe name presentation and authoritative propagation transfer + status, including restart protection. +- Aligned `lxmd-rs` delivery and stamp defaults with the proven Python LXMF + compatibility target. diff --git a/Cargo.lock b/Cargo.lock index 0172101..8ec5d04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -643,13 +643,14 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "lxmf-core" -version = "1.0.1" +version = "1.1.0" dependencies = [ "base64", "bytes", "hex", "proptest", "rand 0.8.5", + "rmp", "rmp-serde", "rmpv", "rns-crypto", @@ -664,11 +665,12 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "unicode-normalization", ] [[package]] name = "lxmf-tools" -version = "1.0.1" +version = "1.1.0" dependencies = [ "base64", "bytes", @@ -1049,7 +1051,7 @@ dependencies = [ [[package]] name = "rns-crypto" -version = "1.0.1" +version = "1.1.0" dependencies = [ "aes", "cbc", @@ -1067,7 +1069,7 @@ dependencies = [ [[package]] name = "rns-identity" -version = "1.0.1" +version = "1.1.0" dependencies = [ "hex", "rand 0.8.5", @@ -1085,13 +1087,14 @@ dependencies = [ [[package]] name = "rns-interface" -version = "1.0.1" +version = "1.1.0" dependencies = [ "bytes", "hex", "if-addrs", "jni", "libc", + "md-5", "objc2", "objc2-core-bluetooth", "objc2-foundation", @@ -1112,7 +1115,7 @@ dependencies = [ [[package]] name = "rns-link" -version = "1.0.1" +version = "1.1.0" dependencies = [ "hex", "rand 0.8.5", @@ -1127,7 +1130,7 @@ dependencies = [ [[package]] name = "rns-protocol" -version = "1.0.1" +version = "1.1.0" dependencies = [ "bzip2", "hex", @@ -1143,7 +1146,7 @@ dependencies = [ [[package]] name = "rns-runtime" -version = "1.0.1" +version = "1.1.0" dependencies = [ "bytes", "hex", @@ -1169,7 +1172,7 @@ dependencies = [ [[package]] name = "rns-transport" -version = "1.0.1" +version = "1.1.0" dependencies = [ "bytes", "hex", @@ -1188,7 +1191,7 @@ dependencies = [ [[package]] name = "rns-wire" -version = "1.0.1" +version = "1.1.0" dependencies = [ "rns-crypto", "sha2", @@ -1481,6 +1484,21 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.50.0" @@ -1593,6 +1611,15 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-xid" version = "0.2.6" diff --git a/Cargo.toml b/Cargo.toml index 3b3de1c..13a305c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,30 +6,31 @@ members = [ ] [workspace.package] -version = "1.0.1" +version = "1.1.0" edition = "2024" license = "AGPL-3.0-or-later" rust-version = "1.85" [workspace.dependencies] # Reticulum crates from a sibling rsReticulum checkout during development. -rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.0.1" } -rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.0.1" } -rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.0.1" } -rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.0.1" } -rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.0.1" } -rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.0.1" } -rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.0.1" } -rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.0.1" } +rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.1.0" } +rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.1.0" } +rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.1.0" } +rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.1.0" } +rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.1.0" } +rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.1.0" } +rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.1.0" } +rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.1.0" } # Workspace LXMF crates -lxmf-core = { path = "crates/lxmf-core", version = "1.0.1" } -lxmf-tools = { path = "crates/lxmf-tools", version = "1.0.1" } +lxmf-core = { path = "crates/lxmf-core", version = "1.1.0" } +lxmf-tools = { path = "crates/lxmf-tools", version = "1.1.0" } # Encoding base64 = "0.22" # Serialization +rmp = "0.8" rmp-serde = "1" rmpv = "1" serde = { version = "1", features = ["derive"] } @@ -56,6 +57,7 @@ thiserror = "2" # Misc hex = "0.4" tempfile = "3" +unicode-normalization = "0.1" # Testing proptest = "1" diff --git a/README.md b/README.md index 89292ba..7126562 100644 --- a/README.md +++ b/README.md @@ -238,8 +238,8 @@ Minimal config: [lxmf] display_name = Rat announce_at_start = no +# stamp_cost = 12 delivery_transfer_max_accepted_size = 1000 -# stamp_cost = 8 # on_inbound = /path/to/handler [propagation] diff --git a/crates/lxmf-core/Cargo.toml b/crates/lxmf-core/Cargo.toml index 5232133..0b2e03a 100644 --- a/crates/lxmf-core/Cargo.toml +++ b/crates/lxmf-core/Cargo.toml @@ -17,12 +17,14 @@ thiserror = { workspace = true } tokio = { workspace = true } bytes = { workspace = true } tracing = { workspace = true } +rmp = { workspace = true } rmp-serde = { workspace = true } rmpv = { workspace = true } serde = { workspace = true } sha2 = { workspace = true } rand = { workspace = true } hex = { workspace = true } +unicode-normalization = { workspace = true } [dev-dependencies] tempfile = { workspace = true } diff --git a/crates/lxmf-core/src/handlers.rs b/crates/lxmf-core/src/handlers.rs index 97b14e0..09a759d 100644 --- a/crates/lxmf-core/src/handlers.rs +++ b/crates/lxmf-core/src/handlers.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; use crate::constants::*; +use crate::presentation::{MAX_ADVERTISED_NAME_CHARS, sanitize_name}; /// Announce handler type. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -99,7 +100,12 @@ impl PropagationNodeAnnounceData { } pub fn set_name(&mut self, name: &str) { - self.metadata.insert(PN_META_NAME, name.as_bytes().to_vec()); + let name = sanitize_name(name, MAX_ADVERTISED_NAME_CHARS); + if name.is_empty() { + self.metadata.remove(&PN_META_NAME); + } else { + self.metadata.insert(PN_META_NAME, name.into_bytes()); + } } } @@ -144,6 +150,17 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec< /// dropped because it duplicated this function's checks and every /// in-tree caller called both back-to-back. pub fn parse_pn_announce_data(data: &[u8]) -> Option { + fn nonnegative_u64(value: &rmpv::Value) -> Option { + value + .as_u64() + .or_else(|| value.as_i64().and_then(|number| number.try_into().ok())) + .or_else(|| { + value.as_f64().and_then(|number| { + (number.is_finite() && number >= 0.0).then_some(number as u64) + }) + }) + } + let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?; let arr = value.as_array()?; if arr.len() < 7 { @@ -155,38 +172,27 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option Option { /// Encode delivery-announce `app_data` as msgpack /// `[display_name, stamp_cost, supported_functionality]` where the feature -/// list advertises [`SF_COMPRESSION`](crate::constants::SF_COMPRESSION). +/// list advertises [`SF_COMPRESSION`]. /// /// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil. /// @@ -220,10 +226,10 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option { pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option) -> Vec { use rmpv::Value; - let name_val = match display_name { - Some(name) => Value::Binary(name.as_bytes().to_vec()), - None => Value::Nil, - }; + let name_val = display_name + .map(|name| sanitize_name(name, MAX_ADVERTISED_NAME_CHARS)) + .filter(|name| !name.is_empty()) + .map_or(Value::Nil, |name| Value::Binary(name.into_bytes())); let cost_val = match stamp_cost { Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64), @@ -252,7 +258,8 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option, Option bool { pub fn pn_name_from_app_data(data: &[u8]) -> Option { let parsed = parse_pn_announce_data(data)?; let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?; - String::from_utf8(name_bytes.clone()).ok() + String::from_utf8(name_bytes.clone()) + .ok() + .map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS)) + .filter(|name| !name.is_empty()) } /// Outcome of a resource transfer, matching Python `resource_concluded` / @@ -441,12 +451,10 @@ impl PropagationRequestHandler { true }; - let peer_hash = remote_identity_hash.copied().unwrap_or([0u8; 16]); - node.handle_offer_request( request_data, crate::propagation_node::OfferRequestContext { - peer_hash, + peer_hash: remote_identity_hash.copied().unwrap_or([0u8; 16]), identity_known, is_throttled, access_allowed, @@ -457,8 +465,9 @@ impl PropagationRequestHandler { } /// Handle a `/get` request from a client downloading messages. Phase-2 - /// responses come back as a [`GetRequestAction::ServeFiles`] plan — the - /// embedder resolves it after releasing the node lock. + /// responses come back as a + /// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles) + /// plan — the embedder resolves it after releasing the node lock. /// /// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499. pub fn handle_message_get_request( @@ -717,6 +726,47 @@ mod tests { assert!(parse_pn_announce_data(&[]).is_none()); assert!(parse_pn_announce_data(&[0x91, 0xC2]).is_none()); assert!(parse_pn_announce_data(&[0x01]).is_none()); + + let non_map_metadata = rmpv::Value::Array(vec![ + rmpv::Value::Boolean(false), + rmpv::Value::from(1_777_716_440u64), + rmpv::Value::Boolean(true), + rmpv::Value::from(10_240), + rmpv::Value::from(10_240), + rmpv::Value::Array(vec![ + rmpv::Value::from(16), + rmpv::Value::from(3), + rmpv::Value::from(18), + ]), + rmpv::Value::Array(Vec::new()), + ]); + assert!( + parse_pn_announce_data(&crate::encode_value(&non_map_metadata)).is_none(), + "Python rejects propagation announces whose metadata is not a map" + ); + } + + #[test] + fn test_pn_announce_data_rejects_wrapping_policy_values() { + use rmpv::Value; + + let encode = |transfer_limit: Value, stamp_cost: Value| { + let value = Value::Array(vec![ + Value::Boolean(false), + Value::from(1_777_716_440u64), + Value::Boolean(true), + transfer_limit, + Value::from(10240), + Value::Array(vec![stamp_cost, Value::from(3), Value::from(18)]), + Value::Map(vec![]), + ]); + let mut packed = Vec::new(); + rmpv::encode::write_value(&mut packed, &value).unwrap(); + packed + }; + + assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none()); + assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none()); } #[test] @@ -804,6 +854,18 @@ mod tests { ); } + #[test] + fn test_display_name_from_app_data_sanitizes_untrusted_unicode() { + let packed = get_announce_app_data( + Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "), + Some(12), + ); + assert_eq!( + display_name_from_app_data(&packed), + Some("AliceNetwork".to_string()) + ); + } + #[test] fn test_stamp_cost_from_app_data() { let packed = get_announce_app_data(Some("Alice"), Some(12)); diff --git a/crates/lxmf-core/src/inbound_resource.rs b/crates/lxmf-core/src/inbound_resource.rs new file mode 100644 index 0000000..d928645 --- /dev/null +++ b/crates/lxmf-core/src/inbound_resource.rs @@ -0,0 +1,484 @@ +//! Actor-owned tracking for inbound LXMF delivery Resources. +//! +//! The Reticulum runtime owns the actual transfers. Embedders project its +//! lifecycle notifications into [`InboundResourceEvent`] and forward bounded +//! [`InboundResourceCancelRequest`] values back to that owner. This keeps the +//! public LXMF API independent of a concrete Reticulum runtime while retaining +//! exact `(link_id, logical_resource_id)` cancellation authority. + +use std::collections::HashMap; + +use tokio::sync::{mpsc, watch}; + +/// Exact owner key for one logical inbound Resource. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct InboundResourceKey { + pub link_id: [u8; 16], + pub resource_id: [u8; 32], +} + +impl InboundResourceKey { + pub const fn new(link_id: [u8; 16], resource_id: [u8; 32]) -> Self { + Self { + link_id, + resource_id, + } + } +} + +/// Terminal result of an inbound Resource transfer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InboundResourceConclusion { + Complete, + Cancelled, + Rejected, + Failed, +} + +/// Current public state of an inbound Resource. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InboundResourceStatus { + Receiving, + Complete, + Cancelled, + Rejected, + Failed, +} + +impl InboundResourceStatus { + pub const fn is_closed(self) -> bool { + !matches!(self, Self::Receiving) + } +} + +impl From for InboundResourceStatus { + fn from(value: InboundResourceConclusion) -> Self { + match value { + InboundResourceConclusion::Complete => Self::Complete, + InboundResourceConclusion::Cancelled => Self::Cancelled, + InboundResourceConclusion::Rejected => Self::Rejected, + InboundResourceConclusion::Failed => Self::Failed, + } + } +} + +/// Owned, non-sensitive snapshot of one inbound transfer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InboundResourceSnapshot { + pub key: InboundResourceKey, + pub data_size: usize, + pub transferred: usize, + pub total_segments: usize, + pub status: InboundResourceStatus, +} + +impl InboundResourceSnapshot { + pub const fn is_closed(&self) -> bool { + self.status.is_closed() + } +} + +/// Transport-neutral lifecycle input consumed by [`InboundResourceTracker`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum InboundResourceEvent { + Started { + key: InboundResourceKey, + data_size: usize, + total_segments: usize, + }, + Progress { + key: InboundResourceKey, + transferred: usize, + total: usize, + }, + Concluded { + key: InboundResourceKey, + conclusion: InboundResourceConclusion, + }, + LinkClosed { + link_id: [u8; 16], + }, +} + +/// Exact cancellation request for the embedding runtime's Resource owner. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InboundResourceCancelRequest { + key: InboundResourceKey, +} + +impl InboundResourceCancelRequest { + pub const fn new(key: InboundResourceKey) -> Self { + Self { key } + } + + pub const fn key(self) -> InboundResourceKey { + self.key + } +} + +/// Cloneable live handle retained by a caller after the active list changes. +#[derive(Debug, Clone)] +pub struct InboundResourceHandle { + key: InboundResourceKey, + snapshot_rx: watch::Receiver, + cancel_tx: Option>, +} + +impl InboundResourceHandle { + pub const fn key(&self) -> InboundResourceKey { + self.key + } + + pub fn snapshot(&self) -> InboundResourceSnapshot { + self.snapshot_rx.borrow().clone() + } + + /// Wait for the next lifecycle/progress update. + /// + /// Returns `None` after the terminal snapshot has been published and the + /// actor owner has dropped its sender. + pub async fn changed(&mut self) -> Option { + if self.snapshot_rx.changed().await.is_err() { + return None; + } + Some(self.snapshot()) + } + + /// Queue exact inbound cancellation without blocking the actor owner. + /// + /// `false` means the transfer is already closed, cancellation is not + /// wired by the embedder, or the bounded command channel cannot accept the + /// request. Authoritative closure arrives through the lifecycle stream. + pub fn cancel(&self) -> bool { + if self.snapshot().is_closed() { + return false; + } + self.cancel_tx.as_ref().is_some_and(|tx| { + tx.try_send(InboundResourceCancelRequest::new(self.key)) + .is_ok() + }) + } +} + +struct ActiveInboundResource { + snapshot_tx: watch::Sender, +} + +/// Single-owner active Resource registry. +/// +/// Terminal records are removed immediately, so the registry is bounded by +/// concurrent transfers. Previously returned handles retain the final owned +/// snapshot without keeping actor state alive. +#[derive(Default)] +pub struct InboundResourceTracker { + active: HashMap, + cancel_tx: Option>, +} + +impl InboundResourceTracker { + pub fn new(cancel_tx: mpsc::Sender) -> Self { + Self { + active: HashMap::new(), + cancel_tx: Some(cancel_tx), + } + } + + pub fn set_cancel_sender(&mut self, cancel_tx: mpsc::Sender) { + self.cancel_tx = Some(cancel_tx); + } + + /// Number of currently active inbound Resources. + pub fn inbound_count(&self) -> usize { + self.active.len() + } + + /// Deterministic snapshot of all active Resource handles. + pub fn inbound_resources(&self) -> Vec { + let mut keys = self.active.keys().copied().collect::>(); + keys.sort_unstable(); + keys.into_iter() + .filter_map(|key| self.handle_for(key)) + .collect() + } + + /// Return the active Resource matching `resource_id`. + /// + /// A cryptographic ID collision across two Links fails closed instead of + /// choosing the wrong cancellation authority. + pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option { + let mut matches = self + .active + .keys() + .filter(|key| &key.resource_id == resource_id) + .copied(); + let key = matches.next()?; + if matches.next().is_some() { + return None; + } + self.handle_for(key) + } + + /// Return one exact active Resource. + pub fn inbound_resource_exact(&self, key: InboundResourceKey) -> Option { + self.handle_for(key) + } + + /// Queue cancellation for one unique active logical Resource. + pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool { + self.inbound_resource(resource_id) + .is_some_and(|handle| handle.cancel()) + } + + /// Queue cancellation for one exact active Resource. + pub fn cancel_inbound_exact(&self, key: InboundResourceKey) -> bool { + self.handle_for(key).is_some_and(|handle| handle.cancel()) + } + + /// Queue cancellation for a stable snapshot of every active Resource. + /// + /// The returned count is the number accepted by the bounded command + /// channel, matching Python's count-oriented `cancel_all_inbound` API. + pub fn cancel_all_inbound(&self) -> usize { + self.inbound_resources() + .into_iter() + .filter(InboundResourceHandle::cancel) + .count() + } + + /// Apply one lifecycle update from the embedding runtime. + pub fn handle_event(&mut self, event: InboundResourceEvent) { + match event { + InboundResourceEvent::Started { + key, + data_size, + total_segments, + } => self.started(key, data_size, total_segments), + InboundResourceEvent::Progress { + key, + transferred, + total, + } => self.progress(key, transferred, total), + InboundResourceEvent::Concluded { key, conclusion } => self.concluded(key, conclusion), + InboundResourceEvent::LinkClosed { link_id } => self.link_closed(link_id), + } + } + + fn handle_for(&self, key: InboundResourceKey) -> Option { + let active = self.active.get(&key)?; + Some(InboundResourceHandle { + key, + snapshot_rx: active.snapshot_tx.subscribe(), + cancel_tx: self.cancel_tx.clone(), + }) + } + + fn started(&mut self, key: InboundResourceKey, data_size: usize, total_segments: usize) { + if let Some(active) = self.active.get(&key) { + let mut snapshot = active.snapshot_tx.borrow().clone(); + snapshot.data_size = snapshot.data_size.max(data_size); + snapshot.total_segments = snapshot.total_segments.max(total_segments.max(1)); + active.snapshot_tx.send_replace(snapshot); + return; + } + + let snapshot = InboundResourceSnapshot { + key, + data_size, + transferred: 0, + total_segments: total_segments.max(1), + status: InboundResourceStatus::Receiving, + }; + let (snapshot_tx, _snapshot_rx) = watch::channel(snapshot); + self.active + .insert(key, ActiveInboundResource { snapshot_tx }); + } + + fn progress(&mut self, key: InboundResourceKey, transferred: usize, total: usize) { + let Some(active) = self.active.get(&key) else { + return; + }; + let mut snapshot = active.snapshot_tx.borrow().clone(); + snapshot.data_size = snapshot.data_size.max(total); + snapshot.transferred = transferred.min(snapshot.data_size); + active.snapshot_tx.send_replace(snapshot); + } + + fn concluded(&mut self, key: InboundResourceKey, conclusion: InboundResourceConclusion) { + let Some(active) = self.active.remove(&key) else { + return; + }; + let mut snapshot = active.snapshot_tx.borrow().clone(); + snapshot.status = conclusion.into(); + if conclusion == InboundResourceConclusion::Complete { + snapshot.transferred = snapshot.data_size; + } + active.snapshot_tx.send_replace(snapshot); + } + + fn link_closed(&mut self, link_id: [u8; 16]) { + let keys = self + .active + .keys() + .filter(|key| key.link_id == link_id) + .copied() + .collect::>(); + for key in keys { + self.concluded(key, InboundResourceConclusion::Failed); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(link: u8, resource: u8) -> InboundResourceKey { + InboundResourceKey::new([link; 16], [resource; 32]) + } + + fn started(key: InboundResourceKey, size: usize) -> InboundResourceEvent { + InboundResourceEvent::Started { + key, + data_size: size, + total_segments: 1, + } + } + + #[tokio::test] + async fn active_handle_tracks_progress_and_terminal_snapshot() { + let (cancel_tx, _cancel_rx) = mpsc::channel(4); + let mut tracker = InboundResourceTracker::new(cancel_tx); + let resource = key(1, 2); + + tracker.handle_event(started(resource, 100)); + let mut handle = tracker.inbound_resource(&resource.resource_id).unwrap(); + assert_eq!(tracker.inbound_count(), 1); + assert_eq!(handle.snapshot().transferred, 0); + + tracker.handle_event(InboundResourceEvent::Progress { + key: resource, + transferred: 40, + total: 100, + }); + assert_eq!(handle.changed().await.unwrap().transferred, 40); + + tracker.handle_event(InboundResourceEvent::Concluded { + key: resource, + conclusion: InboundResourceConclusion::Complete, + }); + let terminal = handle.changed().await.unwrap(); + assert_eq!(terminal.status, InboundResourceStatus::Complete); + assert_eq!(terminal.transferred, 100); + assert!(terminal.is_closed()); + assert_eq!(tracker.inbound_count(), 0); + assert!(!handle.cancel()); + assert!(handle.changed().await.is_none()); + } + + #[test] + fn cancellation_is_exact_bounded_and_snapshot_based() { + let (cancel_tx, mut cancel_rx) = mpsc::channel(2); + let mut tracker = InboundResourceTracker::new(cancel_tx); + let first = key(1, 3); + let second = key(2, 4); + tracker.handle_event(started(first, 10)); + tracker.handle_event(started(second, 20)); + + assert!(tracker.cancel_inbound(&first.resource_id)); + assert_eq!(cancel_rx.try_recv().unwrap().key(), first); + assert_eq!(tracker.cancel_all_inbound(), 2); + assert_eq!(cancel_rx.try_recv().unwrap().key(), first); + assert_eq!(cancel_rx.try_recv().unwrap().key(), second); + assert!(!tracker.cancel_inbound(&[9; 32])); + } + + #[test] + fn full_cancel_channel_fails_without_removing_active_state() { + let (cancel_tx, _cancel_rx) = mpsc::channel(1); + let mut tracker = InboundResourceTracker::new(cancel_tx); + let first = key(1, 5); + let second = key(1, 6); + tracker.handle_event(started(first, 10)); + tracker.handle_event(started(second, 10)); + + assert!(tracker.cancel_inbound_exact(first)); + assert!(!tracker.cancel_inbound_exact(second)); + assert_eq!(tracker.inbound_count(), 2); + } + + #[test] + fn duplicate_start_preserves_one_logical_handle() { + let (cancel_tx, _cancel_rx) = mpsc::channel(2); + let mut tracker = InboundResourceTracker::new(cancel_tx); + let split = key(3, 7); + tracker.handle_event(InboundResourceEvent::Started { + key: split, + data_size: 100, + total_segments: 3, + }); + tracker.handle_event(InboundResourceEvent::Started { + key: split, + data_size: 100, + total_segments: 3, + }); + + assert_eq!(tracker.inbound_count(), 1); + let snapshot = tracker.inbound_resource_exact(split).unwrap().snapshot(); + assert_eq!(snapshot.total_segments, 3); + } + + #[test] + fn rejected_or_unknown_resources_never_become_visible() { + let mut tracker = InboundResourceTracker::default(); + let unknown = key(4, 8); + tracker.handle_event(InboundResourceEvent::Progress { + key: unknown, + transferred: 5, + total: 10, + }); + tracker.handle_event(InboundResourceEvent::Concluded { + key: unknown, + conclusion: InboundResourceConclusion::Rejected, + }); + assert_eq!(tracker.inbound_count(), 0); + } + + #[tokio::test] + async fn link_close_fails_only_resources_owned_by_that_link() { + let mut tracker = InboundResourceTracker::default(); + let closed = key(5, 9); + let retained = key(6, 10); + tracker.handle_event(started(closed, 10)); + tracker.handle_event(started(retained, 20)); + let mut closed_handle = tracker.inbound_resource_exact(closed).unwrap(); + + tracker.handle_event(InboundResourceEvent::LinkClosed { + link_id: closed.link_id, + }); + assert_eq!( + closed_handle.changed().await.unwrap().status, + InboundResourceStatus::Failed + ); + assert!(tracker.inbound_resource_exact(closed).is_none()); + assert!(tracker.inbound_resource_exact(retained).is_some()); + } + + #[test] + fn cancel_then_complete_is_terminal_and_not_requeued() { + let (cancel_tx, mut cancel_rx) = mpsc::channel(2); + let mut tracker = InboundResourceTracker::new(cancel_tx); + let resource = key(7, 11); + tracker.handle_event(started(resource, 10)); + let handle = tracker.inbound_resource_exact(resource).unwrap(); + + assert!(handle.cancel()); + assert_eq!(cancel_rx.try_recv().unwrap().key(), resource); + tracker.handle_event(InboundResourceEvent::Concluded { + key: resource, + conclusion: InboundResourceConclusion::Complete, + }); + assert_eq!(handle.snapshot().status, InboundResourceStatus::Complete); + assert!(!handle.cancel()); + assert_eq!(tracker.inbound_count(), 0); + } +} diff --git a/crates/lxmf-core/src/lib.rs b/crates/lxmf-core/src/lib.rs index 862660b..47b14bf 100644 --- a/crates/lxmf-core/src/lib.rs +++ b/crates/lxmf-core/src/lib.rs @@ -13,6 +13,8 @@ //! | --------------------- | -------------------------------------------------- | //! | [`message`] | Message object: fields, packing, stamp, encryption | //! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction | +//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation | +//! | [`presentation`] | Safe bounded presentation of untrusted names | //! | [`router`] | Actor-driven routing and delivery state machine | //! | [`peer`] | Propagation-peer state and sync bookkeeping | //! | [`propagation`] | On-disk store-and-forward message pool | @@ -45,13 +47,17 @@ pub mod constants; pub mod delivery_ratchet; pub mod discovery_stamper; pub mod handlers; +pub mod inbound_resource; pub mod link_delivery; pub mod message; pub mod peer; pub mod persist; +pub mod presentation; pub mod propagation; +pub mod propagation_admission; pub mod propagation_client; pub mod propagation_node; +pub mod propagation_offer; pub mod propagation_sync; pub mod router; pub mod stamper; diff --git a/crates/lxmf-core/src/link_delivery.rs b/crates/lxmf-core/src/link_delivery.rs index fc12604..d9988d2 100644 --- a/crates/lxmf-core/src/link_delivery.rs +++ b/crates/lxmf-core/src/link_delivery.rs @@ -3157,6 +3157,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: proof_raw.into(), interface_id: 0, + metrics: Default::default(), }) .unwrap(); mgr.drain_events(&HashMap::new()); @@ -3780,6 +3781,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: raw.clone(), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -3850,6 +3852,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: raw.clone(), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -4279,6 +4282,7 @@ mod tests { &close_body, ), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -4320,6 +4324,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -4411,6 +4416,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: proof_raw.into(), interface_id: 0, + metrics: Default::default(), }) .unwrap(); mgr.drain_events(&HashMap::new()); @@ -4460,6 +4466,7 @@ mod tests { &close_body, ), interface_id: 0, + metrics: Default::default(), }) .unwrap(); diff --git a/crates/lxmf-core/src/peer.rs b/crates/lxmf-core/src/peer.rs index dd9ab54..20ba4aa 100644 --- a/crates/lxmf-core/src/peer.rs +++ b/crates/lxmf-core/src/peer.rs @@ -2,12 +2,15 @@ //! //! Python reference: LXMF/LXMPeer.py. +use std::collections::{HashMap, HashSet}; use std::time::{SystemTime, UNIX_EPOCH}; +use serde::{Deserialize, Serialize}; + use crate::constants::*; use crate::types::PropagationTransientId; -type StoredPeer = ( +type LegacyStoredPeer = ( Vec, f64, u32, @@ -19,6 +22,133 @@ type StoredPeer = ( Vec>, ); +const STORED_PEER_VERSION: u8 = 2; +const MAX_PEER_METADATA_ENTRIES: usize = 16; +const MAX_PEER_METADATA_VALUE_BYTES: usize = 1024; +const MAX_PEER_METADATA_BYTES: usize = 4096; + +fn bounded_peer_metadata(metadata: Option>>) -> Option>> { + let metadata = metadata?; + let mut entries = metadata.into_iter().collect::>(); + entries.sort_by_key(|(key, _)| *key); + + let mut retained = HashMap::new(); + let mut retained_bytes = 0usize; + for (key, value) in entries.into_iter().take(MAX_PEER_METADATA_ENTRIES) { + if value.len() > MAX_PEER_METADATA_VALUE_BYTES { + continue; + } + let entry_bytes = 1usize.saturating_add(value.len()); + if retained_bytes.saturating_add(entry_bytes) > MAX_PEER_METADATA_BYTES { + continue; + } + retained_bytes += entry_bytes; + retained.insert(key, value); + } + + Some(retained) +} + +/// Versioned peer persistence used by propagation sync. +/// +/// The original Rust format was a nine-element tuple. Readers continue to +/// accept that tuple, while new writes retain the announce-derived policy +/// needed to prepare a correct outbound offer after restart. +#[derive(Debug, Serialize, Deserialize)] +struct StoredPeerV2 { + version: u8, + destination_hash: Vec, + last_sync: f64, + unreachable_count: u32, + peering_cost: u8, + stamp_cost: Option, + stamp_cost_flexibility: Option, + autopeered: bool, + is_static: bool, + handled_ids: Vec>, + peering_timebase: f64, + propagation_transfer_limit: Option, + propagation_sync_limit: Option, + peering_key: Option<(Vec, u32)>, + metadata: Option>>, + last_heard: f64, + alive: bool, +} + +/// Immutable inputs for one outbound propagation offer. +/// +/// `LxmPeer` remains the authoritative mutable owner. The network task gets a +/// clone of this snapshot so offer selection cannot silently fall back to a +/// newly-created peer that lacks announce or handled-message state. +#[derive(Debug, Clone, PartialEq)] +pub struct OutboundOfferPolicy { + pub peer_hash: [u8; 16], + pub handled_messages: HashSet, + pub stamp_cost: Option, + pub stamp_cost_flexibility: Option, + pub minimum_stamp_cost: u8, + pub peering_cost: u8, + pub propagation_transfer_limit: Option, + pub propagation_sync_limit: Option, + pub peering_key: Vec, + pub peering_key_value: Option, + pub peering_timebase: f64, + pub autopeered: bool, + pub is_static: bool, + pub metadata: Option>>, +} + +impl OutboundOfferPolicy { + /// Compatibility policy for callers that only know a peer hash. + /// + /// This preserves the old unbounded selection behavior. Production + /// callers should construct a snapshot from the authoritative `LxmPeer`. + pub fn unrestricted(peer_hash: [u8; 16]) -> Self { + Self { + peer_hash, + handled_messages: HashSet::new(), + stamp_cost: None, + stamp_cost_flexibility: None, + minimum_stamp_cost: 0, + peering_cost: PEERING_COST, + propagation_transfer_limit: None, + propagation_sync_limit: None, + peering_key: Vec::new(), + peering_key_value: None, + peering_timebase: 0.0, + autopeered: false, + is_static: false, + metadata: None, + } + } + + pub(crate) fn to_peer(&self) -> LxmPeer { + let mut peer = LxmPeer::new(self.peer_hash); + self.apply_to_peer(&mut peer); + peer + } + + pub(crate) fn apply_to_peer(&self, peer: &mut LxmPeer) { + if self.peering_timebase >= peer.peering_timebase { + peer.peering_timebase = self.peering_timebase; + peer.stamp_cost = self.stamp_cost; + peer.stamp_cost_flexibility = self.stamp_cost_flexibility; + peer.peering_cost = self.peering_cost; + peer.propagation_transfer_limit = self.propagation_transfer_limit; + peer.propagation_sync_limit = self.propagation_sync_limit; + peer.peering_key = self.peering_key_value.and_then(|value| { + let stamp: [u8; 32] = self.peering_key.clone().try_into().ok()?; + Some((stamp, value)) + }); + peer.autopeered = self.autopeered; + peer.is_static = self.is_static; + peer.metadata = self.metadata.clone(); + } + peer.handled_messages + .extend(self.handled_messages.iter().copied()); + } +} + /// An LXMF peer propagation node. #[derive(Debug)] pub struct LxmPeer { @@ -58,11 +188,15 @@ pub struct LxmPeer { pub last_sync_attempt: f64, pub next_sync_attempt: f64, pub sync_backoff: f64, - pub metadata: Option>, + pub metadata: Option>>, + /// Last local propagation-store revision conclusively processed by this + /// peer. This is intentionally process-local because node revisions reset + /// when the store is reconstructed at startup. + pub last_offer_generation: u64, /// Static peers are operator-configured; autopeered peers come from announces. pub is_static: bool, /// Message hashes already handled by this peer, for sync filtering. - pub handled_messages: std::collections::HashSet, + pub handled_messages: HashSet, } impl LxmPeer { @@ -100,8 +234,9 @@ impl LxmPeer { next_sync_attempt: 0.0, sync_backoff: 0.0, metadata: None, + last_offer_generation: 0, is_static: false, - handled_messages: std::collections::HashSet::new(), + handled_messages: HashSet::new(), } } @@ -118,18 +253,115 @@ impl LxmPeer { stamp_cost: Option, stamp_flexibility: Option, peering_cost: Option, + ) -> Self { + Self::from_announce_with_metadata( + destination_hash, + timebase, + transfer_limit, + sync_limit, + stamp_cost, + stamp_flexibility, + peering_cost, + None, + ) + } + + /// Construct a peer from announce data, retaining bounded metadata. + #[allow(clippy::too_many_arguments)] + pub fn from_announce_with_metadata( + destination_hash: [u8; 16], + timebase: f64, + transfer_limit: Option, + sync_limit: Option, + stamp_cost: Option, + stamp_flexibility: Option, + peering_cost: Option, + metadata: Option>>, ) -> Self { let mut peer = Self::new(destination_hash); peer.peering_timebase = timebase; peer.propagation_transfer_limit = transfer_limit; - peer.propagation_sync_limit = sync_limit; + peer.propagation_sync_limit = sync_limit.or(transfer_limit); peer.stamp_cost = stamp_cost; peer.stamp_cost_flexibility = stamp_flexibility; peer.peering_cost = peering_cost.unwrap_or(PEERING_COST); + peer.metadata = bounded_peer_metadata(metadata); peer.autopeered = true; peer } + /// Refresh announce-derived policy only when `timebase` is newer. + /// + /// Returns `true` when the peer was updated. Runtime counters, handled + /// messages and static-peer status remain owned by the existing peer. + #[allow(clippy::too_many_arguments)] + pub fn refresh_from_announce( + &mut self, + timebase: f64, + transfer_limit: Option, + sync_limit: Option, + stamp_cost: Option, + stamp_flexibility: Option, + peering_cost: Option, + ) -> bool { + let metadata = self.metadata.clone(); + self.refresh_from_announce_with_metadata( + timebase, + transfer_limit, + sync_limit, + stamp_cost, + stamp_flexibility, + peering_cost, + metadata, + ) + } + + /// Refresh announce-derived policy and bounded metadata only when newer. + #[allow(clippy::too_many_arguments)] + pub fn refresh_from_announce_with_metadata( + &mut self, + timebase: f64, + transfer_limit: Option, + sync_limit: Option, + stamp_cost: Option, + stamp_flexibility: Option, + peering_cost: Option, + metadata: Option>>, + ) -> bool { + if timebase <= self.peering_timebase { + return false; + } + + let offer_constraints_changed = self.propagation_transfer_limit != transfer_limit + || self.propagation_sync_limit != sync_limit.or(transfer_limit) + || self.stamp_cost != stamp_cost + || self.stamp_cost_flexibility != stamp_flexibility + || self.peering_cost != peering_cost.unwrap_or(PEERING_COST); + self.peering_timebase = timebase; + self.propagation_transfer_limit = transfer_limit; + self.propagation_sync_limit = sync_limit.or(transfer_limit); + self.stamp_cost = stamp_cost; + self.stamp_cost_flexibility = stamp_flexibility; + self.peering_cost = peering_cost.unwrap_or(PEERING_COST); + self.metadata = bounded_peer_metadata(metadata); + if offer_constraints_changed { + self.last_offer_generation = 0; + } + + // A key remains usable when it still meets the new target. Otherwise + // the daemon must generate a replacement before taking a snapshot. + if self + .peering_key + .is_some_and(|(_, value)| value < self.peering_cost as u32) + { + self.peering_key = None; + } + + self.heard(); + self.next_sync_attempt = 0.0; + true + } + /// Effective minimum stamp cost this peer will accept, using the peer's /// announced flexibility when known (Python `LXMPeer.sync`: cost - flex). pub fn minimum_accepted_stamp_cost(&self) -> u8 { @@ -145,6 +377,11 @@ impl LxmPeer { self.stamp_cost.is_some() && self.stamp_cost_flexibility.is_some() } + /// Snapshot the complete immutable policy for one outbound sync offer. + pub fn outbound_offer_policy(&self) -> OutboundOfferPolicy { + OutboundOfferPolicy::from(self) + } + pub fn add_unhandled_message(&mut self) { self.unhandled_count_cached = false; self.unhandled_count += 1; @@ -174,27 +411,50 @@ impl LxmPeer { self.handled_messages.contains(hash) } + pub fn needs_offer_generation(&self, generation: u64) -> bool { + generation > self.last_offer_generation + } + + pub fn mark_offer_generation_processed(&mut self, generation: u64) { + self.last_offer_generation = self.last_offer_generation.max(generation); + } + /// Serialize peer state, including handled messages, for persistence. pub fn to_bytes_with_handled(&self) -> Vec { - let handled: Vec> = self.handled_messages.iter().map(|h| h.to_vec()).collect(); - let data = ( - self.destination_hash.to_vec(), - self.last_sync, - self.unreachable_count, - self.peering_cost, - self.stamp_cost, - self.stamp_cost_flexibility, - self.autopeered, - self.is_static, - handled, - ); - rmp_serde::to_vec(&data).unwrap_or_default() + let mut handled: Vec> = self.handled_messages.iter().map(|h| h.to_vec()).collect(); + handled.sort(); + let data = StoredPeerV2 { + version: STORED_PEER_VERSION, + destination_hash: self.destination_hash.to_vec(), + last_sync: self.last_sync, + unreachable_count: self.unreachable_count, + peering_cost: self.peering_cost, + stamp_cost: self.stamp_cost, + stamp_cost_flexibility: self.stamp_cost_flexibility, + autopeered: self.autopeered, + is_static: self.is_static, + handled_ids: handled, + peering_timebase: self.peering_timebase, + propagation_transfer_limit: self.propagation_transfer_limit, + propagation_sync_limit: self.propagation_sync_limit, + peering_key: self + .peering_key + .map(|(stamp, value)| (stamp.to_vec(), value)), + metadata: self.metadata.clone(), + last_heard: self.last_heard, + alive: self.alive, + }; + rmp_serde::to_vec_named(&data).unwrap_or_default() } /// Deserialize peer state, including handled messages, from [`to_bytes_with_handled`] output. /// /// [`to_bytes_with_handled`]: Self::to_bytes_with_handled pub fn from_bytes_with_handled(data: &[u8]) -> Option { + if let Ok(stored) = rmp_serde::from_slice::(data) { + return Self::from_stored_v2(stored); + } + let ( dest_hash_vec, last_sync, @@ -205,7 +465,7 @@ impl LxmPeer { autopeered, is_static, handled_vec, - ): StoredPeer = rmp_serde::from_slice(data).ok()?; + ): LegacyStoredPeer = rmp_serde::from_slice(data).ok()?; if dest_hash_vec.len() != 16 { return None; } @@ -234,6 +494,39 @@ impl LxmPeer { Some(peer) } + fn from_stored_v2(stored: StoredPeerV2) -> Option { + if stored.version != STORED_PEER_VERSION || stored.destination_hash.len() != 16 { + return None; + } + + let mut destination_hash = [0u8; 16]; + destination_hash.copy_from_slice(&stored.destination_hash); + let mut peer = Self::new(destination_hash); + peer.last_sync = stored.last_sync; + peer.unreachable_count = stored.unreachable_count; + peer.peering_cost = stored.peering_cost; + peer.stamp_cost = stored.stamp_cost; + peer.stamp_cost_flexibility = stored.stamp_cost_flexibility; + peer.autopeered = stored.autopeered; + peer.is_static = stored.is_static; + peer.peering_timebase = stored.peering_timebase; + peer.propagation_transfer_limit = stored.propagation_transfer_limit; + peer.propagation_sync_limit = stored.propagation_sync_limit; + peer.peering_key = stored.peering_key.and_then(|(stamp, value)| { + let stamp: [u8; 32] = stamp.try_into().ok()?; + Some((stamp, value)) + }); + peer.metadata = stored.metadata; + peer.last_heard = stored.last_heard; + peer.alive = stored.alive; + peer.handled_messages = stored + .handled_ids + .into_iter() + .filter_map(|value| value.try_into().ok()) + .collect(); + Some(peer) + } + pub fn mark_unreachable(&mut self) { self.unreachable_count += 1; let now = now_f64(); @@ -375,6 +668,32 @@ impl LxmPeer { } } +impl From<&LxmPeer> for OutboundOfferPolicy { + fn from(peer: &LxmPeer) -> Self { + let peering_key = peer + .peering_key + .filter(|(_, value)| *value >= peer.peering_cost as u32) + .map(|(stamp, _)| stamp.to_vec()) + .unwrap_or_default(); + Self { + peer_hash: peer.destination_hash, + handled_messages: peer.handled_messages.clone(), + stamp_cost: peer.stamp_cost, + stamp_cost_flexibility: peer.stamp_cost_flexibility, + minimum_stamp_cost: peer.minimum_accepted_stamp_cost(), + peering_cost: peer.peering_cost, + propagation_transfer_limit: peer.propagation_transfer_limit, + propagation_sync_limit: peer.propagation_sync_limit, + peering_key, + peering_key_value: peer.peering_key.map(|(_, value)| value), + peering_timebase: peer.peering_timebase, + autopeered: peer.autopeered, + is_static: peer.is_static, + metadata: peer.metadata.clone(), + } + } +} + /// Select the best peer to sync with from a set of candidates. /// /// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers, @@ -477,6 +796,157 @@ mod tests { assert_eq!(peer.minimum_accepted_stamp_cost(), 16); } + #[test] + fn outbound_offer_policy_captures_authoritative_peer_state() { + let mut peer = LxmPeer::new([0xAA; 16]); + peer.stamp_cost = Some(16); + peer.stamp_cost_flexibility = Some(3); + peer.propagation_transfer_limit = Some(1.5); + peer.propagation_sync_limit = Some(4.5); + peer.peering_cost = 18; + peer.peering_key = Some(([0x77; 32], 18)); + peer.add_handled_message(&tid(0x11)); + + let policy = peer.outbound_offer_policy(); + + assert_eq!(policy.peer_hash, [0xAA; 16]); + assert_eq!(policy.minimum_stamp_cost, 13); + assert_eq!(policy.propagation_transfer_limit, Some(1.5)); + assert_eq!(policy.propagation_sync_limit, Some(4.5)); + assert_eq!(policy.peering_key, vec![0x77; 32]); + assert!(policy.handled_messages.contains(&tid(0x11))); + } + + #[test] + fn stale_announce_cannot_overwrite_newer_peer_policy() { + let mut peer = LxmPeer::from_announce( + [0xAA; 16], + 200.0, + Some(2.0), + Some(8.0), + Some(16), + Some(3), + Some(18), + ); + + assert!(!peer.refresh_from_announce( + 199.0, + Some(1.0), + Some(4.0), + Some(8), + Some(1), + Some(4), + )); + assert_eq!(peer.peering_timebase, 200.0); + assert_eq!(peer.propagation_transfer_limit, Some(2.0)); + assert_eq!(peer.stamp_cost, Some(16)); + + peer.peering_key = Some(([0x55; 32], 18)); + assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),)); + assert_eq!(peer.propagation_sync_limit, Some(3.0)); + assert_eq!(peer.stamp_cost, Some(20)); + assert!(peer.peering_key.is_none(), "under-cost key must be cleared"); + } + + #[test] + fn peer_persistence_retains_offer_policy_and_reads_legacy_tuple() { + let mut peer = LxmPeer::from_announce( + [0xAA; 16], + 1234.0, + Some(1.25), + Some(9.5), + Some(16), + Some(3), + Some(18), + ); + peer.peering_key = Some(([0x66; 32], 19)); + peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])])); + peer.add_handled_message(&tid(0x22)); + + let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap(); + assert_eq!(restored.peering_timebase, 1234.0); + assert_eq!(restored.propagation_transfer_limit, Some(1.25)); + assert_eq!(restored.propagation_sync_limit, Some(9.5)); + assert_eq!(restored.peering_key, Some(([0x66; 32], 19))); + assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])]))); + assert!(restored.has_handled(&tid(0x22))); + + let legacy: LegacyStoredPeer = ( + vec![0xBB; 16], + 42.0, + 2, + 18, + Some(12), + Some(2), + true, + false, + vec![tid(0x33).to_vec()], + ); + let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap(); + let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap(); + assert_eq!(restored_legacy.destination_hash, [0xBB; 16]); + assert_eq!(restored_legacy.stamp_cost, Some(12)); + assert!(restored_legacy.has_handled(&tid(0x33))); + } + + #[test] + fn announce_metadata_is_typed_bounded_and_persisted() { + let mut metadata = HashMap::new(); + metadata.insert(0, b"node name".to_vec()); + metadata.insert(1, vec![0xAA; MAX_PEER_METADATA_VALUE_BYTES + 1]); + for key in 2..=30 { + metadata.insert(key, vec![key; 8]); + } + + let peer = LxmPeer::from_announce_with_metadata( + [0xAA; 16], + 10.0, + Some(1.0), + Some(2.0), + Some(12), + Some(3), + Some(18), + Some(metadata), + ); + let retained = peer.metadata.as_ref().unwrap(); + assert_eq!(retained.get(&0), Some(&b"node name".to_vec())); + assert!(!retained.contains_key(&1)); + assert!(retained.len() <= MAX_PEER_METADATA_ENTRIES); + + let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap(); + assert_eq!(restored.metadata, peer.metadata); + + let empty = LxmPeer::from_announce_with_metadata( + [0xBB; 16], + 10.0, + None, + None, + None, + None, + None, + Some(HashMap::new()), + ); + assert_eq!(empty.metadata, Some(HashMap::new())); + } + + #[test] + fn newer_policy_invalidates_processed_store_generation() { + let mut peer = + LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None); + peer.mark_offer_generation_processed(7); + assert!(!peer.needs_offer_generation(7)); + + assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None)); + assert!(peer.needs_offer_generation(7)); + + peer.mark_offer_generation_processed(7); + assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None)); + assert!( + !peer.needs_offer_generation(7), + "a newer announce with unchanged offer constraints must not rescan an unchanged store" + ); + } + /// T0-4: an absurd announce-supplied peering cost must fail the bounded /// key search instead of spinning forever; sane costs still succeed. #[test] diff --git a/crates/lxmf-core/src/persist.rs b/crates/lxmf-core/src/persist.rs index fc4567b..8d91bb7 100644 --- a/crates/lxmf-core/src/persist.rs +++ b/crates/lxmf-core/src/persist.rs @@ -23,6 +23,16 @@ pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs"; pub const TICKETS_FILE: &str = "available_tickets"; pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries"; pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed"; +pub const NODE_STATS_FILE: &str = "node_stats"; + +/// Counters persisted by Python's `LXMRouter.save_node_stats`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct PersistedNodeStats { + pub client_propagation_messages_received: u64, + pub client_propagation_messages_served: u64, + pub unpeered_propagation_incoming: u64, + pub unpeered_propagation_rx_bytes: u64, +} /// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename. /// @@ -78,10 +88,7 @@ fn write_mpk(path: &Path, value: &T) -> io::Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } - let tmp = path.with_extension("tmp"); - fs::write(&tmp, &bytes)?; - fs::rename(&tmp, path)?; - Ok(()) + write_file_atomic(path, &bytes) } fn read_mpk(path: &Path) -> io::Result> { @@ -134,6 +141,17 @@ pub fn load_locally_processed(dir: &Path) -> io::Result io::Result<()> { + let bytes = rmp_serde::to_vec_named(stats) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + fs::create_dir_all(dir)?; + write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes) +} + +pub fn load_node_stats(dir: &Path) -> io::Result { + Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default()) +} + #[cfg(test)] mod tests { use super::*; @@ -184,6 +202,37 @@ mod tests { assert!(load_tickets(tmp.path()).unwrap().is_empty()); assert!(load_local_deliveries(tmp.path()).unwrap().is_empty()); assert!(load_locally_processed(tmp.path()).unwrap().is_empty()); + assert_eq!( + load_node_stats(tmp.path()).unwrap(), + PersistedNodeStats::default() + ); + } + + #[test] + fn node_stats_roundtrip_uses_named_python_fields() { + let tmp = TempDir::new().unwrap(); + let expected = PersistedNodeStats { + client_propagation_messages_received: 11, + client_propagation_messages_served: 12, + unpeered_propagation_incoming: 13, + unpeered_propagation_rx_bytes: 14, + }; + + save_node_stats(tmp.path(), &expected).unwrap(); + assert_eq!(load_node_stats(tmp.path()).unwrap(), expected); + + let encoded = fs::read(tmp.path().join(NODE_STATS_FILE)).unwrap(); + let value = rmpv::decode::read_value(&mut std::io::Cursor::new(encoded)).unwrap(); + let keys = value + .as_map() + .unwrap() + .iter() + .filter_map(|(key, _)| key.as_str()) + .collect::>(); + assert!(keys.contains("client_propagation_messages_received")); + assert!(keys.contains("client_propagation_messages_served")); + assert!(keys.contains("unpeered_propagation_incoming")); + assert!(keys.contains("unpeered_propagation_rx_bytes")); } #[test] @@ -223,4 +272,63 @@ mod tests { .collect(); assert!(leftovers.is_empty()); } + + #[test] + fn serialization_failure_preserves_existing_file_without_temp_residue() { + struct FailsToSerialize; + + impl serde::Serialize for FailsToSerialize { + fn serialize(&self, _serializer: S) -> Result + where + S: serde::Serializer, + { + Err(serde::ser::Error::custom("intentional failure")) + } + } + + let tmp = TempDir::new().unwrap(); + let path = tmp.path().join("state"); + fs::write(&path, b"previous-good-state").unwrap(); + + assert!(write_mpk(&path, &FailsToSerialize).is_err()); + assert_eq!(fs::read(&path).unwrap(), b"previous-good-state"); + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1); + } + + #[test] + fn concurrent_atomic_writers_never_publish_torn_data_or_collide_on_temp_names() { + use std::sync::{Arc, Barrier}; + + let tmp = TempDir::new().unwrap(); + let path = Arc::new(tmp.path().join("shared")); + let barrier = Arc::new(Barrier::new(8)); + let payloads = (0u8..8) + .map(|value| vec![value; 16 * 1024]) + .collect::>(); + let threads = payloads + .iter() + .cloned() + .map(|payload| { + let path = Arc::clone(&path); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + write_file_atomic(path.as_ref(), &payload).unwrap(); + }) + }) + .collect::>(); + + for thread in threads { + thread.join().unwrap(); + } + + let published = fs::read(path.as_ref()).unwrap(); + assert!(payloads.contains(&published)); + let leftovers = fs::read_dir(tmp.path()) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().contains(".tmp.")) + .count(); + assert_eq!(leftovers, 0); + } } diff --git a/crates/lxmf-core/src/presentation.rs b/crates/lxmf-core/src/presentation.rs new file mode 100644 index 0000000..126e907 --- /dev/null +++ b/crates/lxmf-core/src/presentation.rs @@ -0,0 +1,157 @@ +//! Safe presentation helpers for untrusted announce metadata. + +use unicode_normalization::UnicodeNormalization; + +/// Maximum retained characters for an advertised LXMF display/node name. +pub const MAX_ADVERTISED_NAME_CHARS: usize = 128; + +/// Normalize and bound an untrusted display name. +/// +/// The result is NFKC-normalized, contains no control or presentation-control +/// codepoints, collapses all Unicode whitespace to one ASCII space, and is +/// truncated by Unicode scalar values rather than UTF-8 bytes. +pub fn sanitize_name(input: &str, max_chars: usize) -> String { + if max_chars == 0 { + return String::new(); + } + + let mut output = String::new(); + let mut pending_space = false; + let mut retained = 0usize; + + for character in input.nfkc() { + if is_filtered_name_character(character) { + continue; + } + if character.is_whitespace() { + pending_space = !output.is_empty(); + continue; + } + if pending_space { + // A collapsed separator is useful only when the current visible + // character also fits. Never consume the final slot with a + // trailing space that disappears on the next sanitization pass. + if max_chars.saturating_sub(retained) < 2 { + break; + } + output.push(' '); + retained += 1; + pending_space = false; + } + if retained == max_chars { + break; + } + output.push(character); + retained += 1; + } + + output +} + +fn is_filtered_name_character(character: char) -> bool { + let codepoint = character as u32; + character.is_control() + || is_bidi_control(codepoint) + || is_private_use(codepoint) + || is_zero_width(codepoint) + || is_variation_selector(codepoint) + || is_emoji(codepoint) +} + +fn is_bidi_control(codepoint: u32) -> bool { + matches!( + codepoint, + 0x061C + | 0x200E + | 0x200F + | 0x202A..=0x202E + | 0x2066..=0x2069 + | 0x206A..=0x206F + ) +} + +fn is_private_use(codepoint: u32) -> bool { + matches!( + codepoint, + 0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD + ) +} + +fn is_zero_width(codepoint: u32) -> bool { + matches!( + codepoint, + 0x034F | 0x180E | 0x200B..=0x200D | 0x2060 | 0xFEFF + ) +} + +fn is_variation_selector(codepoint: u32) -> bool { + matches!(codepoint, 0xFE00..=0xFE0F | 0xE0100..=0xE01EF) +} + +// Bounded presentation policy, intentionally broader than a font-dependent +// emoji lookup. It covers the Unicode emoji blocks and legacy symbol ranges +// that gain emoji presentation through variation selectors. +fn is_emoji(codepoint: u32) -> bool { + matches!( + codepoint, + 0x00A9 + | 0x00AE + | 0x203C + | 0x2049 + | 0x2122 + | 0x2139 + | 0x2190..=0x21FF + | 0x2300..=0x23FF + | 0x2460..=0x24FF + | 0x25A0..=0x27BF + | 0x2934..=0x2935 + | 0x2B00..=0x2BFF + | 0x3030 + | 0x303D + | 0x3297 + | 0x3299 + | 0x1F000..=0x1FAFF + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + #[test] + fn normalizes_nfkc_and_collapses_unicode_whitespace() { + assert_eq!( + sanitize_name(" RNS\u{00A0}\tCommunity ", 128), + "RNS Community" + ); + } + + #[test] + fn removes_controls_bidi_private_use_emoji_variants_and_zero_width() { + let hostile = "safe\n\u{202E}txt\u{E000}\u{1F680}\u{FE0F}\u{200D} name"; + assert_eq!(sanitize_name(hostile, 128), "safetxt name"); + } + + #[test] + fn truncates_multibyte_text_by_characters_without_panicking() { + assert_eq!(sanitize_name("Ångström東京", 8), "Ångström"); + assert_eq!(sanitize_name("東京通信", 3), "東京通"); + assert_eq!(sanitize_name("anything", 0), ""); + } + + #[test] + fn truncation_never_retains_a_separator_without_following_text() { + assert_eq!(sanitize_name("¡ A", 2), "¡"); + assert_eq!(sanitize_name("A B", 3), "A B"); + } + + proptest! { + #[test] + fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) { + let sanitized = sanitize_name(&input, limit); + prop_assert!(sanitized.chars().count() <= limit); + prop_assert_eq!(sanitize_name(&sanitized, limit), sanitized); + } + } +} diff --git a/crates/lxmf-core/src/propagation_admission.rs b/crates/lxmf-core/src/propagation_admission.rs new file mode 100644 index 0000000..3914cc4 --- /dev/null +++ b/crates/lxmf-core/src/propagation_admission.rs @@ -0,0 +1,1586 @@ +//! Pure admission and lifecycle accounting for inbound propagation-node syncs. +//! +//! Peering-key validation and Resource I/O deliberately live outside this +//! module. Callers first obtain a cheap [`PnOfferCandidate`] with +//! [`PnInboundAdmission::preflight_offer`], then validate the peering key and +//! determine the wanted response before calling +//! [`PnInboundAdmission::commit_validated_offer`]. Failed validation should +//! call [`PnInboundAdmission::discard_candidate`]; merely dropping a candidate +//! is also safe and is pruned on the next preflight. +//! +//! Every caller-supplied [`Duration`] for one coordinator instance must be +//! elapsed time from the same stable monotonic origin. Mixing origins or +//! supplying wall-clock values invalidates throttle-deadline ordering. + +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use rns_identity::destination::Destination; + +use crate::constants::PN_STAMP_THROTTLE; + +const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation"; + +/// Default maximum number of concurrently transferring or validating syncs. +pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3; +/// Smallest accepted configured inbound-sync limit. +pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1; +/// Duration applied after a known peer submits an invalid-stamp batch. +pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE); + +/// Policy applied to inbound propagation-node offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PnInboundAdmissionConfig { + /// Postpone non-bypassing offers while any stamp validation is active. + pub sequential_validation: bool, + /// Make static peers obey sequential validation and the inbound-sync cap. + /// + /// The LXMF default is `false`, so a configured static peer bypasses both + /// admission gates. + pub static_sequential: bool, + /// Maximum concurrent Resources in `Transferring` or `Validating` state. + pub max_inbound_syncs: usize, + /// Accept propagation offers only from configured static peers. + pub from_static_only: bool, +} + +impl Default for PnInboundAdmissionConfig { + fn default() -> Self { + Self { + sequential_validation: true, + static_sequential: false, + max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS, + from_static_only: false, + } + } +} + +/// The caller's already-computed wire response for an offer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnOfferResponse { + HaveAll, + WantAll, + WantSome, +} + +/// Why an otherwise well-formed offer was not admitted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnOfferRejection { + NoIdentity, + NoAccess, + InvalidStampThrottle, + SequentialValidationActive, + InboundSyncLimit, + LinkAlreadyTracked, + LinkCandidatePending, + StaleCandidate, +} + +/// Result of applying admission policy to an offer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnOfferAdmission { + /// The peer offered no messages that are wanted; no record was created. + HaveAll, + /// The wanted offer was recorded in [`PnInboundState::Accepted`]. + Accepted, + Rejected(PnOfferRejection), +} + +/// Opaque result of a successful cheap offer preflight. +/// +/// The candidate binds the actual link ID to the known peer identity and its +/// derived propagation destination. It is intentionally neither `Clone` nor +/// `Copy`: the validated commit consumes it, and callers cannot substitute a +/// different link or identity at that boundary. +#[must_use = "a preflight candidate must be externally validated or discarded"] +pub struct PnOfferCandidate { + link_id: [u8; 16], + peer_identity_hash: [u8; 16], + peer_destination_hash: [u8; 16], + lifecycle: Arc, +} + +struct PnOfferLifecycleToken; + +impl PnOfferCandidate { + pub fn link_id(&self) -> [u8; 16] { + self.link_id + } + + /// Raw identity hash used by the caller's external peering-key validator. + pub fn peer_identity_hash(&self) -> [u8; 16] { + self.peer_identity_hash + } + + pub fn peer_destination_hash(&self) -> [u8; 16] { + self.peer_destination_hash + } +} + +impl fmt::Debug for PnOfferCandidate { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("PnOfferCandidate") + .field("link_id", &"") + .field("peer_identity_hash", &"") + .field("peer_destination_hash", &"") + .finish() + } +} + +/// Lifecycle state of a recorded, wanted propagation offer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnInboundState { + Accepted, + Transferring, + Validating, +} + +/// Result of stamp validation for a transferred batch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnValidationResult { + Valid, + InvalidStamp, + Failed, +} + +/// Why an invalid-stamp throttle could not be installed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnThrottleInstallError { + /// An all-zero destination is an unknown-peer sentinel, not a known + /// derived `lxmf.propagation` destination. + UnknownPeerDestination, +} + +/// State-machine operation used in typed transition errors. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnTransitionOperation { + ResourceStarted, + ResourceConcluded, + ValidationConcluded, +} + +/// An attempted non-terminal transition was not legal. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnTransitionError { + LinkNotTracked, + IllegalState { + state: PnInboundState, + operation: PnTransitionOperation, + }, +} + +/// Outcome of an idempotent terminal cleanup. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnCleanupResult { + Removed(PnInboundState), + CandidateRevoked, + NotTracked, +} + +/// Outcome of explicitly discarding a preflight candidate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnCandidateDiscardResult { + Discarded, + Stale, +} + +/// A wanted offer retained until its Resource or link reaches a terminal path. +#[derive(Clone, PartialEq, Eq)] +pub struct PnInboundRecord { + peer_identity_hash: [u8; 16], + peer_destination_hash: [u8; 16], + offer_response: PnOfferResponse, + state: PnInboundState, +} + +impl PnInboundRecord { + /// Raw identity hash retained for later peering-key or peer bookkeeping. + pub fn peer_identity_hash(&self) -> &[u8; 16] { + &self.peer_identity_hash + } + + /// Derived `lxmf.propagation` SINGLE destination hash for the peer. + pub fn peer_destination_hash(&self) -> &[u8; 16] { + &self.peer_destination_hash + } + + pub fn offer_response(&self) -> PnOfferResponse { + self.offer_response + } + + pub fn state(&self) -> PnInboundState { + self.state + } +} + +impl fmt::Debug for PnInboundRecord { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("PnInboundRecord") + .field("peer_identity_hash", &"") + .field("peer_destination_hash", &"") + .field("offer_response", &self.offer_response) + .field("state", &self.state) + .finish() + } +} + +/// Long-lived owner of inbound propagation offer accounting and throttles. +pub struct PnInboundAdmission { + config: PnInboundAdmissionConfig, + static_peers: HashSet<[u8; 16]>, + records: HashMap<[u8; 16], PnInboundRecord>, + pending_candidates: HashMap<[u8; 16], Weak>, + throttle_deadlines: HashMap<[u8; 16], Duration>, +} + +impl PnInboundAdmission { + pub fn new(mut config: PnInboundAdmissionConfig) -> Self { + config.max_inbound_syncs = config.max_inbound_syncs.max(PN_MIN_MAX_INBOUND_SYNCS); + + Self { + config, + static_peers: HashSet::new(), + records: HashMap::new(), + pending_candidates: HashMap::new(), + throttle_deadlines: HashMap::new(), + } + } + + pub fn config(&self) -> PnInboundAdmissionConfig { + self.config + } + + /// Replace the configured static propagation destination hashes. + pub fn set_static_peers(&mut self, peers: I) + where + I: IntoIterator, + { + self.static_peers = peers.into_iter().collect(); + } + + pub fn add_static_peer(&mut self, peer_destination_hash: [u8; 16]) -> bool { + self.static_peers.insert(peer_destination_hash) + } + + pub fn remove_static_peer(&mut self, peer_destination_hash: &[u8; 16]) -> bool { + self.static_peers.remove(peer_destination_hash) + } + + pub fn is_static_peer(&self, peer_destination_hash: &[u8; 16]) -> bool { + self.static_peers.contains(peer_destination_hash) + } + + /// Derive the remote peer's `lxmf.propagation` destination hash. + pub fn peer_destination_hash(peer_identity_hash: &[u8; 16]) -> [u8; 16] { + Destination::hash_from_name_and_identity( + PROPAGATION_DESTINATION_NAME, + Some(peer_identity_hash), + ) + } + + /// Apply all cheap gates before peering-key validation or wanted-ID work. + /// + /// A successful preflight creates no admission record. The returned + /// candidate binds the link and peer values that the caller must use for + /// external key validation. + pub fn preflight_offer( + &mut self, + link_id: [u8; 16], + peer_identity_hash: Option<[u8; 16]>, + now: Duration, + ) -> Result { + self.prune_abandoned_candidates(); + + let Some(peer_identity_hash) = peer_identity_hash else { + return Err(PnOfferRejection::NoIdentity); + }; + let peer_destination_hash = Self::peer_destination_hash(&peer_identity_hash); + if self.pending_candidates.contains_key(&link_id) { + return Err(PnOfferRejection::LinkCandidatePending); + } + self.check_offer_gates(&link_id, &peer_destination_hash, now)?; + + let lifecycle = Arc::new(PnOfferLifecycleToken); + self.pending_candidates + .insert(link_id, Arc::downgrade(&lifecycle)); + + Ok(PnOfferCandidate { + link_id, + peer_identity_hash, + peer_destination_hash, + lifecycle, + }) + } + + /// Commit the externally key-validated candidate and wanted response. + /// + /// Calling this method is the caller's assertion that peering-key + /// validation succeeded for the exact values exposed by `candidate`. + /// Every mutable admission gate is checked again before any record is + /// created. The candidate is consumed and no replacement link or identity + /// can be supplied at commit time. + pub fn commit_validated_offer( + &mut self, + candidate: PnOfferCandidate, + offer_response: PnOfferResponse, + now: Duration, + ) -> PnOfferAdmission { + if !self.remove_exact_pending_candidate(&candidate) { + return PnOfferAdmission::Rejected(PnOfferRejection::StaleCandidate); + } + + if let Err(rejection) = + self.check_offer_gates(&candidate.link_id, &candidate.peer_destination_hash, now) + { + return PnOfferAdmission::Rejected(rejection); + } + + if offer_response == PnOfferResponse::HaveAll { + return PnOfferAdmission::HaveAll; + } + + self.records.insert( + candidate.link_id, + PnInboundRecord { + peer_identity_hash: candidate.peer_identity_hash, + peer_destination_hash: candidate.peer_destination_hash, + offer_response, + state: PnInboundState::Accepted, + }, + ); + PnOfferAdmission::Accepted + } + + /// Discard a candidate after external key validation or wanted-ID work + /// fails. + /// + /// Dropping a candidate without calling this method is also safe: the next + /// preflight prunes its abandoned weak lifecycle entry. Explicit discard + /// releases the entry immediately. + pub fn discard_candidate(&mut self, candidate: PnOfferCandidate) -> PnCandidateDiscardResult { + if self.remove_exact_pending_candidate(&candidate) { + PnCandidateDiscardResult::Discarded + } else { + PnCandidateDiscardResult::Stale + } + } + + fn check_offer_gates( + &mut self, + link_id: &[u8; 16], + peer_destination_hash: &[u8; 16], + now: Duration, + ) -> Result<(), PnOfferRejection> { + self.expire_throttles(now); + + let is_static = self.static_peers.contains(peer_destination_hash); + // Match LXMF's observable policy precedence. Static peers bypass only + // the sequential-validation and inbound-cap gates when configured to; + // they never bypass a peer throttle or static-only access policy. + let bypass_limits = is_static && !self.config.static_sequential; + if !bypass_limits && self.config.sequential_validation && self.validation_count() != 0 { + return Err(PnOfferRejection::SequentialValidationActive); + } + + if !bypass_limits && self.inbound_sync_count() >= self.config.max_inbound_syncs { + return Err(PnOfferRejection::InboundSyncLimit); + } + + if self.throttle_deadlines.contains_key(peer_destination_hash) { + return Err(PnOfferRejection::InvalidStampThrottle); + } + + if self.config.from_static_only && !is_static { + return Err(PnOfferRejection::NoAccess); + } + + // This Rust-specific lifecycle guard follows the upstream policy + // gates so their rejection precedence remains observable. + if self.records.contains_key(link_id) { + return Err(PnOfferRejection::LinkAlreadyTracked); + } + + Ok(()) + } + + fn prune_abandoned_candidates(&mut self) { + self.pending_candidates + .retain(|_, lifecycle| lifecycle.upgrade().is_some()); + } + + fn remove_exact_pending_candidate(&mut self, candidate: &PnOfferCandidate) -> bool { + let is_exact = self + .pending_candidates + .get(&candidate.link_id) + .and_then(Weak::upgrade) + .is_some_and(|pending| Arc::ptr_eq(&pending, &candidate.lifecycle)); + + if is_exact { + self.pending_candidates.remove(&candidate.link_id); + } + is_exact + } + + pub fn record(&self, link_id: &[u8; 16]) -> Option<&PnInboundRecord> { + self.records.get(link_id) + } + + pub fn len(&self) -> usize { + self.records.len() + } + + pub fn is_empty(&self) -> bool { + self.records.is_empty() + } + + /// Number of syncs consuming the configured concurrency allowance. + /// + /// An accepted offer does not consume a transfer slot until its Resource + /// starts. Both transfer and validation work do consume one. + pub fn inbound_sync_count(&self) -> usize { + self.records + .values() + .filter(|record| { + matches!( + record.state, + PnInboundState::Transferring | PnInboundState::Validating + ) + }) + .count() + } + + pub fn validation_count(&self) -> usize { + self.records + .values() + .filter(|record| record.state == PnInboundState::Validating) + .count() + } + + /// Transition an accepted offer when its inbound Resource starts. + pub fn resource_started(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> { + self.transition( + link_id, + PnInboundState::Accepted, + PnInboundState::Transferring, + PnTransitionOperation::ResourceStarted, + ) + } + + /// Transition a completed inbound Resource into stamp validation. + pub fn resource_concluded(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> { + self.transition( + link_id, + PnInboundState::Transferring, + PnInboundState::Validating, + PnTransitionOperation::ResourceConcluded, + ) + } + + /// Conclude stamp validation and release all active accounting. + /// + /// Only [`PnValidationResult::InvalidStamp`] installs a throttle, and a + /// throttle is possible only for a known peer retained in a valid record. + /// Repeated conclusion after cleanup is a successful no-op. + pub fn validation_concluded( + &mut self, + link_id: &[u8; 16], + result: PnValidationResult, + now: Duration, + ) -> Result { + let Some(record) = self.records.get(link_id) else { + return Ok(PnCleanupResult::NotTracked); + }; + if record.state != PnInboundState::Validating { + return Err(PnTransitionError::IllegalState { + state: record.state, + operation: PnTransitionOperation::ValidationConcluded, + }); + } + + let record = self + .records + .remove(link_id) + .expect("record existence checked above"); + if result == PnValidationResult::InvalidStamp { + // A record's destination was derived from an identified peer at + // preflight. Ignore only the reserved all-zero unknown sentinel. + let _ = self.install_invalid_stamp_throttle(record.peer_destination_hash, now); + } + + Ok(PnCleanupResult::Removed(PnInboundState::Validating)) + } + + /// Install the standard throttle after invalid stamp validation for a + /// known peer, including an unsolicited Resource with no offer record. + /// + /// `peer_destination_hash` must be the peer's already-derived + /// `lxmf.propagation` SINGLE destination hash. The all-zero value is + /// rejected so callers cannot accidentally turn an unknown identity into + /// shared throttle state. `now` must use the same monotonic origin as the + /// other admission calls. + pub fn install_invalid_stamp_throttle( + &mut self, + peer_destination_hash: [u8; 16], + now: Duration, + ) -> Result { + if peer_destination_hash == [0; 16] { + return Err(PnThrottleInstallError::UnknownPeerDestination); + } + + let requested_deadline = now.saturating_add(PN_INVALID_STAMP_THROTTLE); + let deadline = self + .throttle_deadlines + .entry(peer_destination_hash) + .and_modify(|deadline| *deadline = (*deadline).max(requested_deadline)) + .or_insert(requested_deadline); + Ok(*deadline) + } + + /// Release an accepted offer after its Resource advertisement is rejected. + pub fn resource_rejected(&mut self, link_id: &[u8; 16]) -> PnCleanupResult { + self.remove_record(link_id) + } + + /// Release accounting after Resource cancellation. + pub fn resource_cancelled(&mut self, link_id: &[u8; 16]) -> PnCleanupResult { + self.remove_record(link_id) + } + + /// Release accounting after Resource failure. + pub fn resource_failed(&mut self, link_id: &[u8; 16]) -> PnCleanupResult { + self.remove_record(link_id) + } + + /// Release accounting when the owning Reticulum link closes. + pub fn link_closed(&mut self, link_id: &[u8; 16]) -> PnCleanupResult { + let candidate_revoked = self.pending_candidates.remove(link_id).is_some(); + match self.remove_record(link_id) { + PnCleanupResult::NotTracked if candidate_revoked => PnCleanupResult::CandidateRevoked, + result => result, + } + } + + /// Remove expired invalid-stamp throttles using caller-supplied time. + pub fn expire_throttles(&mut self, now: Duration) { + self.throttle_deadlines + .retain(|_, deadline| *deadline > now); + } + + pub fn is_peer_throttled(&mut self, peer_destination_hash: &[u8; 16], now: Duration) -> bool { + self.expire_throttles(now); + self.throttle_deadlines.contains_key(peer_destination_hash) + } + + pub fn throttle_deadline( + &mut self, + peer_destination_hash: &[u8; 16], + now: Duration, + ) -> Option { + self.expire_throttles(now); + self.throttle_deadlines.get(peer_destination_hash).copied() + } + + pub fn throttle_count(&self) -> usize { + self.throttle_deadlines.len() + } + + fn transition( + &mut self, + link_id: &[u8; 16], + expected: PnInboundState, + next: PnInboundState, + operation: PnTransitionOperation, + ) -> Result<(), PnTransitionError> { + let record = self + .records + .get_mut(link_id) + .ok_or(PnTransitionError::LinkNotTracked)?; + if record.state != expected { + return Err(PnTransitionError::IllegalState { + state: record.state, + operation, + }); + } + + record.state = next; + Ok(()) + } + + fn remove_record(&mut self, link_id: &[u8; 16]) -> PnCleanupResult { + self.records + .remove(link_id) + .map(|record| PnCleanupResult::Removed(record.state)) + .unwrap_or(PnCleanupResult::NotTracked) + } +} + +impl Default for PnInboundAdmission { + fn default() -> Self { + Self::new(PnInboundAdmissionConfig::default()) + } +} + +impl fmt::Debug for PnInboundAdmission { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("PnInboundAdmission") + .field("config", &self.config) + .field("static_peer_count", &self.static_peers.len()) + .field("pending_candidate_count", &self.pending_candidates.len()) + .field("record_count", &self.records.len()) + .field("inbound_sync_count", &self.inbound_sync_count()) + .field("validation_count", &self.validation_count()) + .field("throttle_count", &self.throttle_deadlines.len()) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TEST_NOW: Duration = Duration::from_secs(1_000); + + fn identity(byte: u8) -> [u8; 16] { + [byte; 16] + } + + fn link(byte: u8) -> [u8; 16] { + [byte; 16] + } + + fn admit( + admission: &mut PnInboundAdmission, + link_id: [u8; 16], + identity_hash: [u8; 16], + response: PnOfferResponse, + ) -> PnOfferAdmission { + let candidate = admission + .preflight_offer(link_id, Some(identity_hash), TEST_NOW) + .expect("test offer passes preflight"); + admission.commit_validated_offer(candidate, response, TEST_NOW) + } + + fn start_validation(admission: &mut PnInboundAdmission, link_id: &[u8; 16]) { + admission.resource_started(link_id).unwrap(); + admission.resource_concluded(link_id).unwrap(); + } + + #[test] + fn defaults_match_lxmf_and_configured_limit_has_a_floor() { + let defaults = PnInboundAdmission::default(); + assert_eq!( + defaults.config(), + PnInboundAdmissionConfig { + sequential_validation: true, + static_sequential: false, + max_inbound_syncs: 3, + from_static_only: false, + } + ); + assert_eq!(PN_INVALID_STAMP_THROTTLE, Duration::from_secs(180)); + + let floored = PnInboundAdmission::new(PnInboundAdmissionConfig { + max_inbound_syncs: 0, + ..PnInboundAdmissionConfig::default() + }); + assert_eq!(floored.config().max_inbound_syncs, 1); + } + + #[test] + fn unknown_identity_and_static_only_access_create_no_sentinel_state() { + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }); + + assert!(matches!( + admission.preflight_offer(link(1), None, Duration::from_secs(10)), + Err(PnOfferRejection::NoIdentity) + )); + assert!(admission.is_empty()); + assert_eq!(admission.throttle_count(), 0); + + let peer_identity = identity(0xA1); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer_identity); + assert_eq!( + peer_destination, + [ + 0x3f, 0x77, 0x7c, 0x3f, 0x69, 0x1a, 0x9f, 0x56, 0x28, 0x01, 0x72, 0x6e, 0xf1, 0x9e, + 0x49, 0x01, + ] + ); + assert!(matches!( + admission.preflight_offer(link(2), Some(peer_identity), TEST_NOW), + Err(PnOfferRejection::NoAccess) + )); + assert!(admission.is_empty()); + + admission.add_static_peer(peer_destination); + assert_eq!( + admit( + &mut admission, + link(2), + peer_identity, + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + let record = admission.record(&link(2)).unwrap(); + assert_eq!(record.peer_identity_hash(), &peer_identity); + assert_eq!(record.peer_destination_hash(), &peer_destination); + assert_eq!(record.state(), PnInboundState::Accepted); + + let debug = format!("{record:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("161")); + assert!(!format!("{admission:?}").contains("161")); + } + + #[test] + fn cap_counts_transferring_and_validating_but_not_accepted() { + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + max_inbound_syncs: 2, + ..PnInboundAdmissionConfig::default() + }); + + assert_eq!( + admit( + &mut admission, + link(1), + identity(1), + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + assert_eq!( + admit( + &mut admission, + link(2), + identity(2), + PnOfferResponse::WantSome, + ), + PnOfferAdmission::Accepted + ); + assert_eq!(admission.inbound_sync_count(), 0); + + admission.resource_started(&link(1)).unwrap(); + start_validation(&mut admission, &link(2)); + assert_eq!(admission.inbound_sync_count(), 2); + assert_eq!(admission.validation_count(), 1); + assert!(matches!( + admission.preflight_offer(link(3), Some(identity(3)), TEST_NOW), + Err(PnOfferRejection::InboundSyncLimit) + )); + assert_eq!(admission.len(), 2); + } + + #[test] + fn sequential_validation_and_static_bypass_follow_both_static_modes() { + let normal_identity = identity(1); + let static_identity = identity(2); + let static_destination = PnInboundAdmission::peer_destination_hash(&static_identity); + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + max_inbound_syncs: 1, + ..PnInboundAdmissionConfig::default() + }); + admission.add_static_peer(static_destination); + + assert_eq!( + admit( + &mut admission, + link(1), + normal_identity, + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + start_validation(&mut admission, &link(1)); + assert!(matches!( + admission.preflight_offer(link(2), Some(identity(3)), TEST_NOW), + Err(PnOfferRejection::SequentialValidationActive) + )); + + // The default static_sequential=false bypasses both the sequential + // validation gate and the already-full inbound Resource limit. + assert_eq!( + admit( + &mut admission, + link(3), + static_identity, + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + + let mut static_sequential = PnInboundAdmission::new(PnInboundAdmissionConfig { + static_sequential: true, + max_inbound_syncs: 1, + ..PnInboundAdmissionConfig::default() + }); + static_sequential.add_static_peer(static_destination); + admit( + &mut static_sequential, + link(4), + normal_identity, + PnOfferResponse::WantAll, + ); + start_validation(&mut static_sequential, &link(4)); + assert!(matches!( + static_sequential.preflight_offer(link(5), Some(static_identity), TEST_NOW), + Err(PnOfferRejection::SequentialValidationActive) + )); + + let mut static_capped = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + static_sequential: true, + max_inbound_syncs: 1, + ..PnInboundAdmissionConfig::default() + }); + static_capped.add_static_peer(static_destination); + admit( + &mut static_capped, + link(8), + normal_identity, + PnOfferResponse::WantAll, + ); + static_capped.resource_started(&link(8)).unwrap(); + assert!(matches!( + static_capped.preflight_offer(link(9), Some(static_identity), TEST_NOW), + Err(PnOfferRejection::InboundSyncLimit) + )); + + let mut non_sequential = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + max_inbound_syncs: 2, + ..PnInboundAdmissionConfig::default() + }); + admit( + &mut non_sequential, + link(6), + normal_identity, + PnOfferResponse::WantAll, + ); + start_validation(&mut non_sequential, &link(6)); + assert_eq!( + admit( + &mut non_sequential, + link(7), + identity(7), + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + } + + #[test] + fn offer_policy_gates_follow_upstream_precedence() { + let blocked_identity = identity(9); + let blocked_destination = PnInboundAdmission::peer_destination_hash(&blocked_identity); + + // Sequential validation wins over a full cap, an invalid-stamp + // throttle, and static-only access rejection. + let mut sequential = PnInboundAdmission::new(PnInboundAdmissionConfig { + max_inbound_syncs: 1, + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }); + let active_identity = identity(1); + sequential.add_static_peer(PnInboundAdmission::peer_destination_hash(&active_identity)); + admit( + &mut sequential, + link(1), + active_identity, + PnOfferResponse::WantAll, + ); + start_validation(&mut sequential, &link(1)); + sequential + .install_invalid_stamp_throttle(blocked_destination, TEST_NOW) + .unwrap(); + assert!(matches!( + sequential.preflight_offer(link(2), Some(blocked_identity), TEST_NOW), + Err(PnOfferRejection::SequentialValidationActive) + )); + + // With sequential validation disabled, the full cap wins over the + // same peer throttle and static-only access rejection. + let mut capped = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + max_inbound_syncs: 1, + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }); + capped.add_static_peer(PnInboundAdmission::peer_destination_hash(&active_identity)); + admit( + &mut capped, + link(3), + active_identity, + PnOfferResponse::WantAll, + ); + capped.resource_started(&link(3)).unwrap(); + capped + .install_invalid_stamp_throttle(blocked_destination, TEST_NOW) + .unwrap(); + assert!(matches!( + capped.preflight_offer(link(4), Some(blocked_identity), TEST_NOW), + Err(PnOfferRejection::InboundSyncLimit) + )); + + // With capacity available, an active throttle wins over static-only + // access rejection. Once it expires, access is the remaining gate. + let mut throttled = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }); + let deadline = throttled + .install_invalid_stamp_throttle(blocked_destination, TEST_NOW) + .unwrap(); + assert!(matches!( + throttled.preflight_offer(link(5), Some(blocked_identity), TEST_NOW), + Err(PnOfferRejection::InvalidStampThrottle) + )); + assert!(matches!( + throttled.preflight_offer(link(5), Some(blocked_identity), deadline), + Err(PnOfferRejection::NoAccess) + )); + } + + #[test] + fn want_all_and_want_some_are_recorded_while_have_all_is_not() { + let mut admission = PnInboundAdmission::default(); + + assert_eq!( + admit( + &mut admission, + link(1), + identity(1), + PnOfferResponse::HaveAll, + ), + PnOfferAdmission::HaveAll + ); + assert!(admission.record(&link(1)).is_none()); + + assert_eq!( + admit( + &mut admission, + link(2), + identity(2), + PnOfferResponse::WantAll, + ), + PnOfferAdmission::Accepted + ); + assert_eq!( + admission.record(&link(2)).unwrap().offer_response(), + PnOfferResponse::WantAll + ); + + assert_eq!( + admit( + &mut admission, + link(3), + identity(3), + PnOfferResponse::WantSome, + ), + PnOfferAdmission::Accepted + ); + assert_eq!( + admission.record(&link(3)).unwrap().offer_response(), + PnOfferResponse::WantSome + ); + assert_eq!(admission.len(), 2); + } + + #[test] + fn successful_preflight_creates_no_state_and_candidate_cannot_be_rebound() { + let mut admission = PnInboundAdmission::default(); + let bound_link = link(1); + let bound_identity = identity(0xA1); + let bound_destination = PnInboundAdmission::peer_destination_hash(&bound_identity); + let candidate = admission + .preflight_offer(bound_link, Some(bound_identity), TEST_NOW) + .unwrap(); + + assert!(admission.is_empty()); + assert_eq!(admission.pending_candidates.len(), 1); + assert_eq!(candidate.link_id(), bound_link); + assert_eq!(candidate.peer_identity_hash(), bound_identity); + assert_eq!(candidate.peer_destination_hash(), bound_destination); + + // Accessors return copies. Mutating caller-owned values cannot change + // the opaque candidate consumed by the validated commit boundary. + let mut exposed_link = candidate.link_id(); + let mut exposed_identity = candidate.peer_identity_hash(); + exposed_link.copy_from_slice(&link(2)); + exposed_identity.copy_from_slice(&identity(2)); + assert_eq!(candidate.link_id(), bound_link); + assert_eq!(candidate.peer_identity_hash(), bound_identity); + + let debug = format!("{candidate:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("161")); + + assert_eq!( + admission.commit_validated_offer(candidate, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Accepted + ); + assert!(admission.pending_candidates.is_empty()); + assert!(admission.record(&exposed_link).is_none()); + let record = admission.record(&bound_link).unwrap(); + assert_eq!(record.peer_identity_hash(), &bound_identity); + assert_ne!(record.peer_identity_hash(), &exposed_identity); + } + + #[test] + fn link_close_revokes_preflight_candidate_without_revoking_replacement() { + let mut admission = PnInboundAdmission::default(); + let link_id = link(1); + let revoked = admission + .preflight_offer(link_id, Some(identity(1)), TEST_NOW) + .unwrap(); + + assert_eq!( + admission.link_closed(&link_id), + PnCleanupResult::CandidateRevoked + ); + assert!(admission.pending_candidates.is_empty()); + assert!(admission.is_empty()); + + let replacement = admission + .preflight_offer(link_id, Some(identity(2)), TEST_NOW) + .unwrap(); + assert_eq!( + admission.commit_validated_offer(revoked, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::StaleCandidate) + ); + assert_eq!(admission.pending_candidates.len(), 1); + assert!(admission.is_empty()); + + assert_eq!( + admission.commit_validated_offer(replacement, PnOfferResponse::WantSome, TEST_NOW), + PnOfferAdmission::Accepted + ); + assert_eq!( + admission.record(&link_id).unwrap().peer_identity_hash(), + &identity(2) + ); + } + + #[test] + fn failed_external_validation_can_explicitly_discard_candidate() { + let mut admission = PnInboundAdmission::default(); + let link_id = link(1); + let candidate = admission + .preflight_offer(link_id, Some(identity(1)), TEST_NOW) + .unwrap(); + + assert_eq!( + admission.discard_candidate(candidate), + PnCandidateDiscardResult::Discarded + ); + assert!(admission.pending_candidates.is_empty()); + assert!(admission.is_empty()); + + let retry = admission + .preflight_offer(link_id, Some(identity(1)), TEST_NOW) + .unwrap(); + assert_eq!( + admission.discard_candidate(retry), + PnCandidateDiscardResult::Discarded + ); + } + + #[test] + fn dropped_candidate_is_pruned_by_next_preflight() { + let mut admission = PnInboundAdmission::default(); + let abandoned = admission + .preflight_offer(link(1), Some(identity(1)), TEST_NOW) + .unwrap(); + assert_eq!(admission.pending_candidates.len(), 1); + drop(abandoned); + assert_eq!(admission.pending_candidates.len(), 1); + + let next = admission + .preflight_offer(link(2), Some(identity(2)), TEST_NOW) + .unwrap(); + assert_eq!(admission.pending_candidates.len(), 1); + assert!(!admission.pending_candidates.contains_key(&link(1))); + assert!(admission.pending_candidates.contains_key(&link(2))); + assert_eq!( + admission.discard_candidate(next), + PnCandidateDiscardResult::Discarded + ); + } + + #[test] + fn duplicate_live_preflight_for_link_is_rejected_without_recording() { + let mut admission = PnInboundAdmission::default(); + let candidate = admission + .preflight_offer(link(1), Some(identity(1)), TEST_NOW) + .unwrap(); + + assert!(matches!( + admission.preflight_offer(link(1), Some(identity(2)), TEST_NOW), + Err(PnOfferRejection::LinkCandidatePending) + )); + assert!(admission.is_empty()); + assert_eq!(admission.pending_candidates.len(), 1); + assert_eq!( + admission.discard_candidate(candidate), + PnCandidateDiscardResult::Discarded + ); + } + + #[test] + fn foreign_candidate_cannot_commit_or_discard_real_pending_token() { + let mut target = PnInboundAdmission::default(); + let mut foreign_owner = PnInboundAdmission::default(); + + let real = target + .preflight_offer(link(1), Some(identity(1)), TEST_NOW) + .unwrap(); + let foreign = foreign_owner + .preflight_offer(link(1), Some(identity(1)), TEST_NOW) + .unwrap(); + assert_eq!( + target.commit_validated_offer(foreign, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::StaleCandidate) + ); + assert_eq!(target.pending_candidates.len(), 1); + assert!(target.is_empty()); + assert_eq!( + target.commit_validated_offer(real, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Accepted + ); + + let real = target + .preflight_offer(link(2), Some(identity(2)), TEST_NOW) + .unwrap(); + let foreign = foreign_owner + .preflight_offer(link(2), Some(identity(2)), TEST_NOW) + .unwrap(); + assert_eq!( + target.discard_candidate(foreign), + PnCandidateDiscardResult::Stale + ); + assert_eq!(target.pending_candidates.len(), 1); + assert_eq!( + target.discard_candidate(real), + PnCandidateDiscardResult::Discarded + ); + assert!(target.pending_candidates.is_empty()); + } + + #[test] + fn commit_rechecks_static_access_and_duplicate_link_gates() { + let peer_identity = identity(1); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer_identity); + let mut static_only = PnInboundAdmission::new(PnInboundAdmissionConfig { + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }); + static_only.add_static_peer(peer_destination); + let candidate = static_only + .preflight_offer(link(1), Some(peer_identity), TEST_NOW) + .unwrap(); + static_only.remove_static_peer(&peer_destination); + assert_eq!( + static_only.commit_validated_offer(candidate, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::NoAccess) + ); + assert!(static_only.is_empty()); + + let mut duplicate = PnInboundAdmission::default(); + let stale = duplicate + .preflight_offer(link(2), Some(identity(2)), TEST_NOW) + .unwrap(); + // Simulate an independently installed active record between the two + // phases. Public preflight correctly prevents a second candidate for + // this link, but commit must still defend its active-record gate. + duplicate.records.insert( + link(2), + PnInboundRecord { + peer_identity_hash: identity(3), + peer_destination_hash: PnInboundAdmission::peer_destination_hash(&identity(3)), + offer_response: PnOfferResponse::WantSome, + state: PnInboundState::Accepted, + }, + ); + assert_eq!( + duplicate.commit_validated_offer(stale, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::LinkAlreadyTracked) + ); + assert_eq!(duplicate.len(), 1); + assert_eq!( + duplicate.record(&link(2)).unwrap().peer_identity_hash(), + &identity(3) + ); + } + + #[test] + fn commit_rechecks_sequential_and_inbound_limit_gates() { + let mut sequential = PnInboundAdmission::default(); + let stale = sequential + .preflight_offer(link(2), Some(identity(2)), TEST_NOW) + .unwrap(); + admit( + &mut sequential, + link(1), + identity(1), + PnOfferResponse::WantAll, + ); + start_validation(&mut sequential, &link(1)); + assert_eq!( + sequential.commit_validated_offer(stale, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::SequentialValidationActive) + ); + assert_eq!(sequential.len(), 1); + + let mut capped = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + max_inbound_syncs: 1, + ..PnInboundAdmissionConfig::default() + }); + let stale = capped + .preflight_offer(link(4), Some(identity(4)), TEST_NOW) + .unwrap(); + admit(&mut capped, link(3), identity(3), PnOfferResponse::WantAll); + capped.resource_started(&link(3)).unwrap(); + assert_eq!( + capped.commit_validated_offer(stale, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::InboundSyncLimit) + ); + assert_eq!(capped.len(), 1); + } + + #[test] + fn commit_rechecks_invalid_stamp_throttle_gate() { + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + ..PnInboundAdmissionConfig::default() + }); + let peer_identity = identity(1); + let stale = admission + .preflight_offer(link(2), Some(peer_identity), TEST_NOW) + .unwrap(); + + admit( + &mut admission, + link(1), + peer_identity, + PnOfferResponse::WantSome, + ); + start_validation(&mut admission, &link(1)); + admission + .validation_concluded(&link(1), PnValidationResult::InvalidStamp, TEST_NOW) + .unwrap(); + + assert_eq!( + admission.commit_validated_offer(stale, PnOfferResponse::WantAll, TEST_NOW), + PnOfferAdmission::Rejected(PnOfferRejection::InvalidStampThrottle) + ); + assert!(admission.is_empty()); + } + + #[test] + fn transitions_reject_illegal_or_untracked_operations_without_mutation() { + let mut admission = PnInboundAdmission::default(); + let link_id = link(1); + + assert_eq!( + admission.resource_started(&link_id), + Err(PnTransitionError::LinkNotTracked) + ); + admit( + &mut admission, + link_id, + identity(1), + PnOfferResponse::WantAll, + ); + assert_eq!( + admission.resource_concluded(&link_id), + Err(PnTransitionError::IllegalState { + state: PnInboundState::Accepted, + operation: PnTransitionOperation::ResourceConcluded, + }) + ); + assert_eq!( + admission.record(&link_id).unwrap().state(), + PnInboundState::Accepted + ); + + admission.resource_started(&link_id).unwrap(); + assert_eq!( + admission.resource_started(&link_id), + Err(PnTransitionError::IllegalState { + state: PnInboundState::Transferring, + operation: PnTransitionOperation::ResourceStarted, + }) + ); + assert_eq!( + admission.validation_concluded( + &link_id, + PnValidationResult::Valid, + Duration::from_secs(20), + ), + Err(PnTransitionError::IllegalState { + state: PnInboundState::Transferring, + operation: PnTransitionOperation::ValidationConcluded, + }) + ); + assert!(matches!( + admission.preflight_offer(link_id, Some(identity(9)), TEST_NOW), + Err(PnOfferRejection::LinkAlreadyTracked) + )); + assert_eq!( + admission.record(&link_id).unwrap().state(), + PnInboundState::Transferring + ); + } + + #[test] + fn every_terminal_path_is_idempotent() { + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + ..PnInboundAdmissionConfig::default() + }); + + for (link_byte, cleanup) in [ + ( + 1, + PnInboundAdmission::resource_rejected + as fn(&mut PnInboundAdmission, &[u8; 16]) -> PnCleanupResult, + ), + (2, PnInboundAdmission::resource_cancelled), + (3, PnInboundAdmission::resource_failed), + (4, PnInboundAdmission::link_closed), + ] { + let link_id = link(link_byte); + admit( + &mut admission, + link_id, + identity(link_byte), + PnOfferResponse::WantAll, + ); + if link_byte != 1 { + admission.resource_started(&link_id).unwrap(); + } + if link_byte == 4 { + admission.resource_concluded(&link_id).unwrap(); + } + assert!(matches!( + cleanup(&mut admission, &link_id), + PnCleanupResult::Removed(_) + )); + assert_eq!( + cleanup(&mut admission, &link_id), + PnCleanupResult::NotTracked + ); + } + + let link_id = link(5); + admit( + &mut admission, + link_id, + identity(5), + PnOfferResponse::WantSome, + ); + start_validation(&mut admission, &link_id); + assert_eq!( + admission.validation_concluded( + &link_id, + PnValidationResult::Valid, + Duration::from_secs(50), + ), + Ok(PnCleanupResult::Removed(PnInboundState::Validating)) + ); + assert_eq!( + admission.validation_concluded( + &link_id, + PnValidationResult::Valid, + Duration::from_secs(51), + ), + Ok(PnCleanupResult::NotTracked) + ); + assert!(admission.is_empty()); + } + + #[test] + fn only_invalid_stamp_validation_throttles_known_peer_until_deadline() { + let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig { + sequential_validation: false, + ..PnInboundAdmissionConfig::default() + }); + + for (link_byte, result) in [ + (1, PnValidationResult::Valid), + (2, PnValidationResult::Failed), + ] { + let link_id = link(link_byte); + admit( + &mut admission, + link_id, + identity(link_byte), + PnOfferResponse::WantAll, + ); + start_validation(&mut admission, &link_id); + admission + .validation_concluded(&link_id, result, Duration::from_secs(100)) + .unwrap(); + } + assert_eq!(admission.throttle_count(), 0); + + assert_eq!( + admission.validation_concluded( + &link(99), + PnValidationResult::InvalidStamp, + Duration::from_secs(100), + ), + Ok(PnCleanupResult::NotTracked) + ); + assert_eq!(admission.throttle_count(), 0); + + let bad_identity = identity(3); + let bad_destination = PnInboundAdmission::peer_destination_hash(&bad_identity); + let bad_link = link(3); + admit( + &mut admission, + bad_link, + bad_identity, + PnOfferResponse::WantSome, + ); + start_validation(&mut admission, &bad_link); + assert_eq!( + admission.validation_concluded( + &bad_link, + PnValidationResult::InvalidStamp, + Duration::from_secs(100), + ), + Ok(PnCleanupResult::Removed(PnInboundState::Validating)) + ); + assert_eq!( + admission.throttle_deadline(&bad_destination, Duration::from_secs(100)), + Some(Duration::from_secs(280)) + ); + assert!(matches!( + admission.preflight_offer(link(4), Some(bad_identity), Duration::from_millis(279_999),), + Err(PnOfferRejection::InvalidStampThrottle) + )); + + // No global or zero-key throttle is created for unrelated peers. + let unrelated_now = Duration::from_millis(279_999); + let unrelated = admission + .preflight_offer(link(5), Some(identity(5)), unrelated_now) + .unwrap(); + assert_eq!( + admission.commit_validated_offer(unrelated, PnOfferResponse::HaveAll, unrelated_now,), + PnOfferAdmission::HaveAll + ); + assert!(!admission.is_peer_throttled(&[0; 16], unrelated_now)); + + let deadline = Duration::from_secs(280); + let expired = admission + .preflight_offer(link(6), Some(bad_identity), deadline) + .unwrap(); + assert_eq!( + admission.commit_validated_offer(expired, PnOfferResponse::HaveAll, deadline), + PnOfferAdmission::HaveAll + ); + assert_eq!(admission.throttle_count(), 0); + } + + #[test] + fn unsolicited_invalid_stamp_throttle_is_expiring_and_peer_scoped() { + let mut admission = PnInboundAdmission::default(); + let bad_identity = identity(0xA1); + let bad_destination = PnInboundAdmission::peer_destination_hash(&bad_identity); + let other_identity = identity(0xB2); + + assert_eq!( + admission.install_invalid_stamp_throttle([0; 16], TEST_NOW), + Err(PnThrottleInstallError::UnknownPeerDestination) + ); + assert_eq!(admission.throttle_count(), 0); + + let deadline = admission + .install_invalid_stamp_throttle(bad_destination, TEST_NOW) + .unwrap(); + assert_eq!(deadline, TEST_NOW.saturating_add(PN_INVALID_STAMP_THROTTLE)); + assert_eq!( + admission + .install_invalid_stamp_throttle( + bad_destination, + TEST_NOW.saturating_sub(Duration::from_secs(1)), + ) + .unwrap(), + deadline, + "an out-of-order timestamp cannot shorten a live throttle" + ); + assert_eq!(admission.throttle_count(), 1); + assert!(matches!( + admission.preflight_offer(link(1), Some(bad_identity), TEST_NOW), + Err(PnOfferRejection::InvalidStampThrottle) + )); + + let other = admission + .preflight_offer(link(2), Some(other_identity), TEST_NOW) + .expect("an unsolicited peer throttle is isolated to that peer"); + assert_eq!( + admission.discard_candidate(other), + PnCandidateDiscardResult::Discarded + ); + + let expired = admission + .preflight_offer(link(1), Some(bad_identity), deadline) + .expect("throttle expires at its monotonic deadline"); + assert_eq!( + admission.discard_candidate(expired), + PnCandidateDiscardResult::Discarded + ); + assert_eq!(admission.throttle_count(), 0); + } + + #[test] + fn invalid_stamp_deadline_saturates_at_duration_max() { + let mut admission = PnInboundAdmission::default(); + let peer_identity = identity(1); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer_identity); + let link_id = link(1); + admit( + &mut admission, + link_id, + peer_identity, + PnOfferResponse::WantAll, + ); + start_validation(&mut admission, &link_id); + + let near_max = Duration::MAX.saturating_sub(Duration::from_secs(1)); + admission + .validation_concluded(&link_id, PnValidationResult::InvalidStamp, near_max) + .unwrap(); + assert_eq!( + admission.throttle_deadline(&peer_destination, near_max), + Some(Duration::MAX) + ); + assert!(matches!( + admission.preflight_offer(link(2), Some(peer_identity), near_max), + Err(PnOfferRejection::InvalidStampThrottle) + )); + + // At the greatest representable caller time, the saturated deadline + // expires deterministically instead of overflowing or becoming NaN. + let candidate = admission + .preflight_offer(link(2), Some(peer_identity), Duration::MAX) + .unwrap(); + assert_eq!( + admission.commit_validated_offer(candidate, PnOfferResponse::HaveAll, Duration::MAX,), + PnOfferAdmission::HaveAll + ); + assert_eq!(admission.throttle_count(), 0); + } +} diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index 1793beb..7b1df90 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -40,12 +40,35 @@ pub enum PropagationClientState { ListRequested, /// `/get` with `[wants, haves, limit]` sent. GetRequested, + /// A Resource response is actively transferring. + Receiving, /// `/get` with `[None, received_ids]` sent. PurgeRequested, Complete, Failed, } +/// One coherent public snapshot of a propagation-node download. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct PropagationTransferStatus { + pub state: PropagationClientState, + pub progress: f64, + pub data_size: Option, + /// Number of message blobs decoded from the completed response. + pub result: Option, +} + +impl Default for PropagationTransferStatus { + fn default() -> Self { + Self { + state: PropagationClientState::Idle, + progress: 0.0, + data_size: None, + result: None, + } + } +} + struct SegmentRoute { original_hash: [u8; 32], segment_index: usize, @@ -58,7 +81,9 @@ pub struct PropagationClient { outbound_propagation_node: Option<[u8; 16]>, link: Option, link_id: Option<[u8; 16]>, - pub state: PropagationClientState, + status: PropagationTransferStatus, + /// Request phase whose response is currently arriving as a Resource. + receiving_for: Option, identity_pub: Option<[u8; 64]>, identity_key: Option, /// Phase 1 response: transient IDs the server has. @@ -93,7 +118,8 @@ impl PropagationClient { outbound_propagation_node: None, link: None, link_id: None, - state: PropagationClientState::Idle, + status: PropagationTransferStatus::default(), + receiving_for: None, identity_pub, identity_key, available_messages: Vec::new(), @@ -135,11 +161,47 @@ impl PropagationClient { std::mem::take(&mut self.received_messages) } + pub const fn state(&self) -> PropagationClientState { + self.status.state + } + + pub const fn transfer_status(&self) -> PropagationTransferStatus { + self.status + } + + /// Clear a terminal presentation snapshot after the caller has consumed + /// its result. Active transfers are never reset by acknowledgement. + pub fn acknowledge_transfer(&mut self) -> bool { + if !matches!( + self.status.state, + PropagationClientState::Complete | PropagationClientState::Failed + ) { + return false; + } + self.cleanup(); + self.status = PropagationTransferStatus::default(); + true + } + pub fn start_download(&mut self) -> bool { let node_hash = match self.outbound_propagation_node { Some(h) => h, None => return false, }; + if !matches!( + self.status.state, + PropagationClientState::Idle + | PropagationClientState::Complete + | PropagationClientState::Failed + ) { + return false; + } + if matches!( + self.status.state, + PropagationClientState::Complete | PropagationClientState::Failed + ) { + self.cleanup(); + } let (link, request_data) = Link::new_initiator(node_hash, 1); let link_id = link.link_id; @@ -180,9 +242,13 @@ impl PropagationClient { destination_hash: node_hash, })); + self.status = PropagationTransferStatus { + state: PropagationClientState::LinkEstablishing, + ..PropagationTransferStatus::default() + }; + self.receiving_for = None; self.link = Some(link); self.link_id = Some(link_id); - self.state = PropagationClientState::LinkEstablishing; self.started_at = Some(Instant::now()); self.identified = false; self.available_messages.clear(); @@ -225,7 +291,7 @@ impl PropagationClient { if header.flags.packet_type == rns_wire::flags::PacketType::Proof || header.context == rns_wire::context::PacketContext::Lrproof => { - if self.state != PropagationClientState::LinkEstablishing { + if self.status.state != PropagationClientState::LinkEstablishing { continue; } let node_hex = self.outbound_propagation_node.map(|h| hex_encode(&h)); @@ -293,7 +359,7 @@ impl PropagationClient { self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } verified @@ -336,16 +402,26 @@ impl PropagationClient { destination_hash: link_id, })); } - self.state = PropagationClientState::LinkEstablished; + self.status.state = PropagationClientState::LinkEstablished; } Err(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } } fn handle_response_data(&mut self, response_data: &[u8]) { - match self.state { + let response_phase = if self.status.state == PropagationClientState::Receiving { + let Some(phase) = self.receiving_for.take() else { + self.status.state = PropagationClientState::Failed; + return; + }; + phase + } else { + self.status.state + }; + + match response_phase { PropagationClientState::ListRequested => { self.handle_list_response(response_data); } @@ -364,11 +440,11 @@ impl PropagationClient { return; }; let Ok(plaintext) = link.decrypt(data) else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; }; let Ok(adv) = ResourceAdvertisement::unpack(&plaintext) else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; }; @@ -376,12 +452,29 @@ impl PropagationClient { return; } + if self.status.state != PropagationClientState::Receiving { + if !matches!( + self.status.state, + PropagationClientState::ListRequested + | PropagationClientState::GetRequested + | PropagationClientState::PurgeRequested + ) { + return; + } + self.receiving_for = Some(self.status.state); + } else if self.receiving_for.is_none() { + self.status.state = PropagationClientState::Failed; + return; + } + self.status.state = PropagationClientState::Receiving; + self.status.data_size = Some(self.status.data_size.unwrap_or_default().max(adv.data_size)); + if adv.total_segments > 1 { if adv.total_segments > MAX_SEGMENTS || adv.segment_index == 0 || adv.segment_index > adv.total_segments { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } @@ -390,7 +483,7 @@ impl PropagationClient { .entry(adv.original_hash) .or_insert_with(|| MultiSegmentInbound::new(adv.total_segments, adv.original_hash)); if entry.total_segments != adv.total_segments { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } self.segment_routing.insert( @@ -422,7 +515,7 @@ impl PropagationClient { map_hashes, rtt, ) else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; }; @@ -442,6 +535,7 @@ impl PropagationClient { fn handle_resource_part(&mut self, data: &[u8]) { let mut control_actions = Vec::new(); let mut completed = None; + let mut observed_progress = None; for (resource_hash, transfer) in &mut self.inbound_resources { let action = transfer.receive_part(data.to_vec()); @@ -453,7 +547,7 @@ impl PropagationClient { control_actions.push((rns_wire::context::PacketContext::ResourceReq, req)); } TransferAction::Failed(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } _ => {} @@ -462,6 +556,7 @@ impl PropagationClient { if transfer.resource.is_complete() { completed = Some(*resource_hash); } + observed_progress = Some((*resource_hash, transfer.resource.progress())); if completed.is_some() || !control_actions.is_empty() { break; @@ -472,6 +567,23 @@ impl PropagationClient { self.send_encrypted_resource_control(context, &payload); } + if let Some((resource_hash, segment_progress)) = observed_progress { + let progress = self + .segment_routing + .get(&resource_hash) + .and_then(|route| { + self.inbound_split_resources + .get(&route.original_hash) + .map(|coordinator| { + (coordinator.assembled_count() as f64 + segment_progress) + / coordinator.total_segments.max(1) as f64 + }) + }) + .unwrap_or(segment_progress); + self.status.state = PropagationClientState::Receiving; + self.status.progress = self.status.progress.max(progress.clamp(0.0, 1.0)); + } + if let Some(resource_hash) = completed { self.complete_resource(resource_hash); } @@ -518,7 +630,7 @@ impl PropagationClient { ); } TransferAction::Failed(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } _ => {} } @@ -543,7 +655,7 @@ impl PropagationClient { if let Some(link) = self.link.as_mut() { link.untrack_resource(&resource_hash); } - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } fn complete_resource(&mut self, resource_hash: [u8; 32]) { @@ -564,7 +676,7 @@ impl PropagationClient { assembled } Err(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } } @@ -587,7 +699,7 @@ impl PropagationClient { .set_segment_data(route.segment_index, assembled) .is_err() { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } if let Some(meta) = metadata { @@ -597,7 +709,7 @@ impl PropagationClient { match coord.reassemble() { Ok(payload) => complete_payload = Some(payload), Err(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } } @@ -620,7 +732,7 @@ impl PropagationClient { match link.handle_response_plaintext(payload) { Ok((_request_id, response_data)) => response_data, Err(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } } @@ -685,7 +797,7 @@ impl PropagationClient { let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) { Ok(v) => v, Err(_) => { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } }; @@ -701,12 +813,14 @@ impl PropagationClient { } if self.available_messages.is_empty() { - self.state = PropagationClientState::Complete; + self.status.state = PropagationClientState::Complete; + self.status.progress = 1.0; + self.status.result = Some(0); } else { self.send_get_request(); } } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } @@ -715,47 +829,52 @@ impl PropagationClient { let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) { Ok(v) => v, Err(_) => { - self.state = PropagationClientState::Failed; + 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.state = PropagationClientState::Complete; + self.status.state = PropagationClientState::Complete; } } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } /// Phase 3: mark the download complete. fn handle_purge_response(&mut self) { - self.state = PropagationClientState::Complete; + self.status.state = PropagationClientState::Complete; + self.status.progress = 1.0; } pub fn tick(&mut self) { if let Some(started) = self.started_at && started.elapsed() > self.timeout - && self.state != PropagationClientState::Idle - && self.state != PropagationClientState::Complete + && self.status.state != PropagationClientState::Idle + && self.status.state != PropagationClientState::Complete { self.cleanup(); - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; return; } - match self.state { + match self.status.state { PropagationClientState::Idle => {} PropagationClientState::LinkEstablishing => {} PropagationClientState::LinkEstablished => { @@ -767,10 +886,10 @@ impl PropagationClient { } PropagationClientState::ListRequested | PropagationClientState::GetRequested + | PropagationClientState::Receiving | PropagationClientState::PurgeRequested => {} PropagationClientState::Complete | PropagationClientState::Failed => { self.cleanup(); - self.state = PropagationClientState::Idle; } } } @@ -808,15 +927,16 @@ impl PropagationClient { 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.state = PropagationClientState::ListRequested; + self.status.state = PropagationClientState::ListRequested; } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } @@ -824,6 +944,11 @@ impl PropagationClient { fn send_get_request(&mut self) { use rmpv::Value; + 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() @@ -841,15 +966,17 @@ impl PropagationClient { if wants.is_empty() { if haves.is_empty() { - self.state = PropagationClientState::Complete; + 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.state = PropagationClientState::PurgeRequested; + self.status.state = PropagationClientState::PurgeRequested; } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } return; } @@ -863,9 +990,9 @@ impl PropagationClient { let buf = crate::encode_value(&array); if self.send_get_path_request(&buf) { - self.state = PropagationClientState::GetRequested; + self.status.state = PropagationClientState::GetRequested; } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } @@ -873,6 +1000,7 @@ impl PropagationClient { fn send_purge_request(&mut self) { use rmpv::Value; + self.receiving_for = None; let received: Vec = self .received_ids .iter() @@ -883,9 +1011,9 @@ impl PropagationClient { let buf = crate::encode_value(&array); if self.send_get_path_request(&buf) { - self.state = PropagationClientState::PurgeRequested; + self.status.state = PropagationClientState::PurgeRequested; } else { - self.state = PropagationClientState::Failed; + self.status.state = PropagationClientState::Failed; } } @@ -946,6 +1074,7 @@ impl PropagationClient { self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); + self.receiving_for = None; self.started_at = None; } @@ -978,6 +1107,7 @@ impl PropagationClient { #[cfg(test)] mod tests { use super::*; + use rns_protocol::resource::OutboundTransfer; fn active_link_pair(dest_hash: [u8; 16]) -> (Link, Link) { let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); @@ -1019,7 +1149,7 @@ mod tests { fn test_client_creation() { let (tx, _rx) = mpsc::channel(16); let client = PropagationClient::new(tx, None, None); - assert_eq!(client.state, PropagationClientState::Idle); + assert_eq!(client.status.state, PropagationClientState::Idle); assert_eq!(client.received_count(), 0); } @@ -1038,7 +1168,7 @@ mod tests { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); assert!(!client.start_download()); - assert_eq!(client.state, PropagationClientState::Idle); + assert_eq!(client.status.state, PropagationClientState::Idle); } #[test] @@ -1048,7 +1178,10 @@ mod tests { client.set_propagation_node([0xBB; 16]); assert!(client.start_download()); - assert_eq!(client.state, PropagationClientState::LinkEstablishing); + assert_eq!( + client.status.state, + PropagationClientState::LinkEstablishing + ); assert!(client.link_id.is_some()); let reg = rx.try_recv(); @@ -1060,6 +1193,20 @@ mod tests { assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_))); } + #[test] + fn test_start_download_rejects_an_active_transfer() { + let (tx, mut rx) = mpsc::channel(64); + let mut client = PropagationClient::new(tx, None, None); + client.set_propagation_node([0xBC; 16]); + + assert!(client.start_download()); + while rx.try_recv().is_ok() {} + + assert!(!client.start_download()); + assert!(rx.try_recv().is_err()); + assert_eq!(client.state(), PropagationClientState::LinkEstablishing); + } + #[test] fn test_add_local_messages() { let (tx, _rx) = mpsc::channel(16); @@ -1099,30 +1246,30 @@ mod tests { fn test_handle_list_response_empty() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &rmpv::Value::Array(vec![])).unwrap(); client.handle_list_response(&buf); - assert_eq!(client.state, PropagationClientState::Complete); + assert_eq!(client.status.state, PropagationClientState::Complete); } #[test] fn test_handle_list_response_invalid() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; client.handle_list_response(&[0xFF, 0xFF]); - assert_eq!(client.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::Failed); } #[test] fn test_handle_list_response_accepts_python_full_hash_ids() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; let id32 = vec![0xAB; 32]; let response = rmpv::Value::Array(vec![rmpv::Value::Binary(id32.clone())]); @@ -1133,14 +1280,14 @@ mod tests { assert_eq!(client.available_messages, vec![id32]); // It accepted the 32-byte ID, then failed only because this unit test // has no live link on which to send the follow-up `/get`. - assert_eq!(client.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::Failed); } #[test] fn test_handle_list_response_rejects_pre_fix_16_byte_ids() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAB; 16])]); let mut buf = Vec::new(); @@ -1148,7 +1295,7 @@ mod tests { client.handle_list_response(&buf); assert!(client.available_messages.is_empty()); - assert_eq!(client.state, PropagationClientState::Complete); + assert_eq!(client.status.state, PropagationClientState::Complete); } #[test] @@ -1157,7 +1304,7 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xBB; 16]); client.start_download(); - client.state = PropagationClientState::GetRequested; + client.status.state = PropagationClientState::GetRequested; let msg1 = vec![0xAA; 100]; let msg2 = vec![0xBB; 200]; @@ -1178,30 +1325,105 @@ mod tests { rns_crypto::sha::full_hash(&msg1).to_vec() ); assert_eq!(client.received_ids[0].len(), 32); + assert_eq!(client.transfer_status().progress, 1.0); + assert_eq!(client.transfer_status().result, Some(2)); } #[test] fn test_handle_get_response_empty() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::GetRequested; + client.status.state = PropagationClientState::GetRequested; let response = rmpv::Value::Array(vec![]); let mut buf = Vec::new(); rmpv::encode::write_value(&mut buf, &response).unwrap(); client.handle_get_response(&buf); - assert_eq!(client.state, PropagationClientState::Complete); + assert_eq!(client.status.state, PropagationClientState::Complete); + } + + #[test] + fn resource_response_retains_the_request_phase() { + let (tx, _rx) = mpsc::channel(16); + let mut client = PropagationClient::new(tx, None, None); + client.status.state = PropagationClientState::Receiving; + client.receiving_for = Some(PropagationClientState::GetRequested); + + let response = rmpv::Value::Array(vec![]); + let mut buf = Vec::new(); + rmpv::encode::write_value(&mut buf, &response).unwrap(); + client.handle_response_data(&buf); + + assert_eq!(client.status.state, PropagationClientState::Complete); + assert_eq!(client.status.progress, 1.0); + assert_eq!(client.status.result, Some(0)); + assert!(client.receiving_for.is_none()); + } + + #[test] + fn resource_response_reports_size_and_monotonic_progress() { + let (tx, mut rx) = mpsc::channel(64); + let mut client = PropagationClient::new(tx, None, None); + let (initiator, responder) = active_link_pair([0xE3; 16]); + client.link_id = Some(initiator.link_id); + client.link = Some(initiator); + client.status.state = PropagationClientState::GetRequested; + + let payload = vec![0xAB; 3_000]; + let mut sender = OutboundTransfer::new_encrypted( + payload.clone(), + false, + Duration::from_millis(50), + responder.session_keys().unwrap(), + ) + .unwrap(); + sender.resource.flags.is_response = true; + let advertisement = match sender.tick() { + TransferAction::SendAdvertisement(data) => data, + other => panic!("expected Resource advertisement, got {other:?}"), + }; + let encrypted_advertisement = responder.encrypt(&advertisement).unwrap(); + + client.handle_resource_advertisement(&encrypted_advertisement); + assert_eq!(client.status.state, PropagationClientState::Receiving); + assert_eq!(client.status.data_size, Some(payload.len())); + assert_eq!( + client.receiving_for, + Some(PropagationClientState::GetRequested) + ); + + let request = match rx.try_recv().unwrap() { + TransportMessage::Outbound(request) => request, + other => panic!("expected Resource request, got {other:?}"), + }; + let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + let request_data = responder.decrypt(&request.raw[offset..]).unwrap(); + let first_part = sender + .handle_request(&request_data) + .into_iter() + .find_map(|action| match action { + TransferAction::SendPart(_, data) => Some(data), + _ => None, + }) + .expect("sender emits at least one requested part"); + + client.handle_resource_part(&first_part); + assert!(client.status.progress > 0.0); + assert!(client.status.progress < 1.0); + let first_progress = client.status.progress; + client.handle_resource_part(&first_part); + assert!(client.status.progress >= first_progress); } #[test] fn test_handle_purge_response() { let (tx, _rx) = mpsc::channel(16); let mut client = PropagationClient::new(tx, None, None); - client.state = PropagationClientState::PurgeRequested; + client.status.state = PropagationClientState::PurgeRequested; client.handle_purge_response(); - assert_eq!(client.state, PropagationClientState::Complete); + assert_eq!(client.status.state, PropagationClientState::Complete); } #[test] @@ -1210,15 +1432,20 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xCC; 16]); client.start_download(); - assert_eq!(client.state, PropagationClientState::LinkEstablishing); + assert_eq!( + client.status.state, + PropagationClientState::LinkEstablishing + ); client.timeout = Duration::ZERO; client.tick(); - assert_eq!(client.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::Failed); client.tick(); - assert_eq!(client.state, PropagationClientState::Idle); + assert_eq!(client.status.state, PropagationClientState::Failed); + assert!(client.acknowledge_transfer()); + assert_eq!(client.status.state, PropagationClientState::Idle); } #[test] @@ -1229,7 +1456,7 @@ mod tests { client.start_download(); while rx.try_recv().is_ok() {} - client.state = PropagationClientState::Complete; + client.status.state = PropagationClientState::Complete; client.tick(); let dereg = rx.try_recv(); @@ -1248,7 +1475,7 @@ mod tests { let link_id = link.link_id; client.link = Some(link); client.link_id = Some(link_id); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; client.started_at = Some(Instant::now()); let close_body = responder_link @@ -1263,19 +1490,22 @@ mod tests { &close_body, ), interface_id: 0, + metrics: Default::default(), }) .unwrap(); client.drain_events(&std::collections::HashMap::new()); - assert_eq!(client.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::Failed); client.tick(); - assert_eq!(client.state, PropagationClientState::Idle); + assert_eq!(client.status.state, PropagationClientState::Failed); assert!(client.link.is_none()); assert!(matches!( rx.try_recv().unwrap(), TransportMessage::DeregisterDestination { hash } if hash == link_id )); + assert!(client.acknowledge_transfer()); + assert_eq!(client.status.state, PropagationClientState::Idle); } #[test] @@ -1287,18 +1517,19 @@ mod tests { let link_id = link.link_id; client.link = Some(link); client.link_id = Some(link_id); - client.state = PropagationClientState::ListRequested; + client.status.state = PropagationClientState::ListRequested; client .event_tx .try_send(DestinationEvent::InboundPacket { raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, + metrics: Default::default(), }) .unwrap(); client.drain_events(&std::collections::HashMap::new()); - assert_eq!(client.state, PropagationClientState::ListRequested); + assert_eq!(client.status.state, PropagationClientState::ListRequested); assert!(client.link.is_some()); } } diff --git a/crates/lxmf-core/src/propagation_node.rs b/crates/lxmf-core/src/propagation_node.rs index 5032269..d3d58da 100644 --- a/crates/lxmf-core/src/propagation_node.rs +++ b/crates/lxmf-core/src/propagation_node.rs @@ -10,8 +10,10 @@ use std::path::PathBuf; use crate::constants::*; use crate::message::LxMessage; -use crate::peer::LxmPeer; +use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::{PropagationEntry, PropagationStore, hex_encode}; +use crate::propagation_admission::PnOfferCandidate; +use crate::propagation_offer::{PnOfferEvaluation, PnOfferEvaluationError}; use crate::sync::{OfferResponse, SyncGet, SyncOffer, SyncSession}; use crate::types::PropagationTransientId; @@ -24,6 +26,9 @@ pub struct PropagationNodeConfig { pub min_stamp_cost: u8, pub peering_cost: u8, pub max_message_size: usize, + /// Maximum encoded inbound `/offer` request size. This follows the + /// node's advertised propagation sync budget. + pub max_offer_size: usize, } impl Default for PropagationNodeConfig { @@ -35,6 +40,7 @@ impl Default for PropagationNodeConfig { min_stamp_cost: 0, peering_cost: PEERING_COST, max_message_size: DELIVERY_LIMIT * 1024, + max_offer_size: SYNC_LIMIT * 1000, } } } @@ -141,14 +147,142 @@ pub fn read_planned_messages( .collect() } +#[derive(Debug, Clone)] +pub(crate) struct SyncOfferCandidateSnapshot { + transient_id: PropagationTransientId, + weight: f64, + size: usize, + stamp_value: u8, +} + +/// Cheap, owned view captured while the shared node lock is held. Expensive +/// peer-file loading and full-store sorting happen from this snapshot on a +/// blocking worker. +#[derive(Debug, Clone)] +pub(crate) struct SyncOfferPreparationSnapshot { + pub policy: OutboundOfferPolicy, + pub generation: u64, + peer_path: Option, + candidates: Vec, +} + +#[derive(Debug)] +pub(crate) struct PreparedSyncOffer { + pub policy: OutboundOfferPolicy, + pub generation: u64, + pub selected_ids: Vec, + pub terminal_handled_ids: Vec, + pub generation_exhausted: bool, +} + +#[derive(Debug)] +pub(crate) enum InstallPreparedSyncOffer { + Installed { + offer: SyncOffer, + generation: u64, + terminal_handled_ids: Vec, + generation_exhausted: bool, + }, + Stale, +} + +/// Blocking half of outbound-offer preparation. This function owns its input +/// and never touches a live `PropagationNode` or shared lock. +pub(crate) fn prepare_sync_offer_snapshot( + snapshot: SyncOfferPreparationSnapshot, +) -> PreparedSyncOffer { + const PER_MESSAGE_OVERHEAD: usize = 16; + const INITIAL_STRUCTURE_OVERHEAD: usize = 24; + + let transfer_limit = snapshot + .policy + .propagation_transfer_limit + .map(kilobytes_to_bytes_fail_closed); + let sync_limit = snapshot + .policy + .propagation_sync_limit + .map(kilobytes_to_bytes_fail_closed); + let mut handled_messages = snapshot.policy.handled_messages.clone(); + if let Some(path) = snapshot.peer_path.as_ref() + && let Ok(data) = std::fs::read(path) + && let Some(peer) = LxmPeer::from_bytes_with_handled(&data) + { + handled_messages.extend(peer.handled_messages); + } + + let mut candidates = snapshot.candidates; + candidates.sort_by(|left, right| { + left.weight + .total_cmp(&right.weight) + .then_with(|| left.transient_id.cmp(&right.transient_id)) + }); + + let mut cumulative_size = INITIAL_STRUCTURE_OVERHEAD; + let mut selected_ids = Vec::new(); + let mut terminal_handled_ids = Vec::new(); + let mut cumulative_deferred = false; + for candidate in candidates { + if handled_messages.contains(&candidate.transient_id) { + continue; + } + if candidate.stamp_value < snapshot.policy.minimum_stamp_cost { + terminal_handled_ids.push(candidate.transient_id); + continue; + } + + let transfer_size = candidate.size.saturating_add(PER_MESSAGE_OVERHEAD); + if transfer_limit.is_some_and(|limit| transfer_size > limit) { + terminal_handled_ids.push(candidate.transient_id); + continue; + } + + let next_size = cumulative_size.saturating_add(transfer_size); + if sync_limit.is_some_and(|limit| next_size >= limit) { + // The cumulative limit is session-local. Keep this candidate + // pending so a later sync can offer it. + cumulative_deferred = true; + continue; + } + + cumulative_size = next_size; + selected_ids.push(candidate.transient_id); + } + + // If not even one candidate fits the peer's cumulative limit, retrying + // this unchanged generation would only establish another Link and reach + // the same empty result. Treat that generation as scheduled-and-exhausted + // for the current constraints. A store revision or material announce + // policy change re-enables scheduling. + let generation_exhausted = !cumulative_deferred || selected_ids.is_empty(); + PreparedSyncOffer { + policy: snapshot.policy, + generation: snapshot.generation, + selected_ids, + terminal_handled_ids, + generation_exhausted, + } +} + +fn kilobytes_to_bytes_fail_closed(kilobytes: f64) -> usize { + if !kilobytes.is_finite() || kilobytes <= 0.0 { + return 0; + } + (kilobytes * 1000.0).floor() as usize +} + pub struct PropagationNode { config: PropagationNodeConfig, store: PropagationStore, sync_sessions: HashMap<[u8; 16], SyncSession>, pub dest_hash: [u8; 16], storage_path: Option, - /// Per-peer last offer time, for rate-limiting. + /// Transitional pre-1.1 behavior; removed when the daemon-lifetime + /// `PnInboundAdmission` becomes the live throttle owner. last_offer_times: HashMap<[u8; 16], f64>, + /// Monotonic in-process revision of the propagation store. Outbound peer + /// scheduling and offer-preparation revalidation use this to avoid both + /// stale offers and repeated scans of an unchanged fully-handled store. + offer_generation: u64, } impl PropagationNode { @@ -161,6 +295,7 @@ impl PropagationNode { dest_hash, storage_path: None, last_offer_times: HashMap::new(), + offer_generation: 0, } } @@ -172,6 +307,14 @@ impl PropagationNode { self.config.min_stamp_cost = cost; } + pub fn offer_generation(&self) -> u64 { + self.offer_generation + } + + fn advance_offer_generation(&mut self) { + self.offer_generation = self.offer_generation.saturating_add(1); + } + /// Disk-backed node. Loads existing messages from `storage_path` on startup. pub fn with_storage( config: PropagationNodeConfig, @@ -186,6 +329,7 @@ impl PropagationNode { dest_hash, storage_path: Some(storage_path), last_offer_times: HashMap::new(), + offer_generation: 0, }; node.load_from_disk()?; Ok(node) @@ -259,8 +403,11 @@ impl PropagationNode { } } - self.store.insert(entry); - true + let inserted = self.store.insert(entry); + if inserted { + self.advance_offer_generation(); + } + inserted } /// Store an already propagation-packed LXMF blob (`dest_hash || encrypted_data`). @@ -306,7 +453,11 @@ impl PropagationNode { } } - self.store.insert(entry) + let inserted = self.store.insert(entry); + if inserted { + self.advance_offer_generation(); + } + inserted } /// Store a validated propagated LXMF blob with its propagation-node stamp. @@ -362,7 +513,11 @@ impl PropagationNode { } } - self.store.insert(entry) + let inserted = self.store.insert(entry); + if inserted { + self.advance_offer_generation(); + } + inserted } fn load_from_disk(&mut self) -> std::io::Result<()> { @@ -446,14 +601,18 @@ impl PropagationNode { pe.stamped = false; } - self.store.insert(pe); - loaded += 1; + if self.store.insert(pe) { + loaded += 1; + } } } if loaded > 0 || quarantined > 0 { tracing::info!(loaded, quarantined, "loaded propagation messages from disk"); } + if loaded > 0 { + self.advance_offer_generation(); + } Ok(()) } @@ -468,6 +627,10 @@ impl PropagationNode { self.store.cull_by_weight(self.config.max_storage); let after = self.store.len(); + if before != after { + self.advance_offer_generation(); + } + if before > after && let Some(ref dir) = self.storage_path { @@ -564,11 +727,25 @@ impl PropagationNode { let filename = format!("{}.peer", hex_encode(&peer.destination_hash)); let path = dir.join(filename); let data = peer.to_bytes_with_handled(); - std::fs::write(path, data)?; + crate::persist::write_file_atomic(&path, &data)?; } Ok(()) } + /// Remove persisted state for an explicitly unpeered destination. + pub fn delete_peer(&mut self, peer_hash: &[u8; 16]) -> std::io::Result<()> { + self.remove_session(peer_hash); + let Some(dir) = self.storage_path.as_ref() else { + return Ok(()); + }; + let path = dir.join(format!("{}.peer", hex_encode(peer_hash))); + match std::fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } + } + /// Inverse-offer pattern: the peer lists what it has; we return the IDs /// we hold that the peer does not. Python reference: /// LXMRouter.offer_request_received(). @@ -586,49 +763,6 @@ impl PropagationNode { .collect() } - /// Offer request with typed error responses. Python reference: - /// LXMRouter.offer_request() (LXMRouter.py:2139-2189). - /// - /// The returned `OfferResponse` distinguishes - /// NoIdentity/Throttled/NoAccess/InvalidKey errors from - /// HaveAll/WantAll/WantSome outcomes. - pub fn offer_request_checked( - &mut self, - _peer_hash: [u8; 16], - identity_known: bool, - is_throttled: bool, - access_allowed: bool, - peering_key_valid: bool, - offered_ids: &[PropagationTransientId], - ) -> OfferResponse { - if !identity_known { - return OfferResponse::ErrorNoIdentity; - } - if is_throttled { - return OfferResponse::ErrorThrottled; - } - if !access_allowed { - return OfferResponse::ErrorNoAccess; - } - if !peering_key_valid { - return OfferResponse::ErrorInvalidKey; - } - - let wanted: Vec = offered_ids - .iter() - .filter(|id| !self.store.contains(id)) - .copied() - .collect(); - - if wanted.is_empty() { - OfferResponse::HaveAll - } else if wanted.len() == offered_ids.len() { - OfferResponse::WantAll - } else { - OfferResponse::WantSome(wanted.iter().map(|id| id.to_vec()).collect()) - } - } - /// Wire format matches Python: Boolean for WantAll/HaveAll, integer for /// error codes, array of binary IDs for WantSome. pub fn encode_offer_response(response: &OfferResponse) -> Vec { @@ -656,8 +790,10 @@ impl PropagationNode { /// LXMRouter.offer_request() (LXMRouter.py:2139-2189). /// /// `request_data` is msgpack `[peering_key, [transient_id_1, ...]]`. - /// Decodes, runs `offer_request_checked`, and returns an encoded - /// `OfferResponse` ready for `link.create_response()`. + /// Transitional compatibility wrapper for callers that still compute the + /// outer identity/access/throttle gates. New daemon code must preflight a + /// long-lived `PnInboundAdmission` and call `evaluate_offer_request` + /// directly before committing the exact candidate. pub fn handle_offer_request( &mut self, request_data: &[u8], @@ -665,78 +801,65 @@ impl PropagationNode { ) -> Vec { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs_f64()) + .map(|duration| duration.as_secs_f64()) .unwrap_or(0.0); - if let Some(&last_time) = self.last_offer_times.get(&ctx.peer_hash) - && now - last_time < PN_STAMP_THROTTLE as f64 + if self + .last_offer_times + .get(&ctx.peer_hash) + .is_some_and(|last_time| now - last_time < PN_STAMP_THROTTLE as f64) { return Self::encode_offer_response(&OfferResponse::ErrorThrottled); } - let (peering_key, offered_ids) = match Self::decode_offer_request(request_data) { - Some(parsed) => parsed, - None => { - return Self::encode_offer_response(&OfferResponse::ErrorInvalidData); - } + let offer = match crate::propagation_offer::decode(request_data, self.config.max_offer_size) + { + Ok(offer) => offer, + Err(error) => return Self::encode_offer_response(&error.wire_response()), }; - // Python validates peering_id = local_identity.hash || remote_identity.hash. - let peering_key_valid = if peering_key.is_empty() { - self.config.peering_cost == 0 - } else if peering_key.len() == 32 { - if let (Some(local_hash), Some(remote_hash)) = - (ctx.local_identity_hash, ctx.remote_identity_hash) - { - let mut key = [0u8; 32]; - key.copy_from_slice(&peering_key); - let mut peering_id = Vec::with_capacity(32); - peering_id.extend_from_slice(local_hash); - peering_id.extend_from_slice(remote_hash); - crate::stamper::validate_peering_key(&peering_id, &key, self.config.peering_cost) - } else { - false + let response = if !ctx.identity_known { + OfferResponse::ErrorNoIdentity + } else if ctx.is_throttled { + OfferResponse::ErrorThrottled + } else if !ctx.access_allowed { + OfferResponse::ErrorNoAccess + } else if let (Some(local_hash), Some(remote_hash)) = + (ctx.local_identity_hash, ctx.remote_identity_hash) + { + match crate::propagation_offer::evaluate_decoded( + offer, + local_hash, + remote_hash, + self.config.peering_cost, + |transient_id| self.store.contains(transient_id), + ) { + Ok(evaluation) => evaluation.into_wire_response(), + Err(error) => error.wire_response(), } } else { - false + OfferResponse::ErrorInvalidKey }; - let response = self.offer_request_checked( - ctx.peer_hash, - ctx.identity_known, - ctx.is_throttled, - ctx.access_allowed, - peering_key_valid, - &offered_ids, - ); - self.last_offer_times.insert(ctx.peer_hash, now); - Self::encode_offer_response(&response) } - /// Expected wire format: `[peering_key_bytes, [transient_id_1, ...]]`. - fn decode_offer_request(data: &[u8]) -> Option<(Vec, Vec)> { - let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?; - let arr = value.as_array()?; - if arr.len() < 2 { - return None; - } - - let peering_key = arr[0].as_slice().unwrap_or(&[]).to_vec(); - - let ids_array = arr[1].as_array()?; - let mut offered_ids = Vec::with_capacity(ids_array.len()); - for id_val in ids_array { - if let Some(id_bytes) = id_val.as_slice() - && id_bytes.len() == 32 - { - let mut tid = [0u8; 32]; - tid.copy_from_slice(id_bytes); - offered_ids.push(tid); - } - } - - Some((peering_key, offered_ids)) + /// Evaluate a preflighted `/offer` without mutating admission state. + pub fn evaluate_offer_request( + &self, + request_data: &[u8], + local_identity_hash: &[u8; 16], + candidate: &PnOfferCandidate, + ) -> Result { + let remote_identity_hash = candidate.peer_identity_hash(); + crate::propagation_offer::evaluate( + request_data, + local_identity_hash, + &remote_identity_hash, + self.config.peering_cost, + self.config.max_offer_size, + |transient_id| self.store.contains(transient_id), + ) } /// Handle a Link REQUEST at the `/get` path for client download. Python @@ -853,11 +976,12 @@ impl PropagationNode { if !owned { return; } - if let Some(entry) = self.store.remove(tid) - && let Some(ref dir) = self.storage_path - { - let path = dir.join(entry.filename()); - let _ = std::fs::remove_file(&path); + if let Some(entry) = self.store.remove(tid) { + self.advance_offer_generation(); + if let Some(ref dir) = self.storage_path { + let path = dir.join(entry.filename()); + let _ = std::fs::remove_file(&path); + } } } @@ -899,18 +1023,104 @@ impl PropagationNode { /// The caller sends it over an established link. Python reference: /// LXMRouter.sync_request_received(). pub fn prepare_sync_offer(&mut self, peer_hash: [u8; 16]) -> SyncOffer { - // Compute IDs before borrowing sync_sessions mutably. - let our_ids = if let Some(peer) = self.load_peer(&peer_hash) { - self.create_offer_filtered(&peer.handled_messages) - } else { - self.create_offer(peer_hash, None) - }; + let policy = self + .load_peer(&peer_hash) + .as_ref() + .map(OutboundOfferPolicy::from) + .unwrap_or_else(|| OutboundOfferPolicy::unrestricted(peer_hash)); + self.prepare_sync_offer_with_policy(&policy) + } + + /// Capture an owned offer-preparation snapshot while holding the node lock. + /// The returned value contains no references into the live store. + pub(crate) fn snapshot_sync_offer_preparation( + &self, + policy: &OutboundOfferPolicy, + ) -> SyncOfferPreparationSnapshot { + let now = crate::now_f64(); + let candidates = self + .store + .entries() + .map(|entry| SyncOfferCandidateSnapshot { + transient_id: entry.transient_id, + weight: self.store.compute_weight(entry, now), + size: entry.size, + stamp_value: entry.stamp_value, + }) + .collect(); + let peer_path = self + .storage_path + .as_ref() + .map(|dir| dir.join(format!("{}.peer", hex_encode(&policy.peer_hash)))); + + SyncOfferPreparationSnapshot { + policy: policy.clone(), + generation: self.offer_generation, + peer_path, + candidates, + } + } + + /// Revalidate and install a prepared offer. A store mutation invalidates + /// the entire result so weight ordering and limits are recomputed from a + /// fresh snapshot instead of partially accepting stale work. + pub(crate) fn install_prepared_sync_offer( + &mut self, + prepared: PreparedSyncOffer, + ) -> InstallPreparedSyncOffer { + if prepared.generation != self.offer_generation + || prepared + .selected_ids + .iter() + .any(|transient_id| !self.store.contains(transient_id)) + { + return InstallPreparedSyncOffer::Stale; + } let session = self .sync_sessions - .entry(peer_hash) - .or_insert_with(|| SyncSession::new(peer_hash)); - session.prepare_offer(our_ids, Vec::new()) + .entry(prepared.policy.peer_hash) + .or_insert_with(|| SyncSession::new(prepared.policy.peer_hash)); + let offer = + session.prepare_offer(prepared.selected_ids, prepared.policy.peering_key.clone()); + InstallPreparedSyncOffer::Installed { + offer, + generation: prepared.generation, + terminal_handled_ids: prepared.terminal_handled_ids, + generation_exhausted: prepared.generation_exhausted, + } + } + + /// Prepare one offer from an authoritative peer-policy snapshot. + /// + /// Selection mirrors `LXMPeer.sync`: only existing, unhandled messages + /// meeting the peer's stamp and transfer limits are eligible. Candidates + /// are ordered by ascending store weight before the cumulative sync cap is + /// applied. The chosen IDs are retained in the session so a subsequent + /// response cannot request data outside this offer. + pub fn prepare_sync_offer_with_policy(&mut self, policy: &OutboundOfferPolicy) -> SyncOffer { + loop { + let snapshot = self.snapshot_sync_offer_preparation(policy); + let prepared = prepare_sync_offer_snapshot(snapshot); + match self.install_prepared_sync_offer(prepared) { + InstallPreparedSyncOffer::Installed { + offer, + terminal_handled_ids, + .. + } => { + // Compatibility wrapper: production uses the staged task + // path and exposes this delta to the daemon for off-loop + // persistence. + if !terminal_handled_ids.is_empty() + && let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids) + { + tracing::warn!(%error, "failed to persist terminal offer dispositions"); + } + return offer; + } + InstallPreparedSyncOffer::Stale => continue, + } + } } /// Compare a peer's `SyncOffer` against our store and return a `SyncGet` @@ -974,6 +1184,23 @@ impl PropagationNode { } } + /// Merge peer-handled observations into persisted state using the same + /// authoritative policy that produced the offer. + pub fn persist_peer_handled( + &self, + policy: &OutboundOfferPolicy, + transient_ids: &[PropagationTransientId], + ) -> std::io::Result<()> { + let mut peer = self + .load_peer(&policy.peer_hash) + .unwrap_or_else(|| policy.to_peer()); + policy.apply_to_peer(&mut peer); + for transient_id in transient_ids { + peer.add_handled_message(transient_id); + } + self.save_peer(&peer) + } + pub fn complete_sync(&mut self, peer_hash: &[u8; 16]) { if let Some(session) = self.sync_sessions.get_mut(peer_hash) { session.mark_complete(); @@ -1051,6 +1278,17 @@ mod tests { [byte; 32] } + fn insert_offer_entry( + node: &mut PropagationNode, + transient_id: PropagationTransientId, + size: usize, + stamp_value: u8, + ) { + let entry = + PropagationEntry::new(transient_id, transient_id, [0xDD; 16], size, stamp_value); + assert!(node.store.insert(entry)); + } + fn id(byte: u8) -> Vec { vec![byte; 32] } @@ -1174,6 +1412,140 @@ mod tests { assert_eq!(filtered.len(), 1); } + #[test] + fn authoritative_offer_policy_combines_all_filters_and_real_key() { + let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + insert_offer_entry(&mut node, tid(0x01), 100, 20); // handled + insert_offer_entry(&mut node, tid(0x02), 100, 12); // low stamp + insert_offer_entry(&mut node, tid(0x03), 100, 13); // accepted + insert_offer_entry(&mut node, tid(0x04), 985, 20); // 1001 B with overhead + insert_offer_entry(&mut node, tid(0x05), 984, 13); // exact 1000 B + + let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + policy.handled_messages.insert(tid(0x01)); + policy.minimum_stamp_cost = 13; + policy.propagation_transfer_limit = Some(1.0); + policy.propagation_sync_limit = Some(10.0); + policy.peering_key = vec![0x77; 32]; + + let offer = node.prepare_sync_offer_with_policy(&policy); + + assert_eq!(offer.peering_key, vec![0x77; 32]); + assert_eq!( + offer.transient_ids, + vec![tid(0x03).to_vec(), tid(0x05).to_vec()] + ); + assert_eq!( + node.get_session(&policy.peer_hash).unwrap().offered_ids, + vec![tid(0x03), tid(0x05)] + ); + } + + #[test] + fn offer_cumulative_limit_is_decimal_and_excludes_exact_boundary() { + let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + insert_offer_entry(&mut node, tid(0x01), 50, 0); + insert_offer_entry(&mut node, tid(0x02), 50, 0); + let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + // 24 initial + (50 + 16) + (50 + 16) = 156 bytes. The second + // candidate is excluded because upstream uses next_size >= limit. + policy.propagation_sync_limit = Some(0.156); + + let offer = node.prepare_sync_offer_with_policy(&policy); + + assert_eq!(offer.transient_ids, vec![tid(0x01).to_vec()]); + } + + #[test] + fn prepared_offer_distinguishes_terminal_filters_from_cumulative_deferral() { + let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + insert_offer_entry(&mut node, tid(0x01), 10, 9); // terminal low stamp + insert_offer_entry(&mut node, tid(0x02), 100, 20); // selected + insert_offer_entry(&mut node, tid(0x03), 100, 20); // cumulative deferred + insert_offer_entry(&mut node, tid(0x04), 1000, 20); // terminal oversize + let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + policy.minimum_stamp_cost = 10; + policy.propagation_transfer_limit = Some(0.5); + policy.propagation_sync_limit = Some(0.2); + + let prepared = prepare_sync_offer_snapshot(node.snapshot_sync_offer_preparation(&policy)); + + assert_eq!(prepared.selected_ids, vec![tid(0x02)]); + assert_eq!(prepared.terminal_handled_ids, vec![tid(0x01), tid(0x04)]); + assert!( + !prepared.generation_exhausted, + "cumulative-only skips must stay pending for another batch" + ); + } + + #[test] + fn all_cumulatively_deferred_candidates_exhaust_unchanged_generation() { + let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + insert_offer_entry(&mut node, tid(0x01), 50, 20); + insert_offer_entry(&mut node, tid(0x02), 50, 20); + let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + // Initial overhead (24) + either transfer (50 + 16) exceeds this + // generation's peer policy, so a reconnect cannot make progress. + policy.propagation_sync_limit = Some(0.05); + + let prepared = prepare_sync_offer_snapshot(node.snapshot_sync_offer_preparation(&policy)); + + assert!(prepared.selected_ids.is_empty()); + assert!(prepared.terminal_handled_ids.is_empty()); + assert!( + prepared.generation_exhausted, + "zero-progress cumulative deferral must not hot-loop the same generation" + ); + } + + #[test] + fn prepared_offer_revalidates_store_generation_before_install() { + let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut first = vec![0x11; DESTINATION_LENGTH + 1]; + first[0] = 0x01; + assert!(node.accept_propagated_blob(&first, 0)); + let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + let snapshot = node.snapshot_sync_offer_preparation(&policy); + + let mut second = vec![0x22; DESTINATION_LENGTH + 1]; + second[0] = 0x02; + assert!(node.accept_propagated_blob(&second, 0)); + let prepared = prepare_sync_offer_snapshot(snapshot); + + assert!(matches!( + node.install_prepared_sync_offer(prepared), + InstallPreparedSyncOffer::Stale + )); + } + + #[test] + fn passed_and_persisted_handled_sets_are_unioned() { + let dir = std::env::temp_dir().join("lxmf_test_offer_handled_union"); + let _ = std::fs::remove_dir_all(&dir); + let mut node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + dir.clone(), + ) + .unwrap(); + insert_offer_entry(&mut node, tid(0x01), 50, 0); + insert_offer_entry(&mut node, tid(0x02), 50, 0); + insert_offer_entry(&mut node, tid(0x03), 50, 0); + + let mut persisted = LxmPeer::new([0xBB; 16]); + persisted.add_handled_message(&tid(0x01)); + node.save_peer(&persisted).unwrap(); + let mut policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + policy.handled_messages.insert(tid(0x02)); + + let offer = node.prepare_sync_offer_with_policy(&policy); + assert_eq!(offer.transient_ids, vec![tid(0x03).to_vec()]); + + node.delete_peer(&[0xBB; 16]).unwrap(); + assert!(node.load_peers().is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn test_propagation_disk_persistence() { let dir = std::env::temp_dir().join("lxmf_test_prop_persist"); @@ -1484,6 +1856,14 @@ mod tests { peer.add_handled_message(&tid(0xCC)); node.save_peer(&peer).unwrap(); + drop(node); + let node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + dir.clone(), + ) + .unwrap(); + let loaded_peers = node.load_peers(); assert_eq!(loaded_peers.len(), 1); assert!(loaded_peers[0].has_handled(&live_id)); @@ -1781,84 +2161,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] - fn test_offer_request_checked_no_identity() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let resp = node.offer_request_checked([0xDD; 16], false, false, true, true, &[]); - assert_eq!(resp, OfferResponse::ErrorNoIdentity); - } - - #[test] - fn test_offer_request_checked_throttled() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let resp = node.offer_request_checked([0xDD; 16], true, true, true, true, &[]); - assert_eq!(resp, OfferResponse::ErrorThrottled); - } - - #[test] - fn test_offer_request_checked_no_access() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let resp = node.offer_request_checked([0xDD; 16], true, false, false, true, &[]); - assert_eq!(resp, OfferResponse::ErrorNoAccess); - } - - #[test] - fn test_offer_request_checked_invalid_key() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let resp = node.offer_request_checked([0xDD; 16], true, false, true, false, &[]); - assert_eq!(resp, OfferResponse::ErrorInvalidKey); - } - - #[test] - fn test_offer_request_checked_have_all() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - let tid = msg.transient_id.unwrap(); - node.accept_message(&msg); - - let resp = node.offer_request_checked([0xDD; 16], true, false, true, true, &[tid]); - assert_eq!(resp, OfferResponse::HaveAll); - } - - #[test] - fn test_offer_request_checked_want_all() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - - let resp = node.offer_request_checked( - [0xDD; 16], - true, - false, - true, - true, - &[tid(0x11), tid(0x22)], - ); - assert_eq!(resp, OfferResponse::WantAll); - } - - #[test] - fn test_offer_request_checked_want_some() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); - let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); - let stored_tid = msg.transient_id.unwrap(); - node.accept_message(&msg); - - let resp = node.offer_request_checked( - [0xDD; 16], - true, - false, - true, - true, - &[stored_tid, tid(0x99)], - ); - match resp { - OfferResponse::WantSome(ids) => { - assert_eq!(ids.len(), 1); - assert_eq!(ids[0], id(0x99)); - } - _ => panic!("expected WantSome"), - } - } - #[test] fn test_encode_offer_response_roundtrip() { let encoded = PropagationNode::encode_offer_response(&OfferResponse::WantAll); @@ -1923,6 +2225,32 @@ mod tests { assert_eq!(response, OfferResponse::WantAll); } + #[test] + fn test_offer_evaluation_uses_preflight_candidate_identity() { + let cost = 8; + let local_identity = [0xAA; 16]; + let remote_identity = [0xBB; 16]; + let config = PropagationNodeConfig { + peering_cost: cost, + ..Default::default() + }; + let node = PropagationNode::new(config, [0xCC; 16]); + let mut admission = crate::propagation_admission::PnInboundAdmission::default(); + let candidate = admission + .preflight_offer([0xDD; 16], Some(remote_identity), std::time::Duration::ZERO) + .unwrap(); + let key = peering_key(&local_identity, &remote_identity, cost); + let request = crate::encode_value(&rmpv::Value::Array(vec![ + rmpv::Value::Binary(key.to_vec()), + rmpv::Value::Array(vec![rmpv::Value::Binary(id(0x11))]), + ])); + + assert_eq!( + node.evaluate_offer_request(&request, &local_identity, &candidate), + Ok(PnOfferEvaluation::WantAll) + ); + } + #[test] fn test_handle_offer_request_rejects_empty_peering_key_when_cost_required() { let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); @@ -2004,52 +2332,47 @@ mod tests { #[test] fn test_handle_offer_request_invalid_data() { - let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]); + let mut node = PropagationNode::new( + PropagationNodeConfig { + peering_cost: 0, + ..Default::default() + }, + [0xAA; 16], + ); + let local_identity = [0xAA; 16]; + let remote_identity = [0xBB; 16]; let response_bytes = node.handle_offer_request( &[0xFF, 0xFF], - offer_ctx([0xBB; 16], true, false, true, None, None), + offer_ctx( + [0xBB; 16], + true, + false, + true, + Some(&local_identity), + Some(&remote_identity), + ), ); let response = OfferResponse::from_msgpack(&response_bytes); assert_eq!(response, OfferResponse::ErrorInvalidData); - } - #[test] - fn test_decode_offer_request_valid() { - use rmpv::Value; - let offer = Value::Array(vec![ - Value::Binary(vec![0xAA; 32]), - Value::Array(vec![Value::Binary(id(0x11)), Value::Binary(id(0x22))]), - ]); - let mut buf = Vec::new(); - rmpv::encode::write_value(&mut buf, &offer).unwrap(); - - let result = PropagationNode::decode_offer_request(&buf); - assert!(result.is_some()); - let (key, ids) = result.unwrap(); - assert_eq!(key, vec![0xAA; 32]); - assert_eq!(ids.len(), 2); - assert_eq!(ids[0], tid(0x11)); - assert_eq!(ids[1], tid(0x22)); - } - - #[test] - fn test_decode_offer_request_filters_bad_ids() { - use rmpv::Value; - let offer = Value::Array(vec![ - Value::Binary(vec![]), - Value::Array(vec![ - Value::Binary(vec![0x11; 16]), - Value::Binary(vec![0x22; 8]), - Value::Binary(id(0x33)), - ]), - ]); - let mut buf = Vec::new(); - rmpv::encode::write_value(&mut buf, &offer).unwrap(); - - let (_, ids) = PropagationNode::decode_offer_request(&buf).unwrap(); - assert_eq!(ids.len(), 1); - assert_eq!(ids[0], tid(0x33)); + let valid_request = crate::encode_value(&rmpv::Value::Array(vec![ + rmpv::Value::Binary(vec![]), + rmpv::Value::Array(vec![rmpv::Value::Binary(id(0x11))]), + ])); + let response_bytes = node.handle_offer_request( + &valid_request, + offer_ctx( + [0xBB; 16], + true, + false, + true, + Some(&local_identity), + Some(&remote_identity), + ), + ); + let response = OfferResponse::from_msgpack(&response_bytes); + assert_eq!(response, OfferResponse::WantAll); } #[test] diff --git a/crates/lxmf-core/src/propagation_offer.rs b/crates/lxmf-core/src/propagation_offer.rs new file mode 100644 index 0000000..4b40728 --- /dev/null +++ b/crates/lxmf-core/src/propagation_offer.rs @@ -0,0 +1,327 @@ +//! Typed evaluation of an inbound propagation-node `/offer` request. +//! +//! Admission policy and lifecycle accounting deliberately live in +//! [`crate::propagation_admission`]. Callers must pass that cheap preflight +//! before performing the peering-key work in this module, then commit the +//! returned wanted outcome to the same admission candidate. + +use crate::propagation_admission::PnOfferResponse; +use crate::stamper; +use crate::sync::OfferResponse; +use crate::types::PropagationTransientId; + +/// A binary 32-byte transient ID requires at least 34 MessagePack bytes. +const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34; + +/// A peering-key-validated offer and the subset not present in local storage. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PnOfferEvaluation { + HaveAll, + WantAll, + WantSome(Vec), +} + +impl PnOfferEvaluation { + /// Lifecycle outcome recorded by [`crate::propagation_admission`]. + pub fn admission_response(&self) -> PnOfferResponse { + match self { + Self::HaveAll => PnOfferResponse::HaveAll, + Self::WantAll => PnOfferResponse::WantAll, + Self::WantSome(_) => PnOfferResponse::WantSome, + } + } + + /// Python-compatible response value for the `/offer` request. + pub fn into_wire_response(self) -> OfferResponse { + match self { + Self::HaveAll => OfferResponse::HaveAll, + Self::WantAll => OfferResponse::WantAll, + Self::WantSome(ids) => { + OfferResponse::WantSome(ids.into_iter().map(Vec::from).collect()) + } + } + } +} + +/// Failure before an offer can be committed to admission accounting. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PnOfferEvaluationError { + InvalidData, + InvalidKey, +} + +impl PnOfferEvaluationError { + pub fn wire_response(self) -> OfferResponse { + match self { + Self::InvalidData => OfferResponse::ErrorInvalidData, + Self::InvalidKey => OfferResponse::ErrorInvalidKey, + } + } +} + +enum DecodedPeeringKey { + Empty, + Key([u8; 32]), + InvalidLength, +} + +pub(crate) struct DecodedOffer { + peering_key: DecodedPeeringKey, + transient_ids: Vec, +} + +/// Decode, validate, and determine the wanted subset without mutating +/// admission state. +pub(crate) fn evaluate( + request_data: &[u8], + local_identity_hash: &[u8; 16], + remote_identity_hash: &[u8; 16], + peering_cost: u8, + max_offer_size: usize, + contains: F, +) -> Result +where + F: FnMut(&PropagationTransientId) -> bool, +{ + let offer = decode(request_data, max_offer_size)?; + evaluate_decoded( + offer, + local_identity_hash, + remote_identity_hash, + peering_cost, + contains, + ) +} + +pub(crate) fn evaluate_decoded( + offer: DecodedOffer, + local_identity_hash: &[u8; 16], + remote_identity_hash: &[u8; 16], + peering_cost: u8, + mut contains: F, +) -> Result +where + F: FnMut(&PropagationTransientId) -> bool, +{ + let peering_key_valid = match offer.peering_key { + DecodedPeeringKey::Empty => peering_cost == 0, + DecodedPeeringKey::Key(key) => { + let mut peering_id = [0u8; 32]; + peering_id[..16].copy_from_slice(local_identity_hash); + peering_id[16..].copy_from_slice(remote_identity_hash); + stamper::validate_peering_key(&peering_id, &key, peering_cost) + } + DecodedPeeringKey::InvalidLength => false, + }; + + if !peering_key_valid { + return Err(PnOfferEvaluationError::InvalidKey); + } + + let wanted: Vec = offer + .transient_ids + .iter() + .filter(|transient_id| !contains(transient_id)) + .copied() + .collect(); + + if wanted.is_empty() { + Ok(PnOfferEvaluation::HaveAll) + } else if wanted.len() == offer.transient_ids.len() { + Ok(PnOfferEvaluation::WantAll) + } else { + Ok(PnOfferEvaluation::WantSome(wanted)) + } +} + +pub(crate) fn decode( + data: &[u8], + max_offer_size: usize, +) -> Result { + use std::io::Read; + + if data.len() > max_offer_size { + return Err(PnOfferEvaluationError::InvalidData); + } + + let mut remaining = data; + let field_count = rmp::decode::read_array_len(&mut remaining) + .map_err(|_| PnOfferEvaluationError::InvalidData)?; + if field_count != 2 { + return Err(PnOfferEvaluationError::InvalidData); + } + + let peering_key_len = rmp::decode::read_bin_len(&mut remaining) + .map_err(|_| PnOfferEvaluationError::InvalidData)? as usize; + if peering_key_len > remaining.len() { + return Err(PnOfferEvaluationError::InvalidData); + } + let peering_key = match peering_key_len { + 0 => DecodedPeeringKey::Empty, + 32 => { + let mut key = [0u8; 32]; + key.copy_from_slice(&remaining[..32]); + DecodedPeeringKey::Key(key) + } + _ => DecodedPeeringKey::InvalidLength, + }; + remaining = &remaining[peering_key_len..]; + + let transient_id_count = rmp::decode::read_array_len(&mut remaining) + .map_err(|_| PnOfferEvaluationError::InvalidData)? as usize; + if transient_id_count > remaining.len() / ENCODED_TRANSIENT_ID_MIN_BYTES { + return Err(PnOfferEvaluationError::InvalidData); + } + + let mut transient_ids = Vec::with_capacity(transient_id_count); + for _ in 0..transient_id_count { + let encoded_len = rmp::decode::read_bin_len(&mut remaining) + .map_err(|_| PnOfferEvaluationError::InvalidData)? as usize; + if encoded_len != 32 { + return Err(PnOfferEvaluationError::InvalidData); + } + let mut transient_id = [0u8; 32]; + remaining + .read_exact(&mut transient_id) + .map_err(|_| PnOfferEvaluationError::InvalidData)?; + transient_ids.push(transient_id); + } + + if !remaining.is_empty() { + return Err(PnOfferEvaluationError::InvalidData); + } + + Ok(DecodedOffer { + peering_key, + transient_ids, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use rmpv::Value; + + fn encode_offer(key: Value, ids: Value) -> Vec { + crate::encode_value(&Value::Array(vec![key, ids])) + } + + fn id(value: u8) -> PropagationTransientId { + [value; 32] + } + + #[test] + fn strict_decode_rejects_malformed_fields_and_trailing_bytes() { + let malformed = [ + vec![0xc1], + crate::encode_value(&Value::Array(vec![])), + crate::encode_value(&Value::Array(vec![ + Value::Binary(vec![]), + Value::Array(vec![]), + Value::Nil, + ])), + encode_offer(Value::Nil, Value::Array(vec![])), + encode_offer(Value::String("key".into()), Value::Array(vec![])), + encode_offer(Value::Binary(vec![]), Value::Nil), + encode_offer( + Value::Binary(vec![]), + Value::Array(vec![Value::Binary(vec![1; 31])]), + ), + encode_offer(Value::Binary(vec![]), Value::Array(vec![Value::from(1)])), + encode_offer( + Value::Binary(vec![]), + Value::Array(vec![Value::String( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), + )]), + ), + ]; + + for request in malformed { + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false), + Err(PnOfferEvaluationError::InvalidData) + ); + } + + let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![])); + trailing.push(0xc0); + assert_eq!( + evaluate(&trailing, &[1; 16], &[2; 16], 0, 1024, |_| false), + Err(PnOfferEvaluationError::InvalidData) + ); + } + + #[test] + fn decode_rejects_requests_over_the_bounded_sync_budget() { + let request = vec![0xc0; 65]; + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 0, 64, |_| false), + Err(PnOfferEvaluationError::InvalidData) + ); + } + + #[test] + fn decode_rejects_declared_id_count_before_allocating_entries() { + let mut request = Vec::new(); + rmp::encode::write_array_len(&mut request, 2).unwrap(); + rmp::encode::write_bin_len(&mut request, 0).unwrap(); + rmp::encode::write_array_len(&mut request, u32::MAX).unwrap(); + + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false), + Err(PnOfferEvaluationError::InvalidData) + ); + } + + #[test] + fn empty_key_is_valid_only_when_peering_work_is_disabled() { + let request = encode_offer( + Value::Binary(vec![]), + Value::Array(vec![Value::Binary(id(3).to_vec())]), + ); + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false), + Ok(PnOfferEvaluation::WantAll) + ); + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false), + Err(PnOfferEvaluationError::InvalidKey) + ); + } + + #[test] + fn wanted_evaluation_preserves_offer_order_and_duplicates() { + let request = encode_offer( + Value::Binary(vec![]), + Value::Array(vec![ + Value::Binary(id(1).to_vec()), + Value::Binary(id(2).to_vec()), + Value::Binary(id(2).to_vec()), + Value::Binary(id(3).to_vec()), + ]), + ); + + assert_eq!( + evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]), + Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)])) + ); + } + + #[test] + fn outcomes_map_to_admission_and_wire_types() { + assert_eq!( + PnOfferEvaluation::HaveAll.admission_response(), + PnOfferResponse::HaveAll + ); + assert_eq!( + PnOfferEvaluation::WantAll.admission_response(), + PnOfferResponse::WantAll + ); + let some = PnOfferEvaluation::WantSome(vec![id(7)]); + assert_eq!(some.admission_response(), PnOfferResponse::WantSome); + assert_eq!( + some.into_wire_response(), + OfferResponse::WantSome(vec![id(7).to_vec()]) + ); + } +} diff --git a/crates/lxmf-core/src/propagation_sync.rs b/crates/lxmf-core/src/propagation_sync.rs index 525f14c..bae8686 100644 --- a/crates/lxmf-core/src/propagation_sync.rs +++ b/crates/lxmf-core/src/propagation_sync.rs @@ -9,22 +9,27 @@ //! 3. Receive a Response packet (context 0x0A) with OfferResponse. //! 4. Transfer requested messages as a Resource. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use bytes::Bytes; -use rns_crypto::ed25519::Ed25519PublicKey; +use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use rns_link::link::{CloseReason, Link}; -use rns_protocol::resource::{OutboundTransfer, TransferAction}; +use rns_protocol::resource::{ + MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundTransfer, ResourceError, TransferAction, +}; use rns_transport::link_messages::DestinationEvent; use rns_transport::messages::{OutboundRequest, TransportMessage}; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, oneshot}; use crate::constants::OFFER_REQUEST_PATH; -use crate::peer::LxmPeer; +use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::hex_encode; -use crate::propagation_node::{PropagationNode, PropagationNodeConfig}; +use crate::propagation_node::{ + InstallPreparedSyncOffer, PreparedSyncOffer, PropagationNode, PropagationNodeConfig, + prepare_sync_offer_snapshot, read_planned_messages, +}; use crate::sync::OfferResponse; use crate::types::PropagationTransientId; @@ -39,6 +44,61 @@ pub enum SyncTaskState { Failed, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PeerSyncTerminalState { + Complete, + Failed, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PeerSyncTerminalResult { + pub peer_hash: [u8; 16], + pub state: PeerSyncTerminalState, + /// Store generation used by successful offer preparation. Failures leave + /// this unset so unchanged-store work remains retryable after backoff. + pub offer_generation: Option, + /// True only when no cumulative-limit or vanished-file work remains for + /// this generation. + pub generation_exhausted: bool, +} + +#[derive(Debug)] +struct PreparedTransferBatch { + requested_count: usize, + transient_ids: Vec, + payload: Vec, +} + +fn prepare_outbound_resource_transfers( + payload: Vec, + auto_compress: bool, + rtt: Duration, + link_keys: rns_link::key_derivation::LinkKeys, +) -> Result, ResourceError> { + if payload.len() <= MAX_EFFICIENT_SIZE { + return Ok(VecDeque::from([OutboundTransfer::new_encrypted( + payload, + auto_compress, + rtt, + link_keys, + )?])); + } + + // Reticulum encrypts each logical Resource segment as one assembled blob + // before chunking it into raw RESOURCE packets. MultiSegmentOutbound also + // enforces the protocol's MAX_RESOURCE_SIZE / MAX_SEGMENTS bounds. + let encrypt = |plaintext: &[u8]| { + rns_link::encryption::link_encrypt(&link_keys, plaintext) + .unwrap_or_else(|_| plaintext.to_vec()) + }; + let resources = + MultiSegmentOutbound::with_encrypt(payload, auto_compress, Some(&encrypt))?.segments; + Ok(resources + .into_iter() + .map(|resource| OutboundTransfer::from_prebuilt(resource, rtt)) + .collect()) +} + pub struct PropagationSyncTask { transport_tx: mpsc::Sender, event_tx: mpsc::Sender, @@ -52,9 +112,22 @@ pub struct PropagationSyncTask { sync_interval: Duration, sync_started: Option, sync_timeout: Duration, - transfer_queue: Vec>, active_transfer: Option, + pending_transfer_segments: VecDeque, + active_transfer_ids: Vec, + transfer_preparation_rx: Option>, + ready_transfer_batch: Option, peer: Option, + offer_policy: Option, + offer_preparation_rx: Option>, + ready_prepared_offer: Option, + handled_updates: Vec, + runtime_handle: Option, + identity_pub: Option<[u8; 64]>, + identity_key: Option, + active_offer_generation: Option, + generation_exhausted: bool, + terminal_result: Option, } impl PropagationSyncTask { @@ -76,9 +149,22 @@ impl PropagationSyncTask { sync_interval: Duration::from_secs(300), sync_started: None, sync_timeout: Duration::from_secs(120), - transfer_queue: Vec::new(), active_transfer: None, + pending_transfer_segments: VecDeque::new(), + active_transfer_ids: Vec::new(), + transfer_preparation_rx: None, + ready_transfer_batch: None, peer: None, + offer_policy: None, + offer_preparation_rx: None, + ready_prepared_offer: None, + handled_updates: Vec::new(), + runtime_handle: tokio::runtime::Handle::try_current().ok(), + identity_pub: None, + identity_key: None, + active_offer_generation: None, + generation_exhausted: false, + terminal_result: None, } } @@ -106,9 +192,22 @@ impl PropagationSyncTask { sync_interval: Duration::from_secs(300), sync_started: None, sync_timeout: Duration::from_secs(120), - transfer_queue: Vec::new(), active_transfer: None, + pending_transfer_segments: VecDeque::new(), + active_transfer_ids: Vec::new(), + transfer_preparation_rx: None, + ready_transfer_batch: None, peer: None, + offer_policy: None, + offer_preparation_rx: None, + ready_prepared_offer: None, + handled_updates: Vec::new(), + runtime_handle: tokio::runtime::Handle::try_current().ok(), + identity_pub: None, + identity_key: None, + active_offer_generation: None, + generation_exhausted: false, + terminal_result: None, }) } @@ -132,13 +231,32 @@ impl PropagationSyncTask { sync_interval: Duration::from_secs(300), sync_started: None, sync_timeout: Duration::from_secs(120), - transfer_queue: Vec::new(), active_transfer: None, + pending_transfer_segments: VecDeque::new(), + active_transfer_ids: Vec::new(), + transfer_preparation_rx: None, + ready_transfer_batch: None, peer: None, + offer_policy: None, + offer_preparation_rx: None, + ready_prepared_offer: None, + handled_updates: Vec::new(), + runtime_handle: tokio::runtime::Handle::try_current().ok(), + identity_pub: None, + identity_key: None, + active_offer_generation: None, + generation_exhausted: false, + terminal_result: None, } } pub fn set_node(&mut self, dest_hash: [u8; 16]) { + if self.state != SyncTaskState::Idle && self.node_dest_hash != Some(dest_hash) { + return; + } + if self.node_dest_hash != Some(dest_hash) { + self.offer_policy = None; + } self.node_dest_hash = Some(dest_hash); } @@ -147,18 +265,96 @@ impl PropagationSyncTask { /// Python `LXMPeer.sync()` is called directly by lxmd control requests; /// this public shim preserves that behavior without waiting for the /// periodic sync interval. - pub fn request_sync_now(&mut self, dest_hash: [u8; 16]) { - self.node_dest_hash = Some(dest_hash); - if self.state == SyncTaskState::Idle { - self.start_sync(dest_hash); - self.last_sync = Instant::now(); + pub fn request_sync_now(&mut self, dest_hash: [u8; 16]) -> bool { + if self.state != SyncTaskState::Idle || self.terminal_result.is_some() { + return false; } + self.node_dest_hash = Some(dest_hash); + self.offer_policy = None; + self.start_sync(dest_hash); + self.last_sync = Instant::now(); + true + } + + /// Force an immediate sync using an authoritative peer-policy snapshot. + pub fn request_sync_now_with_policy(&mut self, policy: OutboundOfferPolicy) -> bool { + if self.state != SyncTaskState::Idle || self.terminal_result.is_some() { + return false; + } + let dest_hash = policy.peer_hash; + self.node_dest_hash = Some(dest_hash); + self.offer_policy = Some(policy); + self.start_sync(dest_hash); + self.last_sync = Instant::now(); + true + } + + /// Configure the local identity used for Link identification. Production + /// peer sync must set this before requesting a sync; compatibility callers + /// without identity material retain the historical unidentified behavior. + pub fn set_identity(&mut self, identity_pub: [u8; 64], identity_key: Ed25519PrivateKey) { + self.identity_pub = Some(identity_pub); + self.identity_key = Some(identity_key); + } + + /// Drain peer-handled updates discovered during offer negotiation or + /// proven Resource transfer. The daemon merges these into its authoritative + /// `LxmPeer` and persists that peer. + pub fn take_handled_updates(&mut self) -> Vec { + std::mem::take(&mut self.handled_updates) + } + + pub fn take_terminal_peer_result(&mut self) -> Option { + self.terminal_result.take() + } + + /// Cancel all active and pending work for one peer. Dropping the bounded + /// worker receivers makes late preparation results inert, and clearing + /// handled deltas prevents an explicit unpeer from recreating persistence. + pub fn cancel_peer_sync(&mut self, peer_hash: &[u8; 16]) -> bool { + let matches_active = self.node_dest_hash.as_ref() == Some(peer_hash); + let matches_policy = self + .offer_policy + .as_ref() + .is_some_and(|policy| &policy.peer_hash == peer_hash); + if !matches_active && !matches_policy { + return false; + } + + if matches_active && self.state != SyncTaskState::Idle { + self.cleanup_sync(); + } + if let Ok(mut node) = self.propagation_node.lock() { + node.remove_session(peer_hash); + } + self.node_dest_hash = None; + self.offer_policy = None; + self.offer_preparation_rx = None; + self.ready_prepared_offer = None; + self.transfer_preparation_rx = None; + self.ready_transfer_batch = None; + self.active_transfer = None; + self.pending_transfer_segments.clear(); + self.active_transfer_ids.clear(); + self.active_offer_generation = None; + self.generation_exhausted = false; + self.handled_updates.clear(); + self.terminal_result = None; + self.state = SyncTaskState::Idle; + true } pub fn node_dest_hash(&self) -> Option<[u8; 16]> { self.node_dest_hash } + fn blocking_runtime(&mut self) -> Option { + if self.runtime_handle.is_none() { + self.runtime_handle = tokio::runtime::Handle::try_current().ok(); + } + self.runtime_handle.clone() + } + pub fn accept_message(&mut self, msg: &crate::message::LxMessage) -> bool { self.propagation_node .lock() @@ -222,14 +418,19 @@ impl PropagationSyncTask { transfer.handle_hmu(&plaintext); } } + rns_wire::context::PacketContext::ResourceReq => { + self.handle_resource_request(data); + } rns_wire::context::PacketContext::ResourcePrf => { // Python Packet.pack() sends PROOF+RESOURCE_PRF as // plaintext (Packet.py:195-197) on PacketType::Proof. // Body = resource_hash(32) || proof(32). - if let Some(ref mut transfer) = self.active_transfer - && transfer.handle_proof(data) - { - self.active_transfer = None; + let completed = self + .active_transfer + .as_mut() + .is_some_and(|transfer| transfer.handle_proof(data)); + if completed { + self.complete_active_transfer_segment(); } } rns_wire::context::PacketContext::Response => { @@ -241,6 +442,10 @@ impl PropagationSyncTask { self.handle_offer_response(offer_response); } } + rns_wire::context::PacketContext::ResourceRcl + | rns_wire::context::PacketContext::ResourceIcl => { + self.handle_resource_cancel(data); + } rns_wire::context::PacketContext::LinkClose => { self.handle_link_closed(header.destination_hash, Some(data)); } @@ -252,6 +457,98 @@ impl PropagationSyncTask { } } + fn handle_resource_request(&mut self, encrypted_data: &[u8]) { + let Some(plaintext) = self + .link + .as_ref() + .and_then(|link| link.decrypt(encrypted_data).ok()) + else { + return; + }; + let resource_hash_start = + if plaintext.first().copied() == Some(rns_protocol::resource::HASHMAP_IS_EXHAUSTED) { + 1 + rns_protocol::resource::MAPHASH_LEN + } else { + 1 + }; + let Some(requested_resource_hash) = + plaintext.get(resource_hash_start..resource_hash_start + 32) + else { + return; + }; + let Some(transfer) = self.active_transfer.as_mut() else { + return; + }; + if requested_resource_hash != transfer.resource.resource_hash { + return; + } + let actions = transfer.handle_request(&plaintext); + + for action in actions { + match action { + TransferAction::SendPart(_, part_data) => self + .send_resource_packet(&part_data, rns_wire::context::PacketContext::Resource), + TransferAction::SendHmu(hmu_data) => self + .send_resource_packet(&hmu_data, rns_wire::context::PacketContext::ResourceHmu), + TransferAction::SendCancel(cancel_type, resource_hash) => { + let context = match cancel_type { + rns_protocol::resource::CancelType::Icl => { + rns_wire::context::PacketContext::ResourceIcl + } + rns_protocol::resource::CancelType::Rcl => { + rns_wire::context::PacketContext::ResourceRcl + } + }; + self.send_resource_packet(&resource_hash, context); + self.fail_active_transfer(); + break; + } + TransferAction::Failed(_) => { + self.fail_active_transfer(); + break; + } + TransferAction::Complete => { + self.complete_active_transfer_segment(); + break; + } + // OutboundTransfer::handle_request currently emits only + // parts, hashmap updates, or initiator-cancel. Ignore actions + // belonging to other Resource lifecycle roles. + TransferAction::None + | TransferAction::SendAdvertisement(_) + | TransferAction::SendProof(_) + | TransferAction::SendRequest(_) => {} + } + } + } + + fn handle_resource_cancel(&mut self, encrypted_data: &[u8]) { + let Some(plaintext) = self + .link + .as_ref() + .and_then(|link| link.decrypt(encrypted_data).ok()) + else { + return; + }; + let Ok(resource_hash) = <[u8; 32]>::try_from(plaintext.as_slice()) else { + return; + }; + let matches_active = self + .active_transfer + .as_ref() + .is_some_and(|transfer| transfer.resource.resource_hash == resource_hash); + if matches_active { + self.fail_active_transfer(); + } + } + + fn fail_active_transfer(&mut self) { + self.active_transfer = None; + self.pending_transfer_segments.clear(); + self.active_transfer_ids.clear(); + self.state = SyncTaskState::Failed; + } + fn handle_link_closed(&mut self, link_id: [u8; 16], encrypted_teardown: Option<&[u8]>) -> bool { if self.link_id != Some(link_id) { return false; @@ -271,7 +568,10 @@ impl PropagationSyncTask { if verified { self.active_transfer = None; - self.transfer_queue.clear(); + self.pending_transfer_segments.clear(); + self.active_transfer_ids.clear(); + self.transfer_preparation_rx = None; + self.ready_transfer_batch = None; self.state = SyncTaskState::Failed; } @@ -325,6 +625,10 @@ impl PropagationSyncTask { peer.link_established(link_id, establishment_rate); } } + if !self.send_identify() { + self.state = SyncTaskState::Failed; + return; + } self.state = SyncTaskState::Offering; } Err(_) => { @@ -340,32 +644,47 @@ impl PropagationSyncTask { None => return, }; + let offered_ids = self + .propagation_node + .lock() + .ok() + .and_then(|node| { + node.get_session(&node_hash) + .map(|session| session.offered_ids.clone()) + }) + .unwrap_or_default(); + match response { - OfferResponse::WantAll => { - let all_ids = self - .propagation_node - .lock() - .map(|node| node.create_offer(node_hash, None)) - .unwrap_or_default(); - self.queue_messages_for_ids(&all_ids); - } + OfferResponse::WantAll => self.prepare_transfer_for_ids(&offered_ids), OfferResponse::HaveAll => { + self.record_handled_updates(&offered_ids); + if let Ok(mut node) = self.propagation_node.lock() { + node.complete_sync(&node_hash); + } self.state = SyncTaskState::Complete; } OfferResponse::WantSome(wanted_id_bytes) => { + let offered = offered_ids.iter().copied().collect::>(); + let mut seen = HashSet::new(); let wanted_ids: Vec = wanted_id_bytes .iter() .filter_map(|id| { if id.len() == 32 { let mut arr = [0u8; 32]; arr.copy_from_slice(id); - Some(arr) + (offered.contains(&arr) && seen.insert(arr)).then_some(arr) } else { None } }) .collect(); - self.queue_messages_for_ids(&wanted_ids); + let already_handled = offered_ids + .iter() + .copied() + .filter(|id| !seen.contains(id)) + .collect::>(); + self.record_handled_updates(&already_handled); + self.prepare_transfer_for_ids(&wanted_ids); } _ => { self.state = SyncTaskState::Failed; @@ -373,7 +692,17 @@ impl PropagationSyncTask { } } - fn queue_messages_for_ids(&mut self, ids: &[PropagationTransientId]) { + fn prepare_transfer_for_ids(&mut self, ids: &[PropagationTransientId]) { + if ids.is_empty() { + if let Some(node_hash) = self.node_dest_hash + && let Ok(mut node) = self.propagation_node.lock() + { + node.complete_sync(&node_hash); + } + self.state = SyncTaskState::Complete; + return; + } + // Resolve paths under the node lock; read the files after dropping it. let plan = match self.propagation_node.lock() { Ok(node) => node.plan_message_reads(ids), @@ -382,14 +711,38 @@ impl PropagationSyncTask { return; } }; - let results = crate::propagation_node::read_planned_messages(&plan); - self.transfer_queue = results.into_iter().map(|(_tid, data)| data).collect(); + let requested_count = ids.len(); + let prepare = move || { + let messages = read_planned_messages(&plan); + let transient_ids = messages.iter().map(|(id, _)| *id).collect::>(); + let payload = { + use rmpv::Value; + let blobs = messages + .into_iter() + .map(|(_, data)| Value::Binary(data)) + .collect::>(); + crate::encode_value(&Value::Array(vec![ + Value::from(crate::now_f64()), + Value::Array(blobs), + ])) + }; + PreparedTransferBatch { + requested_count, + transient_ids, + payload, + } + }; - if self.transfer_queue.is_empty() { - self.state = SyncTaskState::Complete; + if let Some(runtime) = self.blocking_runtime() { + let (tx, rx) = oneshot::channel(); + runtime.spawn_blocking(move || { + let _ = tx.send(prepare()); + }); + self.transfer_preparation_rx = Some(rx); } else { - self.state = SyncTaskState::Transferring; + self.ready_transfer_batch = Some(prepare()); } + self.state = SyncTaskState::Transferring; } pub fn tick(&mut self) { @@ -404,7 +757,9 @@ impl PropagationSyncTask { match self.state { SyncTaskState::Idle => { - if self.last_sync.elapsed() >= self.sync_interval + if self.terminal_result.is_none() + && self.offer_policy.is_none() + && self.last_sync.elapsed() >= self.sync_interval && let Some(node_hash) = self.node_dest_hash { if self.message_count() > 0 { @@ -422,6 +777,23 @@ impl PropagationSyncTask { self.drive_transfers(); } SyncTaskState::Complete | SyncTaskState::Failed => { + if self.terminal_result.is_none() + && let Some(peer_hash) = self.node_dest_hash + { + let complete = self.state == SyncTaskState::Complete; + self.terminal_result = Some(PeerSyncTerminalResult { + peer_hash, + state: if complete { + PeerSyncTerminalState::Complete + } else { + PeerSyncTerminalState::Failed + }, + offer_generation: complete + .then_some(self.active_offer_generation) + .flatten(), + generation_exhausted: complete && self.generation_exhausted, + }); + } self.cleanup_sync(); self.last_sync = Instant::now(); self.state = SyncTaskState::Idle; @@ -439,14 +811,103 @@ impl PropagationSyncTask { } }; - // Wire: msgpack([peering_key, [transient_id_1, transient_id_2, ...]]) - let offer = match self.propagation_node.lock() { - Ok(mut node) => node.prepare_sync_offer(node_hash), - Err(_) => { - self.state = SyncTaskState::Failed; - return; + // Compatibility callers without an authoritative policy keep the + // synchronous wrapper. Production always uses the staged snapshot -> + // bounded blocking worker -> generation revalidation path below. + let offer = if self.offer_policy.is_none() { + match self.propagation_node.lock() { + Ok(mut node) => { + let generation = node.offer_generation(); + let offer = node.prepare_sync_offer(node_hash); + self.active_offer_generation = Some(generation); + self.generation_exhausted = true; + if offer.transient_ids.is_empty() { + node.complete_sync(&node_hash); + } + offer + } + Err(_) => { + self.state = SyncTaskState::Failed; + return; + } + } + } else { + if self.offer_preparation_rx.is_none() && self.ready_prepared_offer.is_none() { + let policy = self.offer_policy.as_ref().expect("policy checked above"); + if policy.peer_hash != node_hash { + self.state = SyncTaskState::Failed; + return; + } + let snapshot = match self.propagation_node.lock() { + Ok(node) => node.snapshot_sync_offer_preparation(policy), + Err(_) => { + self.state = SyncTaskState::Failed; + return; + } + }; + if let Some(runtime) = self.blocking_runtime() { + let (tx, rx) = oneshot::channel(); + runtime.spawn_blocking(move || { + let _ = tx.send(prepare_sync_offer_snapshot(snapshot)); + }); + self.offer_preparation_rx = Some(rx); + return; + } + self.ready_prepared_offer = Some(prepare_sync_offer_snapshot(snapshot)); + } + + let prepared = if let Some(prepared) = self.ready_prepared_offer.take() { + prepared + } else { + let Some(receiver) = self.offer_preparation_rx.as_mut() else { + self.state = SyncTaskState::Failed; + return; + }; + match receiver.try_recv() { + Ok(prepared) => { + self.offer_preparation_rx = None; + prepared + } + Err(oneshot::error::TryRecvError::Empty) => return, + Err(oneshot::error::TryRecvError::Closed) => { + self.offer_preparation_rx = None; + self.state = SyncTaskState::Failed; + return; + } + } + }; + + let installed = match self.propagation_node.lock() { + Ok(mut node) => node.install_prepared_sync_offer(prepared), + Err(_) => { + self.state = SyncTaskState::Failed; + return; + } + }; + match installed { + InstallPreparedSyncOffer::Stale => return, + InstallPreparedSyncOffer::Installed { + offer, + generation, + terminal_handled_ids, + generation_exhausted, + } => { + self.active_offer_generation = Some(generation); + self.generation_exhausted = generation_exhausted; + self.record_handled_updates(&terminal_handled_ids); + if offer.transient_ids.is_empty() + && let Ok(mut node) = self.propagation_node.lock() + { + node.complete_sync(&node_hash); + } + offer + } } }; + if offer.transient_ids.is_empty() { + self.state = SyncTaskState::Complete; + return; + } let offer_data = { use rmpv::Value; let ids: Vec = offer @@ -508,6 +969,15 @@ impl PropagationSyncTask { } fn start_sync(&mut self, node_hash: [u8; 16]) { + self.offer_preparation_rx = None; + self.ready_prepared_offer = None; + self.transfer_preparation_rx = None; + self.ready_transfer_batch = None; + self.active_transfer = None; + self.pending_transfer_segments.clear(); + self.active_transfer_ids.clear(); + self.active_offer_generation = None; + self.generation_exhausted = false; let (link, request_data) = Link::new_initiator(node_hash, 1); let link_id = link.link_id; @@ -559,20 +1029,65 @@ impl PropagationSyncTask { fn drive_transfers(&mut self) { if self.active_transfer.is_none() { - if let Some(msg_data) = self.transfer_queue.pop() { - let rtt = self - .link - .as_ref() - .and_then(|l| l.rtt) - .unwrap_or(Duration::from_millis(500)); - match OutboundTransfer::new(msg_data, true, rtt) { - Ok(transfer) => { - self.active_transfer = Some(transfer); + let batch = if let Some(batch) = self.ready_transfer_batch.take() { + Some(batch) + } else if let Some(receiver) = self.transfer_preparation_rx.as_mut() { + match receiver.try_recv() { + Ok(batch) => { + self.transfer_preparation_rx = None; + Some(batch) + } + Err(oneshot::error::TryRecvError::Empty) => return, + Err(oneshot::error::TryRecvError::Closed) => { + self.transfer_preparation_rx = None; + self.state = SyncTaskState::Failed; + return; } - Err(_) => return, } } else { - self.state = SyncTaskState::Complete; + None + }; + + if let Some(batch) = batch { + if batch.transient_ids.len() != batch.requested_count { + // Requested files that vanished between offer and read are + // not treated as remotely handled; retry this generation. + self.generation_exhausted = false; + } + if batch.transient_ids.is_empty() { + // The offer named data that the disk read could not + // produce. Treat this as a failed attempt so the daemon's + // peer backoff applies; reporting a successful but + // unexhausted generation would reconnect every tick. + self.state = SyncTaskState::Failed; + return; + } + let Some(link) = self.link.as_ref() else { + self.state = SyncTaskState::Failed; + return; + }; + let rtt = link.rtt.unwrap_or(Duration::from_millis(500)); + let Some(link_keys) = link.session_keys() else { + self.state = SyncTaskState::Failed; + return; + }; + let Ok(mut transfers) = + prepare_outbound_resource_transfers(batch.payload, true, rtt, link_keys) + else { + self.state = SyncTaskState::Failed; + return; + }; + let Some(first) = transfers.pop_front() else { + self.state = SyncTaskState::Failed; + return; + }; + self.active_transfer = Some(first); + self.pending_transfer_segments = transfers; + self.active_transfer_ids = batch.transient_ids; + } else { + // Transferring without either a live Resource or a pending + // preparation is an internal failure, never a successful sync. + self.state = SyncTaskState::Failed; return; } } @@ -593,17 +1108,33 @@ impl PropagationSyncTask { ); } TransferAction::Complete => { - self.active_transfer = None; + self.complete_active_transfer_segment(); } TransferAction::Failed(_) => { - self.active_transfer = None; - self.state = SyncTaskState::Failed; + self.fail_active_transfer(); } _ => {} } } } + fn complete_active_transfer_segment(&mut self) { + self.active_transfer = None; + if let Some(next) = self.pending_transfer_segments.pop_front() { + self.active_transfer = Some(next); + return; + } + + let completed_ids = std::mem::take(&mut self.active_transfer_ids); + self.record_handled_updates(&completed_ids); + if let Some(node_hash) = self.node_dest_hash + && let Ok(mut node) = self.propagation_node.lock() + { + node.complete_sync(&node_hash); + } + self.state = SyncTaskState::Complete; + } + fn send_resource_packet(&self, data: &[u8], context: rns_wire::context::PacketContext) { let link_id = match self.link_id { Some(id) => id, @@ -614,29 +1145,73 @@ impl PropagationSyncTask { None => return, }; - if let Ok(encrypted) = link.encrypt(data) { - let header = rns_wire::header::PacketHeader { - flags: rns_wire::flags::PacketFlags { - header_type: rns_wire::flags::HeaderType::Header1, - context_flag: false, - transport_type: rns_wire::flags::TransportType::Broadcast, - destination_type: rns_wire::flags::DestinationType::Link, - packet_type: rns_wire::flags::PacketType::Data, - }, - hops: 0, - transport_id: None, + // Resource ADVs and control frames use ordinary Link encryption. The + // assembled Resource itself was already encrypted before chunking, so + // RESOURCE parts must ride raw or their advertised map hashes will no + // longer match. + let body = if context == rns_wire::context::PacketContext::Resource { + data.to_vec() + } else if let Ok(encrypted) = link.encrypt(data) { + encrypted + } else { + return; + }; + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&body); + let _ = self + .transport_tx + .try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), destination_hash: link_id, - context, - }; - let mut raw = header.pack(); - raw.extend_from_slice(&encrypted); - let _ = self - .transport_tx - .try_send(TransportMessage::Outbound(OutboundRequest { - raw: Bytes::from(raw), - destination_hash: link_id, - })); - } + })); + } + + fn send_identify(&mut self) -> bool { + let (Some(link), Some(link_id), Some(identity_pub), Some(identity_key)) = ( + self.link.as_mut(), + self.link_id, + self.identity_pub.as_ref(), + self.identity_key.as_ref(), + ) else { + return true; + }; + let Ok(identify_data) = link.identify(identity_pub, identity_key) else { + return false; + }; + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Link, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: link_id, + context: rns_wire::context::PacketContext::LinkIdentify, + }; + let mut raw = header.pack(); + raw.extend_from_slice(&identify_data); + self.transport_tx + .try_send(TransportMessage::Outbound(OutboundRequest { + raw: Bytes::from(raw), + destination_hash: link_id, + })) + .is_ok() } /// Python LXMPeer.py:540-542. @@ -654,7 +1229,12 @@ impl PropagationSyncTask { self.link = None; self.peer = None; self.active_transfer = None; - self.transfer_queue.clear(); + self.pending_transfer_segments.clear(); + self.active_transfer_ids.clear(); + self.offer_preparation_rx = None; + self.ready_prepared_offer = None; + self.transfer_preparation_rx = None; + self.ready_transfer_batch = None; self.sync_started = None; } @@ -701,6 +1281,20 @@ impl PropagationSyncTask { pub fn peer(&self) -> Option<&LxmPeer> { self.peer.as_ref() } + + fn record_handled_updates(&mut self, transient_ids: &[PropagationTransientId]) { + if transient_ids.is_empty() { + return; + } + for transient_id in transient_ids { + if !self.handled_updates.contains(transient_id) { + self.handled_updates.push(*transient_id); + } + if let Some(peer) = self.peer.as_mut() { + peer.add_handled_message(transient_id); + } + } + } } #[cfg(test)] @@ -720,6 +1314,391 @@ mod tests { (initiator, responder) } + #[test] + fn resource_is_encrypted_before_chunking_and_advertisement_maps_raw_parts() { + let (initiator, responder) = active_link_pair([0x41; 16]); + let initiator_keys = initiator.session_keys().unwrap(); + let responder_keys = responder.session_keys().unwrap(); + let payload = (0..8192) + .map(|index| ((index * 31) % 251) as u8) + .collect::>(); + + let mut transfers = prepare_outbound_resource_transfers( + payload.clone(), + false, + Duration::from_millis(500), + initiator_keys, + ) + .unwrap(); + assert_eq!(transfers.len(), 1); + let mut transfer = transfers.pop_front().unwrap(); + assert!(transfer.resource.flags.encrypted); + + let advertisement = match transfer.tick() { + TransferAction::SendAdvertisement(data) => { + rns_protocol::resource_adv::ResourceAdvertisement::unpack(&data).unwrap() + } + other => panic!("expected Resource advertisement, got {other:?}"), + }; + assert!(advertisement.flags.encrypted); + assert_eq!(advertisement.resource_hash, transfer.resource.resource_hash); + assert_eq!(advertisement.random_hash, transfer.resource.random_hash); + let advertised_hashes = advertisement.get_map_hashes(); + assert_eq!( + advertised_hashes, + transfer.resource.map_hashes[..advertised_hashes.len()] + ); + + for (part, expected_hash) in transfer + .resource + .parts + .iter() + .zip(&transfer.resource.map_hashes) + { + assert_eq!( + rns_protocol::resource::get_map_hash(part, &transfer.resource.random_hash), + *expected_hash + ); + } + + let encrypted_stream = transfer.resource.parts.concat(); + assert_ne!(encrypted_stream, payload); + let plaintext = + rns_link::encryption::link_decrypt(&responder_keys, &encrypted_stream).unwrap(); + assert_eq!( + &plaintext[..rns_protocol::resource::RANDOM_HASH_SIZE], + &transfer.resource.random_hash + ); + assert_eq!( + &plaintext[rns_protocol::resource::RANDOM_HASH_SIZE..], + payload + ); + } + + #[test] + fn resource_packets_are_raw_while_advertisements_use_link_encryption() { + let (tx, mut rx) = mpsc::channel(4); + let (initiator, responder) = active_link_pair([0x42; 16]); + let link_id = initiator.link_id; + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.link_id = Some(link_id); + task.link = Some(initiator); + + let resource_part = b"already-encrypted-resource-part"; + task.send_resource_packet(resource_part, rns_wire::context::PacketContext::Resource); + let TransportMessage::Outbound(part_request) = rx.try_recv().unwrap() else { + panic!("expected outbound Resource packet"); + }; + let (part_header, part_offset) = + rns_wire::header::PacketHeader::unpack(&part_request.raw).unwrap(); + assert_eq!( + part_header.context, + rns_wire::context::PacketContext::Resource + ); + assert_eq!(&part_request.raw[part_offset..], resource_part); + + let advertisement = b"resource-advertisement"; + task.send_resource_packet(advertisement, rns_wire::context::PacketContext::ResourceAdv); + let TransportMessage::Outbound(adv_request) = rx.try_recv().unwrap() else { + panic!("expected outbound Resource advertisement"); + }; + let (adv_header, adv_offset) = + rns_wire::header::PacketHeader::unpack(&adv_request.raw).unwrap(); + assert_eq!( + adv_header.context, + rns_wire::context::PacketContext::ResourceAdv + ); + assert_ne!(&adv_request.raw[adv_offset..], advertisement); + assert_eq!( + responder.decrypt(&adv_request.raw[adv_offset..]).unwrap(), + advertisement + ); + } + + fn deliver_encrypted_resource_control( + task: &PropagationSyncTask, + responder: &Link, + context: rns_wire::context::PacketContext, + plaintext: &[u8], + ) { + let link_id = task.link_id.unwrap(); + let encrypted = responder.encrypt(plaintext).unwrap(); + task.event_tx + .try_send(DestinationEvent::InboundPacket { + raw: link_data_packet(link_id, context, &encrypted), + interface_id: 0, + metrics: Default::default(), + }) + .unwrap(); + } + + #[test] + fn encrypted_resource_request_retransmits_map_compatible_part_raw() { + let (tx, mut rx) = mpsc::channel(4); + let (initiator, responder) = active_link_pair([0x44; 16]); + let link_id = initiator.link_id; + let mut transfers = prepare_outbound_resource_transfers( + (0..4096).map(|index| (index % 251) as u8).collect(), + false, + Duration::from_millis(500), + initiator.session_keys().unwrap(), + ) + .unwrap(); + let transfer = transfers.pop_front().unwrap(); + let requested_index = 1; + let expected_part = transfer.resource.parts[requested_index].clone(); + let requested_hash = transfer.resource.map_hashes[requested_index]; + let random_hash = transfer.resource.random_hash; + let resource_hash = transfer.resource.resource_hash; + + let mut request = vec![rns_protocol::resource::HASHMAP_IS_NOT_EXHAUSTED]; + request.extend_from_slice(&resource_hash); + request.extend_from_slice(&requested_hash); + + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.link_id = Some(link_id); + task.link = Some(initiator); + task.active_transfer = Some(transfer); + task.state = SyncTaskState::Transferring; + let mut stale_request = request.clone(); + stale_request[1..33].fill(0xFF); + deliver_encrypted_resource_control( + &task, + &responder, + rns_wire::context::PacketContext::ResourceReq, + &stale_request, + ); + task.drain_events(&HashMap::new()); + assert!(rx.try_recv().is_err()); + assert_eq!(task.active_transfer.as_ref().unwrap().sent_parts, 0); + + deliver_encrypted_resource_control( + &task, + &responder, + rns_wire::context::PacketContext::ResourceReq, + &request, + ); + + task.drain_events(&HashMap::new()); + + let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else { + panic!("expected requested Resource part"); + }; + let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap(); + assert_eq!(header.context, rns_wire::context::PacketContext::Resource); + assert_eq!(&response.raw[offset..], expected_part); + assert_eq!( + rns_protocol::resource::get_map_hash(&response.raw[offset..], &random_hash), + requested_hash + ); + assert_eq!(task.state, SyncTaskState::Transferring); + assert_eq!(task.active_transfer.as_ref().unwrap().sent_parts, 1); + } + + #[test] + fn exhausted_resource_request_sends_link_encrypted_hmu() { + let (tx, mut rx) = mpsc::channel(4); + let (initiator, responder) = active_link_pair([0x45; 16]); + let link_id = initiator.link_id; + let hashmap_len = + rns_protocol::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU); + let mut transfers = prepare_outbound_resource_transfers( + vec![0xA7; (hashmap_len + 8) * rns_protocol::resource::SDU], + false, + Duration::from_millis(500), + initiator.session_keys().unwrap(), + ) + .unwrap(); + let transfer = transfers.pop_front().unwrap(); + assert!(transfer.resource.parts.len() > hashmap_len); + let resource_hash = transfer.resource.resource_hash; + + let mut request = vec![rns_protocol::resource::HASHMAP_IS_EXHAUSTED]; + request.extend_from_slice(&transfer.resource.map_hashes[hashmap_len - 1]); + request.extend_from_slice(&resource_hash); + + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.link_id = Some(link_id); + task.link = Some(initiator); + task.active_transfer = Some(transfer); + task.state = SyncTaskState::Transferring; + deliver_encrypted_resource_control( + &task, + &responder, + rns_wire::context::PacketContext::ResourceReq, + &request, + ); + + task.drain_events(&HashMap::new()); + + let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else { + panic!("expected Resource hashmap update"); + }; + let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap(); + assert_eq!( + header.context, + rns_wire::context::PacketContext::ResourceHmu + ); + let plaintext = responder.decrypt(&response.raw[offset..]).unwrap(); + assert_eq!(&plaintext[..32], resource_hash); + let update: rmpv::Value = rmpv::decode::read_value(&mut &plaintext[32..]).unwrap(); + assert_eq!(update.as_array().unwrap()[0].as_u64(), Some(1)); + assert_eq!(task.state, SyncTaskState::Transferring); + } + + #[test] + fn invalid_exhausted_request_sends_encrypted_cancel_and_fails_closed() { + let (tx, mut rx) = mpsc::channel(4); + let (initiator, responder) = active_link_pair([0x46; 16]); + let link_id = initiator.link_id; + let mut transfers = prepare_outbound_resource_transfers( + vec![0xB8; 20_000], + false, + Duration::from_millis(500), + initiator.session_keys().unwrap(), + ) + .unwrap(); + let transfer = transfers.pop_front().unwrap(); + let resource_hash = transfer.resource.resource_hash; + let mut request = vec![rns_protocol::resource::HASHMAP_IS_EXHAUSTED]; + request.extend_from_slice(&transfer.resource.map_hashes[0]); + request.extend_from_slice(&resource_hash); + + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.link_id = Some(link_id); + task.link = Some(initiator); + task.active_transfer = Some(transfer); + task.active_transfer_ids = vec![[0x66; 32]]; + task.state = SyncTaskState::Transferring; + deliver_encrypted_resource_control( + &task, + &responder, + rns_wire::context::PacketContext::ResourceReq, + &request, + ); + + task.drain_events(&HashMap::new()); + + let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else { + panic!("expected initiator Resource cancel"); + }; + let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap(); + assert_eq!( + header.context, + rns_wire::context::PacketContext::ResourceIcl + ); + assert_eq!( + responder.decrypt(&response.raw[offset..]).unwrap(), + resource_hash + ); + assert_eq!(task.state, SyncTaskState::Failed); + assert!(task.active_transfer.is_none()); + assert!(task.active_transfer_ids.is_empty()); + } + + #[test] + fn inbound_resource_cancels_require_exact_active_segment_hash() { + for context in [ + rns_wire::context::PacketContext::ResourceRcl, + rns_wire::context::PacketContext::ResourceIcl, + ] { + let (tx, _rx) = mpsc::channel(4); + let (initiator, responder) = active_link_pair([0x47; 16]); + let link_id = initiator.link_id; + let mut transfers = prepare_outbound_resource_transfers( + b"cancelled Resource".to_vec(), + false, + Duration::from_millis(500), + initiator.session_keys().unwrap(), + ) + .unwrap(); + let transfer = transfers.pop_front().unwrap(); + let resource_hash = transfer.resource.resource_hash; + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.link_id = Some(link_id); + task.link = Some(initiator); + task.active_transfer = Some(transfer); + task.active_transfer_ids = vec![[0x77; 32]]; + task.state = SyncTaskState::Transferring; + + deliver_encrypted_resource_control(&task, &responder, context, &[0xEE; 31]); + deliver_encrypted_resource_control(&task, &responder, context, &[0xEF; 32]); + task.drain_events(&HashMap::new()); + assert_eq!(task.state, SyncTaskState::Transferring); + assert!(task.active_transfer.is_some()); + + deliver_encrypted_resource_control(&task, &responder, context, &resource_hash); + task.drain_events(&HashMap::new()); + assert_eq!(task.state, SyncTaskState::Failed); + assert!(task.active_transfer.is_none()); + assert!(task.active_transfer_ids.is_empty()); + } + } + + #[test] + fn aggregate_above_single_resource_limit_uses_ordered_encrypted_segments() { + let (initiator, responder) = active_link_pair([0x43; 16]); + let initiator_keys = initiator.session_keys().unwrap(); + let responder_keys = responder.session_keys().unwrap(); + let payload_len = MAX_EFFICIENT_SIZE + 4096; + let payload = (0..payload_len) + .map(|index| ((index * 17) % 251) as u8) + .collect::>(); + + let mut transfers = prepare_outbound_resource_transfers( + payload.clone(), + false, + Duration::from_millis(500), + initiator_keys, + ) + .unwrap(); + assert_eq!(transfers.len(), 2); + + let mut reassembled = Vec::with_capacity(payload.len()); + let mut shared_original_hash = None; + for (index, transfer) in transfers.iter().enumerate() { + let resource = &transfer.resource; + assert!(resource.flags.encrypted); + assert!(resource.flags.split); + assert_eq!(resource.segment_index, index + 1); + assert_eq!(resource.total_segments, 2); + assert_eq!(resource.advertisement_data_size, payload.len()); + match shared_original_hash { + Some(expected) => assert_eq!(resource.original_hash, Some(expected)), + None => shared_original_hash = resource.original_hash, + } + + let encrypted_stream = resource.parts.concat(); + let plaintext = + rns_link::encryption::link_decrypt(&responder_keys, &encrypted_stream).unwrap(); + assert_eq!( + &plaintext[..rns_protocol::resource::RANDOM_HASH_SIZE], + &resource.random_hash + ); + reassembled.extend_from_slice(&plaintext[rns_protocol::resource::RANDOM_HASH_SIZE..]); + } + assert_eq!(reassembled, payload); + + let (tx, _rx) = mpsc::channel(4); + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.state = SyncTaskState::Transferring; + task.node_dest_hash = Some([0x43; 16]); + task.active_transfer = transfers.pop_front(); + task.pending_transfer_segments = transfers; + task.active_transfer_ids = vec![[0x55; 32]]; + + task.complete_active_transfer_segment(); + assert_eq!(task.state, SyncTaskState::Transferring); + assert!(task.take_handled_updates().is_empty()); + assert!(task.pending_transfer_segments.is_empty()); + assert!(task.active_transfer.is_some()); + + task.complete_active_transfer_segment(); + assert_eq!(task.state, SyncTaskState::Complete); + assert_eq!(task.take_handled_updates(), vec![[0x55; 32]]); + assert!(task.active_transfer.is_none()); + } + fn link_data_packet( link_id: [u8; 16], context: rns_wire::context::PacketContext, @@ -955,6 +1934,7 @@ mod tests { &close_body, ), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -986,6 +1966,7 @@ mod tests { .try_send(DestinationEvent::InboundPacket { raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]), interface_id: 0, + metrics: Default::default(), }) .unwrap(); @@ -1005,6 +1986,224 @@ mod tests { assert_eq!(task.state, SyncTaskState::Complete); } + #[test] + fn empty_policy_selection_completes_without_sending_offer_request() { + let (tx, mut rx) = mpsc::channel(16); + let shared_node = Arc::new(Mutex::new(PropagationNode::new( + PropagationNodeConfig::default(), + [0xAA; 16], + ))); + let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + let mut message = crate::message::LxMessage::new( + [0xBB; 16], + [0xCC; 16], + "Test", + "already handled", + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + let transient_id = message.transient_id.unwrap(); + assert!(shared_node.lock().unwrap().accept_message(&message)); + + let node_hash = [0xDD; 16]; + let (link, _responder) = active_link_pair(node_hash); + let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); + task.set_node(node_hash); + task.link_id = Some(link.link_id); + task.link = Some(link); + task.state = SyncTaskState::Offering; + let mut policy = OutboundOfferPolicy::unrestricted(node_hash); + policy.handled_messages.insert(transient_id); + task.offer_policy = Some(policy); + + task.send_offer_request(); + + assert_eq!(task.state, SyncTaskState::Complete); + assert!( + rx.try_recv().is_err(), + "empty offer must not emit a request" + ); + } + + #[tokio::test(flavor = "current_thread")] + async fn production_policy_preparation_runs_through_bounded_worker() { + let (tx, mut rx) = mpsc::channel(16); + let shared_node = Arc::new(Mutex::new(PropagationNode::new( + PropagationNodeConfig::default(), + [0xAA; 16], + ))); + let key = Ed25519PrivateKey::generate(); + let mut message = crate::message::LxMessage::new( + [0xBB; 16], + [0xCC; 16], + "Test", + "already handled async", + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + let transient_id = message.transient_id.unwrap(); + assert!(shared_node.lock().unwrap().accept_message(&message)); + + let node_hash = [0xDD; 16]; + let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); + task.set_node(node_hash); + task.state = SyncTaskState::Offering; + let mut policy = OutboundOfferPolicy::unrestricted(node_hash); + policy.handled_messages.insert(transient_id); + task.offer_policy = Some(policy); + + task.send_offer_request(); + assert!(task.offer_preparation_rx.is_some()); + tokio::time::timeout(Duration::from_secs(2), async { + while task.state == SyncTaskState::Offering { + tokio::time::sleep(Duration::from_millis(1)).await; + task.send_offer_request(); + } + }) + .await + .expect("bounded offer-preparation worker did not complete"); + + assert_eq!(task.state, SyncTaskState::Complete); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn terminal_offer_filters_are_exposed_and_complete_without_wire_offer() { + let (tx, mut rx) = mpsc::channel(16); + let node_hash = [0xDD; 16]; + let shared_node = Arc::new(Mutex::new(PropagationNode::new( + PropagationNodeConfig::default(), + [0xAA; 16], + ))); + let low = vec![0x11; 64]; + let oversized = vec![0x22; 700]; + assert!(shared_node.lock().unwrap().accept_propagated_blob(&low, 9)); + assert!( + shared_node + .lock() + .unwrap() + .accept_propagated_blob(&oversized, 20) + ); + let mut policy = OutboundOfferPolicy::unrestricted(node_hash); + policy.minimum_stamp_cost = 10; + policy.propagation_transfer_limit = Some(0.5); + let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); + task.set_node(node_hash); + task.offer_policy = Some(policy); + task.state = SyncTaskState::Offering; + + task.send_offer_request(); + + let mut updates = task.take_handled_updates(); + updates.sort(); + let mut expected = vec![ + rns_crypto::sha::full_hash(&low), + rns_crypto::sha::full_hash(&oversized), + ]; + expected.sort(); + assert_eq!(updates, expected); + assert_eq!(task.state, SyncTaskState::Complete); + assert!(task.generation_exhausted); + assert!(rx.try_recv().is_err()); + } + + #[test] + fn have_all_exposes_every_offered_id_for_authoritative_persistence() { + let dir = std::env::temp_dir().join("lxmf_sync_have_all_persist"); + let _ = std::fs::remove_dir_all(&dir); + let node_hash = [0xBB; 16]; + let node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + dir.clone(), + ) + .unwrap(); + let shared_node = Arc::new(Mutex::new(node)); + let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + for content in ["first", "second"] { + let mut message = crate::message::LxMessage::new( + [0xCC; 16], + [0xDD; 16], + "Test", + content, + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + assert!(shared_node.lock().unwrap().accept_message(&message)); + } + let policy = OutboundOfferPolicy::unrestricted(node_hash); + let offered = { + let mut node = shared_node.lock().unwrap(); + node.prepare_sync_offer_with_policy(&policy); + node.get_session(&node_hash).unwrap().offered_ids.clone() + }; + let (tx, _rx) = mpsc::channel(16); + let mut task = PropagationSyncTask::with_shared_node(tx, shared_node.clone()); + task.set_node(node_hash); + task.offer_policy = Some(policy); + + task.handle_offer_response(OfferResponse::HaveAll); + + assert_eq!(task.state, SyncTaskState::Complete); + let mut updates = task.take_handled_updates(); + updates.sort(); + let mut expected = offered.clone(); + expected.sort(); + assert_eq!(updates, expected); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn want_some_is_intersected_with_offer_and_marks_complement_handled() { + let dir = std::env::temp_dir().join("lxmf_sync_want_some_bound"); + let _ = std::fs::remove_dir_all(&dir); + let node_hash = [0xBB; 16]; + let node = PropagationNode::with_storage( + PropagationNodeConfig::default(), + [0xAA; 16], + dir.clone(), + ) + .unwrap(); + let shared_node = Arc::new(Mutex::new(node)); + let key = rns_crypto::ed25519::Ed25519PrivateKey::generate(); + for content in ["first", "second"] { + let mut message = crate::message::LxMessage::new( + [0xCC; 16], + [0xDD; 16], + "Test", + content, + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + assert!(shared_node.lock().unwrap().accept_message(&message)); + } + let policy = OutboundOfferPolicy::unrestricted(node_hash); + let offered = { + let mut node = shared_node.lock().unwrap(); + node.prepare_sync_offer_with_policy(&policy); + node.get_session(&node_hash).unwrap().offered_ids.clone() + }; + assert_eq!(offered.len(), 2); + let wanted = offered[0]; + let already_handled = offered[1]; + let (tx, _rx) = mpsc::channel(16); + let mut task = PropagationSyncTask::with_shared_node(tx, shared_node); + task.set_node(node_hash); + task.offer_policy = Some(policy); + + task.handle_offer_response(OfferResponse::WantSome(vec![ + wanted.to_vec(), + vec![0xEF; 32], + wanted.to_vec(), + ])); + + assert_eq!(task.state, SyncTaskState::Transferring); + let batch = task.ready_transfer_batch.as_ref().unwrap(); + assert_eq!(batch.transient_ids, vec![wanted]); + assert_eq!(task.take_handled_updates(), vec![already_handled]); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn test_handle_offer_response_error() { let (tx, _rx) = mpsc::channel(16); @@ -1073,14 +2272,127 @@ mod tests { let tid = msg.transient_id.unwrap(); task.accept_message(&msg); + let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]); + task.propagation_node + .lock() + .unwrap() + .prepare_sync_offer_with_policy(&policy); + task.offer_policy = Some(policy); + let wanted = vec![tid.to_vec()]; task.handle_offer_response(OfferResponse::WantSome(wanted)); assert_eq!(task.state, SyncTaskState::Transferring); - assert_eq!(task.transfer_queue.len(), 1); + let batch = task.ready_transfer_batch.as_ref().unwrap(); + assert_eq!(batch.transient_ids, vec![tid]); + let decoded: rmpv::Value = rmpv::decode::read_value(&mut &batch.payload[..]).unwrap(); + let outer = decoded.as_array().unwrap(); + assert_eq!(outer.len(), 2); + assert!(outer[0].as_f64().is_some()); + let blobs = outer[1].as_array().unwrap(); + assert_eq!(blobs.len(), 1, "one Resource carries the exact blob batch"); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn want_all_builds_one_timestamped_resource_batch_and_waits_for_proof() { + let dir = std::env::temp_dir().join("lxmf_test_sync_one_batch"); + let _ = std::fs::remove_dir_all(&dir); + let node_hash = [0xBB; 16]; + let (tx, _rx) = mpsc::channel(16); + let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap(); + task.set_node(node_hash); + let key = Ed25519PrivateKey::generate(); + for content in ["one", "two"] { + let mut message = crate::message::LxMessage::new( + [0xCC; 16], + [0xDD; 16], + "Test", + content, + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + assert!(task.accept_message(&message)); + } + let policy = OutboundOfferPolicy::unrestricted(node_hash); + task.propagation_node + .lock() + .unwrap() + .prepare_sync_offer_with_policy(&policy); + task.offer_policy = Some(policy); + task.state = SyncTaskState::AwaitingResponse; + + task.handle_offer_response(OfferResponse::WantAll); + + let batch = task.ready_transfer_batch.as_ref().unwrap(); + assert_eq!(batch.transient_ids.len(), 2); + let decoded: rmpv::Value = rmpv::decode::read_value(&mut &batch.payload[..]).unwrap(); + let outer = decoded.as_array().unwrap(); + assert_eq!(outer.len(), 2); + assert!(outer[0].as_f64().is_some()); + assert_eq!(outer[1].as_array().unwrap().len(), 2); + assert!( + task.take_handled_updates().is_empty(), + "wanted IDs converge only after the batch Resource is proven" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn vanished_requested_file_fails_retryably_for_peer_backoff() { + let dir = std::env::temp_dir().join("lxmf_test_sync_vanished_batch"); + let _ = std::fs::remove_dir_all(&dir); + let node_hash = [0xBB; 16]; + let (tx, _rx) = mpsc::channel(16); + let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap(); + task.set_node(node_hash); + let key = Ed25519PrivateKey::generate(); + let mut message = crate::message::LxMessage::new( + [0xCC; 16], + [0xDD; 16], + "Test", + "vanish", + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&key).unwrap(); + assert!(task.accept_message(&message)); + let policy = OutboundOfferPolicy::unrestricted(node_hash); + let (generation, reads) = { + let mut node = task.propagation_node.lock().unwrap(); + let offer = node.prepare_sync_offer_with_policy(&policy); + let ids = offer + .transient_ids + .iter() + .map(|id| id.clone().try_into().unwrap()) + .collect::>(); + (node.offer_generation(), node.plan_message_reads(&ids)) + }; + assert_eq!(reads.len(), 1); + std::fs::remove_file(&reads[0].path).unwrap(); + task.offer_policy = Some(policy); + task.active_offer_generation = Some(generation); + task.generation_exhausted = true; + task.state = SyncTaskState::AwaitingResponse; + + task.handle_offer_response(OfferResponse::WantAll); + task.drive_transfers(); + + assert_eq!(task.state, SyncTaskState::Failed); + assert!(!task.generation_exhausted); + assert!(task.take_handled_updates().is_empty()); + task.tick(); + assert_eq!( + task.take_terminal_peer_result(), + Some(PeerSyncTerminalResult { + peer_hash: node_hash, + state: PeerSyncTerminalState::Failed, + offer_generation: None, + generation_exhausted: false, + }) + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn test_peer_created_on_sync_start() { let (tx, _rx) = mpsc::channel(64); @@ -1122,6 +2434,130 @@ mod tests { assert_eq!(peer.destination_hash, [0xBB; 16]); } + #[test] + fn active_sync_rejects_different_request_without_mutating_target_or_policy() { + let (tx, _rx) = mpsc::channel(64); + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let policy_a = OutboundOfferPolicy::unrestricted([0xA1; 16]); + let policy_b = OutboundOfferPolicy::unrestricted([0xB2; 16]); + + assert!(task.request_sync_now_with_policy(policy_a.clone())); + assert!(!task.request_sync_now_with_policy(policy_b)); + assert_eq!(task.node_dest_hash(), Some(policy_a.peer_hash)); + assert_eq!(task.offer_policy, Some(policy_a)); + } + + #[test] + fn cancel_peer_sync_clears_active_pending_and_session_state() { + let (tx, _rx) = mpsc::channel(64); + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let peer_hash = [0xA1; 16]; + assert!(task.request_sync_now_with_policy(OutboundOfferPolicy::unrestricted(peer_hash))); + task.handled_updates.push([0x44; 32]); + task.propagation_node + .lock() + .unwrap() + .start_session(peer_hash); + + assert!(task.cancel_peer_sync(&peer_hash)); + assert_eq!(task.state, SyncTaskState::Idle); + assert_eq!(task.node_dest_hash(), None); + assert!(task.offer_policy.is_none()); + assert!(task.take_handled_updates().is_empty()); + assert!( + task.propagation_node + .lock() + .unwrap() + .get_session(&peer_hash) + .is_none() + ); + } + + #[test] + fn terminal_results_advance_generation_only_on_success_and_must_be_drained() { + let (tx, _rx) = mpsc::channel(64); + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + task.node_dest_hash = Some([0xA1; 16]); + task.active_offer_generation = Some(7); + task.generation_exhausted = false; + task.state = SyncTaskState::Complete; + task.tick(); + + assert!(!task.request_sync_now([0xB2; 16])); + assert_eq!( + task.take_terminal_peer_result(), + Some(PeerSyncTerminalResult { + peer_hash: [0xA1; 16], + state: PeerSyncTerminalState::Complete, + offer_generation: Some(7), + generation_exhausted: false, + }) + ); + assert!(task.request_sync_now([0xB2; 16])); + task.state = SyncTaskState::Failed; + task.tick(); + assert_eq!( + task.take_terminal_peer_result(), + Some(PeerSyncTerminalResult { + peer_hash: [0xB2; 16], + state: PeerSyncTerminalState::Failed, + offer_generation: None, + generation_exhausted: false, + }) + ); + } + + #[test] + fn link_identify_is_emitted_after_rtt_and_before_offer_request() { + let (tx, mut rx) = mpsc::channel(64); + let node_hash = [0xB2; 16]; + let responder_key = Ed25519PrivateKey::generate(); + let responder_pub = responder_key.public_key(); + let (link, request_data) = Link::new_initiator(node_hash, 1); + let (_responder, proof_data) = + Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap(); + + let mut task = PropagationSyncTask::new(tx, [0xAA; 16]); + let local_key = Ed25519PrivateKey::generate(); + let mut local_pub = [0x33; 64]; + local_pub[32..].copy_from_slice(&local_key.public_key().to_bytes()); + task.set_identity(local_pub, local_key); + task.node_dest_hash = Some(node_hash); + task.link_id = Some(link.link_id); + task.link = Some(link); + task.peer = Some(LxmPeer::new(node_hash)); + task.state = SyncTaskState::Establishing; + + let message_key = Ed25519PrivateKey::generate(); + let mut message = crate::message::LxMessage::new( + [0xCC; 16], + [0xDD; 16], + "Test", + "identify ordering", + crate::constants::DeliveryMethod::Propagated, + ); + message.sign(&message_key).unwrap(); + assert!(task.accept_message(&message)); + task.offer_policy = Some(OutboundOfferPolicy::unrestricted(node_hash)); + + task.handle_link_proof(&proof_data, &responder_pub, &responder_pub.to_bytes()); + task.send_offer_request(); + + let mut contexts = Vec::new(); + while let Ok(TransportMessage::Outbound(request)) = rx.try_recv() { + let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap(); + contexts.push(header.context); + } + assert_eq!( + contexts, + vec![ + rns_wire::context::PacketContext::Lrrtt, + rns_wire::context::PacketContext::LinkIdentify, + rns_wire::context::PacketContext::Request, + ] + ); + } + #[test] fn test_peer_cleared_on_cleanup() { let (tx, mut rx) = mpsc::channel(64); diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index df9985f..bccf34a 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -11,11 +11,17 @@ use bytes::Bytes; use tokio::sync::{mpsc, oneshot}; use crate::constants::*; +use crate::inbound_resource::{ + InboundResourceCancelRequest, InboundResourceEvent, InboundResourceHandle, InboundResourceKey, + InboundResourceTracker, +}; use crate::message::{LxMessage, MessageError}; -use crate::peer::LxmPeer; +use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::PropagationStore; +use crate::propagation_client::PropagationTransferStatus; use crate::stamper; use crate::ticket::{Ticket, TicketStore}; +use crate::types::PropagationTransientId; /// Router configuration. /// @@ -27,7 +33,7 @@ pub struct RouterConfig { pub autopeer: bool, pub max_peers: usize, pub propagation_limit_kb: usize, - pub delivery_limit_kb: usize, + pub delivery_limit_kb: f64, pub sync_limit_kb: usize, pub propagation_stamp_cost: u8, pub propagation_stamp_flex: u8, @@ -84,7 +90,7 @@ impl Default for RouterConfig { autopeer: AUTOPEER, max_peers: MAX_PEERS, propagation_limit_kb: PROPAGATION_LIMIT, - delivery_limit_kb: DELIVERY_LIMIT, + delivery_limit_kb: DELIVERY_LIMIT as f64, sync_limit_kb: SYNC_LIMIT, propagation_stamp_cost: PROPAGATION_COST, propagation_stamp_flex: PROPAGATION_COST_FLEX, @@ -260,11 +266,10 @@ pub struct LxmRouter { pub pending_outbound: Vec, /// Messages awaiting deferred stamp generation, keyed by message hash. pub pending_deferred_stamps: HashMap<[u8; 32], LxMessage>, - /// Captured at construction (or via [`set_runtime_handle`](Self::set_runtime_handle)) - /// so deferred-stamp PoW can spawn onto the blocking pool even when the - /// caller is itself on a `spawn_blocking` thread, where - /// `Handle::try_current()` fails. Without it the tick grinds stamps - /// inline while holding the manager lock (observed 53 s stall). + /// Captured at construction so deferred-stamp PoW can spawn onto the + /// blocking pool even when the caller is itself on a `spawn_blocking` + /// thread, where `Handle::try_current()` fails. Without it the tick grinds + /// stamps inline while holding the manager lock (observed 53 s stall). pub runtime_handle: Option, pub active_deferred_stamp: Option, /// Identities allowed for delivery. An empty list means "all allowed". @@ -291,12 +296,15 @@ pub struct LxmRouter { /// the embedder's loop rate. last_jobs_tick: f64, pub outbound_propagation_node: Option<[u8; 16]>, - /// Progress in the range 0.0..=1.0. - pub propagation_transfer_progress: f64, + /// Last coherent propagation-client transfer snapshot. + pub propagation_transfer_status: PropagationTransferStatus, pub client_propagation_messages_received: u64, pub client_propagation_messages_served: u64, pub unpeered_propagation_incoming: u64, pub unpeered_propagation_rx_bytes: u64, + /// Active ordinary delivery Resources. The embedding Reticulum runtime + /// remains the transfer owner and feeds this registry lifecycle events. + inbound_resource_tracker: InboundResourceTracker, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -317,6 +325,9 @@ pub struct AutopeerCandidate { pub stamp_cost: Option, pub stamp_flexibility: Option, pub peering_cost: Option, + /// Parsed propagation-node announce metadata. The peer layer applies + /// deterministic entry/value/aggregate bounds before retaining it. + pub metadata: Option>>, pub hops: Option, } @@ -352,11 +363,12 @@ impl LxmRouter { processing_count: 0, last_jobs_tick: 0.0, outbound_propagation_node: None, - propagation_transfer_progress: 0.0, + propagation_transfer_status: PropagationTransferStatus::default(), client_propagation_messages_received: 0, client_propagation_messages_served: 0, unpeered_propagation_incoming: 0, unpeered_propagation_rx_bytes: 0, + inbound_resource_tracker: InboundResourceTracker::default(), } } @@ -364,10 +376,73 @@ impl LxmRouter { self.transport_tx = Some(tx); } + /// Replace the public propagation transfer snapshot from its actor owner. + pub fn update_propagation_transfer_status(&mut self, status: PropagationTransferStatus) { + self.propagation_transfer_status = status; + } + pub fn has_transport(&self) -> bool { self.transport_tx.is_some() } + /// Install the bounded adapter used to request cancellation from the + /// embedding Reticulum Resource owner. + pub fn set_inbound_resource_cancel_sender( + &mut self, + tx: mpsc::Sender, + ) { + self.inbound_resource_tracker.set_cancel_sender(tx); + } + + /// Project one transport-neutral Resource lifecycle event into the + /// router-owned public registry. + pub fn handle_inbound_resource_event(&mut self, event: InboundResourceEvent) { + self.inbound_resource_tracker.handle_event(event); + } + + /// Number of active ordinary inbound delivery Resources. + /// + /// Python reference: `LXMRouter.inbound_count` — LXMRouter.py:466. + pub fn inbound_count(&self) -> usize { + self.inbound_resource_tracker.inbound_count() + } + + /// Owned handles for all active ordinary inbound delivery Resources. + /// + /// Python reference: `LXMRouter.inbound_resources` — LXMRouter.py:474. + pub fn inbound_resources(&self) -> Vec { + self.inbound_resource_tracker.inbound_resources() + } + + /// Return one unique active logical Resource. + pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option { + self.inbound_resource_tracker.inbound_resource(resource_id) + } + + /// Return one exact active `(Link, Resource)` owner. + pub fn inbound_resource_exact(&self, key: InboundResourceKey) -> Option { + self.inbound_resource_tracker.inbound_resource_exact(key) + } + + /// Queue cancellation for one unique active logical Resource. + /// + /// Python reference: `LXMRouter.cancel_inbound` — LXMRouter.py:484. + pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool { + self.inbound_resource_tracker.cancel_inbound(resource_id) + } + + /// Queue cancellation for one exact active Resource owner. + pub fn cancel_inbound_exact(&self, key: InboundResourceKey) -> bool { + self.inbound_resource_tracker.cancel_inbound_exact(key) + } + + /// Queue cancellation for a stable snapshot of all active Resources. + /// + /// Python reference: `LXMRouter.cancel_all_inbound` — LXMRouter.py:505. + pub fn cancel_all_inbound(&self) -> usize { + self.inbound_resource_tracker.cancel_all_inbound() + } + /// Queue a message for outbound delivery. /// /// Opportunistic messages that exceed the single-packet ceiling are @@ -857,12 +932,55 @@ impl LxmRouter { .and_then(|m| m.stamp_cost) } + /// Return whether a message or propagation transient ID has already been + /// delivered locally. + /// + /// Python reference: `LXMRouter.has_message` — LXMRouter.py:1667-1669. + pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool { + self.propagation_store.is_locally_delivered(transient_id) + } + + /// Atomically admit one already-decoded inbound message and invoke the + /// router callback at most once. + /// + /// Both ordinary packet/Resource delivery and propagation download must + /// use this actor-owned gate before any application-visible side effect. + /// A propagation message may carry a ciphertext-derived `transient_id` + /// distinct from its signed message hash; both identifiers are retained + /// so a later delivery through another representation is still deduped. + pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool { + let Some(message_id) = message.message_id.or(message.hash) else { + return false; + }; + let transient_id = message.transient_id.unwrap_or(message_id); + let propagated = transient_id != message_id; + + if !allow_duplicate + && (self.propagation_store.is_locally_delivered(&message_id) + || self.propagation_store.is_locally_delivered(&transient_id) + || (propagated && self.propagation_store.is_locally_processed(&transient_id))) + { + return false; + } + + self.propagation_store.mark_locally_delivered(message_id); + if propagated { + self.propagation_store.mark_locally_processed(transient_id); + self.propagation_store.mark_locally_delivered(transient_id); + } + + if let Some(ref callback) = self.delivery_callback { + callback(message); + } + true + } + /// Ingest an encrypted paper (`lxm://...`) URI and invoke the delivery callback as if the /// message had arrived via the network. /// /// Python reference: `LXMRouter.ingest_lxm_uri` — LXMRouter.py:2370-2385. pub fn ingest_lxm_uri( - &self, + &mut self, uri: &str, decrypt_fn: F, ) -> Result @@ -870,9 +988,7 @@ impl LxmRouter { F: FnOnce(&[u8]) -> Result, crate::message::MessageError>, { let message = LxMessage::from_paper_uri(uri, decrypt_fn)?; - if let Some(ref cb) = self.delivery_callback { - cb(&message); - } + self.deliver_inbound(&message, false); Ok(message) } @@ -899,6 +1015,11 @@ impl LxmRouter { .replace_locally_delivered(persist::load_local_deliveries(state_dir)?); self.propagation_store .replace_locally_processed(persist::load_locally_processed(state_dir)?); + let stats = persist::load_node_stats(state_dir)?; + self.client_propagation_messages_received = stats.client_propagation_messages_received; + self.client_propagation_messages_served = stats.client_propagation_messages_served; + self.unpeered_propagation_incoming = stats.unpeered_propagation_incoming; + self.unpeered_propagation_rx_bytes = stats.unpeered_propagation_rx_bytes; // Python cleans tickets and stamp costs at load (LXMRouter.py:258-284). let now = now_f64(); self.ticket_store.cull(now); @@ -916,6 +1037,15 @@ impl LxmRouter { persist::save_tickets(state_dir, self.ticket_store.all())?; persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?; persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?; + persist::save_node_stats( + state_dir, + &persist::PersistedNodeStats { + client_propagation_messages_received: self.client_propagation_messages_received, + client_propagation_messages_served: self.client_propagation_messages_served, + unpeered_propagation_incoming: self.unpeered_propagation_incoming, + unpeered_propagation_rx_bytes: self.unpeered_propagation_rx_bytes, + }, + )?; Ok(()) } @@ -940,6 +1070,29 @@ impl LxmRouter { due } + /// Return authoritative policies for peers that have not processed the + /// current propagation-store generation. This is an O(peers) scheduler + /// query; exact message eligibility is intentionally deferred to the + /// sync task's off-loop offer preparation. + /// + /// The method does not mutate peer state, allowing a single shared sync + /// task to accept one policy before the daemon marks that peer started. + pub fn sync_peer_policies_for_store(&self, offer_generation: u64) -> Vec { + let mut policies = self + .peers + .values() + .filter(|peer| { + peer.alive + && peer.state == PeerState::Idle + && peer.should_sync() + && peer.needs_offer_generation(offer_generation) + }) + .map(OutboundOfferPolicy::from) + .collect::>(); + policies.sort_by_key(|policy| policy.peer_hash); + policies + } + pub fn add_peer(&mut self, peer: LxmPeer) -> bool { if self.peers.len() >= self.config.max_peers { return false; @@ -961,31 +1114,69 @@ impl LxmRouter { stamp_cost, stamp_flexibility, peering_cost, + metadata, hops, } = candidate; + let configured_static = self.static_peers.contains(&destination_hash); - if !self.config.autopeer { - return false; - } // Python LXMRouter.peer() (LXMRouter.py:1896-1901): a peering cost // above our accepted maximum refuses the peering — and breaks an - // existing one — before any PoW could be attempted. + // existing one only when that policy announce is not stale. if peering_cost.unwrap_or(0) > self.config.ext.max_peering_cost { - if self.peers.contains_key(&destination_hash) { - self.unpeer(&destination_hash); + if self + .peers + .get(&destination_hash) + .is_some_and(|peer| timebase >= peer.peering_timebase) + { + self.remove_peer(&destination_hash); } return false; } - if self.peers.contains_key(&destination_hash) { + + // Configured static peers always consume newer policy announces. + // Automatically discovered peers remain governed by the live + // autopeer/range policy, matching the upstream announce handler. + if let Some(peer) = self.peers.get(&destination_hash) { + let static_peer = configured_static || peer.is_static; + if !static_peer && !self.config.autopeer { + return false; + } + if !static_peer && hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth) + { + if timebase >= peer.peering_timebase { + self.remove_peer(&destination_hash); + } + return false; + } + } + if let Some(peer) = self.peers.get_mut(&destination_hash) { + let refreshed = peer.refresh_from_announce_with_metadata( + timebase, + transfer_limit, + sync_limit, + stamp_cost, + stamp_flexibility, + peering_cost, + metadata, + ); + if configured_static { + peer.is_static = true; + peer.autopeered = false; + } + return refreshed; + } + + if !configured_static && !self.config.autopeer { return false; } - if let Some(h) = hops + if !configured_static + && let Some(h) = hops && h as usize > self.config.ext.autopeer_maxdepth { return false; } - let peer = LxmPeer::from_announce( + let mut peer = LxmPeer::from_announce_with_metadata( destination_hash, timebase, transfer_limit, @@ -993,7 +1184,12 @@ impl LxmRouter { stamp_cost, stamp_flexibility, peering_cost, + metadata, ); + if configured_static { + peer.is_static = true; + peer.autopeered = false; + } self.add_peer(peer) } @@ -1850,7 +2046,7 @@ pub struct PeerStats { #[derive(Debug)] pub struct NodeStats { pub uptime: f64, - pub delivery_limit: usize, + pub delivery_limit: f64, pub propagation_limit: usize, pub sync_limit: usize, pub stamp_cost: u8, @@ -2491,11 +2687,70 @@ mod tests { fired_clone.store(true, Ordering::Relaxed); }); - let msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); - (router.delivery_callback.as_ref().unwrap())(&msg); + let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct); + msg.hash = Some([0x11; 32]); + msg.message_id = msg.hash; + msg.transient_id = msg.hash; + assert!(router.deliver_inbound(&msg, false)); assert!(fired.load(Ordering::Relaxed)); } + #[test] + fn inbound_delivery_is_deduped_across_packet_and_resource_representations() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let mut router = LxmRouter::new(RouterConfig::default()); + let deliveries = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&deliveries); + router.register_delivery_callback(move |_| { + observed.fetch_add(1, Ordering::Relaxed); + }); + + let mut packet = LxMessage::new( + [0xAA; 16], + [0xBB; 16], + "same", + "message", + DeliveryMethod::Opportunistic, + ); + packet.hash = Some([0x22; 32]); + packet.message_id = packet.hash; + packet.transient_id = packet.hash; + let mut resource = packet.clone(); + resource.method = DeliveryMethod::Direct; + + assert!(router.deliver_inbound(&packet, false)); + assert!(!router.deliver_inbound(&resource, false)); + assert_eq!(deliveries.load(Ordering::Relaxed), 1); + assert!(router.has_message(&[0x22; 32])); + } + + #[test] + fn propagated_delivery_records_ciphertext_and_signed_message_ids() { + let mut router = LxmRouter::new(RouterConfig::default()); + let mut propagated = LxMessage::new( + [0xAA; 16], + [0xBB; 16], + "propagated", + "message", + DeliveryMethod::Propagated, + ); + propagated.hash = Some([0x33; 32]); + propagated.message_id = propagated.hash; + propagated.transient_id = Some([0x44; 32]); + + assert!(router.deliver_inbound(&propagated, false)); + assert!(router.has_message(&[0x33; 32])); + assert!(router.has_message(&[0x44; 32])); + assert!(router.propagation_store.is_locally_processed(&[0x44; 32])); + + let mut direct = propagated.clone(); + direct.method = DeliveryMethod::Direct; + direct.transient_id = direct.hash; + assert!(!router.deliver_inbound(&direct, false)); + } + #[test] fn test_ingest_lxm_uri() { use rns_crypto::ed25519::Ed25519PrivateKey; @@ -2541,6 +2796,10 @@ mod tests { r1.remember_ticket(dest_a, [0x01; 16], 4_102_444_800.0); r1.propagation_store.mark_locally_delivered(transient_a); r1.propagation_store.mark_locally_processed(transient_a); + r1.client_propagation_messages_received = 10; + r1.client_propagation_messages_served = 11; + r1.unpeered_propagation_incoming = 12; + r1.unpeered_propagation_rx_bytes = 13; r1.save_state(tmp.path()).unwrap(); let mut r2 = LxmRouter::new(RouterConfig::default()); @@ -2552,6 +2811,10 @@ mod tests { assert_eq!(r2.get_outbound_ticket(&dest_a), Some([0x01; 16])); assert!(r2.propagation_store.is_locally_delivered(&transient_a)); assert!(r2.propagation_store.is_locally_processed(&transient_a)); + assert_eq!(r2.client_propagation_messages_received, 10); + assert_eq!(r2.client_propagation_messages_served, 11); + assert_eq!(r2.unpeered_propagation_incoming, 12); + assert_eq!(r2.unpeered_propagation_rx_bytes, 13); } /// T1-10: persisted dedup timestamps are the REAL first-seen times — @@ -2629,6 +2892,48 @@ mod tests { assert!(router.sync_peers().is_empty()); } + #[test] + fn store_generation_scheduler_skips_unchanged_and_reenables_on_store_or_policy_change() { + let peer_hash = [0x11; 16]; + let mut router = LxmRouter::new(RouterConfig::default()); + let mut peer = LxmPeer::from_announce( + peer_hash, + 10.0, + Some(1.0), + Some(2.0), + Some(16), + Some(3), + Some(18), + ); + peer.mark_offer_generation_processed(5); + router.add_peer(peer); + + assert!(router.sync_peer_policies_for_store(5).is_empty()); + let due = router.sync_peer_policies_for_store(6); + assert_eq!(due.len(), 1); + assert_eq!(due[0].peer_hash, peer_hash); + assert_eq!(router.peers[&peer_hash].state, PeerState::Idle); + + router + .peers + .get_mut(&peer_hash) + .unwrap() + .mark_offer_generation_processed(6); + assert!(router.sync_peer_policies_for_store(6).is_empty()); + assert!(router.autopeer(AutopeerCandidate { + destination_hash: peer_hash, + timebase: 11.0, + transfer_limit: Some(1.0), + sync_limit: Some(2.0), + stamp_cost: Some(12), + stamp_flexibility: Some(3), + peering_cost: Some(18), + metadata: Some(std::collections::HashMap::new()), + hops: Some(1), + })); + assert_eq!(router.sync_peer_policies_for_store(6).len(), 1); + } + #[test] fn test_validate_stamp() { let router = LxmRouter::new(RouterConfig::default()); @@ -3210,6 +3515,7 @@ mod tests { stamp_cost: Some(16), stamp_flexibility: Some(3), peering_cost: Some(18), + metadata: None, hops: Some(2), })); assert_eq!(router.peers.len(), 1); @@ -3222,6 +3528,7 @@ mod tests { stamp_cost: None, stamp_flexibility: None, peering_cost: None, + metadata: None, hops: None, })); assert!(!router.autopeer(AutopeerCandidate { @@ -3232,10 +3539,163 @@ mod tests { stamp_cost: None, stamp_flexibility: None, peering_cost: None, + metadata: None, hops: Some(10), })); } + #[test] + fn existing_static_peer_accepts_only_newer_policy_when_autopeer_is_disabled() { + let peer_hash = [0xAA; 16]; + let mut router = LxmRouter::new(RouterConfig { + autopeer: false, + ..Default::default() + }); + let mut peer = LxmPeer::new(peer_hash); + peer.is_static = true; + peer.peering_timebase = 100.0; + peer.stamp_cost = Some(8); + router.add_peer(peer); + + let candidate = |timebase, stamp_cost| AutopeerCandidate { + destination_hash: peer_hash, + timebase, + transfer_limit: Some(2.0), + sync_limit: Some(8.0), + stamp_cost: Some(stamp_cost), + stamp_flexibility: Some(3), + peering_cost: Some(18), + metadata: None, + hops: Some(99), + }; + + assert!(router.autopeer(candidate(101.0, 16))); + let refreshed = router.peers.get(&peer_hash).unwrap(); + assert_eq!(refreshed.stamp_cost, Some(16)); + assert_eq!(refreshed.propagation_sync_limit, Some(8.0)); + assert!(refreshed.is_static); + + assert!(!router.autopeer(candidate(100.0, 4))); + assert_eq!(router.peers.get(&peer_hash).unwrap().stamp_cost, Some(16)); + + assert!(!router.autopeer(AutopeerCandidate { + destination_hash: [0xBB; 16], + timebase: 101.0, + transfer_limit: Some(2.0), + sync_limit: Some(8.0), + stamp_cost: Some(16), + stamp_flexibility: Some(3), + peering_cost: Some(18), + metadata: None, + hops: Some(1), + })); + assert!(!router.peers.contains_key(&[0xBB; 16])); + } + + #[test] + fn configured_static_announce_recreates_missing_peer_with_autopeer_disabled() { + let peer_hash = [0xA5; 16]; + let mut router = LxmRouter::new(RouterConfig { + autopeer: false, + ext: RouterConfigExt { + autopeer_maxdepth: 1, + ..Default::default() + }, + ..Default::default() + }); + router.static_peers.push(peer_hash); + router.remove_peer(&peer_hash); + + assert!(router.autopeer(AutopeerCandidate { + destination_hash: peer_hash, + timebase: 101.0, + transfer_limit: Some(2.0), + sync_limit: Some(8.0), + stamp_cost: Some(16), + stamp_flexibility: Some(3), + peering_cost: Some(18), + metadata: Some(std::collections::HashMap::from([( + crate::constants::PN_META_NAME, + b"static".to_vec(), + )])), + hops: Some(99), + })); + let peer = router.peers.get(&peer_hash).unwrap(); + assert!(peer.is_static); + assert!(!peer.autopeered); + assert_eq!( + peer.metadata + .as_ref() + .and_then(|metadata| metadata.get(&crate::constants::PN_META_NAME)), + Some(&b"static".to_vec()) + ); + } + + #[test] + fn stale_over_cost_announce_does_not_remove_newer_peer() { + let peer_hash = [0xAA; 16]; + let mut router = LxmRouter::new(RouterConfig::default()); + let mut peer = LxmPeer::new(peer_hash); + peer.peering_timebase = 200.0; + router.add_peer(peer); + let max = router.config.ext.max_peering_cost; + + assert!(!router.autopeer(AutopeerCandidate { + destination_hash: peer_hash, + timebase: 199.0, + transfer_limit: None, + sync_limit: None, + stamp_cost: None, + stamp_flexibility: None, + peering_cost: Some(max + 1), + metadata: None, + hops: None, + })); + assert!(router.peers.contains_key(&peer_hash)); + } + + #[test] + fn nonstatic_peer_still_obeys_autopeer_and_range_on_refresh() { + let peer_hash = [0xAA; 16]; + let candidate = |timebase, hops| AutopeerCandidate { + destination_hash: peer_hash, + timebase, + transfer_limit: Some(2.0), + sync_limit: Some(8.0), + stamp_cost: Some(16), + stamp_flexibility: Some(3), + peering_cost: Some(18), + metadata: None, + hops: Some(hops), + }; + + let mut disabled = LxmRouter::new(RouterConfig { + autopeer: false, + ..Default::default() + }); + let mut peer = LxmPeer::new(peer_hash); + peer.peering_timebase = 100.0; + disabled.add_peer(peer); + assert!(!disabled.autopeer(candidate(101.0, 1))); + assert_eq!( + disabled.peers.get(&peer_hash).unwrap().peering_timebase, + 100.0 + ); + + let mut ranged = LxmRouter::new(RouterConfig { + ext: RouterConfigExt { + autopeer_maxdepth: 1, + ..Default::default() + }, + ..Default::default() + }); + let mut peer = LxmPeer::new(peer_hash); + peer.peering_timebase = 100.0; + ranged.add_peer(peer); + assert!(!ranged.autopeer(candidate(101.0, 2))); + assert!(!ranged.peers.contains_key(&peer_hash)); + } + /// T0-4: peering cost above `max_peering_cost` refuses peering, and an /// existing peering breaks when the peer raises its cost beyond the cap /// (Python LXMRouter.py:1896-1901). @@ -3252,6 +3712,7 @@ mod tests { stamp_cost: Some(16), stamp_flexibility: Some(3), peering_cost: cost, + metadata: None, hops: Some(2), }; @@ -3286,6 +3747,7 @@ mod tests { stamp_cost: None, stamp_flexibility: None, peering_cost: None, + metadata: None, hops: Some(2), })); assert!(router.autopeer(AutopeerCandidate { @@ -3296,6 +3758,7 @@ mod tests { stamp_cost: None, stamp_flexibility: None, peering_cost: None, + metadata: None, hops: Some(1), })); } diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index c9e7fe1..1242dcd 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -2,6 +2,9 @@ //! //! Python reference: LXMF/Utilities/lxmd.py. +#[path = "lxmd_pn.rs"] +mod lxmd_pn; + use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -16,15 +19,20 @@ use lxmf_core::constants::{ DELIVERY_RETRY_WAIT, DeliveryMethod, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, }; use lxmf_core::delivery_ratchet::{DELIVERY_APP_NAME, DeliveryAnnounceKind, DeliveryRatchetState}; +use lxmf_core::inbound_resource::{ + InboundResourceCancelRequest, InboundResourceConclusion, InboundResourceEvent, + InboundResourceKey, +}; use lxmf_core::link_delivery::{ BackchannelSendCommand, BackchannelSendError, BackchannelSendReceipt, DeliveryResult, is_retryable_link_delivery_failure, }; use lxmf_core::message::LxMessage; +use lxmf_core::peer::{LxmPeer, OutboundOfferPolicy}; use lxmf_core::propagation_node::{PropagationNode, PropagationNodeConfig}; use lxmf_core::router::{ - DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, DirectRouteSnapshot, - LxmRouter, OutboundAction, plan_direct_delivery, + AutopeerCandidate, DirectDeliveryPlan, DirectDeliveryPlanInput, DirectReusableLinkState, + DirectRouteSnapshot, LxmRouter, OutboundAction, plan_direct_delivery, }; use lxmf_tools::daemon::{DaemonConfig, create_router_with_transport, execute_on_inbound}; use lxmf_tools::lxmd_cli::{ @@ -48,10 +56,18 @@ use rns_identity::ratchet::{ ReceivedRatchet, clean_received_ratchets_dir, purge_expired_ratchets_in_memory, }; use rns_runtime::lifecycle::ShutdownSignal; +use rns_runtime::link_manager::{ + LinkManagerAccountingEvent, LinkManagerCommand, LinkResourceConclusion, LinkResourceDirection, + LinkResourceEvent, +}; use rns_transport::messages::{ AnnounceHandlerEvent, TransportMessage, TransportQuery, TransportQueryResponse, }; +use self::lxmd_pn::{ + PnInboundRuntime, PnValidationJob, PnValidationOutcome, PnValidationToken, logical_resource_id, +}; + #[derive(Debug, Clone, Default)] struct ControlSnapshot { allowed_control: Vec<[u8; 16]>, @@ -65,6 +81,250 @@ enum ControlCommand { Unpeer([u8; 16]), } +#[derive(Debug)] +struct ValidatedPnEntry { + lxmf_data: Vec, + stamp_value: u32, + stamp_data: [u8; 32], +} + +#[derive(Debug)] +struct PnValidationWorkerResult { + token: PnValidationToken, + link_id: [u8; 16], + outcome: PnValidationOutcome, + entries: Vec, + rejected: usize, +} + +#[derive(Debug)] +struct PeeringKeyWorkerResult { + peer_hash: [u8; 16], + peering_cost: u8, + peering_key: Option<([u8; 32], u32)>, +} + +fn accepts_delivery_resource(data_size: usize, limit_kb: f64) -> bool { + data_size as f64 <= limit_kb * 1000.0 +} + +fn delivery_resource_event_from_runtime(event: LinkResourceEvent) -> Option { + match event { + LinkResourceEvent::Started { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + data_size, + total_segments, + } => Some(InboundResourceEvent::Started { + key: InboundResourceKey::new(link_id, resource_id), + data_size, + total_segments, + }), + LinkResourceEvent::Progress { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + transferred, + total, + } => Some(InboundResourceEvent::Progress { + key: InboundResourceKey::new(link_id, resource_id), + transferred, + total, + }), + LinkResourceEvent::Concluded { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + conclusion, + } => Some(InboundResourceEvent::Concluded { + key: InboundResourceKey::new(link_id, resource_id), + conclusion: match conclusion { + LinkResourceConclusion::Complete => InboundResourceConclusion::Complete, + LinkResourceConclusion::Cancelled => InboundResourceConclusion::Cancelled, + LinkResourceConclusion::Rejected => InboundResourceConclusion::Rejected, + LinkResourceConclusion::Failed(_) => InboundResourceConclusion::Failed, + }, + }), + LinkResourceEvent::Started { .. } + | LinkResourceEvent::Progress { .. } + | LinkResourceEvent::Concluded { .. } => None, + } +} + +async fn forward_inbound_resource_cancellations( + mut cancel_rx: mpsc::Receiver, + link_command_tx: mpsc::Sender, +) { + while let Some(request) = cancel_rx.recv().await { + let key = request.key(); + if link_command_tx + .send(LinkManagerCommand::CancelLinkResource { + link_id: key.link_id, + resource_id: key.resource_id, + direction: LinkResourceDirection::Inbound, + result_tx: None, + }) + .await + .is_err() + { + break; + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq)] +struct PeerOfferConstraints { + transfer_limit: Option, + sync_limit: Option, + stamp_cost: Option, + stamp_flexibility: Option, + peering_cost: u8, +} + +impl From<&LxmPeer> for PeerOfferConstraints { + fn from(peer: &LxmPeer) -> Self { + Self { + transfer_limit: peer.propagation_transfer_limit, + sync_limit: peer.propagation_sync_limit, + stamp_cost: peer.stamp_cost, + stamp_flexibility: peer.stamp_cost_flexibility, + peering_cost: peer.peering_cost, + } + } +} + +fn generate_peering_key_job( + peer_hash: [u8; 16], + peering_cost: u8, + peer_identity_hash: [u8; 16], + local_identity_hash: [u8; 16], +) -> PeeringKeyWorkerResult { + let mut peer = LxmPeer::new(peer_hash); + peer.peering_cost = peering_cost; + let _ = peer.generate_peering_key(&peer_identity_hash, &local_identity_hash); + PeeringKeyWorkerResult { + peer_hash, + peering_cost, + peering_key: peer.peering_key, + } +} + +fn validate_pn_resource_job( + job: PnValidationJob, + max_transfer_bytes: usize, + min_cost: u8, +) -> PnValidationWorkerResult { + let token = job.token(); + let link_id = job.link_id(); + let allow_multiple = job.allow_multiple(); + let data = job.into_data(); + + let (_, entries) = + match LxMessage::unpack_propagation_wrapper_bounded(&data, max_transfer_bytes) { + Ok(parsed) => parsed, + Err(error) => { + tracing::warn!( + link_id = %hex::encode(link_id), + "failed to unpack propagation Resource: {error}" + ); + return PnValidationWorkerResult { + token, + link_id, + outcome: PnValidationOutcome::Failed, + entries: Vec::new(), + rejected: 0, + }; + } + }; + + if !allow_multiple && entries.len() > 1 { + return PnValidationWorkerResult { + token, + link_id, + outcome: PnValidationOutcome::UnauthorizedMultiple, + entries: Vec::new(), + rejected: entries.len(), + }; + } + + let mut validated = Vec::with_capacity(entries.len()); + let mut rejected = 0usize; + for entry in entries { + match lxmf_core::stamper::validate_pn_stamp(&entry, min_cost) { + Some((_transient_id, lxmf_data, stamp_value, stamp_data)) => { + validated.push(ValidatedPnEntry { + lxmf_data, + stamp_value, + stamp_data, + }); + } + None => rejected += 1, + } + } + + PnValidationWorkerResult { + token, + link_id, + outcome: if rejected == 0 { + PnValidationOutcome::Valid + } else { + PnValidationOutcome::InvalidStamp + }, + entries: validated, + rejected, + } +} + +fn handle_pn_offer_request( + runtime: &Arc>, + node: &Arc>, + local_identity_hash: [u8; 16], + link_id: [u8; 16], + remote_identity_hash: Option<[u8; 16]>, + data: &[u8], +) -> Option> { + let candidate = runtime + .lock() + .ok()? + .preflight_offer(link_id, remote_identity_hash); + let candidate = match candidate { + Ok(candidate) => candidate, + Err(response) => return Some(PropagationNode::encode_offer_response(&response)), + }; + + let evaluation = match node.lock() { + Ok(node) => node.evaluate_offer_request(data, &local_identity_hash, &candidate), + Err(_) => { + if let Ok(mut runtime) = runtime.lock() { + runtime.discard_offer(candidate); + } + return None; + } + }; + + match evaluation { + Ok(evaluation) => { + let response = match runtime.lock() { + Ok(mut runtime) => match runtime.commit_offer(candidate, &evaluation) { + Ok(()) => evaluation.into_wire_response(), + Err(response) => response, + }, + Err(_) => return None, + }; + Some(PropagationNode::encode_offer_response(&response)) + } + Err(error) => { + if let Ok(mut runtime) = runtime.lock() { + runtime.discard_offer(candidate); + } + Some(PropagationNode::encode_offer_response( + &error.wire_response(), + )) + } + } +} + fn setup_logging(verbose: u8, quiet: u8, service: bool) { let level = match (verbose, quiet) { (v, _) if v >= 3 => tracing::Level::TRACE, @@ -483,15 +743,31 @@ struct LxmdRunner { propagation_sync: Option, propagation_client: Option, propagation_node: Option>>, + propagation_admission: Option>>, + prop_link_command_tx: Option>, transport_tx: mpsc::Sender, /// Plaintext application data decoded by the LinkManager. link_packet_rx: mpsc::Receiver<(Vec, [u8; 16])>, - /// Completed resource transfers from the LinkManager. - resource_rx: mpsc::Receiver<(Vec, [u8; 16])>, + /// Ordered, lossless ordinary delivery Resource starts/conclusions and + /// payload completions used by delivery and the public inbound tracker. + delivery_accounting_rx: mpsc::UnboundedReceiver, + /// Bounded best-effort delivery Resource progress. Starts/conclusions are + /// consumed from `delivery_accounting_rx` instead. + delivery_resource_event_rx: mpsc::Receiver, /// Plaintext propagation-wrapper packets decoded by the propagation LinkManager. prop_link_packet_rx: mpsc::Receiver<(Vec, [u8; 16])>, - /// Completed propagation-wrapper resources from the propagation LinkManager. - prop_resource_rx: mpsc::Receiver<(Vec, [u8; 16])>, + /// Ordered, lossless lifecycle and completion stream from the propagation LinkManager. + prop_accounting_rx: + mpsc::UnboundedReceiver, + /// Stamp-validation results returned from blocking workers. + prop_validation_rx: mpsc::Receiver, + /// Retained sender used to dispatch bounded validation results. + prop_validation_tx: mpsc::Sender, + /// Peering keys are CPU-bound PoW and must never run on the daemon loop. + peering_key_result_rx: mpsc::Receiver, + peering_key_result_tx: mpsc::Sender, + peering_key_jobs: HashSet<[u8; 16]>, + pending_peer_syncs: HashSet<[u8; 16]>, /// Non-link inbound packets; still encrypted, need destination-level decrypt. inbound_raw_rx: mpsc::Receiver>, announce_rx: mpsc::Receiver, @@ -597,15 +873,26 @@ impl LxmdRunner { "Crypto state loaded" ); - let router = create_router_with_transport(&config, transport_tx.clone()); + let mut router = create_router_with_transport(&config, transport_tx.clone()); // LinkManager handles link handshakes (ECDH), keepalive, identification, // and resource transfers; it forwards plaintext application data here. let (delivery_tx, delivery_rx) = mpsc::channel(256); let (link_packet_tx, link_packet_rx) = mpsc::channel::<(Vec, [u8; 16])>(256); - let (resource_tx, resource_rx) = mpsc::channel::<(Vec, [u8; 16])>(256); + let (delivery_accounting_tx, delivery_accounting_rx) = + mpsc::unbounded_channel::(); + let (delivery_resource_event_tx, delivery_resource_event_rx) = + mpsc::channel::(256); + let (inbound_resource_cancel_tx, inbound_resource_cancel_rx) = + mpsc::channel::(64); + router.set_inbound_resource_cancel_sender(inbound_resource_cancel_tx); let (prop_link_packet_tx, prop_link_packet_rx) = mpsc::channel::<(Vec, [u8; 16])>(256); - let (prop_resource_tx, prop_resource_rx) = mpsc::channel::<(Vec, [u8; 16])>(256); + let (prop_accounting_tx, prop_accounting_rx) = + mpsc::unbounded_channel::(); + let (prop_validation_tx, prop_validation_rx) = + mpsc::channel::(256); + let (peering_key_result_tx, peering_key_result_rx) = + mpsc::channel::(64); let (inbound_raw_tx, inbound_raw_rx) = mpsc::channel::>(256); let (link_command_tx, link_command_rx) = mpsc::channel::(256); @@ -624,11 +911,17 @@ impl LxmdRunner { signing_key, ); link_mgr.set_link_packet_channel(link_packet_tx); - link_mgr.set_resource_completed_channel(resource_tx); + link_mgr.set_accounting_event_channel(delivery_accounting_tx); + link_mgr.set_resource_event_channel(delivery_resource_event_tx); link_mgr.set_inbound_raw_channel(inbound_raw_tx); link_mgr.set_link_identified_channel(link_identified_tx); link_mgr.set_link_packet_proof_channel(link_packet_proof_tx); link_mgr.set_outbound_resource_proof_channel(link_resource_proof_tx); + link_mgr.set_resource_strategy(rns_runtime::prelude::ResourceStrategy::AcceptApp); + let delivery_limit_kb = config.delivery_transfer_max_accepted_size; + link_mgr.set_resource_accept_handler(move |_, advertisement| { + accepts_delivery_resource(advertisement.data_size, delivery_limit_kb) + }); let _ = transport_tx.try_send(TransportMessage::RegisterDestination { hash: lxmf_dest_hash, @@ -637,6 +930,11 @@ impl LxmdRunner { }); // Spawn the LinkManager as a background task + let cancellation_command_tx = link_command_tx.clone(); + tokio::spawn(forward_inbound_resource_cancellations( + inbound_resource_cancel_rx, + cancellation_command_tx, + )); tokio::spawn(async move { link_mgr.run_with_commands(link_command_rx).await; }); @@ -648,6 +946,8 @@ impl LxmdRunner { })); let (control_command_tx, control_command_rx) = mpsc::channel::(256); + let mut propagation_admission = None; + let mut prop_link_command_tx = None; let propagation_node: Option>> = if config.propagation_enabled { let (prop_delivery_tx, prop_delivery_rx) = mpsc::channel(256); let _ = transport_tx.try_send(TransportMessage::RegisterDestination { @@ -656,11 +956,17 @@ impl LxmdRunner { delivery_tx: Some(prop_delivery_tx), }); + let static_peer_hashes = config + .static_peers + .iter() + .filter_map(|peer| parse_destination_hash(peer).ok()) + .collect::>(); let pn_config = PropagationNodeConfig { max_storage: config .message_storage_limit .unwrap_or(config.propagation_limit_kb * 1024), max_message_size: config.propagation_limit_kb * 1024, + max_offer_size: config.sync_limit_kb.saturating_mul(1000), max_message_age: lxmf_core::constants::MESSAGE_EXPIRY, min_stamp_cost: config .propagation_stamp_cost @@ -682,6 +988,7 @@ impl LxmdRunner { .message_storage_limit .unwrap_or(config.propagation_limit_kb * 1024), max_message_size: config.propagation_limit_kb * 1024, + max_offer_size: config.sync_limit_kb.saturating_mul(1000), max_message_age: lxmf_core::constants::MESSAGE_EXPIRY, min_stamp_cost: config .propagation_stamp_cost @@ -692,6 +999,19 @@ impl LxmdRunner { ))) } }; + if let Ok(node) = pn.lock() { + for mut peer in node.load_peers() { + peer.is_static = static_peer_hashes.contains(&peer.destination_hash); + let _ = router.add_peer(peer); + } + } + + let pn_admission = Arc::new(Mutex::new(PnInboundRuntime::new( + config.to_inbound_admission_config(), + static_peer_hashes, + config.sync_limit_kb.saturating_mul(1000), + ))); + propagation_admission = Some(pn_admission.clone()); // TODO(hardware-identity): route propagation link signing through the // backend-aware Identity path before supporting hardware-backed lxmd. @@ -708,7 +1028,8 @@ impl LxmdRunner { Some(prop_signing_key), ); prop_link_mgr.set_link_packet_channel(prop_link_packet_tx); - prop_link_mgr.set_resource_completed_channel(prop_resource_tx); + prop_link_mgr.set_accounting_event_channel(prop_accounting_tx); + prop_link_mgr.set_resource_strategy(rns_runtime::prelude::ResourceStrategy::AcceptApp); let pn_for_handler = pn.clone(); let offer_path_hash = rns_crypto::sha::truncated_hash( @@ -717,29 +1038,69 @@ impl LxmdRunner { let get_path_hash = rns_crypto::sha::truncated_hash(lxmf_core::constants::MESSAGE_GET_PATH.as_bytes()); let link_identities = prop_link_mgr.link_identities_handle(); + let accept_link_identities = link_identities.clone(); + let admission_for_resources = pn_admission.clone(); + prop_link_mgr.set_resource_accept_handler(move |link_id, advertisement| { + let remote_identity_hash = accept_link_identities + .lock() + .ok() + .and_then(|identities| identities.get(&link_id).copied()); + let resource_id = logical_resource_id( + advertisement.resource_hash, + advertisement.original_hash, + advertisement.flags.split, + advertisement.total_segments, + ); + admission_for_resources + .lock() + .map(|mut admission| { + admission.accept_resource( + link_id, + resource_id, + advertisement.data_size, + remote_identity_hash, + ) + }) + .unwrap_or(false) + }); + let local_identity_hash = identity.hash; + let admission_for_handler = pn_admission.clone(); prop_link_mgr.set_request_handler(move |link_id, path_hash, data| { let remote_identity_hash = link_identities .lock() .ok() .and_then(|ids| ids.get(&link_id).copied()); let remote_identity_ref = remote_identity_hash.as_ref(); - let client_dest_hash = remote_identity_hash - .map(|identity_hash| { - Destination::hash_from_name_and_identity( - DELIVERY_APP_NAME, - Some(&identity_hash), - ) - }) - .unwrap_or([0; 16]); - let handler = - lxmf_core::handlers::PropagationRequestHandler::new(local_identity_hash); if path_hash == offer_path_hash { tracing::info!("propagation: handling offer request"); - let mut node = pn_for_handler.lock().ok()?; - Some(handler.handle_offer_request(remote_identity_ref, &data, &mut node)) + handle_pn_offer_request( + &admission_for_handler, + &pn_for_handler, + local_identity_hash, + link_id, + remote_identity_hash, + &data, + ) } else if path_hash == get_path_hash { + if admission_for_handler + .lock() + .map(|admission| admission.is_link_quarantined(&link_id)) + .unwrap_or(true) + { + return None; + } tracing::info!("propagation: handling get request"); + let client_dest_hash = remote_identity_hash + .map(|identity_hash| { + Destination::hash_from_name_and_identity( + DELIVERY_APP_NAME, + Some(&identity_hash), + ) + }) + .unwrap_or([0; 16]); + let handler = + lxmf_core::handlers::PropagationRequestHandler::new(local_identity_hash); let action = { let mut node = pn_for_handler.lock().ok()?; handler.handle_message_get_request( @@ -776,8 +1137,11 @@ impl LxmdRunner { } }); + let (pn_link_command_tx, pn_link_command_rx) = + mpsc::channel::(256); + prop_link_command_tx = Some(pn_link_command_tx); tokio::spawn(async move { - prop_link_mgr.run().await; + prop_link_mgr.run_with_commands(pn_link_command_rx).await; }); let (control_delivery_tx, control_delivery_rx) = mpsc::channel(256); @@ -933,11 +1297,20 @@ impl LxmdRunner { propagation_sync: None, propagation_client: None, propagation_node: None, + propagation_admission, + prop_link_command_tx, transport_tx: transport_tx.clone(), link_packet_rx, - resource_rx, + delivery_accounting_rx, + delivery_resource_event_rx, prop_link_packet_rx, - prop_resource_rx, + prop_accounting_rx, + prop_validation_rx, + prop_validation_tx, + peering_key_result_rx, + peering_key_result_tx, + peering_key_jobs: HashSet::new(), + pending_peer_syncs: HashSet::new(), inbound_raw_rx, announce_rx, last_peer_announce: 0.0, @@ -954,10 +1327,17 @@ impl LxmdRunner { if runner.config.propagation_enabled { if let Some(ref pn) = propagation_node { - let sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node( + let mut sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node( transport_tx.clone(), pn.clone(), ); + if let Some(signing_key) = runner.identity.get_signing_key() { + sync.set_identity(runner.identity.get_public_key(), signing_key); + } else { + tracing::error!( + "local identity has no signing key; outbound peer sync cannot identify" + ); + } runner.propagation_sync = Some(sync); } runner.propagation_node = propagation_node; @@ -971,6 +1351,7 @@ impl LxmdRunner { Some(runner.identity.get_public_key()), runner.identity.get_signing_key(), ); + client.set_delivery_limit(runner.config.delivery_transfer_max_accepted_size); if let Some(ref node_hex) = runner.config.outbound_propagation_node { match hex::decode(node_hex) { Ok(bytes) if bytes.len() == 16 => { @@ -978,11 +1359,12 @@ impl LxmdRunner { node.copy_from_slice(&bytes); client.set_propagation_node(node); runner.router.outbound_propagation_node = Some(node); - runner + let peer = runner .router .peers .entry(node) .or_insert_with(|| lxmf_core::peer::LxmPeer::new(node)); + peer.is_static = true; if !runner.router.static_peers.contains(&node) { runner.router.static_peers.push(node); } @@ -1045,10 +1427,12 @@ impl LxmdRunner { if !self.router.static_peers.contains(&hash) { self.router.static_peers.push(hash); } - self.router + let peer = self + .router .peers .entry(hash) .or_insert_with(|| lxmf_core::peer::LxmPeer::new(hash)); + peer.is_static = true; } Err(e) => { tracing::warn!(hash = %configured, "ignoring invalid static peer hash: {e}") @@ -1177,9 +1561,7 @@ impl LxmdRunner { if !self.router.peers.contains_key(&peer_hash) { continue; } - if let Some(ref mut sync) = self.propagation_sync { - sync.request_sync_now(peer_hash); - } + self.pending_peer_syncs.insert(peer_hash); if let Some(peer) = self.router.peers.get_mut(&peer_hash) { peer.next_sync_attempt = 0.0; peer.alive = true; @@ -1187,7 +1569,22 @@ impl LxmdRunner { tracing::info!(peer = %hex::encode(peer_hash), "control: queued peer sync"); } ControlCommand::Unpeer(peer_hash) => { - self.router.unpeer(&peer_hash); + self.pending_peer_syncs.remove(&peer_hash); + if let Some(sync) = self.propagation_sync.as_mut() { + sync.cancel_peer_sync(&peer_hash); + } + // Upstream control unpeer breaks the live peering without + // mutating the operator's configured static-peer set. + self.router.remove_peer(&peer_hash); + if let Some(ref node) = self.propagation_node + && let Ok(mut node) = node.lock() + && let Err(error) = node.delete_peer(&peer_hash) + { + tracing::warn!( + peer = %hex::encode(peer_hash), + "failed to remove persisted propagation peer: {error}" + ); + } if let Err(e) = self.router.save_state(&self.data_dir) { tracing::warn!("Failed to save router state after control unpeer: {e}"); } @@ -1197,6 +1594,157 @@ impl LxmdRunner { } } + fn drain_peering_key_results(&mut self) { + while let Ok(result) = self.peering_key_result_rx.try_recv() { + self.peering_key_jobs.remove(&result.peer_hash); + + let mut applied = false; + let mut current_cost = false; + if let Some(peer) = self.router.peers.get_mut(&result.peer_hash) { + current_cost = peer.peering_cost == result.peering_cost; + // Peering-key work binds only the two identities. A newer + // announce timebase (or a lower current target) does not make + // a completed key stale if its measured value is still high + // enough for the current policy. + if let Some((key, value)) = result.peering_key + && value >= peer.peering_cost as u32 + { + peer.peering_key = Some((key, value)); + applied = true; + } + } + + if applied { + if let (Some(node), Some(peer)) = ( + self.propagation_node.as_ref(), + self.router.peers.get(&result.peer_hash), + ) && let Ok(node) = node.lock() + && let Err(error) = node.save_peer(peer) + { + tracing::warn!( + peer = %hex::encode(result.peer_hash), + "failed to persist generated peering key: {error}" + ); + } + } else if current_cost { + // A bounded key search can fail for an excessive advertised + // cost. Put this policy generation into the normal peer + // backoff instead of spinning a fresh CPU job every tick. + self.pending_peer_syncs.remove(&result.peer_hash); + if let Some(peer) = self.router.peers.get_mut(&result.peer_hash) { + peer.next_sync_attempt = + now_f64() + lxmf_core::constants::SYNC_BACKOFF_STEP as f64; + } + tracing::warn!( + peer = %hex::encode(result.peer_hash), + peering_cost = result.peering_cost, + "could not generate a peering key; sync remains postponed" + ); + } + // A result for a different cost that no longer satisfies policy + // is ignored. The pending sync remains queued and dispatches a + // new job for the current target. + } + } + + fn queue_due_peer_syncs(&mut self) { + if self.propagation_sync.is_none() { + return; + } + let Some(offer_generation) = self + .propagation_node + .as_ref() + .and_then(|node| node.lock().ok().map(|node| node.offer_generation())) + else { + return; + }; + + for policy in self.router.sync_peer_policies_for_store(offer_generation) { + self.pending_peer_syncs.insert(policy.peer_hash); + } + } + + fn drive_pending_peer_syncs(&mut self) { + if self + .propagation_sync + .as_ref() + .is_none_or(|sync| sync.state != lxmf_core::propagation_sync::SyncTaskState::Idle) + { + return; + } + + let mut pending = self.pending_peer_syncs.iter().copied().collect::>(); + pending.sort_unstable(); + for peer_hash in pending { + let Some(peer_identity_hash) = recall_identity_hash(&self.known_identities, &peer_hash) + else { + tracing::debug!( + peer = %hex::encode(peer_hash), + "peer sync postponed until its identity is known" + ); + continue; + }; + let policy = self.router.peers.get(&peer_hash).and_then(|peer| { + (peer.stamp_costs_known() && (peer.peering_cost == 0 || peer.peering_key_ready())) + .then(|| OutboundOfferPolicy::from(peer)) + }); + if let Some(policy) = policy { + if let Some(sync) = self.propagation_sync.as_mut() + && sync.request_sync_now_with_policy(policy) + { + if let Some(peer) = self.router.peers.get_mut(&peer_hash) { + peer.begin_sync(); + } + self.pending_peer_syncs.remove(&peer_hash); + } + return; + } + + if self + .router + .peers + .get(&peer_hash) + .is_some_and(|peer| !peer.stamp_costs_known()) + { + tracing::debug!( + peer = %hex::encode(peer_hash), + "peer sync postponed until its stamp policy is known" + ); + continue; + } + + if self.peering_key_jobs.contains(&peer_hash) { + continue; + } + let Some(peer) = self.router.peers.get(&peer_hash) else { + self.pending_peer_syncs.remove(&peer_hash); + continue; + }; + + let peering_cost = peer.peering_cost; + let local_identity_hash = self.identity.hash; + let result_tx = self.peering_key_result_tx.clone(); + self.peering_key_jobs.insert(peer_hash); + tokio::spawn(async move { + let result = tokio::task::spawn_blocking(move || { + generate_peering_key_job( + peer_hash, + peering_cost, + peer_identity_hash, + local_identity_hash, + ) + }) + .await + .unwrap_or(PeeringKeyWorkerResult { + peer_hash, + peering_cost, + peering_key: None, + }); + let _ = result_tx.send(result).await; + }); + } + } + fn drain_backchannel_events(&mut self) { let mut identified = Vec::new(); while let Ok(item) = self.link_identified_rx.try_recv() { @@ -1446,6 +1994,9 @@ impl LxmdRunner { let now = now_f64(); self.drain_control_commands(); + self.drain_peering_key_results(); + self.queue_due_peer_syncs(); + self.drive_pending_peer_syncs(); self.drain_backchannel_events(); self.router.process_deferred_stamps(); @@ -1500,13 +2051,64 @@ impl LxmdRunner { } } + let mut peer_handled_updates = None; + let mut peer_terminal_result = None; if let Some(ref mut ps) = self.propagation_sync { ps.drain_events(&self.known_identities); ps.tick(); + let updates = ps.take_handled_updates(); + if !updates.is_empty() + && let Some(peer_hash) = ps.node_dest_hash() + { + peer_handled_updates = Some((peer_hash, updates)); + } + peer_terminal_result = ps.take_terminal_peer_result(); + } + let mut peers_to_persist = HashSet::new(); + if let Some((peer_hash, updates)) = peer_handled_updates + && let Some(peer) = self.router.peers.get_mut(&peer_hash) + { + for transient_id in updates { + peer.add_handled_message(&transient_id); + } + peers_to_persist.insert(peer_hash); + } + if let Some(result) = peer_terminal_result + && let Some(peer) = self.router.peers.get_mut(&result.peer_hash) + { + match result.state { + lxmf_core::propagation_sync::PeerSyncTerminalState::Complete => { + peer.sync_complete(); + if result.generation_exhausted + && let Some(generation) = result.offer_generation + { + peer.mark_offer_generation_processed(generation); + } + } + lxmf_core::propagation_sync::PeerSyncTerminalState::Failed => { + peer.sync_failed(); + } + } + peers_to_persist.insert(result.peer_hash); + } + for peer_hash in peers_to_persist { + if let (Some(node), Some(peer)) = ( + self.propagation_node.as_ref(), + self.router.peers.get(&peer_hash), + ) && let Ok(node) = node.lock() + && let Err(error) = node.save_peer(peer) + { + tracing::warn!( + peer = %hex::encode(peer_hash), + "failed to persist peer sync state: {error}" + ); + } } // Drive propagation client (download from node) let mut downloaded_messages = Vec::new(); + let mut propagation_status = None; + let mut acknowledge_propagation = false; let propagation_node_ready = self .router .outbound_propagation_node @@ -1520,7 +2122,7 @@ impl LxmdRunner { // Auto-download every 90s if now - self.last_propagation_check > 90.0 - && client.state == lxmf_core::propagation_client::PropagationClientState::Idle + && client.state() == lxmf_core::propagation_client::PropagationClientState::Idle { if propagation_node_ready { client.start_download(); @@ -1540,11 +2142,24 @@ impl LxmdRunner { ); } } + let status = client.transfer_status(); + acknowledge_propagation = matches!( + status.state, + lxmf_core::propagation_client::PropagationClientState::Complete + | lxmf_core::propagation_client::PropagationClientState::Failed + ); + propagation_status = Some(status); + } + if let Some(status) = propagation_status { + self.router.update_propagation_transfer_status(status); } // Borrow is released; process downloaded messages. for msg_data in downloaded_messages { self.handle_propagation_downloaded_data(&msg_data); } + if acknowledge_propagation && let Some(client) = self.propagation_client.as_mut() { + client.acknowledge_transfer(); + } if let Some(interval) = self.config.announce_interval && now - self.last_peer_announce > interval as f64 @@ -1680,6 +2295,98 @@ impl LxmdRunner { { self.router .set_stamp_cost(event.destination_hash, pn.stamp_cost); + let is_static = self.router.static_peers.contains(&event.destination_hash); + let previous_offer_constraints = self + .router + .peers + .get(&event.destination_hash) + .map(PeerOfferConstraints::from); + let static_observation = is_static + && (!event.is_path_response + || self + .router + .peers + .get(&event.destination_hash) + .is_some_and(|peer| !peer.stamp_costs_known())); + let autopeer_observation = + !is_static && self.config.autopeer && !event.is_path_response; + let mut peer_changed = false; + let mut peer_removed = false; + if static_observation || (autopeer_observation && pn.node_state) { + let had_peer = self.router.peers.contains_key(&event.destination_hash); + peer_changed = self.router.autopeer(AutopeerCandidate { + destination_hash: event.destination_hash, + timebase: pn.timebase as f64, + transfer_limit: Some(pn.transfer_limit as f64), + sync_limit: Some(pn.sync_limit as f64), + stamp_cost: Some(pn.stamp_cost), + stamp_flexibility: Some(pn.stamp_flex), + peering_cost: Some(pn.peering_cost), + hops: Some(event.hops), + metadata: Some(pn.metadata.clone()), + }); + peer_removed = + had_peer && !self.router.peers.contains_key(&event.destination_hash); + } else if autopeer_observation + && !pn.node_state + && self + .router + .peers + .get(&event.destination_hash) + .is_some_and(|peer| { + !peer.is_static && pn.timebase as f64 >= peer.peering_timebase + }) + { + self.router.remove_peer(&event.destination_hash); + peer_removed = true; + } + + if peer_removed { + self.pending_peer_syncs.remove(&event.destination_hash); + if let Some(sync) = self.propagation_sync.as_mut() { + sync.cancel_peer_sync(&event.destination_hash); + } + if let Some(node) = self.propagation_node.as_ref() + && let Ok(mut node) = node.lock() + && let Err(error) = node.delete_peer(&event.destination_hash) + { + tracing::warn!( + peer = %dest_hex, + "failed to remove retired propagation peer: {error}" + ); + } + } else if peer_changed { + let offer_constraints_changed = + previous_offer_constraints.is_some_and(|previous| { + self.router + .peers + .get(&event.destination_hash) + .map(PeerOfferConstraints::from) + != Some(previous) + }); + if offer_constraints_changed + && self + .propagation_sync + .as_mut() + .is_some_and(|sync| sync.cancel_peer_sync(&event.destination_hash)) + { + if let Some(peer) = self.router.peers.get_mut(&event.destination_hash) { + peer.link_closed(); + } + self.pending_peer_syncs.insert(event.destination_hash); + } + if let (Some(node), Some(peer)) = ( + self.propagation_node.as_ref(), + self.router.peers.get(&event.destination_hash), + ) && let Ok(node) = node.lock() + && let Err(error) = node.save_peer(peer) + { + tracing::warn!( + peer = %dest_hex, + "failed to persist propagation peer policy: {error}" + ); + } + } tracing::debug!( dest = %dest_hex, stamp_cost = pn.stamp_cost, @@ -1730,6 +2437,25 @@ impl LxmdRunner { } fn drain_link_packets(&mut self) { + while let Ok(event) = self.delivery_accounting_rx.try_recv() { + self.handle_delivery_accounting_event(event); + } + + while let Ok(event) = self.delivery_resource_event_rx.try_recv() { + // Starts and conclusions are capacity-lossless on the accounting + // stream. Only progress is intentionally consumed here. + if matches!( + &event, + LinkResourceEvent::Progress { + direction: LinkResourceDirection::Inbound, + .. + } + ) && let Some(event) = delivery_resource_event_from_runtime(event) + { + self.router.handle_inbound_resource_event(event); + } + } + while let Ok((plaintext, link_id)) = self.link_packet_rx.try_recv() { tracing::info!( link_id = %hex::encode(link_id), @@ -1739,31 +2465,44 @@ impl LxmdRunner { self.handle_link_delivered_data(&plaintext); } - while let Ok((data, link_id)) = self.resource_rx.try_recv() { - tracing::info!( - link_id = %hex::encode(link_id), - len = data.len(), - "resource transfer completed on link" - ); - self.handle_link_delivered_data(&data); - } - while let Ok((data, link_id)) = self.prop_link_packet_rx.try_recv() { tracing::info!( link_id = %hex::encode(link_id), len = data.len(), "received propagation packet via link" ); - self.handle_propagation_transfer_data(&data); + self.handle_propagation_transfer_data(link_id, &data); } - while let Ok((data, link_id)) = self.prop_resource_rx.try_recv() { - tracing::info!( - link_id = %hex::encode(link_id), - len = data.len(), - "propagation resource transfer completed" - ); - self.handle_propagation_transfer_data(&data); + while let Ok(event) = self.prop_accounting_rx.try_recv() { + self.handle_propagation_accounting_event(event); + } + + while let Ok(result) = self.prop_validation_rx.try_recv() { + self.handle_propagation_validation_result(result); + } + } + + fn handle_delivery_accounting_event(&mut self, event: LinkManagerAccountingEvent) { + match event { + LinkManagerAccountingEvent::ResourceEvent(event) => { + if let Some(event) = delivery_resource_event_from_runtime(event) { + self.router.handle_inbound_resource_event(event); + } + } + LinkManagerAccountingEvent::LinkClosed { link_id } => { + self.router + .handle_inbound_resource_event(InboundResourceEvent::LinkClosed { link_id }); + } + LinkManagerAccountingEvent::ResourceCompletion(completion) => { + tracing::info!( + link_id = %hex::encode(completion.link_id), + len = completion.data.len(), + "resource transfer completed on link" + ); + self.handle_link_delivered_data(&completion.data); + } + _ => {} } } @@ -1810,7 +2549,133 @@ impl LxmdRunner { } } - fn handle_propagation_transfer_data(&mut self, data: &[u8]) { + fn handle_propagation_accounting_event( + &mut self, + event: rns_runtime::link_manager::LinkManagerAccountingEvent, + ) { + let validation_job = self + .propagation_admission + .as_ref() + .and_then(|admission| admission.lock().ok()?.handle_accounting_event(event)); + if let Some(job) = validation_job { + self.spawn_propagation_validation(job); + } + } + + fn spawn_propagation_validation(&self, job: PnValidationJob) { + let token = job.token(); + let link_id = job.link_id(); + let max_transfer_bytes = self.config.sync_limit_kb.saturating_mul(1000); + let min_cost = self + .config + .propagation_stamp_cost + .saturating_sub(self.config.propagation_stamp_flex); + let result_tx = self.prop_validation_tx.clone(); + + tokio::spawn(async move { + let result = match tokio::task::spawn_blocking(move || { + validate_pn_resource_job(job, max_transfer_bytes, min_cost) + }) + .await + { + Ok(result) => result, + Err(error) => { + tracing::warn!( + link_id = %hex::encode(link_id), + "propagation validation worker failed: {error}" + ); + PnValidationWorkerResult { + token, + link_id, + outcome: PnValidationOutcome::Failed, + entries: Vec::new(), + rejected: 0, + } + } + }; + + if result_tx.send(result).await.is_err() { + tracing::debug!("propagation validation receiver closed"); + } + }); + } + + fn handle_propagation_validation_result(&mut self, result: PnValidationWorkerResult) { + let claim = self.propagation_admission.as_ref().and_then(|admission| { + admission + .lock() + .ok()? + .conclude_validation(result.token, result.link_id, result.outcome) + }); + let Some(claim) = claim else { + tracing::debug!( + link_id = %hex::encode(result.link_id), + "ignoring stale or duplicate propagation validation result" + ); + return; + }; + + let mut accepted = 0usize; + if let Some(ref node) = self.propagation_node + && let Ok(mut node) = node.lock() + { + for entry in result.entries { + let stamp_value = u8::try_from(entry.stamp_value).unwrap_or(u8::MAX); + if node.accept_stamped_propagated_blob( + &entry.lxmf_data, + &entry.stamp_data, + stamp_value, + ) { + accepted += 1; + } + } + } + + tracing::info!( + link_id = %hex::encode(claim.link_id()), + accepted, + rejected = result.rejected, + outcome = ?claim.outcome(), + "processed inbound propagation Resource" + ); + + if claim.should_close_link() + && let Some(command_tx) = self.prop_link_command_tx.clone() + { + let link_id = claim.link_id(); + tokio::spawn(async move { + if command_tx + .send(rns_runtime::link_manager::LinkManagerCommand::CloseLink { + link_id, + reason: rns_runtime::prelude::CloseReason::DestinationClosed, + send_teardown: true, + }) + .await + .is_err() + { + tracing::debug!( + link_id = %hex::encode(link_id), + "propagation Link already closed before validation teardown" + ); + } + }); + } + } + + fn handle_propagation_transfer_data(&mut self, link_id: [u8; 16], data: &[u8]) { + if self + .propagation_admission + .as_ref() + .is_some_and(|admission| { + admission + .lock() + .map(|admission| admission.is_link_quarantined(&link_id)) + .unwrap_or(true) + }) + { + return; + } + let Some(ref pn) = self.propagation_node else { tracing::debug!("received propagation data but node storage is disabled"); return; @@ -1860,6 +2725,12 @@ impl LxmdRunner { return; } + // The propagation transient ID is over the representation received + // from the node, before destination decryption. Retain it alongside + // the signed message hash so redelivery through a different LXMF path + // is still suppressed by the router-owned gate. + let propagation_transient_id = LxMessage::compute_propagation_transient_id(data); + let unpack_data = if data[..16] == self.lxmf_dest_hash { match self.decrypt_inbound(&data[16..]) { Some(plaintext) => { @@ -1876,6 +2747,7 @@ impl LxmdRunner { match LxMessage::unpack(&unpack_data) { Ok(mut msg) => { msg.method = lxmf_core::constants::DeliveryMethod::Propagated; + msg.transient_id = Some(propagation_transient_id); tracing::info!( from = %hex::encode(msg.source_hash), title = %msg.title, @@ -2026,7 +2898,15 @@ impl LxmdRunner { } /// Write a received LXMF message to disk and invoke `on_inbound`. - fn handle_inbound_message(&self, msg: LxMessage) { + fn handle_inbound_message(&mut self, msg: LxMessage) { + if !self.router.deliver_inbound(&msg, false) { + tracing::debug!( + message = ?msg.message_id.or(msg.hash).map(hex::encode), + "ignoring already delivered inbound LXMF message" + ); + return; + } + // Also deposit into the propagation store (if enabled) so peers can // download it via offer/get sync. if let Some(ref pn) = self.propagation_node @@ -2345,6 +3225,7 @@ impl LxmdRunner { } let msg_hash = message.hash; + let destination_public_key = self.known_identities.get(&dest_hex).copied(); let mut missing_identity = false; let payload = match message.pack_opportunistic_encrypted(|plaintext| { self.encrypt_for_destination(&dest_hex, plaintext) @@ -2389,6 +3270,13 @@ impl LxmdRunner { continue; } }; + let Some(destination_public_key) = destination_public_key else { + tracing::error!( + dest = %dest_hex, + "opportunistic encryption succeeded without a retained destination identity" + ); + continue; + }; let flags = rns_wire::flags::PacketFlags { header_type: rns_wire::flags::HeaderType::Header1, @@ -2465,6 +3353,8 @@ impl LxmdRunner { .try_send(TransportMessage::RegisterReceipt { truncated_hash: trunc, full_hash: full, + destination_hash: dest_hash, + destination_public_key, msg_id: hex::encode(hash), timeout: Some(Duration::from_secs(15)), }); @@ -3158,12 +4048,33 @@ pub(crate) async fn main() { runner.handle_link_delivered_data(&plaintext); runner.drain_link_packets(); } - Some((data, _link_id)) = runner.prop_link_packet_rx.recv() => { - runner.handle_propagation_transfer_data(&data); + Some(event) = runner.delivery_accounting_rx.recv() => { + runner.handle_delivery_accounting_event(event); runner.drain_link_packets(); } - Some((data, _link_id)) = runner.prop_resource_rx.recv() => { - runner.handle_propagation_transfer_data(&data); + Some(event) = runner.delivery_resource_event_rx.recv() => { + if matches!( + &event, + LinkResourceEvent::Progress { + direction: LinkResourceDirection::Inbound, + .. + } + ) && let Some(event) = delivery_resource_event_from_runtime(event) + { + runner.router.handle_inbound_resource_event(event); + } + runner.drain_link_packets(); + } + Some((data, link_id)) = runner.prop_link_packet_rx.recv() => { + runner.handle_propagation_transfer_data(link_id, &data); + runner.drain_link_packets(); + } + Some(event) = runner.prop_accounting_rx.recv() => { + runner.handle_propagation_accounting_event(event); + runner.drain_link_packets(); + } + Some(result) = runner.prop_validation_rx.recv() => { + runner.handle_propagation_validation_result(result); runner.drain_link_packets(); } } @@ -3183,6 +4094,73 @@ mod tests { use super::*; use lxmf_core::constants::DeliveryMethod; + #[tokio::test] + async fn inbound_resource_cancel_adapter_preserves_exact_owner_and_direction() { + let (cancel_tx, cancel_rx) = mpsc::channel(2); + let (link_command_tx, mut link_command_rx) = mpsc::channel(2); + tokio::spawn(forward_inbound_resource_cancellations( + cancel_rx, + link_command_tx, + )); + + let mut router = LxmRouter::new(lxmf_core::router::RouterConfig::default()); + router.set_inbound_resource_cancel_sender(cancel_tx); + let key = InboundResourceKey::new([0x11; 16], [0x22; 32]); + router.handle_inbound_resource_event(InboundResourceEvent::Started { + key, + data_size: 512, + total_segments: 2, + }); + + assert_eq!(router.inbound_count(), 1); + assert!(router.cancel_inbound_exact(key)); + let command = link_command_rx.recv().await.expect("cancellation command"); + let LinkManagerCommand::CancelLinkResource { + link_id, + resource_id, + direction, + result_tx, + } = command + else { + panic!("expected exact LinkManager Resource cancellation"); + }; + assert_eq!(link_id, key.link_id); + assert_eq!(resource_id, key.resource_id); + assert_eq!(direction, LinkResourceDirection::Inbound); + assert!(result_tx.is_none()); + } + + #[test] + fn runtime_resource_projection_tracks_only_inbound_resources() { + let key = InboundResourceKey::new([0x33; 16], [0x44; 32]); + let projected = delivery_resource_event_from_runtime(LinkResourceEvent::Progress { + link_id: key.link_id, + resource_id: key.resource_id, + direction: LinkResourceDirection::Inbound, + transferred: 12, + total: 24, + }); + assert_eq!( + projected, + Some(InboundResourceEvent::Progress { + key, + transferred: 12, + total: 24, + }) + ); + + assert!( + delivery_resource_event_from_runtime(LinkResourceEvent::Progress { + link_id: key.link_id, + resource_id: key.resource_id, + direction: LinkResourceDirection::Outbound, + transferred: 12, + total: 24, + }) + .is_none() + ); + } + fn unpack_announce(raw: &[u8]) -> (rns_wire::header::PacketHeader, AnnounceData) { let (header, header_len) = rns_wire::header::PacketHeader::unpack(raw).unwrap(); let announce = AnnounceData::unpack(&raw[header_len..], header.flags.context_flag).unwrap(); @@ -3205,6 +4183,47 @@ mod tests { assert_eq!(announce.ratchet, None); } + #[test] + fn delivery_resource_admission_uses_decimal_kilobytes_with_exact_boundary() { + let default_limit = DaemonConfig::default().delivery_transfer_max_accepted_size; + assert_eq!(default_limit, 1000.0); + assert!(accepts_delivery_resource(1_000_000, default_limit)); + assert!(!accepts_delivery_resource(1_000_001, default_limit)); + + assert!(accepts_delivery_resource(380, 0.38)); + assert!(!accepts_delivery_resource(381, 0.38)); + } + + #[tokio::test(flavor = "current_thread")] + async fn delivery_announce_stamp_cost_is_independent_of_enforcement() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + for enforce_stamps in [false, true] { + let temp = std::env::temp_dir().join(format!( + "lxmd-delivery-announce-stamp-{}-{unique}-{enforce_stamps}", + std::process::id() + )); + let (tx, _rx) = mpsc::channel::(64); + let config = DaemonConfig { + stamp_cost: Some(12), + enforce_stamps, + ..Default::default() + }; + let mut runner = LxmdRunner::new(config, &temp, tx).expect("runner"); + let raw = runner.create_announce_packet().expect("delivery announce"); + let (_, announce) = unpack_announce(&raw); + let (_, stamp_cost) = lxmf_core::handlers::parse_announce_app_data( + announce.app_data.as_deref().expect("delivery app data"), + ) + .expect("valid delivery app data"); + assert_eq!(stamp_cost, Some(12)); + drop(runner); + let _ = std::fs::remove_dir_all(&temp); + } + } + /// Blackhole gating mirrors LXMessage.py:804: only a recallable source /// identity can be matched against the blackhole table; unknown sources /// never drop. @@ -3473,6 +4492,71 @@ mod tests { let _ = std::fs::remove_dir_all(&temp); } + #[tokio::test] + async fn packet_then_link_resource_delivers_one_application_message() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let temp = std::env::temp_dir().join(format!( + "lxmd-cross-path-dedup-{}-{unique}", + std::process::id() + )); + let (tx, _rx) = mpsc::channel::(64); + let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx).expect("runner"); + + let deliveries = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&deliveries); + runner.router.register_delivery_callback(move |_| { + observed.fetch_add(1, Ordering::Relaxed); + }); + + let mut message = LxMessage::new( + runner.lxmf_dest_hash, + [0xCD; 16], + "one", + "delivery", + DeliveryMethod::Direct, + ); + message.signature = Some([0u8; 64]); + let packed = message.pack().expect("pack"); + let message_id = LxMessage::unpack(&packed) + .expect("unpack") + .message_id + .expect("message id"); + + let ciphertext = runner + .identity + .encrypt(&packed[16..], None) + .expect("encrypt opportunistic payload"); + let header = rns_wire::header::PacketHeader { + flags: rns_wire::flags::PacketFlags { + header_type: rns_wire::flags::HeaderType::Header1, + context_flag: false, + transport_type: rns_wire::flags::TransportType::Broadcast, + destination_type: rns_wire::flags::DestinationType::Single, + packet_type: rns_wire::flags::PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: runner.lxmf_dest_hash, + context: rns_wire::context::PacketContext::None, + }; + let mut packet = header.pack(); + packet.extend_from_slice(&ciphertext); + + runner.handle_inbound_packet(&packet); + runner.handle_link_delivered_data(&packed); + + assert_eq!(deliveries.load(Ordering::Relaxed), 1); + assert!(runner.router.has_message(&message_id)); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + let _ = std::fs::remove_dir_all(&temp); + } + #[test] fn direct_reusable_link_state_uses_registered_backchannel() { let (tx, _rx) = mpsc::channel(8); @@ -3491,4 +4575,165 @@ mod tests { DirectReusableLinkState::None ); } + + fn pn_test_entry(stamp_byte: u8) -> Vec { + let mut entry = + vec![0x42; LxMessage::MIN_PROPAGATION_ENTRY_SIZE - lxmf_core::constants::STAMP_SIZE]; + entry.extend_from_slice(&[stamp_byte; lxmf_core::constants::STAMP_SIZE]); + entry + } + + fn pn_test_wrapper(entries: Vec>) -> Vec { + let value = rmpv::Value::Array(vec![ + rmpv::Value::from(0.0f64), + rmpv::Value::Array(entries.into_iter().map(rmpv::Value::Binary).collect()), + ]); + let mut encoded = Vec::new(); + rmpv::encode::write_value(&mut encoded, &value).expect("propagation wrapper"); + encoded + } + + fn pn_test_offer(transient_ids: Vec<[u8; 32]>) -> Vec { + let value = rmpv::Value::Array(vec![ + rmpv::Value::Binary(Vec::new()), + rmpv::Value::Array( + transient_ids + .into_iter() + .map(|id| rmpv::Value::Binary(id.to_vec())) + .collect(), + ), + ]); + let mut encoded = Vec::new(); + rmpv::encode::write_value(&mut encoded, &value).expect("offer request"); + encoded + } + + #[test] + fn pn_offer_handler_uses_one_persistent_admission_owner() { + let local_identity = [0x11; 16]; + let remote_identity = [0x22; 16]; + let link_id = [0x33; 16]; + let runtime = Arc::new(Mutex::new(PnInboundRuntime::new( + lxmf_core::propagation_admission::PnInboundAdmissionConfig::default(), + [], + 1_000, + ))); + let node = Arc::new(Mutex::new(PropagationNode::new( + PropagationNodeConfig { + peering_cost: 0, + ..PropagationNodeConfig::default() + }, + local_identity, + ))); + let offer = pn_test_offer(vec![[0x44; 32]]); + + let response = handle_pn_offer_request( + &runtime, + &node, + local_identity, + link_id, + Some(remote_identity), + &offer, + ) + .unwrap(); + assert_eq!( + response, + PropagationNode::encode_offer_response(&lxmf_core::sync::OfferResponse::WantAll) + ); + + let repeated = handle_pn_offer_request( + &runtime, + &node, + local_identity, + link_id, + Some(remote_identity), + &offer, + ) + .unwrap(); + assert_eq!( + repeated, + PropagationNode::encode_offer_response(&lxmf_core::sync::OfferResponse::ErrorThrottled) + ); + } + + #[test] + fn peer_key_worker_binds_remote_identity_before_local_identity() { + let remote_identity = [0x21; 16]; + let local_identity = [0x43; 16]; + let result = generate_peering_key_job([0x65; 16], 1, remote_identity, local_identity); + let (key, value) = result.peering_key.expect("cost-one key"); + assert!(value >= 1); + + let mut peering_id = [0u8; 32]; + peering_id[..16].copy_from_slice(&remote_identity); + peering_id[16..].copy_from_slice(&local_identity); + assert!(lxmf_core::stamper::validate_peering_key( + &peering_id, + &key, + 1 + )); + } + + #[test] + fn pn_validation_worker_enforces_client_batch_authorization() { + let wrapper = pn_test_wrapper(vec![pn_test_entry(0), pn_test_entry(1)]); + let result = validate_pn_resource_job( + PnValidationJob::for_test(wrapper.clone(), false), + wrapper.len(), + 0, + ); + assert_eq!(result.outcome, PnValidationOutcome::UnauthorizedMultiple); + assert!(result.entries.is_empty()); + assert_eq!(result.rejected, 2); + + let result = validate_pn_resource_job( + PnValidationJob::for_test(wrapper.clone(), true), + wrapper.len(), + 0, + ); + assert_eq!(result.outcome, PnValidationOutcome::Valid); + assert_eq!(result.entries.len(), 2); + assert_eq!(result.rejected, 0); + } + + #[test] + fn pn_validation_worker_preserves_valid_siblings_in_invalid_batch() { + let mut valid = None; + let mut invalid = None; + for stamp_byte in 0u8..=u8::MAX { + let entry = pn_test_entry(stamp_byte); + if lxmf_core::stamper::validate_pn_stamp(&entry, 1).is_some() { + valid.get_or_insert(entry); + } else { + invalid.get_or_insert(entry); + } + if valid.is_some() && invalid.is_some() { + break; + } + } + let wrapper = pn_test_wrapper(vec![valid.unwrap(), invalid.unwrap()]); + let result = validate_pn_resource_job( + PnValidationJob::for_test(wrapper.clone(), true), + wrapper.len(), + 1, + ); + assert_eq!(result.outcome, PnValidationOutcome::InvalidStamp); + assert_eq!(result.entries.len(), 1); + assert_eq!(result.rejected, 1); + } + + #[test] + fn pn_validation_worker_fails_malformed_or_oversized_wrapper() { + let malformed = vec![0xc1]; + let result = validate_pn_resource_job(PnValidationJob::for_test(malformed, true), 100, 0); + assert_eq!(result.outcome, PnValidationOutcome::Failed); + + let wrapper = pn_test_wrapper(vec![pn_test_entry(0)]); + let result = validate_pn_resource_job( + PnValidationJob::for_test(wrapper.clone(), true), + wrapper.len() - 1, + 0, + ); + assert_eq!(result.outcome, PnValidationOutcome::Failed); + } } diff --git a/crates/lxmf-tools/src/commands/lxmd_pn.rs b/crates/lxmf-tools/src/commands/lxmd_pn.rs new file mode 100644 index 0000000..ece59e5 --- /dev/null +++ b/crates/lxmf-tools/src/commands/lxmd_pn.rs @@ -0,0 +1,1188 @@ +//! Daemon-owned inbound propagation admission and Resource accounting. +//! +//! Reticulum request Resources share a Link with ordinary propagation +//! Resources, so Link identity alone is not sufficient lifecycle ownership. +//! Only the `AcceptApp` callback may create an exact +//! `(link_id, logical_resource_id)` correlation. The ordered accounting stream +//! can then advance or conclude that exact record without mistaking `/offer` +//! or `/get` request Resources for an accepted propagation transfer. + +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +use lxmf_core::propagation_admission::{ + PnCandidateDiscardResult, PnInboundAdmission, PnInboundAdmissionConfig, PnInboundState, + PnOfferAdmission, PnOfferCandidate, PnOfferRejection, PnValidationResult, +}; +use lxmf_core::propagation_offer::PnOfferEvaluation; +use lxmf_core::sync::OfferResponse; +use rns_runtime::link_manager::{ + LinkManagerAccountingEvent, LinkResourceConclusion, LinkResourceDirection, LinkResourceEvent, +}; + +type LinkId = [u8; 16]; +type LogicalResourceId = [u8; 32]; +type ResourceKey = (LinkId, LogicalResourceId); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ResourceOwner { + /// Resource promised by an accepted `WantAll` or `WantSome` offer. + Offered, + /// Ordinary Resource on a Link that previously proved a peering key. + ValidatedPeer, + /// Ordinary client/originator Resource without a peering-key proof. + Client, +} + +#[derive(Debug, Clone, Copy)] +struct ResourceCorrelation { + owner: ResourceOwner, + peer_destination_hash: Option<[u8; 16]>, + started: bool, + completion_dispatched: bool, +} + +#[derive(Debug, Clone, Copy)] +struct PendingValidation { + key: ResourceKey, + owner: ResourceOwner, + peer_destination_hash: Option<[u8; 16]>, + link_closed: bool, +} + +/// Opaque daemon-local identity for one dispatched validation job. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(super) struct PnValidationToken(u64); + +/// CPU-validation work emitted after an exact ordinary Resource completion. +#[derive(Debug)] +pub(super) struct PnValidationJob { + token: PnValidationToken, + link_id: LinkId, + data: Vec, + allow_multiple: bool, +} + +impl PnValidationJob { + pub(super) fn token(&self) -> PnValidationToken { + self.token + } + + pub(super) fn link_id(&self) -> LinkId { + self.link_id + } + + pub(super) fn into_data(self) -> Vec { + self.data + } + + pub(super) fn allow_multiple(&self) -> bool { + self.allow_multiple + } + + #[cfg(test)] + pub(super) fn for_test(data: Vec, allow_multiple: bool) -> Self { + Self { + token: PnValidationToken(1), + link_id: [1; 16], + data, + allow_multiple, + } + } +} + +/// Semantic result of parsing and stamp-validating one completed transfer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum PnValidationOutcome { + Valid, + InvalidStamp, + UnauthorizedMultiple, + Failed, +} + +/// One accepted validation result. A missing claim means the result was stale, +/// duplicated, or did not match the token's original Link. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct PnValidationClaim { + link_id: LinkId, + outcome: PnValidationOutcome, +} + +impl PnValidationClaim { + pub(super) fn link_id(self) -> LinkId { + self.link_id + } + + pub(super) fn outcome(self) -> PnValidationOutcome { + self.outcome + } + + pub(super) fn should_close_link(self) -> bool { + matches!( + self.outcome, + PnValidationOutcome::InvalidStamp | PnValidationOutcome::UnauthorizedMultiple + ) + } +} + +/// One daemon-lifetime owner for inbound offer admission, peer-key +/// authorization, exact ordinary Resource correlations, and validation tokens. +pub(super) struct PnInboundRuntime { + admission: PnInboundAdmission, + validated_links: HashMap, + quarantined_links: HashSet, + correlations: HashMap, + pending_validations: HashMap, + next_validation_token: u64, + max_resource_bytes: usize, + clock_origin: Instant, +} + +impl PnInboundRuntime { + pub(super) fn new( + config: PnInboundAdmissionConfig, + static_peers: I, + max_resource_bytes: usize, + ) -> Self + where + I: IntoIterator, + { + let mut admission = PnInboundAdmission::new(config); + admission.set_static_peers(static_peers); + Self { + admission, + validated_links: HashMap::new(), + quarantined_links: HashSet::new(), + correlations: HashMap::new(), + pending_validations: HashMap::new(), + next_validation_token: 1, + max_resource_bytes, + clock_origin: Instant::now(), + } + } + + fn now(&self) -> Duration { + self.clock_origin.elapsed() + } + + /// Cheap policy preflight. The returned opaque candidate is externally + /// bound to this Link and peer identity for the peering-key evaluator. + pub(super) fn preflight_offer( + &mut self, + link_id: LinkId, + peer_identity_hash: Option<[u8; 16]>, + ) -> Result { + if self.quarantined_links.contains(&link_id) { + return Err(OfferResponse::ErrorThrottled); + } + + if let Some(peer_identity_hash) = peer_identity_hash { + let peer_destination_hash = + PnInboundAdmission::peer_destination_hash(&peer_identity_hash); + if !self.resource_bypasses_limits(Some(peer_destination_hash)) { + let config = self.admission.config(); + if config.sequential_validation && !self.pending_validations.is_empty() { + return Err(OfferResponse::ErrorThrottled); + } + if self.active_limited_resource_count() >= config.max_inbound_syncs { + return Err(OfferResponse::ErrorThrottled); + } + } + } + + let now = self.now(); + self.admission + .preflight_offer(link_id, peer_identity_hash, now) + .map_err(offer_rejection_response) + } + + /// Commit the exact externally validated candidate and remember that its + /// Link has proved a peering key. A failed commit never grants Link-wide + /// multi-message authorization. + pub(super) fn commit_offer( + &mut self, + candidate: PnOfferCandidate, + evaluation: &PnOfferEvaluation, + ) -> Result<(), OfferResponse> { + let link_id = candidate.link_id(); + let peer_destination_hash = candidate.peer_destination_hash(); + + // Match upstream's observable ordering: mutable concurrency gates are + // rechecked before a successful peering-key proof can authorize the + // Link. The core coordinator repeats its own record-based gates below. + if self.quarantined_links.contains(&link_id) + || (!self.resource_bypasses_limits(Some(peer_destination_hash)) + && ((self.admission.config().sequential_validation + && !self.pending_validations.is_empty()) + || self.active_limited_resource_count() + >= self.admission.config().max_inbound_syncs)) + { + self.admission.discard_candidate(candidate); + return Err(OfferResponse::ErrorThrottled); + } + + let now = self.now(); + match self + .admission + .commit_validated_offer(candidate, evaluation.admission_response(), now) + { + PnOfferAdmission::HaveAll | PnOfferAdmission::Accepted => { + self.validated_links.insert(link_id, peer_destination_hash); + Ok(()) + } + PnOfferAdmission::Rejected(rejection) => Err(offer_rejection_response(rejection)), + } + } + + pub(super) fn discard_offer( + &mut self, + candidate: PnOfferCandidate, + ) -> PnCandidateDiscardResult { + self.admission.discard_candidate(candidate) + } + + pub(super) fn is_link_quarantined(&self, link_id: &LinkId) -> bool { + self.quarantined_links.contains(link_id) + } + + /// Apply the Resource-advertisement policy and create exact ownership + /// before returning `true` to Reticulum's `AcceptApp` callback. + /// + /// Request/response Resources bypass this callback in Reticulum and can + /// therefore never acquire one of these correlations. + pub(super) fn accept_resource( + &mut self, + link_id: LinkId, + logical_resource_id: LogicalResourceId, + data_size: usize, + peer_identity_hash: Option<[u8; 16]>, + ) -> bool { + if self.quarantined_links.contains(&link_id) { + return false; + } + + let key = (link_id, logical_resource_id); + let supplied_peer_destination = + peer_identity_hash.map(|identity| PnInboundAdmission::peer_destination_hash(&identity)); + + if let Some(existing) = self.correlations.get(&key) { + // A later split segment retains the original exact owner. If its + // advertisement is now rejected, the accounting conclusion owns + // terminal cleanup. + return self.resource_policy_allows(data_size, existing.peer_destination_hash); + } + + let admission_record = self + .admission + .record(&link_id) + .map(|record| (record.state(), *record.peer_destination_hash())); + let has_offered_correlation = + self.correlations + .iter() + .any(|((existing_link, _), correlation)| { + *existing_link == link_id && correlation.owner == ResourceOwner::Offered + }); + + let owner = match admission_record { + Some((PnInboundState::Accepted, _)) if !has_offered_correlation => { + // One accepted offer owns one logical Resource. A second + // unrelated Resource remains authorized by the already-proved + // peering key, but must not steal Offered ownership. + ResourceOwner::Offered + } + Some(( + PnInboundState::Accepted + | PnInboundState::Transferring + | PnInboundState::Validating, + _, + )) => ResourceOwner::ValidatedPeer, + None if self.validated_links.contains_key(&link_id) => ResourceOwner::ValidatedPeer, + None => ResourceOwner::Client, + }; + + let owner_peer_destination = match owner { + ResourceOwner::Offered => admission_record.map(|(_, peer)| peer), + ResourceOwner::ValidatedPeer => self + .validated_links + .get(&link_id) + .copied() + .or_else(|| admission_record.map(|(_, peer)| peer)), + ResourceOwner::Client => supplied_peer_destination, + }; + + let capacity_allows = self.resource_bypasses_limits(owner_peer_destination) + || self.active_limited_resource_count() < self.admission.config().max_inbound_syncs; + let policy_allows = + capacity_allows && self.resource_policy_allows(data_size, owner_peer_destination); + if !policy_allows { + // A first AcceptApp rejection creates no Reticulum lifecycle event, + // so the offer record must be released synchronously here. + if owner == ResourceOwner::Offered { + self.admission.resource_rejected(&link_id); + } + return false; + } + + self.correlations.insert( + key, + ResourceCorrelation { + owner, + peer_destination_hash: owner_peer_destination, + started: false, + completion_dispatched: false, + }, + ); + true + } + + fn resource_policy_allows( + &self, + data_size: usize, + peer_destination_hash: Option<[u8; 16]>, + ) -> bool { + data_size <= self.max_resource_bytes + && (!self.admission.config().from_static_only + || peer_destination_hash + .as_ref() + .is_some_and(|peer| self.admission.is_static_peer(peer))) + } + + fn resource_bypasses_limits(&self, peer_destination_hash: Option<[u8; 16]>) -> bool { + peer_destination_hash.is_some_and(|peer| { + self.admission.is_static_peer(&peer) && !self.admission.config().static_sequential + }) + } + + fn active_limited_resource_count(&self) -> usize { + let correlated = self + .correlations + .values() + .filter(|correlation| !self.resource_bypasses_limits(correlation.peer_destination_hash)) + .count(); + let validating = self + .pending_validations + .values() + .filter(|pending| { + !self.correlations.contains_key(&pending.key) + && !self.resource_bypasses_limits(pending.peer_destination_hash) + }) + .count(); + correlated.saturating_add(validating) + } + + /// Consume the lossless ordered Reticulum accounting stream. + pub(super) fn handle_accounting_event( + &mut self, + event: LinkManagerAccountingEvent, + ) -> Option { + match event { + LinkManagerAccountingEvent::ResourceEvent(event) => { + self.handle_resource_event(event); + None + } + LinkManagerAccountingEvent::ResourceCompletion(completion) => self.resource_completed( + (completion.link_id, completion.resource_hash), + completion.data, + ), + LinkManagerAccountingEvent::LinkClosed { link_id } => { + self.link_closed(link_id); + None + } + _ => None, + } + } + + fn handle_resource_event(&mut self, event: LinkResourceEvent) { + match event { + LinkResourceEvent::Started { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + .. + } => self.resource_started((link_id, resource_id)), + LinkResourceEvent::Concluded { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + conclusion, + } => self.resource_concluded((link_id, resource_id), conclusion), + LinkResourceEvent::Started { .. } + | LinkResourceEvent::Progress { .. } + | LinkResourceEvent::Concluded { .. } => {} + } + } + + fn resource_started(&mut self, key: ResourceKey) { + let Some(correlation) = self.correlations.get_mut(&key) else { + return; + }; + if correlation.started { + return; + } + if correlation.owner == ResourceOwner::Offered + && self.admission.resource_started(&key.0).is_err() + { + self.correlations.remove(&key); + self.admission.resource_failed(&key.0); + return; + } + correlation.started = true; + } + + fn resource_completed(&mut self, key: ResourceKey, data: Vec) -> Option { + let (owner, peer_destination_hash, started, already_dispatched) = + self.correlations.get(&key).map(|correlation| { + ( + correlation.owner, + correlation.peer_destination_hash, + correlation.started, + correlation.completion_dispatched, + ) + })?; + if already_dispatched { + return None; + } + + if !started { + self.correlations.remove(&key); + if owner == ResourceOwner::Offered { + self.admission.resource_failed(&key.0); + } + return None; + } + if owner == ResourceOwner::Offered && self.admission.resource_concluded(&key.0).is_err() { + self.correlations.remove(&key); + self.admission.resource_failed(&key.0); + return None; + } + + let token = self.allocate_validation_token(); + self.pending_validations.insert( + token, + PendingValidation { + key, + owner, + peer_destination_hash, + link_closed: false, + }, + ); + if let Some(correlation) = self.correlations.get_mut(&key) { + correlation.completion_dispatched = true; + } + + Some(PnValidationJob { + token, + link_id: key.0, + data, + allow_multiple: owner != ResourceOwner::Client, + }) + } + + fn resource_concluded(&mut self, key: ResourceKey, conclusion: LinkResourceConclusion) { + let Some(correlation) = self.correlations.remove(&key) else { + return; + }; + + match conclusion { + LinkResourceConclusion::Complete if correlation.completion_dispatched => { + // ResourceCompletion already moved the offered record into + // Validating and owns the one pending validation token. + } + LinkResourceConclusion::Complete => { + // Defensive fail-clean: a complete conclusion without its + // preceding payload must not leave an accepted offer resident. + if correlation.owner == ResourceOwner::Offered { + self.admission.resource_failed(&key.0); + } + } + LinkResourceConclusion::Rejected => { + self.cancel_pending_for_key(key); + if correlation.owner == ResourceOwner::Offered { + self.admission.resource_rejected(&key.0); + } + } + LinkResourceConclusion::Cancelled => { + self.cancel_pending_for_key(key); + if correlation.owner == ResourceOwner::Offered { + self.admission.resource_cancelled(&key.0); + } + } + LinkResourceConclusion::Failed(_) => { + self.cancel_pending_for_key(key); + if correlation.owner == ResourceOwner::Offered { + self.admission.resource_failed(&key.0); + } + } + } + } + + fn cancel_pending_for_key(&mut self, key: ResourceKey) { + self.pending_validations + .retain(|_, pending| pending.key != key); + } + + fn link_closed(&mut self, link_id: LinkId) { + self.validated_links.remove(&link_id); + self.quarantined_links.remove(&link_id); + self.correlations + .retain(|(correlation_link, _), _| *correlation_link != link_id); + for pending in self.pending_validations.values_mut() { + if pending.key.0 == link_id { + pending.link_closed = true; + } + } + self.admission.link_closed(&link_id); + // Completed validation jobs intentionally survive Link closure. Their + // unique token still permits exactly one result and, for invalid + // stamps, a peer-specific throttle. + } + + /// Claim a worker result exactly once and perform terminal admission + /// cleanup. Valid message ingestion happens only after this succeeds. + pub(super) fn conclude_validation( + &mut self, + token: PnValidationToken, + link_id: LinkId, + outcome: PnValidationOutcome, + ) -> Option { + let pending = self.pending_validations.get(&token).copied()?; + if pending.key.0 != link_id { + return None; + } + self.pending_validations.remove(&token); + + if matches!( + outcome, + PnValidationOutcome::InvalidStamp | PnValidationOutcome::UnauthorizedMultiple + ) && !pending.link_closed + { + self.quarantined_links.insert(link_id); + } + + let now = self.now(); + let validation_result = match outcome { + PnValidationOutcome::Valid => PnValidationResult::Valid, + PnValidationOutcome::InvalidStamp => PnValidationResult::InvalidStamp, + PnValidationOutcome::UnauthorizedMultiple | PnValidationOutcome::Failed => { + PnValidationResult::Failed + } + }; + + if pending.owner == ResourceOwner::Offered { + match self + .admission + .validation_concluded(&link_id, validation_result, now) + { + Ok(lxmf_core::propagation_admission::PnCleanupResult::NotTracked) + if outcome == PnValidationOutcome::InvalidStamp => + { + self.install_untracked_invalid_throttle(pending.peer_destination_hash, now); + } + Err(_) => { + self.admission.resource_failed(&link_id); + if outcome == PnValidationOutcome::InvalidStamp { + self.install_untracked_invalid_throttle(pending.peer_destination_hash, now); + } + } + Ok(_) => {} + } + } else if outcome == PnValidationOutcome::InvalidStamp { + self.install_untracked_invalid_throttle(pending.peer_destination_hash, now); + } + + Some(PnValidationClaim { link_id, outcome }) + } + + fn install_untracked_invalid_throttle( + &mut self, + peer_destination_hash: Option<[u8; 16]>, + now: Duration, + ) { + if let Some(peer_destination_hash) = peer_destination_hash { + let _ = self + .admission + .install_invalid_stamp_throttle(peer_destination_hash, now); + } + } + + fn allocate_validation_token(&mut self) -> PnValidationToken { + loop { + let token = PnValidationToken(self.next_validation_token); + self.next_validation_token = self.next_validation_token.wrapping_add(1).max(1); + if !self.pending_validations.contains_key(&token) { + return token; + } + } + } + + #[cfg(test)] + fn admission_state(&self, link_id: &LinkId) -> Option { + self.admission.record(link_id).map(|record| record.state()) + } + + #[cfg(test)] + fn correlation_count(&self) -> usize { + self.correlations.len() + } + + #[cfg(test)] + fn pending_validation_count(&self) -> usize { + self.pending_validations.len() + } + + #[cfg(test)] + fn throttle_count(&self) -> usize { + self.admission.throttle_count() + } +} + +pub(super) fn logical_resource_id( + resource_hash: LogicalResourceId, + original_hash: LogicalResourceId, + split: bool, + total_segments: usize, +) -> LogicalResourceId { + if split || total_segments > 1 { + original_hash + } else { + resource_hash + } +} + +pub(super) fn offer_rejection_response(rejection: PnOfferRejection) -> OfferResponse { + match rejection { + PnOfferRejection::NoIdentity => OfferResponse::ErrorNoIdentity, + PnOfferRejection::NoAccess => OfferResponse::ErrorNoAccess, + PnOfferRejection::InvalidStampThrottle + | PnOfferRejection::SequentialValidationActive + | PnOfferRejection::InboundSyncLimit + | PnOfferRejection::LinkAlreadyTracked + | PnOfferRejection::LinkCandidatePending + | PnOfferRejection::StaleCandidate => OfferResponse::ErrorThrottled, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rns_runtime::link_manager::ResourceCompletion; + + fn link(value: u8) -> LinkId { + [value; 16] + } + + fn identity(value: u8) -> [u8; 16] { + [value; 16] + } + + fn resource(value: u8) -> LogicalResourceId { + [value; 32] + } + + fn runtime(config: PnInboundAdmissionConfig) -> PnInboundRuntime { + PnInboundRuntime::new(config, [], 1_000) + } + + fn accept_offer( + runtime: &mut PnInboundRuntime, + link_id: LinkId, + peer: [u8; 16], + evaluation: &PnOfferEvaluation, + ) { + let candidate = runtime.preflight_offer(link_id, Some(peer)).unwrap(); + runtime.commit_offer(candidate, evaluation).unwrap(); + } + + fn started(link_id: LinkId, resource_id: LogicalResourceId) -> LinkManagerAccountingEvent { + LinkManagerAccountingEvent::ResourceEvent(LinkResourceEvent::Started { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + data_size: 100, + total_segments: 1, + }) + } + + fn completed( + link_id: LinkId, + resource_id: LogicalResourceId, + data: Vec, + ) -> LinkManagerAccountingEvent { + LinkManagerAccountingEvent::ResourceCompletion(ResourceCompletion { + link_id, + resource_hash: resource_id, + data, + metadata: None, + }) + } + + fn concluded( + link_id: LinkId, + resource_id: LogicalResourceId, + conclusion: LinkResourceConclusion, + ) -> LinkManagerAccountingEvent { + LinkManagerAccountingEvent::ResourceEvent(LinkResourceEvent::Concluded { + link_id, + resource_id, + direction: LinkResourceDirection::Inbound, + conclusion, + }) + } + + #[test] + fn rejection_mapping_preserves_public_wire_errors() { + assert_eq!( + offer_rejection_response(PnOfferRejection::NoIdentity), + OfferResponse::ErrorNoIdentity + ); + assert_eq!( + offer_rejection_response(PnOfferRejection::NoAccess), + OfferResponse::ErrorNoAccess + ); + for rejection in [ + PnOfferRejection::InvalidStampThrottle, + PnOfferRejection::SequentialValidationActive, + PnOfferRejection::InboundSyncLimit, + PnOfferRejection::LinkAlreadyTracked, + PnOfferRejection::LinkCandidatePending, + PnOfferRejection::StaleCandidate, + ] { + assert_eq!( + offer_rejection_response(rejection), + OfferResponse::ErrorThrottled + ); + } + } + + #[test] + fn stale_candidate_after_link_close_cannot_authorize_the_link() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + let candidate = runtime.preflight_offer(link(1), Some(identity(2))).unwrap(); + runtime + .handle_accounting_event(LinkManagerAccountingEvent::LinkClosed { link_id: link(1) }); + assert_eq!( + runtime.commit_offer(candidate, &PnOfferEvaluation::HaveAll), + Err(OfferResponse::ErrorThrottled) + ); + + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(3))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(3), vec![])) + .unwrap(); + assert!(!job.allow_multiple()); + } + + #[test] + fn have_all_authorizes_multi_message_resources_until_link_close() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::HaveAll, + ); + assert_eq!(runtime.admission_state(&link(1)), None); + + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(3))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(3), vec![1])) + .unwrap(); + assert!(job.allow_multiple()); + + runtime + .handle_accounting_event(LinkManagerAccountingEvent::LinkClosed { link_id: link(1) }); + runtime + .conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid) + .unwrap(); + assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(4))); + let client_job = runtime + .handle_accounting_event(completed(link(1), resource(4), vec![2])) + .unwrap(); + assert!(!client_job.allow_multiple()); + } + + #[test] + fn capacity_recheck_rejection_does_not_authorize_the_link() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + let postponed = runtime.preflight_offer(link(1), Some(identity(2))).unwrap(); + + accept_offer( + &mut runtime, + link(3), + identity(4), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource(link(3), resource(5), 10, Some(identity(4)))); + runtime.handle_accounting_event(started(link(3), resource(5))); + runtime.handle_accounting_event(completed(link(3), resource(5), vec![6])); + assert_eq!( + runtime.admission_state(&link(3)), + Some(PnInboundState::Validating) + ); + + assert_eq!( + runtime.commit_offer(postponed, &PnOfferEvaluation::HaveAll), + Err(OfferResponse::ErrorThrottled) + ); + assert!(runtime.accept_resource(link(1), resource(7), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(7))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(7), vec![8])) + .unwrap(); + assert!(!job.allow_multiple()); + } + + #[test] + fn split_continuation_uses_the_original_stored_peer_identity() { + let peer = identity(2); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer); + let mut runtime = PnInboundRuntime::new( + PnInboundAdmissionConfig { + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }, + [peer_destination], + 100, + ); + + assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer))); + assert!( + runtime.accept_resource(link(1), resource(3), 100, Some(identity(9))), + "later split advertisements retain the exact original owner" + ); + } + + #[test] + fn extra_resource_on_offered_link_uses_validated_peer_ownership() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2)))); + + runtime.handle_accounting_event(started(link(1), resource(4))); + let extra = runtime + .handle_accounting_event(completed(link(1), resource(4), vec![5])) + .unwrap(); + assert!(extra.allow_multiple()); + assert_eq!( + runtime.admission_state(&link(1)), + Some(PnInboundState::Accepted), + "the unrelated Resource cannot steal offered admission state" + ); + + runtime.handle_accounting_event(started(link(1), resource(3))); + assert_eq!( + runtime.admission_state(&link(1)), + Some(PnInboundState::Transferring) + ); + } + + #[test] + fn request_resource_events_cannot_advance_a_newly_accepted_offer() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + + runtime.handle_accounting_event(started(link(1), resource(90))); + runtime.handle_accounting_event(concluded( + link(1), + resource(90), + LinkResourceConclusion::Complete, + )); + assert_eq!( + runtime.admission_state(&link(1)), + Some(PnInboundState::Accepted) + ); + assert_eq!(runtime.correlation_count(), 0); + + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(3))); + assert_eq!( + runtime.admission_state(&link(1)), + Some(PnInboundState::Transferring) + ); + } + + #[test] + fn completion_dispatches_once_and_complete_only_consumes_correlation() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + + runtime.handle_accounting_event(started(link(1), resource(3))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(3), vec![4])) + .unwrap(); + assert_eq!( + runtime.admission_state(&link(1)), + Some(PnInboundState::Validating) + ); + assert_eq!(runtime.pending_validation_count(), 1); + assert!( + runtime + .handle_accounting_event(completed(link(1), resource(3), vec![5])) + .is_none() + ); + + runtime.handle_accounting_event(concluded( + link(1), + resource(3), + LinkResourceConclusion::Complete, + )); + assert_eq!(runtime.correlation_count(), 0); + assert_eq!(runtime.pending_validation_count(), 1); + + let claim = runtime + .conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid) + .unwrap(); + assert_eq!(claim.outcome(), PnValidationOutcome::Valid); + assert_eq!(runtime.admission_state(&link(1)), None); + assert!( + runtime + .conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid) + .is_none() + ); + } + + #[test] + fn link_close_before_failed_is_idempotent_and_keeps_completed_job_claimable() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(3))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(3), vec![4])) + .unwrap(); + + runtime + .handle_accounting_event(LinkManagerAccountingEvent::LinkClosed { link_id: link(1) }); + runtime.handle_accounting_event(concluded( + link(1), + resource(3), + LinkResourceConclusion::Failed("link closed".to_string()), + )); + assert_eq!(runtime.admission_state(&link(1)), None); + assert_eq!(runtime.correlation_count(), 0); + assert_eq!(runtime.pending_validation_count(), 1); + + let claim = runtime + .conclude_validation( + job.token(), + job.link_id(), + PnValidationOutcome::InvalidStamp, + ) + .unwrap(); + assert!(claim.should_close_link()); + assert_eq!(runtime.throttle_count(), 1); + assert!(!runtime.is_link_quarantined(&link(1))); + } + + #[test] + fn first_advertisement_rejection_releases_offer_without_terminal_event() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + assert!(!runtime.accept_resource(link(1), resource(3), 1_001, Some(identity(2)))); + assert_eq!(runtime.admission_state(&link(1)), None); + } + + #[test] + fn static_only_resource_policy_uses_derived_propagation_destination() { + let peer = identity(2); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer); + let mut runtime = PnInboundRuntime::new( + PnInboundAdmissionConfig { + from_static_only: true, + ..PnInboundAdmissionConfig::default() + }, + [peer_destination], + 100, + ); + + assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer))); + assert!(!runtime.accept_resource(link(2), resource(4), 100, Some(identity(9)))); + assert!(!runtime.accept_resource(link(3), resource(5), 100, None)); + } + + #[test] + fn complete_without_payload_fail_cleans_offered_record() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + accept_offer( + &mut runtime, + link(1), + identity(2), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)))); + runtime.handle_accounting_event(started(link(1), resource(3))); + runtime.handle_accounting_event(concluded( + link(1), + resource(3), + LinkResourceConclusion::Complete, + )); + assert_eq!(runtime.admission_state(&link(1)), None); + assert_eq!(runtime.pending_validation_count(), 0); + } + + #[test] + fn rejected_cancelled_and_failed_resources_release_exact_offer_ownership() { + for (index, conclusion) in [ + LinkResourceConclusion::Rejected, + LinkResourceConclusion::Cancelled, + LinkResourceConclusion::Failed("transfer failed".to_string()), + ] + .into_iter() + .enumerate() + { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + let link_id = link(index as u8 + 1); + let resource_id = resource(index as u8 + 10); + accept_offer( + &mut runtime, + link_id, + identity(index as u8 + 20), + &PnOfferEvaluation::WantAll, + ); + assert!(runtime.accept_resource( + link_id, + resource_id, + 10, + Some(identity(index as u8 + 20)) + )); + runtime.handle_accounting_event(started(link_id, resource_id)); + runtime.handle_accounting_event(concluded(link_id, resource_id, conclusion)); + + assert_eq!(runtime.admission_state(&link_id), None); + assert_eq!(runtime.correlation_count(), 0); + assert_eq!(runtime.pending_validation_count(), 0); + } + } + + #[test] + fn logical_resource_id_uses_original_for_all_split_forms() { + assert_eq!( + logical_resource_id(resource(1), resource(2), false, 1), + resource(1) + ); + assert_eq!( + logical_resource_id(resource(1), resource(2), true, 1), + resource(2) + ); + assert_eq!( + logical_resource_id(resource(1), resource(2), false, 2), + resource(2) + ); + } + + #[test] + fn invalid_unidentified_client_closes_without_shared_throttle_state() { + let mut runtime = runtime(PnInboundAdmissionConfig::default()); + assert!(runtime.accept_resource(link(1), resource(3), 10, None)); + runtime.handle_accounting_event(started(link(1), resource(3))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(3), vec![4])) + .unwrap(); + let claim = runtime + .conclude_validation( + job.token(), + job.link_id(), + PnValidationOutcome::InvalidStamp, + ) + .unwrap(); + assert!(claim.should_close_link()); + assert_eq!(runtime.throttle_count(), 0); + assert!(runtime.is_link_quarantined(&link(1))); + assert!(!runtime.accept_resource(link(1), resource(4), 10, None)); + assert!(matches!( + runtime.preflight_offer(link(1), Some(identity(5))), + Err(OfferResponse::ErrorThrottled) + )); + } + + #[test] + fn non_static_resource_and_validation_work_respects_inbound_cap() { + let mut runtime = runtime(PnInboundAdmissionConfig { + sequential_validation: false, + max_inbound_syncs: 1, + ..PnInboundAdmissionConfig::default() + }); + assert!(runtime.accept_resource(link(1), resource(2), 10, Some(identity(3)))); + assert!(!runtime.accept_resource(link(4), resource(5), 10, Some(identity(6)))); + + runtime.handle_accounting_event(started(link(1), resource(2))); + let job = runtime + .handle_accounting_event(completed(link(1), resource(2), vec![7])) + .unwrap(); + runtime.handle_accounting_event(concluded( + link(1), + resource(2), + LinkResourceConclusion::Complete, + )); + assert!( + !runtime.accept_resource(link(4), resource(5), 10, Some(identity(6))), + "a completed Resource retains its slot through stamp validation" + ); + + runtime + .conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid) + .unwrap(); + assert!(runtime.accept_resource(link(4), resource(5), 10, Some(identity(6)))); + } + + #[test] + fn configured_static_bypass_applies_to_resource_capacity() { + let peer = identity(2); + let peer_destination = PnInboundAdmission::peer_destination_hash(&peer); + let mut bypass = PnInboundRuntime::new( + PnInboundAdmissionConfig { + sequential_validation: false, + static_sequential: false, + max_inbound_syncs: 1, + from_static_only: true, + }, + [peer_destination], + 100, + ); + assert!(bypass.accept_resource(link(1), resource(3), 10, Some(peer))); + assert!(bypass.accept_resource(link(1), resource(4), 10, Some(peer))); + + let mut limited = PnInboundRuntime::new( + PnInboundAdmissionConfig { + sequential_validation: false, + static_sequential: true, + max_inbound_syncs: 1, + from_static_only: true, + }, + [peer_destination], + 100, + ); + assert!(limited.accept_resource(link(1), resource(3), 10, Some(peer))); + assert!(!limited.accept_resource(link(1), resource(4), 10, Some(peer))); + } +} diff --git a/crates/lxmf-tools/src/daemon.rs b/crates/lxmf-tools/src/daemon.rs index 53935c6..b3e04a5 100644 --- a/crates/lxmf-tools/src/daemon.rs +++ b/crates/lxmf-tools/src/daemon.rs @@ -3,6 +3,9 @@ //! Python reference: LXMF/Utilities/lxmd.py. use lxmf_core::constants::*; +use lxmf_core::propagation_admission::{ + PN_DEFAULT_MAX_INBOUND_SYNCS, PN_MIN_MAX_INBOUND_SYNCS, PnInboundAdmissionConfig, +}; use lxmf_core::router::{LxmRouter, RouterConfig, RouterConfigExt}; use rns_runtime::config::{Config, ConfigSection}; @@ -16,6 +19,7 @@ pub struct PythonLxmdConfig { pub display_name: String, pub peer_announce_at_start: bool, pub peer_announce_interval: Option, + pub peer_stamp_cost: i64, pub delivery_transfer_max_accepted_size: f64, pub on_inbound: Option, pub enable_propagation_node: bool, @@ -24,6 +28,9 @@ pub struct PythonLxmdConfig { pub node_announce_at_start: bool, pub autopeer: bool, pub autopeer_maxdepth: Option, + pub sequential_pn_stamp_validation: bool, + pub static_peers_bypass_sequential: bool, + pub max_inbound_syncs: i64, pub node_announce_interval: Option, pub message_storage_limit: f64, pub propagation_transfer_max_accepted_size: f64, @@ -58,6 +65,9 @@ impl PythonLxmdConfig { .to_string(), peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false), peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60), + peer_stamp_cost: get_int(lxmf, "stamp_cost") + .map(|value| value.max(1)) + .unwrap_or(12), delivery_transfer_max_accepted_size: get_float_or_floor( lxmf, "delivery_transfer_max_accepted_size", @@ -75,6 +85,19 @@ impl PythonLxmdConfig { node_announce_at_start: get_bool_or(propagation, "announce_at_start", false), autopeer: get_bool_or(propagation, "autopeer", true), autopeer_maxdepth: get_int(propagation, "autopeer_maxdepth"), + sequential_pn_stamp_validation: get_bool_or( + propagation, + "sequential_pn_stamp_validation", + true, + ), + static_peers_bypass_sequential: get_bool_or( + propagation, + "static_peers_bypass_sequential", + true, + ), + max_inbound_syncs: get_int(propagation, "max_inbound_syncs") + .map(|value| value.max(PN_MIN_MAX_INBOUND_SYNCS as i64)) + .unwrap_or(PN_DEFAULT_MAX_INBOUND_SYNCS as i64), node_announce_interval: get_int(propagation, "announce_interval").map(|v| v * 60), message_storage_limit: get_float_or_floor( propagation, @@ -152,6 +175,9 @@ pub struct DaemonConfig { pub max_peers: usize, pub autopeer: bool, pub autopeer_maxdepth: usize, + pub sequential_pn_stamp_validation: bool, + pub static_peers_bypass_sequential: bool, + pub max_inbound_syncs: usize, pub propagation_limit_kb: usize, pub sync_limit_kb: usize, pub on_inbound_command: Option, @@ -166,7 +192,7 @@ pub struct DaemonConfig { pub from_static_only: bool, /// Max accepted inbound delivery transfer size in KB. Python reference: /// `delivery_transfer_max_accepted_size` in `lxmd.py`. - pub delivery_transfer_max_accepted_size: usize, + pub delivery_transfer_max_accepted_size: f64, } impl Default for DaemonConfig { @@ -176,7 +202,7 @@ impl Default for DaemonConfig { node_name: None, announce_at_start: false, announce_interval: None, - stamp_cost: None, + stamp_cost: Some(12), propagation_enabled: false, outbound_propagation_node: None, propagation_stamp_cost: PROPAGATION_COST, @@ -186,6 +212,9 @@ impl Default for DaemonConfig { max_peers: MAX_PEERS, autopeer: true, autopeer_maxdepth: AUTOPEER_MAXDEPTH, + sequential_pn_stamp_validation: true, + static_peers_bypass_sequential: true, + max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS, propagation_limit_kb: PROPAGATION_LIMIT, sync_limit_kb: SYNC_LIMIT, on_inbound_command: None, @@ -198,7 +227,7 @@ impl Default for DaemonConfig { enforce_stamps: false, message_storage_limit: Some(500_000_000), from_static_only: false, - delivery_transfer_max_accepted_size: DELIVERY_LIMIT, + delivery_transfer_max_accepted_size: 1000.0, } } } @@ -228,6 +257,16 @@ impl DaemonConfig { } } + /// Build the long-lived inbound propagation admission policy. + pub fn to_inbound_admission_config(&self) -> PnInboundAdmissionConfig { + PnInboundAdmissionConfig { + sequential_validation: self.sequential_pn_stamp_validation, + static_sequential: !self.static_peers_bypass_sequential, + max_inbound_syncs: self.max_inbound_syncs, + from_static_only: self.from_static_only, + } + } + /// Parse from `[lxmf]`, `[propagation]`, and `[control]` sections. pub fn from_config(config: &Config) -> Self { let py = PythonLxmdConfig::from_config(config); @@ -236,6 +275,7 @@ impl DaemonConfig { node_name: py.node_name, announce_at_start: py.peer_announce_at_start, announce_interval: seconds_to_u64(py.peer_announce_interval), + stamp_cost: normalize_peer_stamp_cost(py.peer_stamp_cost), propagation_enabled: py.enable_propagation_node, propagation_stamp_cost: clamp_python_cost_to_u8( py.propagation_stamp_cost_target, @@ -256,6 +296,9 @@ impl DaemonConfig { .autopeer_maxdepth .and_then(|value| usize::try_from(value).ok()) .unwrap_or(AUTOPEER_MAXDEPTH), + sequential_pn_stamp_validation: py.sequential_pn_stamp_validation, + static_peers_bypass_sequential: py.static_peers_bypass_sequential, + max_inbound_syncs: usize::try_from(py.max_inbound_syncs).unwrap_or(usize::MAX), propagation_limit_kb: kb_to_usize_ceil(py.propagation_transfer_max_accepted_size), sync_limit_kb: kb_to_usize_ceil(py.propagation_sync_max_accepted_size), on_inbound_command: py.on_inbound, @@ -267,18 +310,10 @@ impl DaemonConfig { prioritise_destinations: py.prioritised_lxmf_destinations, message_storage_limit: megabytes_to_bytes(py.message_storage_limit), from_static_only: py.from_static_only, - delivery_transfer_max_accepted_size: kb_to_usize_ceil( - py.delivery_transfer_max_accepted_size, - ), + delivery_transfer_max_accepted_size: py.delivery_transfer_max_accepted_size, ..DaemonConfig::default() }; - if let Some(sec) = config.section("lxmf") - && let Some(cost) = sec.get_uint("stamp_cost") - { - dc.stamp_cost = Some(cost as u8); - } - if let Some(sec) = config.section("propagation") { if let Some(node) = sec.get("outbound_node") { let trimmed = node.trim(); @@ -323,6 +358,13 @@ fn clamp_python_cost_to_u8(value: i64, floor: i64) -> u8 { value.max(floor).min(u8::MAX as i64) as u8 } +/// Apply Python lxmd's signed floor, then mirror `set_inbound_stamp_cost`: +/// delivery stamp costs are valid only in `1..=254`. +fn normalize_peer_stamp_cost(value: i64) -> Option { + let cost = u8::try_from(value.max(1)).ok()?; + (cost < u8::MAX).then_some(cost) +} + fn get_float(section: Option<&ConfigSection>, key: &str) -> Option { section.and_then(|sec| sec.get_float(key)) } @@ -389,6 +431,7 @@ mod tests { assert_eq!(dc.display_name.as_deref(), Some("Anonymous Peer")); assert!(!dc.announce_at_start); assert_eq!(dc.announce_interval, None); + assert_eq!(dc.stamp_cost, Some(12)); assert!(!dc.propagation_enabled); assert_eq!(dc.propagation_stamp_cost, 16); assert_eq!(dc.propagation_stamp_flex, 3); @@ -397,12 +440,19 @@ mod tests { assert_eq!(dc.max_peers, 20); assert!(dc.autopeer); assert_eq!(dc.autopeer_maxdepth, AUTOPEER_MAXDEPTH); + assert!(dc.sequential_pn_stamp_validation); + assert!(dc.static_peers_bypass_sequential); + assert_eq!(dc.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS); + assert_eq!( + dc.to_inbound_admission_config(), + PnInboundAdmissionConfig::default() + ); assert_eq!(dc.propagation_limit_kb, 256); assert_eq!(dc.sync_limit_kb, 10_240); assert!(!dc.node_announce_at_start); assert_eq!(dc.node_announce_interval, None); assert_eq!(dc.message_storage_limit, Some(500_000_000)); - assert_eq!(dc.delivery_transfer_max_accepted_size, 1000); + assert_eq!(dc.delivery_transfer_max_accepted_size, 1000.0); assert!(!dc.from_static_only); } @@ -414,6 +464,7 @@ mod tests { assert_eq!(py.display_name, "Anonymous Peer"); assert!(!py.peer_announce_at_start); assert_eq!(py.peer_announce_interval, None); + assert_eq!(py.peer_stamp_cost, 12); assert_eq!(py.delivery_transfer_max_accepted_size, 1000.0); assert_eq!(py.on_inbound, None); assert!(!py.enable_propagation_node); @@ -422,6 +473,9 @@ mod tests { assert!(!py.node_announce_at_start); assert!(py.autopeer); assert_eq!(py.autopeer_maxdepth, None); + assert!(py.sequential_pn_stamp_validation); + assert!(py.static_peers_bypass_sequential); + assert_eq!(py.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS as i64); assert_eq!(py.node_announce_interval, None); assert_eq!(py.message_storage_limit, 500.0); assert_eq!(py.propagation_transfer_max_accepted_size, 256.0); @@ -455,9 +509,13 @@ prioritise_destinations = 0102030405060708090a0b0c0d0e0f10 control_allowed = 11111111111111111111111111111111 from_static_only = yes max_peers = 7 +sequential_pn_stamp_validation = no +static_peers_bypass_sequential = no +max_inbound_syncs = 0 [lxmf] announce_interval = 3 +stamp_cost = -9 delivery_transfer_max_accepted_size = 0.1 [logging] @@ -468,6 +526,7 @@ loglevel = 6 assert_eq!(py.peer_announce_interval, Some(180)); assert_eq!(py.node_announce_interval, Some(120)); + assert_eq!(py.peer_stamp_cost, 1); assert_eq!(py.delivery_transfer_max_accepted_size, 0.38); assert_eq!(py.message_storage_limit, 0.005); assert_eq!(py.propagation_transfer_max_accepted_size, 0.38); @@ -486,6 +545,9 @@ loglevel = 6 ["11111111111111111111111111111111"] ); assert_eq!(py.max_peers, Some(7)); + assert!(!py.sequential_pn_stamp_validation); + assert!(!py.static_peers_bypass_sequential); + assert_eq!(py.max_inbound_syncs, PN_MIN_MAX_INBOUND_SYNCS as i64); assert!(py.from_static_only); assert_eq!(py.target_loglevel, Some(6)); } @@ -526,7 +588,8 @@ propagation_transfer_max_accepted_size = 12 let rc = dc.to_router_config(); assert!(!rc.propagation_enabled); assert_eq!(rc.max_peers, 20); - assert_eq!(rc.delivery_limit_kb, 1000); + assert_eq!(rc.delivery_limit_kb, 1000.0); + assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0); assert_eq!(rc.propagation_limit_kb, 256); assert_eq!(rc.sync_limit_kb, 10_240); assert_eq!(rc.propagation_stamp_cost, 16); @@ -582,6 +645,9 @@ remote_peering_cost_max = -2 max_peers = 10 autopeer = no autopeer_maxdepth = 2 +sequential_pn_stamp_validation = no +static_peers_bypass_sequential = no +max_inbound_syncs = 5 static_peers = 00112233445566778899aabbccddeeff prioritise_destinations = 0102030405060708090a0b0c0d0e0f10 control_allowed = 11111111111111111111111111111111 @@ -592,7 +658,7 @@ from_static_only = yes assert_eq!(dc.display_name.as_deref(), Some("TestNode")); assert!(dc.announce_at_start); assert_eq!(dc.announce_interval, Some(180)); - assert_eq!(dc.delivery_transfer_max_accepted_size, 1); + assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38); assert_eq!(dc.stamp_cost, Some(8)); assert!(dc.propagation_enabled); assert_eq!(dc.node_name.as_deref(), Some("PropNode")); @@ -612,6 +678,18 @@ from_static_only = yes assert_eq!(dc.max_peers, 10); assert!(!dc.autopeer); assert_eq!(dc.autopeer_maxdepth, 2); + assert!(!dc.sequential_pn_stamp_validation); + assert!(!dc.static_peers_bypass_sequential); + assert_eq!(dc.max_inbound_syncs, 5); + assert_eq!( + dc.to_inbound_admission_config(), + PnInboundAdmissionConfig { + sequential_validation: false, + static_sequential: true, + max_inbound_syncs: 5, + from_static_only: true, + } + ); assert_eq!(dc.static_peers, ["00112233445566778899aabbccddeeff"]); assert_eq!( dc.prioritise_destinations, @@ -621,6 +699,38 @@ from_static_only = yes assert!(dc.from_static_only); } + #[test] + fn delivery_stamp_cost_matches_python_floor_and_destination_range() { + for (configured, normalized, expected) in [ + (-7, 1, Some(1)), + (0, 1, Some(1)), + (254, 254, Some(254)), + (255, 255, None), + (256, 256, None), + (1000, 1000, None), + ] { + let input = format!("[lxmf]\nstamp_cost = {configured}\n"); + let config = rns_runtime::config::Config::parse(&input).unwrap(); + let py = PythonLxmdConfig::from_config(&config); + let dc = DaemonConfig::from_config(&config); + + assert_eq!(py.peer_stamp_cost, normalized, "configured {configured}"); + assert_eq!(dc.stamp_cost, expected, "configured {configured}"); + } + } + + #[test] + fn fractional_delivery_limit_survives_daemon_and_router_config() { + let config = rns_runtime::config::Config::parse( + "[lxmf]\ndelivery_transfer_max_accepted_size = 0.38\n", + ) + .unwrap(); + let dc = DaemonConfig::from_config(&config); + + assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38); + assert_eq!(dc.to_router_config().delivery_limit_kb, 0.38); + } + #[test] fn test_parse_python_stamp_target_key_with_floor() { let input = r#" diff --git a/crates/lxmf-tools/src/lxmd_cli.rs b/crates/lxmf-tools/src/lxmd_cli.rs index 77b79a3..5e633e7 100644 --- a/crates/lxmf-tools/src/lxmd_cli.rs +++ b/crates/lxmf-tools/src/lxmd_cli.rs @@ -94,7 +94,7 @@ pub struct Args { #[arg(long, value_name = "PATH")] pub identity: Option, - /// Send a single message and exit: --send + /// Send a single message and exit: `--send `. #[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])] pub send: Option>, @@ -180,6 +180,15 @@ autopeer = yes autopeer_maxdepth = 6 +# Validate inbound propagation stamp batches sequentially by default. +# sequential_pn_stamp_validation = yes + +# Let configured static peers bypass sequential validation and inbound limits. +# static_peers_bypass_sequential = yes + +# Maximum concurrent inbound propagation sync transfers. +# max_inbound_syncs = 3 + # message_storage_limit = 500 # propagation_message_max_accepted_size = 256 @@ -213,6 +222,8 @@ announce_at_start = no # announce_interval = 360 +# stamp_cost = 12 + delivery_transfer_max_accepted_size = 1000 # on_inbound = /path/to/handler diff --git a/crates/lxmf-tools/src/lxmd_control.rs b/crates/lxmf-tools/src/lxmd_control.rs index ba1ef1d..c54dda3 100644 --- a/crates/lxmf-tools/src/lxmd_control.rs +++ b/crates/lxmf-tools/src/lxmd_control.rs @@ -300,7 +300,7 @@ pub fn encode_router_control_stats( (Value::String("uptime".into()), Value::F64(uptime)), ( Value::String("delivery_limit".into()), - Value::from(router.config.delivery_limit_kb as u64), + Value::F64(router.config.delivery_limit_kb), ), ( Value::String("propagation_limit".into()), @@ -612,12 +612,10 @@ pub fn format_remote_status( } _ => "never synced".to_string(), }; - let name = map_str(peer, "name") - .unwrap_or("") - .trim() - .replace(['\n', '\r'], ""); - let display_name = if name.len() > 45 { - format!("{}...", &name[..45]) + let name = + lxmf_core::presentation::sanitize_name(map_str(peer, "name").unwrap_or(""), 46); + let display_name = if name.chars().count() > 45 { + format!("{}...", name.chars().take(45).collect::()) } else { name }; @@ -955,6 +953,34 @@ mod tests { assert!(out.contains("4 propagation messages served to clients")); } + #[test] + fn status_formatter_bounds_multibyte_untrusted_peer_names() { + let hostile_name = format!("{}\u{202e}\u{1f680}", "界".repeat(50)); + let peer = Value::Map(vec![ + ( + Value::String("name".into()), + Value::String(hostile_name.into()), + ), + (Value::String("alive".into()), Value::Boolean(true)), + ]); + let stats = Value::Map(vec![ + ( + Value::String("destination_hash".into()), + Value::Binary(vec![0x01; 16]), + ), + ( + Value::String("peers".into()), + Value::Map(vec![(Value::Binary(vec![0x02; 16]), peer)]), + ), + ]); + + let out = format_remote_status(&stats, false, true, 0.0); + let expected = format!("Name : {}...", "界".repeat(45)); + assert!(out.contains(&expected)); + assert!(!out.contains('\u{202e}')); + assert!(!out.contains('\u{1f680}')); + } + #[test] fn stats_encoder_uses_python_compile_stats_shape() { use lxmf_core::peer::LxmPeer; @@ -964,6 +990,7 @@ mod tests { propagation_enabled: true, ..Default::default() }; + config.delivery_limit_kb = 0.38; config.ext.message_storage_limit = Some(500_000_000); let mut router = LxmRouter::new(config); router.propagation_start_time = Some(1_700_000_000.0); @@ -1022,6 +1049,7 @@ mod tests { assert_eq!(map_u64(&stats, "static_peers"), Some(1)); assert_eq!(map_u64(&stats, "discovered_peers"), Some(0)); assert_eq!(map_u64(&stats, "total_peers"), Some(1)); + assert_eq!(map_f64(&stats, "delivery_limit"), Some(0.38)); let peers = map_value(&stats, "peers").unwrap().as_map().unwrap(); let peer_stats = &peers[0].1; diff --git a/crates/lxmf-tools/tests/lxmd_cli.rs b/crates/lxmf-tools/tests/lxmd_cli.rs index 9a1def4..d2a6702 100644 --- a/crates/lxmf-tools/tests/lxmd_cli.rs +++ b/crates/lxmf-tools/tests/lxmd_cli.rs @@ -227,11 +227,15 @@ fn example_config_exits_before_runtime_initialisation() { assert!(text.contains("[lxmf]")); assert!(text.contains("display_name = Anonymous Peer")); assert!(text.contains("announce_at_start = no")); + assert!(text.contains("# stamp_cost = 12")); assert!(text.contains("delivery_transfer_max_accepted_size = 1000")); assert!(text.contains("[propagation]")); assert!(text.contains("enable_node = no")); assert!(text.contains("announce_interval = 360")); assert!(text.contains("announce_at_start = yes")); + assert!(text.contains("# sequential_pn_stamp_validation = yes")); + assert!(text.contains("# static_peers_bypass_sequential = yes")); + assert!(text.contains("# max_inbound_syncs = 3")); assert!(text.contains("[logging]")); assert!(text.contains("loglevel = 4")); assert!(!text.contains("[control]"));