Compare commits

...
Author SHA1 Message Date
DeFiDude 90e44916a4 release: bump rsLXMF to 1.0.1 2026-06-13 23:43:19 -06:00
DeFiDude 134a17c704 release: point LXMF builds at Reticulum 1.0.0 2026-06-13 21:52:06 -06:00
DeFiDude 89689fbdb4 release: align crates at 1.0.0 2026-06-13 21:40:26 -06:00
DeFiDude c4f4a04dbb core, lxmd: wire router jobloop and node maintenance; 300s route_hops re-baseline 2026-06-12 11:50:23 -06:00
DeFiDude 68d9d5541f core: prune peer handled sets against store; weight-cap the node store in tick 2026-06-12 11:50:23 -06:00
DeFiDude 1a2acd32f6 router: drive deferred stamp PoW via stored runtime handle; defer delivery-time stamps 2026-06-10 14:39:31 -06:00
DeFiDude 62f30baa0f propagation: stage store file reads outside the node lock; drop lxmd per-tick map clones 2026-06-10 03:46:57 -06:00
DeFiDude 167e571a3a lxmf-core: drop dead max_message_size config and stamp-validation branch 2026-06-10 03:28:42 -06:00
DeFiDude 06015ae181 lxmd: clean startup errors instead of panics; quarantine corrupt store files on load 2026-06-10 00:37:26 -06:00
DeFiDude 9e44e8a407 propagation: age-based dedup cache retention with persisted timestamps 2026-06-10 00:33:43 -06:00
DeFiDude 2fc60703ea message: bound propagation wrapper decode against transfer limits 2026-06-10 00:26:49 -06:00
DeFiDude b61724d1f1 router: enforce max peering cost at announce ingest and bound stamp searches 2026-06-10 00:21:41 -06:00
DeFiDude c7736b9d24 propagation: gate client get and purge on entry ownership 2026-06-10 00:16:00 -06:00
DeFiDude 19187146c8 lint: rustfmt and clippy cleanup 2026-06-09 18:21:54 -06:00
DeFiDude b41c7ac263 lxmd: incremental ratchet persistence and identity cache cap 2026-06-09 17:45:15 -06:00
DeFiDude 8f59b66854 stamper: unify message stamps on the Python HKDF workblock 2026-06-09 17:45:15 -06:00
Oleg Belousov 5ea513bb95 lxmd: drop full crypto-state save from announce processing 2026-06-09 17:17:52 -06:00
DeFiDude 6ac04f0311 deps: refresh rns runtime lockfile 2026-05-30 22:59:31 -06:00
DeFiDude b790ca91d3 lxmd: exit promptly during startup shutdown 2026-05-30 00:06:50 -06:00
DeFiDude 511e0a77f1 lxmd: note hardware signing gap 2026-05-29 23:45:35 -06:00
DeFiDude fedba0bdfa deps: bump bzip2 to 0.6.1 (pure-Rust libbz2-rs-sys) 2026-05-29 02:21:43 -06:00
DeFiDude c0bf58eb52 lxmd: pass Option to LinkManager::with_destination
Adapts to the optional link signing key in rns-runtime; lxmd identities always have one.
2026-05-28 23:41:03 -06:00
15 changed files with 1610 additions and 491 deletions

No files matched your search

+1 -1
View File
@@ -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: v0.9.4
RSLXMF_RSRETICULUM_REF: v1.0.1
jobs:
build:
Generated
+30 -51
View File
@@ -149,21 +149,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bzip2"
version = "0.5.2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"bzip2-sys",
]
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
dependencies = [
"cc",
"pkg-config",
"libbz2-rs-sys",
]
[[package]]
@@ -175,16 +165,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.2.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
@@ -411,12 +391,6 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
name = "fnv"
version = "1.0.7"
@@ -634,6 +608,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.183"
@@ -663,7 +643,7 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"base64",
"bytes",
@@ -688,7 +668,7 @@ dependencies = [
[[package]]
name = "lxmf-tools"
version = "0.9.2"
version = "1.0.1"
dependencies = [
"base64",
"bytes",
@@ -716,6 +696,16 @@ dependencies = [
"libc",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.0"
@@ -870,12 +860,6 @@ dependencies = [
"spki",
]
[[package]]
name = "pkg-config"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -1065,7 +1049,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"aes",
"cbc",
@@ -1083,7 +1067,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1099,7 +1083,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"bytes",
"hex",
@@ -1125,7 +1109,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1140,7 +1124,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"bzip2",
"hex",
@@ -1156,11 +1140,12 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1181,7 +1166,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"bytes",
"hex",
@@ -1200,7 +1185,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.4"
version = "1.0.1"
dependencies = [
"rns-crypto",
"sha2",
@@ -1353,12 +1338,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
+11 -11
View File
@@ -6,25 +6,25 @@ members = [
]
[workspace.package]
version = "0.9.2"
version = "1.0.1"
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" }
rns-wire = { path = "../rsReticulum/crates/rns-wire" }
rns-identity = { path = "../rsReticulum/crates/rns-identity" }
rns-link = { path = "../rsReticulum/crates/rns-link" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol" }
rns-transport = { path = "../rsReticulum/crates/rns-transport" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime" }
rns-interface = { path = "../rsReticulum/crates/rns-interface" }
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" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core" }
lxmf-tools = { path = "crates/lxmf-tools" }
lxmf-core = { path = "crates/lxmf-core", version = "1.0.1" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.0.1" }
# Encoding
base64 = "0.22"
+10 -14
View File
@@ -13,15 +13,11 @@
//! (RNS/Discovery.py:220), where `stamp_workblock` is the
//! HKDF-expanded construction: one HKDF expand per round, each round
//! producing 256 bytes, total `expand_rounds * 256` bytes.
//!
//! The matching Rust primitive is [`crate::stamper::stamp_workblock_raw`]
//! (the plain `stamp_workblock` in `lxmf-core` uses an iterative
//! SHA-256 workblock for a *different* path and is **not** wire
//! compatible with Python's discovery stamps).
//! [`crate::stamper::stamp_workblock`] is the same construction.
//!
use rns_transport::discovery::DiscoveryStamper;
use crate::stamper::{stamp_valid_raw, stamp_value_raw, stamp_workblock_raw};
use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
/// Python `RNS.Discovery.InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`,
/// the expand-round count discovery uses when building its workblock.
@@ -75,11 +71,11 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
return Some(vec![0u8; 32]);
}
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..self.effective_max_iterations() {
let candidate = crate::stamper::rand_bytes();
if stamp_valid_raw(&candidate, target_value, &workblock) {
if stamp_valid(&candidate, target_value, &workblock) {
return Some(candidate.to_vec());
}
}
@@ -92,8 +88,8 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
}
let mut stamp_arr = [0u8; 32];
stamp_arr.copy_from_slice(stamp);
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let v = stamp_value_raw(&workblock, &stamp_arr);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let v = stamp_value(&workblock, &stamp_arr);
v.min(u8::MAX as u32) as u8
}
@@ -106,8 +102,8 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
}
let mut stamp_arr = [0u8; 32];
stamp_arr.copy_from_slice(stamp);
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
stamp_valid_raw(&stamp_arr, required_value, &workblock)
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
stamp_valid(&stamp_arr, required_value, &workblock)
}
}
@@ -123,10 +119,10 @@ pub fn generate_discovery_stamp(
if target_value == 0 {
return Some([0u8; 32]);
}
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..max_iterations {
let candidate = crate::stamper::rand_bytes();
if stamp_valid_raw(&candidate, target_value, &workblock) {
if stamp_valid(&candidate, target_value, &workblock) {
return Some(candidate);
}
}
+13 -12
View File
@@ -422,7 +422,9 @@ impl PropagationRequestHandler {
)
}
/// Handle a `/get` request from a client downloading messages.
/// 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.
///
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499.
pub fn handle_message_get_request(
@@ -431,14 +433,15 @@ impl PropagationRequestHandler {
client_dest_hash: &[u8; 16],
request_data: &[u8],
node: &mut crate::propagation_node::PropagationNode,
) -> Vec<u8> {
) -> crate::propagation_node::GetRequestAction {
use crate::propagation_node::GetRequestAction;
use rmpv::Value;
let _identity_hash = match remote_identity_hash {
Some(h) => h,
None => {
let error = Value::from(PeerError::NoIdentity as u64);
return crate::encode_value(&error);
return GetRequestAction::Respond(crate::encode_value(&error));
}
};
@@ -936,7 +939,7 @@ mod tests {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(&local_identity);
peering_id.extend_from_slice(&peer_hash);
crate::stamper::generate_stamp_raw(
crate::stamper::generate_stamp(
&peering_id,
cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
@@ -979,8 +982,9 @@ mod tests {
buf
};
let response =
handler.handle_message_get_request(None, &client_dest, &request_data, &mut node);
let response = handler
.handle_message_get_request(None, &client_dest, &request_data, &mut node)
.into_response();
let value: rmpv::Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_u64(), Some(PeerError::NoIdentity as u64));
}
@@ -1004,12 +1008,9 @@ mod tests {
buf
};
let response = handler.handle_message_get_request(
Some(&identity),
&client_dest,
&request_data,
&mut node,
);
let response = handler
.handle_message_get_request(Some(&identity), &client_dest, &request_data, &mut node)
.into_response();
let value: rmpv::Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
let arr = value.as_array().unwrap();
assert!(arr.is_empty());
+8
View File
@@ -32,6 +32,14 @@
//!
//! [`DiscoveryStamper`]: rns_transport::discovery::DiscoveryStamper
/// Unix time as f64 seconds — Python `time.time()` equivalent.
pub(crate) fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
pub mod constants;
pub mod discovery_stamper;
pub mod handlers;
+90 -11
View File
@@ -383,7 +383,7 @@ impl LxMessage {
if let Some(target_cost) = propagation_stamp_cost
&& self.propagation_stamp.is_none()
{
let (stamp, value) = crate::stamper::generate_stamp_raw(
let (stamp, value) = crate::stamper::generate_stamp(
&tid,
target_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
@@ -397,11 +397,11 @@ impl LxMessage {
if let Some(ref prop_stamp) = self.propagation_stamp {
if stamp_value == 0 {
let workblock = crate::stamper::stamp_workblock_raw(
let workblock = crate::stamper::stamp_workblock(
&tid,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
stamp_value = crate::stamper::stamp_value_raw(&workblock, prop_stamp);
stamp_value = crate::stamper::stamp_value(&workblock, prop_stamp);
}
lxmf_data.extend_from_slice(prop_stamp);
}
@@ -439,6 +439,54 @@ impl LxMessage {
Ok(wrapper)
}
/// Smallest possible valid propagation entry: anything at or below
/// `LXMF_OVERHEAD + STAMP_SIZE` cannot carry a message (Python
/// `LXStamper.validate_pn_stamp` rejects it before building a workblock).
pub const MIN_PROPAGATION_ENTRY_SIZE: usize =
crate::constants::LXMF_OVERHEAD + crate::constants::STAMP_SIZE + 1;
/// [`Self::unpack_propagation_wrapper`] with ingest bounds applied before
/// any per-entry stamp validation can be reached. `max_transfer_bytes` is
/// the receiving node's configured propagation/transfer limit. Each stamp
/// validation builds a ~256 KB workblock, so a wrapper stuffed with junk
/// entries is a CPU-amplification vector — under-floor entries and
/// transfers whose entry count couldn't possibly be legitimate are
/// rejected cheaply here instead.
pub fn unpack_propagation_wrapper_bounded(
data: &[u8],
max_transfer_bytes: usize,
) -> Result<(f64, Vec<Vec<u8>>), MessageError> {
if data.len() > max_transfer_bytes {
return Err(MessageError::UnpackFailed(format!(
"propagation wrapper: {} bytes exceeds transfer limit {}",
data.len(),
max_transfer_bytes
)));
}
let (timestamp, entries) = Self::unpack_propagation_wrapper(data)?;
let max_entries = max_transfer_bytes / Self::MIN_PROPAGATION_ENTRY_SIZE;
if entries.len() > max_entries {
return Err(MessageError::UnpackFailed(format!(
"propagation wrapper: {} entries exceeds maximum {} for transfer limit",
entries.len(),
max_entries
)));
}
if let Some(undersized) = entries
.iter()
.position(|e| e.len() < Self::MIN_PROPAGATION_ENTRY_SIZE)
{
return Err(MessageError::UnpackFailed(format!(
"propagation wrapper: entry {} below minimum message size",
undersized
)));
}
Ok((timestamp, entries))
}
/// Compute `transient_id = full_hash(lxmf_data)` for a propagation blob.
///
/// The input must be `dest_hash + encrypted_data` without the propagation stamp; callers must
@@ -785,15 +833,13 @@ impl LxMessage {
None => return false,
};
// A missing stamp can never match a ticket hash or a PoW workblock,
// so it is always invalid (Python `validate_stamp`: the ticket loop
// compares `self.stamp == hash`, which is False when stamp is None,
// then `if self.stamp == None: return False`).
let stamp = match self.stamp.as_deref() {
Some(s) => s,
None => {
// Check tickets even without a stamp — tickets generate stamps
if tickets.is_none() {
return false;
}
return false;
}
None => return false,
};
// Ticket-based stamps take precedence over PoW.
@@ -815,7 +861,7 @@ impl LxMessage {
};
let workblock = crate::stamper::stamp_workblock(&message_id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
if crate::stamper::stamp_valid(stamp, target_cost, &workblock) {
self.stamp_value = Some(crate::stamper::stamp_value(stamp, &workblock) as u16);
self.stamp_value = Some(crate::stamper::stamp_value(&workblock, stamp) as u16);
return true;
}
@@ -2050,6 +2096,39 @@ mod tests {
assert_eq!(&lxmf_data[..16], &[0xAA; 16]);
}
/// T0-7: the bounded wrapper decode must reject CPU-amplification shapes
/// (junk-stuffed entry lists) cheaply, before per-entry stamp validation
/// could build any ~256 KB workblocks; legitimate transfers still pass.
#[test]
fn test_unpack_propagation_wrapper_bounded() {
let entry_floor = LxMessage::MIN_PROPAGATION_ENTRY_SIZE;
let limit = 16 * 1024;
// Hostile: thousands of tiny entries in a small blob.
let junk: Vec<Vec<u8>> = (0..2000).map(|_| vec![0xAB; 3]).collect();
let hostile = rmp_serde::to_vec(&(1000.0f64, junk)).unwrap();
assert!(hostile.len() <= limit, "test blob must fit the limit");
assert!(LxMessage::unpack_propagation_wrapper_bounded(&hostile, limit).is_err());
// Hostile: a single under-floor entry hidden among valid-sized ones.
let mixed: Vec<Vec<u8>> = vec![vec![0xAB; entry_floor], vec![0xAB; entry_floor - 1]];
let mixed_blob = rmp_serde::to_vec(&(1000.0f64, mixed)).unwrap();
assert!(LxMessage::unpack_propagation_wrapper_bounded(&mixed_blob, limit).is_err());
// Hostile: blob bigger than the configured transfer limit.
let oversize: Vec<Vec<u8>> = vec![vec![0xAB; 2 * limit]];
let oversize_blob = rmp_serde::to_vec(&(1000.0f64, oversize)).unwrap();
assert!(LxMessage::unpack_propagation_wrapper_bounded(&oversize_blob, limit).is_err());
// Legitimate multi-entry sync passes and round-trips.
let good: Vec<Vec<u8>> = (0..8).map(|i| vec![i as u8; entry_floor + 64]).collect();
let good_blob = rmp_serde::to_vec(&(1000.0f64, good.clone())).unwrap();
let (ts, entries) =
LxMessage::unpack_propagation_wrapper_bounded(&good_blob, limit).unwrap();
assert_eq!(ts, 1000.0);
assert_eq!(entries, good);
}
#[test]
fn test_pack_opportunistic_encrypted_strips_destination_hash() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
+22 -8
View File
@@ -291,18 +291,18 @@ impl LxmPeer {
key_material.extend_from_slice(peer_identity_hash);
key_material.extend_from_slice(our_identity_hash);
let workblock = crate::stamper::stamp_workblock_raw(
// Bounded search (stamper::stamp_iteration_cap): an announce-supplied
// hostile peering_cost can no longer pin this thread forever.
match crate::stamper::generate_stamp(
&key_material,
self.peering_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
loop {
let stamp: [u8; 32] = crate::stamper::rand_bytes();
if crate::stamper::stamp_valid_raw(&stamp, self.peering_cost, &workblock) {
let value = crate::stamper::stamp_value_raw(&workblock, &stamp);
) {
Some((stamp, value)) => {
self.peering_key = Some((stamp, value));
return true;
true
}
None => false,
}
}
@@ -467,6 +467,20 @@ mod tests {
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
}
/// T0-4: an absurd announce-supplied peering cost must fail the bounded
/// key search instead of spinning forever; sane costs still succeed.
#[test]
fn test_generate_peering_key_capped() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.peering_cost = 255;
assert!(!peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
assert!(peer.peering_key.is_none());
peer.peering_cost = 4;
assert!(peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
assert!(peer.peering_key.is_some());
}
#[test]
fn test_mark_unreachable() {
let mut peer = LxmPeer::new([0; 16]);
+51 -16
View File
@@ -98,8 +98,10 @@ impl PropagationEntry {
pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>,
total_size: usize,
locally_delivered_ids: HashSet<PropagationTransientId>,
locally_processed_ids: HashSet<PropagationTransientId>,
/// Dedup caches: transient ID → first-seen Unix time. Age-based retention
/// (`MESSAGE_EXPIRY * 6`), persisted with their real timestamps.
locally_delivered_ids: HashMap<PropagationTransientId, f64>,
locally_processed_ids: HashMap<PropagationTransientId, f64>,
ignored_destinations: HashSet<[u8; 16]>,
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[u8; 16]>,
@@ -256,45 +258,49 @@ impl PropagationStore {
}
pub fn mark_locally_delivered(&mut self, transient_id: PropagationTransientId) {
self.locally_delivered_ids.insert(transient_id);
self.locally_delivered_ids
.insert(transient_id, crate::now_f64());
}
pub fn is_locally_delivered(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_delivered_ids.contains(transient_id)
self.locally_delivered_ids.contains_key(transient_id)
}
pub fn mark_locally_processed(&mut self, transient_id: PropagationTransientId) {
self.locally_processed_ids.insert(transient_id);
self.locally_processed_ids
.insert(transient_id, crate::now_f64());
}
pub fn is_locally_processed(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_processed_ids.contains(transient_id)
self.locally_processed_ids.contains_key(transient_id)
}
pub fn locally_delivered_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_delivered_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_delivered_ids
}
pub fn locally_processed_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_processed_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_processed_ids
}
pub fn replace_locally_delivered(&mut self, ids: HashSet<PropagationTransientId>) {
pub fn replace_locally_delivered(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_delivered_ids = ids;
}
pub fn replace_locally_processed(&mut self, ids: HashSet<PropagationTransientId>) {
pub fn replace_locally_processed(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_processed_ids = ids;
}
/// Drop cache entries whose transient IDs no longer exist in `entries`
/// (i.e. were culled). Python removes them once older than
/// MESSAGE_EXPIRY * 6; the caller decides the cutoff here.
pub fn clean_transient_caches(&mut self) {
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
/// `LXMRouter.clean_transient_id_caches`, LXMRouter.py:956). Retention is
/// purely age-based: entries must outlive their store membership so a
/// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
self.locally_delivered_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
self.locally_processed_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
}
/// `from_peer` is the peer we received this message from, or `None` if it
@@ -515,6 +521,35 @@ mod tests {
assert!(store.is_locally_processed(&transient_id));
}
/// T1-10: dedup caches are age-based (Python MESSAGE_EXPIRY*6), not keyed
/// to store membership — a culled-and-reoffered message must still be
/// recognised; entries expire only once their timestamp ages out.
#[test]
fn test_transient_caches_age_based_retention() {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
let mut store = PropagationStore::new();
let transient_id = tid(0xAA);
store.mark_locally_delivered(transient_id);
store.mark_locally_processed(transient_id);
let stamped_at = *store.locally_delivered_ids().get(&transient_id).unwrap();
// The entry was never inserted into the store at all — cleaning must
// still retain it while it is young (store-cull independence).
store.clean_transient_caches(stamped_at + 60.0);
assert!(store.is_locally_delivered(&transient_id));
assert!(store.is_locally_processed(&transient_id));
// Still retained just inside the expiry horizon...
store.clean_transient_caches(stamped_at + expiry - 1.0);
assert!(store.is_locally_delivered(&transient_id));
// ...and dropped once aged out.
store.clean_transient_caches(stamped_at + expiry + 1.0);
assert!(!store.is_locally_delivered(&transient_id));
assert!(!store.is_locally_processed(&transient_id));
}
#[test]
fn test_cull_by_weight() {
let mut store = PropagationStore::new();
+614 -116
View File
@@ -49,6 +49,98 @@ pub struct OfferRequestContext<'a> {
pub remote_identity_hash: Option<&'a [u8; 16]>,
}
/// Outcome of [`PropagationNode::handle_get_request`]. Phases 1/3 (and
/// malformed input) are answered from the store alone; phase 2 returns a
/// read plan so the embedder performs blocking file I/O after releasing
/// the node lock.
#[derive(Debug)]
pub enum GetRequestAction {
Respond(Vec<u8>),
ServeFiles(GetServePlan),
}
impl GetRequestAction {
/// Resolve to response bytes, performing any planned file reads inline.
/// Blocking; do not call while holding a shared node lock.
pub fn into_response(self) -> Vec<u8> {
match self {
GetRequestAction::Respond(bytes) => bytes,
GetRequestAction::ServeFiles(plan) => plan.serve(),
}
}
}
/// Phase-2 read plan: wants resolved and ownership-gated under the node
/// lock; [`GetServePlan::serve`] does the file reads outside it.
#[derive(Debug)]
pub struct GetServePlan {
reads: Vec<PlannedRead>,
/// Client transfer limit in bytes (wire value is kB ×1000, Python parity).
limit_bytes: Option<f64>,
}
#[derive(Debug)]
struct PlannedRead {
path: PathBuf,
stamped: bool,
}
impl GetServePlan {
/// Read planned files and encode the phase-2 response. Mirrors Python
/// LXMRouter.message_get_request limit accounting (LXMRouter.py:1477-1494):
/// 24-byte base + 16 bytes per message, full stored size counted,
/// over-limit entries skipped (not a transfer abort), stamps stripped
/// for client download. Unreadable files are skipped.
pub fn serve(&self) -> Vec<u8> {
use rmpv::Value;
const PER_MESSAGE_OVERHEAD: f64 = 16.0;
let mut cumulative_size: f64 = 24.0;
let mut messages: Vec<Value> = Vec::new();
for read in &self.reads {
let Ok(data) = std::fs::read(&read.path) else {
continue;
};
let next_size = cumulative_size + data.len() as f64 + PER_MESSAGE_OVERHEAD;
if self.limit_bytes.is_some_and(|limit| next_size > limit) {
continue;
}
cumulative_size = next_size;
let payload = if read.stamped && data.len() >= 32 {
data[..data.len() - 32].to_vec()
} else {
data
};
messages.push(Value::Binary(payload));
}
crate::encode_value(&Value::Array(messages))
}
}
/// One pending store-file read produced by
/// [`PropagationNode::plan_message_reads`].
#[derive(Debug)]
pub struct PlannedMessageRead {
pub transient_id: PropagationTransientId,
pub path: PathBuf,
}
/// Blocking reads for a plan from [`PropagationNode::plan_message_reads`];
/// call without holding the node lock. Missing/unreadable files are skipped.
pub fn read_planned_messages(
plan: &[PlannedMessageRead],
) -> Vec<(PropagationTransientId, Vec<u8>)> {
plan.iter()
.filter_map(|read| {
std::fs::read(&read.path)
.ok()
.map(|data| (read.transient_id, data))
})
.collect()
}
pub struct PropagationNode {
config: PropagationNodeConfig,
store: PropagationStore,
@@ -138,12 +230,12 @@ impl PropagationNode {
// PN expand rounds. Matches Python LXStamper.validate_pn_stamp().
let sv = if let Some(ref stamp) = message.stamp {
let transient_id_full = rns_crypto::sha::full_hash(&packed);
let workblock = crate::stamper::stamp_workblock_raw(
let workblock = crate::stamper::stamp_workblock(
&transient_id_full,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
if let Ok(stamp) = <&[u8; 32]>::try_from(stamp.as_slice()) {
crate::stamper::stamp_value_raw(&workblock, stamp) as u8
crate::stamper::stamp_value(&workblock, stamp) as u8
} else {
0
}
@@ -284,8 +376,18 @@ impl PropagationNode {
}
let mut loaded = 0;
let mut quarantined = 0;
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
// One unreadable directory entry or file must not abort the whole
// store load — quarantine it and keep loading the rest.
let entry = match entry {
Ok(e) => e,
Err(e) => {
tracing::warn!(error = %e, "skipping unreadable messagestore entry");
quarantined += 1;
continue;
}
};
let path = entry.path();
if !path.is_file() {
continue;
@@ -296,12 +398,27 @@ impl PropagationNode {
None => continue,
};
if filename.ends_with(".peer") || filename.ends_with(".msgpack") {
if filename.ends_with(".peer")
|| filename.ends_with(".msgpack")
|| filename.ends_with(".corrupt")
{
continue;
}
if let Some((tid, ts, sv)) = PropagationEntry::parse_filename(&filename) {
let data = std::fs::read(&path)?;
let data = match std::fs::read(&path) {
Ok(d) => d,
Err(e) => {
tracing::warn!(
file = %path.display(),
error = %e,
"quarantining unreadable propagation message"
);
let _ = std::fs::rename(&path, path.with_extension("corrupt"));
quarantined += 1;
continue;
}
};
let size = data.len();
if self.store.contains(&tid) {
@@ -334,17 +451,21 @@ impl PropagationNode {
}
}
if loaded > 0 {
tracing::info!(loaded, "loaded propagation messages from disk");
if loaded > 0 || quarantined > 0 {
tracing::info!(loaded, quarantined, "loaded propagation messages from disk");
}
Ok(())
}
/// Periodic maintenance: cull expired entries and clean up orphaned files.
/// Periodic maintenance: cull expired entries, enforce the storage cap by
/// weight (Python `clean_message_store` parity — makes room for new
/// messages instead of wedging at the ingest reject), and clean up
/// orphaned files.
pub fn tick(&mut self) {
let before = self.store.len();
self.store.cull_expired(self.config.max_message_age);
self.store.cull_by_weight(self.config.max_storage);
let after = self.store.len();
if before > after
@@ -619,36 +740,30 @@ impl PropagationNode {
}
/// Handle a Link REQUEST at the `/get` path for client download. Python
/// reference: LXMRouter.message_get_request() (LXMRouter.py:484-587).
/// reference: LXMRouter.message_get_request() (LXMRouter.py:1425-1499).
///
/// Wire format is msgpack `[wants, haves]` or `[wants, haves, delivery_limit]`:
/// - Phase 1 (list): `[None, None]` -> available transient IDs for the client.
/// - Phase 2 (get): `[[wants...], [haves...]]` -> message payloads; haves
/// are purged in the same call.
/// - Phase 1 (list): `[None, None]` -> available transient IDs for the client,
/// smallest message first (Python sorts by file size ascending).
/// - Phase 2 (get): `[[wants...], [haves...]]` -> haves are purged first
/// (Python order), then wants resolve to a [`GetServePlan`] whose file
/// reads the embedder performs without holding the node lock.
/// - Phase 3 (purge): `[None, [received_ids...]]` -> delete from store.
pub fn handle_get_request(
&mut self,
request_data: &[u8],
client_dest_hash: &[u8; 16],
) -> Vec<u8> {
) -> GetRequestAction {
use rmpv::Value;
let value: rmpv::Value = match rmpv::decode::read_value(&mut &request_data[..]) {
Ok(v) => v,
Err(_) => {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &Value::Nil).ok();
return buf;
}
Err(_) => return GetRequestAction::Respond(crate::encode_value(&Value::Nil)),
};
let arr = match value.as_array() {
Some(a) if a.len() >= 2 => a,
_ => {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &Value::Nil).ok();
return buf;
}
_ => return GetRequestAction::Respond(crate::encode_value(&Value::Nil)),
};
let wants_is_nil = arr[0].is_nil();
@@ -667,101 +782,117 @@ impl PropagationNode {
}
if wants_is_nil && haves_is_nil {
// Phase 1: list available messages for this client.
let available = self.store.entries_for_destination(client_dest_hash);
// Phase 1: list available messages for this client, smallest first.
let mut available = self.store.entries_for_destination(client_dest_hash);
available.sort_by_key(|e| e.size);
let id_list: Vec<Value> = available
.iter()
.map(|e| Value::Binary(e.transient_id.to_vec()))
.collect();
let response = Value::Array(id_list);
crate::encode_value(&response)
GetRequestAction::Respond(crate::encode_value(&Value::Array(id_list)))
} else if wants_is_nil && !haves_is_nil {
// Phase 3: purge messages the client already received.
// Phase 3: purge messages the client already received. Python
// returns the (empty) response_messages list here.
if let Some(haves_arr) = arr[1].as_array() {
for have_val in haves_arr {
if let Some(tid) = parse_store_id(have_val)
&& 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(tid) = parse_store_id(have_val) {
self.purge_client_entry(&tid, client_dest_hash);
}
}
}
crate::encode_value(&Value::Boolean(true))
GetRequestAction::Respond(crate::encode_value(&Value::Array(Vec::new())))
} else {
// Phase 2: return requested message data.
let mut messages: Vec<Value> = Vec::new();
// Phase 2: purge haves first (Python order — an ID in both wants
// and haves is purged, not served), then resolve wants into a
// read plan executed after the node lock is released.
if let Some(haves_arr) = arr[1].as_array() {
for have_val in haves_arr {
if let Some(tid) = parse_store_id(have_val) {
self.purge_client_entry(&tid, client_dest_hash);
}
}
}
let mut reads = Vec::new();
if let Some(wants_arr) = arr[0].as_array() {
let delivery_limit = if arr.len() > 2 { arr[2].as_f64() } else { None };
let limit_bytes = delivery_limit
.map(|kb| (kb * 1024.0) as usize)
.unwrap_or(usize::MAX);
let mut total_sent = 0usize;
for want_val in wants_arr {
if let Some(tid) = parse_store_id(want_val)
&& let Some(ref dir) = self.storage_path
&& let Some(entry) = self.store.get(&tid)
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
&& entry.destination_hash == *client_dest_hash
{
let path = dir.join(entry.filename());
if let Ok(data) = std::fs::read(&path) {
if total_sent + data.len() > limit_bytes {
break;
}
total_sent += data.len();
let response_data = if entry.stamped && data.len() >= 32 {
data[..data.len() - 32].to_vec()
} else {
data
};
messages.push(Value::Binary(response_data));
}
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
}
}
}
// Purge haves in the same call.
if let Some(haves_arr) = arr[1].as_array() {
for have_val in haves_arr {
if let Some(tid) = parse_store_id(have_val)
&& 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);
}
}
}
// Wire value is kilobytes ×1000 (Python LXMRouter.py:1471).
let limit_bytes = if arr.len() > 2 {
arr[2].as_f64().map(|kb| kb * 1000.0)
} else {
None
};
let response = Value::Array(messages);
crate::encode_value(&response)
GetRequestAction::ServeFiles(GetServePlan { reads, limit_bytes })
}
}
/// Fetch raw packed message data for each requested transient ID. Python
/// reference: LXMRouter.message_get_request_received(). Returns an empty
/// vec when there is no disk storage configured.
pub fn message_get_request(
/// Remove a store entry on a client's behalf — only when the entry is
/// addressed to that client (Python LXMRouter.py:1454 ownership gate);
/// foreign transient IDs are ignored.
fn purge_client_entry(&mut self, tid: &PropagationTransientId, client_dest_hash: &[u8; 16]) {
let owned = self
.store
.get(tid)
.is_some_and(|entry| entry.destination_hash == *client_dest_hash);
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);
}
}
/// Resolve requested transient IDs into store-file read plans (no I/O).
/// Perform the reads via [`read_planned_messages`] after releasing the
/// node lock. Returns an empty vec when there is no disk storage.
pub fn plan_message_reads(
&self,
requested_ids: &[PropagationTransientId],
) -> Vec<(PropagationTransientId, Vec<u8>)> {
) -> Vec<PlannedMessageRead> {
let dir = match &self.storage_path {
Some(d) => d,
None => return Vec::new(),
};
let mut results = Vec::new();
for tid in requested_ids {
if let Some(entry) = self.store.get(tid) {
let path = dir.join(entry.filename());
if let Ok(data) = std::fs::read(&path) {
results.push((*tid, data));
}
}
}
results
requested_ids
.iter()
.filter_map(|tid| {
self.store.get(tid).map(|entry| PlannedMessageRead {
transient_id: *tid,
path: dir.join(entry.filename()),
})
})
.collect()
}
/// Fetch raw packed message data for each requested transient ID. Python
/// reference: LXMRouter.message_get_request_received(). Blocking
/// convenience over [`Self::plan_message_reads`] — prefer the staged pair
/// when the node sits behind a shared lock.
pub fn message_get_request(
&self,
requested_ids: &[PropagationTransientId],
) -> Vec<(PropagationTransientId, Vec<u8>)> {
read_planned_messages(&self.plan_message_reads(requested_ids))
}
/// Produce a `SyncOffer` listing message IDs the peer has not yet handled.
@@ -804,25 +935,23 @@ impl PropagationNode {
self.sync_sessions.insert(peer_hash, session);
}
let mut messages = Vec::new();
for wanted_id_bytes in &get.wanted_ids {
if wanted_id_bytes.len() != 32 {
continue;
}
let mut tid = [0u8; 32];
tid.copy_from_slice(wanted_id_bytes);
if let Some(ref dir) = self.storage_path
&& let Some(entry) = self.store.get(&tid)
{
let path = dir.join(entry.filename());
if let Ok(data) = std::fs::read(&path) {
messages.push(data);
let wanted: Vec<PropagationTransientId> = get
.wanted_ids
.iter()
.filter_map(|id_bytes| {
if id_bytes.len() != 32 {
return None;
}
}
}
let mut tid = [0u8; 32];
tid.copy_from_slice(id_bytes);
Some(tid)
})
.collect();
messages
read_planned_messages(&self.plan_message_reads(&wanted))
.into_iter()
.map(|(_tid, data)| data)
.collect()
}
/// Record a successful transfer for a peer. Loads the peer, adds the
@@ -857,7 +986,9 @@ impl PropagationNode {
let filename = format!("{}.peer", hex_encode(peer_hash));
let path = dir.join(filename);
let data = std::fs::read(&path).ok()?;
LxmPeer::from_bytes_with_handled(&data)
let mut peer = LxmPeer::from_bytes_with_handled(&data)?;
self.prune_handled_against_store(&mut peer);
Some(peer)
}
pub fn load_peers(&self) -> Vec<LxmPeer> {
@@ -872,14 +1003,24 @@ impl PropagationNode {
let path = entry.path();
if path.extension().map(|e| e == "peer").unwrap_or(false)
&& let Ok(data) = std::fs::read(&path)
&& let Some(peer) = LxmPeer::from_bytes_with_handled(&data)
&& let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data)
{
self.prune_handled_against_store(&mut peer);
peers.push(peer);
}
}
}
peers
}
/// Drop handled-message IDs whose store entries no longer exist (Python
/// `LXMPeer.from_dict` keeps only IDs in `router.propagation_entries`).
/// Without this the per-peer sets — and the `.peer` files they round-trip
/// through on every sync — grow with total propagated volume forever.
/// Files converge lazily: the next `mark_peer_handled` saves the pruned set.
fn prune_handled_against_store(&self, peer: &mut LxmPeer) {
peer.handled_messages.retain(|id| self.store.contains(id));
}
}
impl std::fmt::Debug for PropagationNode {
@@ -918,7 +1059,7 @@ mod tests {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(local_identity);
peering_id.extend_from_slice(remote_identity);
crate::stamper::generate_stamp_raw(
crate::stamper::generate_stamp(
&peering_id,
cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
@@ -1087,6 +1228,132 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// T0-1: `/get` ownership gating — a client may only list, download, and
/// purge messages addressed to itself (Python LXMRouter.py:1454/1479).
#[test]
fn test_get_request_ownership_gating() {
use rmpv::Value;
let dir = std::env::temp_dir().join("lxmf_test_get_ownership");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let client_a = [0xCC; 16];
let client_b = [0xDD; 16];
let msg_a = make_signed_message(client_a, [0xBB; 16], "Test", "for A");
let msg_b = make_signed_message(client_b, [0xBB; 16], "Test", "for B");
assert!(node.accept_message(&msg_a));
assert!(node.accept_message(&msg_b));
let tid_a = node.store.entries_for_destination(&client_a)[0].transient_id;
let tid_b = node.store.entries_for_destination(&client_b)[0].transient_id;
let encode_req = |wants: Option<&[[u8; 32]]>, haves: Option<&[[u8; 32]]>| -> Vec<u8> {
let to_val = |ids: Option<&[[u8; 32]]>| match ids {
Some(list) => {
Value::Array(list.iter().map(|t| Value::Binary(t.to_vec())).collect())
}
None => Value::Nil,
};
crate::encode_value(&Value::Array(vec![to_val(wants), to_val(haves)]))
};
let decode_msgs = |resp: &[u8]| -> usize {
match rmpv::decode::read_value(&mut &resp[..]).unwrap() {
Value::Array(items) => items.len(),
_ => panic!("expected array response"),
}
};
// A requesting B's message gets nothing.
let resp = node
.handle_get_request(&encode_req(Some(&[tid_b]), Some(&[])), &client_a)
.into_response();
assert_eq!(decode_msgs(&resp), 0);
assert!(node.store.get(&tid_b).is_some());
// A's haves cannot purge B's entry (Phase 3).
node.handle_get_request(&encode_req(None, Some(&[tid_b])), &client_a);
assert!(
node.store.get(&tid_b).is_some(),
"foreign purge must be ignored"
);
assert!(
dir.join(node.store.get(&tid_b).unwrap().filename())
.exists(),
"B's file must survive A's purge attempt"
);
// A can still fetch its own message...
let resp = node
.handle_get_request(&encode_req(Some(&[tid_a]), Some(&[])), &client_a)
.into_response();
assert_eq!(decode_msgs(&resp), 1);
// ...and purge it.
node.handle_get_request(&encode_req(None, Some(&[tid_a])), &client_a);
assert!(node.store.get(&tid_a).is_none(), "own purge must work");
let _ = std::fs::remove_dir_all(&dir);
}
/// T1-15: one unreadable file in the messagestore must not abort the
/// whole store load — it is quarantined (renamed `.corrupt`) and the
/// remaining entries load.
#[cfg(unix)]
#[test]
fn test_disk_load_quarantines_unreadable_file() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join("lxmf_test_prop_quarantine");
let _ = std::fs::remove_dir_all(&dir);
{
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let msg_a = make_signed_message([0xCC; 16], [0xBB; 16], "Test", "loads fine");
let msg_b = make_signed_message([0xDD; 16], [0xBB; 16], "Test", "will corrupt");
assert!(node.accept_message(&msg_a));
assert!(node.accept_message(&msg_b));
}
// Make one stored file unreadable (read() will fail, parse_filename
// still succeeds — the load must skip + quarantine it).
let victim = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| p.is_file() && !p.to_string_lossy().ends_with(".msgpack"))
.expect("expected a stored message file");
std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o000)).unwrap();
let node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
assert_eq!(
node.message_count(),
1,
"remaining entry must load despite the unreadable file"
);
assert!(
victim.with_extension("corrupt").exists(),
"unreadable file must be quarantined"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_tick_culls_expired() {
let config = PropagationNodeConfig {
@@ -1170,25 +1437,60 @@ mod tests {
assert_eq!(node.message_count(), 1);
}
#[test]
fn test_tick_enforces_weight_cap() {
let mut node = PropagationNode::new(
PropagationNodeConfig {
max_storage: 1,
..PropagationNodeConfig::default()
},
[0xAA; 16],
);
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "weight-cull");
assert!(
node.accept_message(&msg),
"ingest cap checks size before insert, first message is admitted"
);
assert_eq!(node.message_count(), 1);
node.tick();
assert_eq!(
node.message_count(),
0,
"tick must cull the store down to the weight cap"
);
}
#[test]
fn test_peer_persistence() {
let dir = std::env::temp_dir().join("lxmf_test_peer_persist");
let _ = std::fs::remove_dir_all(&dir);
let node = PropagationNode::with_storage(
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
// Load-time prune (Python LXMPeer.from_dict parity): a handled ID
// backed by a live store entry survives; one whose message is gone
// from the store is dropped.
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "peer-persist");
assert!(node.accept_message(&msg));
let live_id = node.create_offer_filtered(&HashSet::new())[0];
let mut peer = LxmPeer::new([0xBB; 16]);
peer.add_handled_message(&live_id);
peer.add_handled_message(&tid(0xCC));
node.save_peer(&peer).unwrap();
let loaded_peers = node.load_peers();
assert_eq!(loaded_peers.len(), 1);
assert!(loaded_peers[0].has_handled(&tid(0xCC)));
assert!(loaded_peers[0].has_handled(&live_id));
assert!(
!loaded_peers[0].has_handled(&tid(0xCC)),
"handled ID without a store entry must be pruned at load"
);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -1770,7 +2072,7 @@ mod tests {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &request).unwrap();
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]);
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]).into_response();
let response: rmpv::Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let arr = response.as_array().unwrap();
assert_eq!(arr.len(), 1);
@@ -1788,7 +2090,7 @@ mod tests {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &request).unwrap();
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]);
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]).into_response();
let response: rmpv::Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let arr = response.as_array().unwrap();
assert!(arr.is_empty());
@@ -1815,7 +2117,9 @@ mod tests {
let list_request = Value::Array(vec![Value::Nil, Value::Nil]);
let mut list_buf = Vec::new();
rmpv::encode::write_value(&mut list_buf, &list_request).unwrap();
let list_response = node.handle_get_request(&list_buf, &[0xBB; 16]);
let list_response = node
.handle_get_request(&list_buf, &[0xBB; 16])
.into_response();
let list_value: Value = rmpv::decode::read_value(&mut &list_response[..]).unwrap();
assert_eq!(list_value.as_array().unwrap().len(), 1);
@@ -1825,7 +2129,9 @@ mod tests {
]);
let mut get_buf = Vec::new();
rmpv::encode::write_value(&mut get_buf, &get_request).unwrap();
let get_response = node.handle_get_request(&get_buf, &[0xBB; 16]);
let get_response = node
.handle_get_request(&get_buf, &[0xBB; 16])
.into_response();
let get_value: Value = rmpv::decode::read_value(&mut &get_response[..]).unwrap();
let messages = get_value.as_array().unwrap();
assert_eq!(messages.len(), 1);
@@ -1866,7 +2172,9 @@ mod tests {
]);
let mut get_buf = Vec::new();
rmpv::encode::write_value(&mut get_buf, &get_request).unwrap();
let get_response = node.handle_get_request(&get_buf, &[0xBB; 16]);
let get_response = node
.handle_get_request(&get_buf, &[0xBB; 16])
.into_response();
let get_value: Value = rmpv::decode::read_value(&mut &get_response[..]).unwrap();
let messages = get_value.as_array().unwrap();
assert_eq!(messages.len(), 1);
@@ -1909,7 +2217,9 @@ mod tests {
]);
let mut get_buf = Vec::new();
rmpv::encode::write_value(&mut get_buf, &get_request).unwrap();
let get_response = reloaded.handle_get_request(&get_buf, &[0xBB; 16]);
let get_response = reloaded
.handle_get_request(&get_buf, &[0xBB; 16])
.into_response();
let get_value: Value = rmpv::decode::read_value(&mut &get_response[..]).unwrap();
let messages = get_value.as_array().unwrap();
assert_eq!(messages.len(), 1);
@@ -1964,7 +2274,9 @@ mod tests {
let list_request = Value::Array(vec![Value::Nil, Value::Nil]);
let mut list_buf = Vec::new();
rmpv::encode::write_value(&mut list_buf, &list_request).unwrap();
let response = reloaded.handle_get_request(&list_buf, &[0xBB; 16]);
let response = reloaded
.handle_get_request(&list_buf, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_array().unwrap().len(), 1);
@@ -1996,7 +2308,7 @@ mod tests {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &request).unwrap();
let _response_bytes = node.handle_get_request(&buf, &[0xBB; 16]);
let _response_bytes = node.handle_get_request(&buf, &[0xBB; 16]).into_response();
assert_eq!(node.message_count(), 0);
let _ = std::fs::remove_dir_all(&dir);
@@ -2026,7 +2338,7 @@ mod tests {
let mut buf = Vec::new();
rmpv::encode::write_value(&mut buf, &request).unwrap();
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]);
let response_bytes = node.handle_get_request(&buf, &[0xBB; 16]).into_response();
let response: rmpv::Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let arr = response.as_array().unwrap();
assert_eq!(arr.len(), 1);
@@ -2035,6 +2347,192 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// T2-8b: phase 2 must come back as a read plan (file I/O deferred until
/// after the node lock is released); phases 1/3 answer immediately.
#[test]
fn test_get_request_phase2_returns_serve_plan() {
use rmpv::Value;
let dir = std::env::temp_dir().join("lxmf_test_get_serve_plan");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let mut blob = vec![0xBB; 16];
blob.extend_from_slice(&[0x11; 64]);
assert!(node.accept_propagated_blob(&blob, 0));
let tid = rns_crypto::sha::full_hash(&blob);
let list_req = crate::encode_value(&Value::Array(vec![Value::Nil, Value::Nil]));
assert!(matches!(
node.handle_get_request(&list_req, &[0xBB; 16]),
GetRequestAction::Respond(_)
));
let purge_req = crate::encode_value(&Value::Array(vec![
Value::Nil,
Value::Array(vec![Value::Binary(vec![0xEE; 32])]),
]));
assert!(matches!(
node.handle_get_request(&purge_req, &[0xBB; 16]),
GetRequestAction::Respond(_)
));
let get_req = crate::encode_value(&Value::Array(vec![
Value::Array(vec![Value::Binary(tid.to_vec())]),
Value::Array(vec![]),
]));
let action = node.handle_get_request(&get_req, &[0xBB; 16]);
let GetRequestAction::ServeFiles(plan) = action else {
panic!("phase 2 must return a serve plan");
};
// Reads resolve after the node borrow ends (embedder drops the lock).
drop(node);
let response: Value = rmpv::decode::read_value(&mut &plan.serve()[..]).unwrap();
let messages = response.as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].as_slice().unwrap(), blob.as_slice());
let _ = std::fs::remove_dir_all(&dir);
}
/// T2-8b parity: haves are purged before wants resolve (Python
/// LXMRouter.py:1451-1462) — an ID in both is purged, not served.
#[test]
fn test_get_phase_purges_haves_before_serving_wants() {
use rmpv::Value;
let dir = std::env::temp_dir().join("lxmf_test_get_purge_first");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let mut blob = vec![0xBB; 16];
blob.extend_from_slice(&[0x22; 48]);
assert!(node.accept_propagated_blob(&blob, 0));
let tid = rns_crypto::sha::full_hash(&blob);
let req = crate::encode_value(&Value::Array(vec![
Value::Array(vec![Value::Binary(tid.to_vec())]),
Value::Array(vec![Value::Binary(tid.to_vec())]),
]));
let response_bytes = node.handle_get_request(&req, &[0xBB; 16]).into_response();
let response: Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
assert!(
response.as_array().unwrap().is_empty(),
"ID in both wants and haves must be purged, not served"
);
assert_eq!(node.message_count(), 0);
let _ = std::fs::remove_dir_all(&dir);
}
/// T2-8b parity: transfer limit is kB ×1000 with 24-byte base and 16-byte
/// per-message overhead, and over-limit entries are skipped rather than
/// aborting the serve loop (Python LXMRouter.py:1471-1494).
#[test]
fn test_get_phase_transfer_limit_python_accounting() {
use rmpv::Value;
let dir = std::env::temp_dir().join("lxmf_test_get_limit_accounting");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let make_blob = |fill: u8, total_len: usize| {
let mut blob = vec![0xBB; 16];
blob.extend(std::iter::repeat_n(fill, total_len - 16));
blob
};
// Cumulative starts at 24, +16 per message: a (100 B) -> 140;
// b (350 B) -> 506 > 500 so skipped (would pass a 1024-unit limit of
// 512, pinning the ×1000 wire unit); c (50 B) -> 206, still served.
let blob_a = make_blob(0x01, 100);
let blob_b = make_blob(0x02, 350);
let blob_c = make_blob(0x03, 50);
for blob in [&blob_a, &blob_b, &blob_c] {
assert!(node.accept_propagated_blob(blob, 0));
}
let wants: Vec<Value> = [&blob_a, &blob_b, &blob_c]
.iter()
.map(|blob| Value::Binary(rns_crypto::sha::full_hash(blob).to_vec()))
.collect();
let req = crate::encode_value(&Value::Array(vec![
Value::Array(wants),
Value::Array(vec![]),
Value::F64(0.5),
]));
let response_bytes = node.handle_get_request(&req, &[0xBB; 16]).into_response();
let response: Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let messages = response.as_array().unwrap();
assert_eq!(messages.len(), 2, "b is skipped, a and c are served");
assert_eq!(messages[0].as_slice().unwrap(), blob_a.as_slice());
assert_eq!(messages[1].as_slice().unwrap(), blob_c.as_slice());
let _ = std::fs::remove_dir_all(&dir);
}
/// T2-8b parity: phase-1 listing is sorted smallest message first
/// (Python LXMRouter.py:1437-1444).
#[test]
fn test_get_list_phase_sorted_smallest_first() {
use rmpv::Value;
let dir = std::env::temp_dir().join("lxmf_test_get_list_sorted");
let _ = std::fs::remove_dir_all(&dir);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.clone(),
)
.unwrap();
let make_blob = |fill: u8, total_len: usize| {
let mut blob = vec![0xBB; 16];
blob.extend(std::iter::repeat_n(fill, total_len - 16));
blob
};
let blob_large = make_blob(0x04, 300);
let blob_small = make_blob(0x05, 100);
let blob_mid = make_blob(0x06, 200);
for blob in [&blob_large, &blob_small, &blob_mid] {
assert!(node.accept_propagated_blob(blob, 0));
}
let list_req = crate::encode_value(&Value::Array(vec![Value::Nil, Value::Nil]));
let response_bytes = node
.handle_get_request(&list_req, &[0xBB; 16])
.into_response();
let response: Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let ids: Vec<Vec<u8>> = response
.as_array()
.unwrap()
.iter()
.map(|v| v.as_slice().unwrap().to_vec())
.collect();
let expected: Vec<Vec<u8>> = [&blob_small, &blob_mid, &blob_large]
.iter()
.map(|blob| rns_crypto::sha::full_hash(blob).to_vec())
.collect();
assert_eq!(ids, expected);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_stamp_cost_validation_rejects_unstamped() {
let config = PropagationNodeConfig {
+4 -2
View File
@@ -374,13 +374,15 @@ impl PropagationSyncTask {
}
fn queue_messages_for_ids(&mut self, ids: &[PropagationTransientId]) {
let results = match self.propagation_node.lock() {
Ok(node) => node.message_get_request(ids),
// 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),
Err(_) => {
self.state = SyncTaskState::Failed;
return;
}
};
let results = crate::propagation_node::read_planned_messages(&plan);
self.transfer_queue = results.into_iter().map(|(_tid, data)| data).collect();
if self.transfer_queue.is_empty() {
+260 -41
View File
@@ -3,6 +3,7 @@
//! Python reference: LXMF/LXMRouter.py. Actor pattern — a single tokio task owns
//! all mutable state.
use crate::now_f64;
use std::collections::HashMap;
use std::fmt;
@@ -15,7 +16,6 @@ use crate::peer::LxmPeer;
use crate::propagation::PropagationStore;
use crate::stamper;
use crate::ticket::{Ticket, TicketStore};
use crate::types::PropagationTransientId;
/// Router configuration.
///
@@ -47,8 +47,6 @@ pub struct RouterConfigExt {
pub processing_outbound: bool,
/// Maximum outbound messages to process per tick (`None` = unlimited).
pub processing_limit: Option<usize>,
/// Maximum message size in bytes (`None` = unlimited).
pub max_message_size: Option<usize>,
pub enforce_ratchets: bool,
pub enforce_stamps: bool,
pub retain_synced_on_node: bool,
@@ -71,7 +69,6 @@ impl Default for RouterConfigExt {
max_peering_cost: MAX_PEERING_COST,
processing_outbound: true,
processing_limit: None,
max_message_size: None,
enforce_ratchets: false,
enforce_stamps: false,
retain_synced_on_node: false,
@@ -267,6 +264,12 @@ pub struct LxmRouter {
pub pending_outbound: Vec<LxMessage>,
/// 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).
pub runtime_handle: Option<tokio::runtime::Handle>,
pub active_deferred_stamp: Option<DeferredStampJob>,
/// Identities allowed for delivery. An empty list means "all allowed".
pub allowed: Vec<[u8; 16]>,
@@ -288,6 +291,9 @@ pub struct LxmRouter {
pub throttled_peers: HashMap<[u8; 16], f64>,
pub propagation_start_time: Option<f64>,
pub processing_count: u64,
/// Wall-clock gate for `run_jobs_tick`, decoupling jobloop cadence from
/// 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,
@@ -331,6 +337,7 @@ impl LxmRouter {
config,
pending_outbound: Vec::new(),
pending_deferred_stamps: HashMap::new(),
runtime_handle: tokio::runtime::Handle::try_current().ok(),
active_deferred_stamp: None,
allowed: Vec::new(),
blocked: Vec::new(),
@@ -347,6 +354,7 @@ impl LxmRouter {
throttled_peers: HashMap::new(),
propagation_start_time: None,
processing_count: 0,
last_jobs_tick: 0.0,
outbound_propagation_node: None,
propagation_transfer_progress: 0.0,
client_propagation_messages_received: 0,
@@ -453,6 +461,22 @@ impl LxmRouter {
Ok(())
}
/// Queue `message` for off-thread stamp generation; it re-enters
/// `pending_outbound` with the stamp attached once the worker finishes.
/// Returns the message back when it carries no id to key the job on.
pub fn defer_stamp(&mut self, mut message: LxMessage) -> Option<LxMessage> {
let id = message.message_id.or(message.hash).or_else(|| {
message.compute_hash().ok();
message.hash
});
let Some(message_hash) = id else {
return Some(message);
};
message.state = MessageState::Outbound;
self.pending_deferred_stamps.insert(message_hash, message);
None
}
/// Process deferred outbound message stamp generation.
///
/// Python reference: `LXMRouter.process_deferred_stamps` — LXMRouter.py:2407-2498.
@@ -474,15 +498,26 @@ impl LxmRouter {
return;
}
if tokio::runtime::Handle::try_current().is_ok() {
let (handle, rx) =
stamper::spawn_deferred_stamp(message_hash, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let runtime = tokio::runtime::Handle::try_current()
.ok()
.or_else(|| self.runtime_handle.clone());
if let Some(runtime) = runtime {
let (handle, rx) = stamper::spawn_deferred_stamp_on(
&runtime,
message_hash,
cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS,
);
self.active_deferred_stamp = Some(DeferredStampJob {
message_hash,
handle,
rx,
});
} else if let Some(mut message) = self.pending_deferred_stamps.remove(&message_hash) {
tracing::warn!(
cost,
"no tokio runtime available; generating stamp inline (sync embedder only)"
);
match stamper::generate_stamp(&message_hash, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS) {
Some((stamp, value)) => {
message.stamp = Some(stamp.to_vec());
@@ -856,18 +891,18 @@ impl LxmRouter {
}
/// Load persisted runtime state (stamp costs, tickets, dedup sets) from
/// `state_dir`. Missing files are treated as empty state.
/// `state_dir`. Missing files are treated as empty state. Dedup-cache
/// timestamps are restored as persisted so age-based expiry survives
/// restarts.
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
self.ticket_store
.replace_all(persist::load_tickets(state_dir)?);
let delivered = persist::load_local_deliveries(state_dir)?;
let processed = persist::load_locally_processed(state_dir)?;
self.propagation_store
.replace_locally_delivered(delivered.keys().copied().collect());
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
self.propagation_store
.replace_locally_processed(processed.keys().copied().collect());
.replace_locally_processed(persist::load_locally_processed(state_dir)?);
Ok(())
}
@@ -875,29 +910,11 @@ impl LxmRouter {
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
use std::time::{SystemTime, UNIX_EPOCH};
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, self.ticket_store.all())?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64();
let delivered: std::collections::HashMap<PropagationTransientId, f64> = self
.propagation_store
.locally_delivered_ids()
.iter()
.map(|id| (*id, now))
.collect();
let processed: std::collections::HashMap<PropagationTransientId, f64> = self
.propagation_store
.locally_processed_ids()
.iter()
.map(|id| (*id, now))
.collect();
persist::save_local_deliveries(state_dir, &delivered)?;
persist::save_locally_processed(state_dir, &processed)?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
Ok(())
}
@@ -949,6 +966,15 @@ impl LxmRouter {
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.
if peering_cost.unwrap_or(0) > self.config.ext.max_peering_cost {
if self.peers.contains_key(&destination_hash) {
self.unpeer(&destination_hash);
}
return false;
}
if self.peers.contains_key(&destination_hash) {
return false;
}
@@ -1718,10 +1744,27 @@ impl LxmRouter {
self.run_periodic_jobs();
}
/// Drive the periodic job machinery for embedders that process outbound
/// themselves via `process_outbound_with_direct` instead of calling
/// [`Self::tick`]. Without this the jobloop counters never advance and
/// transient-cache cleaning, store culls, and peer rotation never run.
/// Time-gated to Python's `PROCESSING_INTERVAL` so callers may invoke it
/// every loop pass regardless of their tick rate (lxmd: 4 s, Ratspeak:
/// 500 ms) without skewing the jobloop cadences.
pub fn run_jobs_tick(&mut self) {
let now = now_f64();
if now - self.last_jobs_tick < PROCESSING_INTERVAL as f64 * 0.9 {
return;
}
self.last_jobs_tick = now;
self.processing_count += 1;
self.run_periodic_jobs();
}
fn run_periodic_jobs(&mut self) {
// Job cadences match the Python LXMRouter jobloop.
if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) {
self.propagation_store.clean_transient_caches();
self.propagation_store.clean_transient_caches(now_f64());
}
if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL)
&& self.config.propagation_enabled
@@ -1825,13 +1868,6 @@ pub struct NodeStats {
pub peer_stats: HashMap<[u8; 16], PeerStats>,
}
fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1856,6 +1892,45 @@ mod tests {
assert!(router.propagation_store.is_empty());
}
#[test]
fn run_jobs_tick_gates_on_processing_interval() {
let mut router = LxmRouter::new(RouterConfig::default());
router.run_jobs_tick();
assert_eq!(router.processing_count, 1);
// Second call inside the PROCESSING_INTERVAL window must not advance
// the jobloop — embedders may call this at arbitrary loop rates.
router.run_jobs_tick();
assert_eq!(router.processing_count, 1);
// Backdating the gate simulates the interval elapsing.
router.last_jobs_tick = now_f64() - PROCESSING_INTERVAL as f64;
router.run_jobs_tick();
assert_eq!(router.processing_count, 2);
}
#[test]
fn run_jobs_tick_cleans_transient_caches_at_job_interval() {
let mut router = LxmRouter::new(RouterConfig::default());
let ancient = 1.0; // far older than MESSAGE_EXPIRY * 6
let mut delivered = std::collections::HashMap::new();
delivered.insert([0xAB; 32], ancient);
router
.propagation_store
.replace_locally_delivered(delivered);
// Land exactly on the transient-cache job multiple.
router.processing_count = JOB_TRANSIENT_INTERVAL - 1;
router.last_jobs_tick = now_f64() - PROCESSING_INTERVAL as f64;
router.run_jobs_tick();
assert!(
!router
.propagation_store
.locally_delivered_ids()
.contains_key(&[0xAB; 32]),
"expired dedup id must be aged out by the jobloop"
);
}
#[test]
fn test_router_config_defaults() {
let config = RouterConfig::default();
@@ -1866,7 +1941,6 @@ mod tests {
assert!(config.ext.processing_outbound);
assert!(config.ext.defer_stamp_generation);
assert!(config.ext.processing_limit.is_none());
assert!(config.ext.max_message_size.is_none());
assert!(!config.ext.enforce_ratchets);
assert!(!config.ext.enforce_stamps);
}
@@ -2233,6 +2307,75 @@ mod tests {
assert!(queued.stamp_value.unwrap_or(0) >= 1);
}
/// Production shape: the manager tick runs on `spawn_blocking`, where
/// `Handle::try_current()` fails. The router's stored handle must still
/// spawn the PoW worker instead of grinding inline under the caller.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_stamps_spawn_from_blocking_thread_via_stored_handle() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
// Constructed inside the runtime: handle captured.
let mut router = LxmRouter::new(RouterConfig::default());
assert!(
router.runtime_handle.is_some(),
"handle captured at construction"
);
let dest = [0xAA; 16];
router.set_stamp_cost(dest, 1);
let mut msg = LxMessage::new(
dest,
[0xBB; 16],
"defer",
"blocking",
DeliveryMethod::Direct,
);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
assert!(router.pending_deferred_stamps.contains_key(&message_id));
// Drive entirely from a blocking thread (no implicit runtime).
let mut router = tokio::task::spawn_blocking(move || {
router.process_deferred_stamps();
assert!(
router.active_deferred_stamp.is_some(),
"must spawn a worker, not grind inline"
);
router
})
.await
.unwrap();
for _ in 0..200 {
router.process_deferred_stamps();
if router.pending_outbound.len() == 1 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(router.pending_outbound.len(), 1);
assert_eq!(
router.pending_outbound[0].stamp.as_ref().map(Vec::len),
Some(32)
);
}
/// Delivery-time deferral: a message that reaches the outbound executor
/// without a stamp goes back through the deferred queue instead of
/// blocking the caller.
#[tokio::test]
async fn defer_stamp_queues_message_with_id() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let mut msg = LxMessage::new([0xAA; 16], [0xBB; 16], "d", "s", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
msg.stamp_cost = Some(1);
let id = msg.message_id.unwrap();
assert!(router.defer_stamp(msg).is_none());
assert!(router.pending_deferred_stamps.contains_key(&id));
}
#[tokio::test]
async fn test_cancel_outbound_cancels_deferred_stamp_job() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
@@ -2399,6 +2542,50 @@ mod tests {
assert!(r2.propagation_store.is_locally_processed(&transient_a));
}
/// T1-10: persisted dedup timestamps are the REAL first-seen times —
/// restored on load (not reset to save-time), so age-based expiry is
/// stable across arbitrarily many save/load cycles.
#[test]
fn test_dedup_cache_timestamps_survive_save_load_cycles() {
let tmp = tempfile::TempDir::new().unwrap();
let transient = [0x42; 32];
let mut router = LxmRouter::new(RouterConfig::default());
router.propagation_store.mark_locally_delivered(transient);
let original_ts = *router
.propagation_store
.locally_delivered_ids()
.get(&transient)
.unwrap();
// Multiple save/load cycles must not refresh the timestamp.
for _ in 0..3 {
router.save_state(tmp.path()).unwrap();
let mut reloaded = LxmRouter::new(RouterConfig::default());
reloaded.load_state(tmp.path()).unwrap();
let loaded_ts = *reloaded
.propagation_store
.locally_delivered_ids()
.get(&transient)
.unwrap();
assert_eq!(loaded_ts, original_ts, "timestamp must survive reload");
router = reloaded;
}
assert_eq!(router.propagation_store.locally_delivered_ids().len(), 1);
// An aged-out entry is gone after the periodic clean, and stays gone
// through persistence (growth bounded).
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
router
.propagation_store
.clean_transient_caches(original_ts + expiry + 1.0);
assert!(!router.propagation_store.is_locally_delivered(&transient));
router.save_state(tmp.path()).unwrap();
let mut fresh = LxmRouter::new(RouterConfig::default());
fresh.load_state(tmp.path()).unwrap();
assert!(fresh.propagation_store.locally_delivered_ids().is_empty());
}
#[test]
fn test_load_state_missing_dir_is_ok() {
let tmp = tempfile::TempDir::new().unwrap();
@@ -3037,6 +3224,38 @@ mod tests {
}));
}
/// 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).
#[test]
fn test_autopeer_enforces_max_peering_cost() {
let mut router = LxmRouter::new(RouterConfig::default());
let max = router.config.ext.max_peering_cost;
let candidate = |cost: Option<u8>| AutopeerCandidate {
destination_hash: [0xAA; 16],
timebase: 1000.0,
transfer_limit: Some(256.0),
sync_limit: None,
stamp_cost: Some(16),
stamp_flexibility: Some(3),
peering_cost: cost,
hops: Some(2),
};
// Over-cost announce: refused outright.
assert!(!router.autopeer(candidate(Some(max + 1))));
assert!(router.peers.is_empty());
// At-cost announce: accepted.
assert!(router.autopeer(candidate(Some(max))));
assert_eq!(router.peers.len(), 1);
// Existing peer raising its cost beyond the cap: peering breaks.
assert!(!router.autopeer(candidate(Some(max + 1))));
assert!(router.peers.is_empty(), "over-cost announce must unpeer");
}
#[test]
fn test_autopeer_respects_configured_maxdepth() {
let mut router = LxmRouter::new(RouterConfig {
+133 -131
View File
@@ -2,11 +2,11 @@
//!
//! Python reference: LXMF/LXStamper.py.
//!
//! Two workblock constructions are used:
//! - `stamp_workblock_raw`: HKDF-expand on arbitrary material. Matches Python
//! exactly for peering keys and PN stamps.
//! - `stamp_workblock`: iterative SHA-256 on a 32-byte message_id (simplified
//! construction used internally for message stamps; cheaper and deterministic).
//! A single workblock construction is used for all stamp kinds (message,
//! propagation-node, peering), matching Python `LXStamper.stamp_workblock`:
//! per-round HKDF expansion concatenated into a `expand_rounds * 256` byte
//! workblock. Only the expand-round count differs per kind (see
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
//!
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`.
@@ -19,7 +19,7 @@ use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use sha2::{Digest, Sha256};
/// Parsed propagation-node stamp parts: `(stamp, lxm_data, value, workblock)`.
/// Parsed propagation-node stamp parts: `(transient_id, lxm_data, value, stamp)`.
pub type PropagationStampParts = ([u8; 32], Vec<u8>, u32, [u8; 32]);
/// Matches Python `LXStamper.stamp_workblock(material, expand_rounds)`:
@@ -29,7 +29,7 @@ pub type PropagationStampParts = ([u8; 32], Vec<u8>, u32, [u8; 32]);
/// workblock += HKDF(length=256, derive_from=material, salt=salt, context=None)
///
/// Produces `expand_rounds * 256` bytes.
pub fn stamp_workblock_raw(material: &[u8], expand_rounds: usize) -> Vec<u8> {
pub fn stamp_workblock(material: &[u8], expand_rounds: usize) -> Vec<u8> {
let mut workblock = Vec::with_capacity(expand_rounds * 256);
for n in 0..expand_rounds {
@@ -53,23 +53,6 @@ fn pack_msgpack_uint(n: usize) -> Vec<u8> {
crate::encode_value(&value)
}
/// `workblock = SHA-256^(expand_rounds)(message_id)`.
///
/// Non-32-byte inputs are first hashed to produce a 32-byte starting point.
pub fn stamp_workblock(message_id: &[u8], expand_rounds: usize) -> [u8; 32] {
let mut current = if message_id.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(message_id);
arr
} else {
sha256(message_id)
};
for _ in 0..expand_rounds {
current = sha256(&current);
}
current
}
fn leading_zero_bits(data: &[u8]) -> u32 {
let mut count = 0u32;
for &byte in data {
@@ -84,89 +67,68 @@ fn leading_zero_bits(data: &[u8]) -> u32 {
}
/// Leading zero bits of `SHA-256(workblock || stamp)`. Matches Python `stamp_value()`.
pub fn stamp_value(workblock: &[u8; 32], stamp: &[u8; 32]) -> u32 {
let mut material = [0u8; 64];
material[..32].copy_from_slice(workblock);
material[32..].copy_from_slice(stamp);
let hash = sha256(&material);
leading_zero_bits(&hash)
pub fn stamp_value(workblock: &[u8], stamp: &[u8; 32]) -> u32 {
let mut hasher = Sha256::new();
hasher.update(workblock);
stamp_value_from_base(&hasher, stamp)
}
pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8; 32]) -> bool {
pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
if cost == 0 {
return true;
}
stamp_value(workblock, stamp) >= cost as u32
}
/// `stamp_value` counterpart for variable-length (HKDF-expanded) workblocks.
pub fn stamp_value_raw(workblock: &[u8], stamp: &[u8; 32]) -> u32 {
let mut hasher = Sha256::new();
hasher.update(workblock);
raw_stamp_value_from_base(&hasher, stamp)
}
/// `stamp_valid` counterpart for variable-length (HKDF-expanded) workblocks.
pub fn stamp_valid_raw(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
if cost == 0 {
return true;
/// Give-up bound for stamp searches: 64× the expected `2^cost` work, so the
/// failure probability for an honest cost is ~e^-64 while a hostile cost can
/// no longer pin a thread forever. Costs ≥ 58 (cap would overflow u64) are
/// unsatisfiable on real hardware and fail immediately. Python has no cap and
/// blocks until success — deliberate divergence, see fix-registry.
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
if cost >= 58 {
return None;
}
stamp_value_raw(workblock, stamp) >= cost as u32
Some(64u64 << cost)
}
/// Single-threaded brute-force stamp search. Blocks until a valid stamp is found.
pub fn generate_stamp(
message_id: &[u8; 32],
cost: u8,
expand_rounds: usize,
) -> Option<([u8; 32], u32)> {
/// Single-threaded brute-force stamp search. Bounded by
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
/// cost is unsatisfiable.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
if cost == 0 {
return Some(([0u8; 32], 0));
}
let started = std::time::Instant::now();
let max_iterations = stamp_iteration_cap(cost)?;
let workblock = stamp_workblock(message_id, expand_rounds);
let mut rng = rand::thread_rng();
loop {
let stamp = rand_bytes_from(&mut rng);
if stamp_valid(&stamp, cost, &workblock) {
let value = stamp_value(&workblock, &stamp);
return Some((stamp, value));
}
}
}
/// Generate a stamp using the Python-compatible variable-length workblock.
///
/// This is used for propagation-node stamps and peering keys, where the
/// workblock material is arbitrary bytes instead of the regular 32-byte LXMF
/// message id.
pub fn generate_stamp_raw(
material: &[u8],
cost: u8,
expand_rounds: usize,
) -> Option<([u8; 32], u32)> {
if cost == 0 {
return Some(([0u8; 32], 0));
}
let workblock = stamp_workblock_raw(material, expand_rounds);
let workblock = stamp_workblock(material, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
loop {
for _ in 0..max_iterations {
let stamp = rand_bytes_from(&mut rng);
let value = raw_stamp_value_from_base(&base_hasher, &stamp);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
let elapsed_ms = started.elapsed().as_millis() as u64;
if elapsed_ms > 250 {
tracing::info!(cost, value, elapsed_ms, "stamp generated");
}
return Some((stamp, value));
}
}
tracing::warn!(
cost,
elapsed_ms = started.elapsed().as_millis() as u64,
"stamp search exhausted iteration cap"
);
None
}
/// Stamp search with a configurable iteration limit (for tests).
pub fn generate_stamp_limited(
message_id: &[u8; 32],
material: &[u8],
cost: u8,
expand_rounds: usize,
max_iterations: u64,
@@ -175,12 +137,14 @@ pub fn generate_stamp_limited(
return Some([0u8; 32]);
}
let workblock = stamp_workblock(message_id, expand_rounds);
let workblock = stamp_workblock(material, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
let stamp = rand_bytes_from(&mut rng);
if stamp_valid(&stamp, cost, &workblock) {
if stamp_value_from_base(&base_hasher, &stamp) >= cost as u32 {
return Some(stamp);
}
}
@@ -203,11 +167,11 @@ pub fn validate_stamp(
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_cost: u8) -> bool {
let workblock = stamp_workblock_raw(
let workblock = stamp_workblock(
peering_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
stamp_valid_raw(peering_key, target_cost, &workblock)
stamp_valid(peering_key, target_cost, &workblock)
}
/// Python reference: LXStamper.py:53-65 (`validate_pn_stamp`).
@@ -229,12 +193,12 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
stamp.copy_from_slice(stamp_bytes);
let transient_id = rns_crypto::sha::full_hash(lxm_data);
let workblock = stamp_workblock_raw(
let workblock = stamp_workblock(
&transient_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = stamp_value_raw(&workblock, &stamp);
let value = stamp_value(&workblock, &stamp);
if value < target_cost as u32 {
return None;
}
@@ -283,12 +247,27 @@ pub fn spawn_deferred_stamp(
) -> (
DeferredStampHandle,
tokio::sync::oneshot::Receiver<DeferredStampResult>,
) {
let handle = tokio::runtime::Handle::current();
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
}
/// Handle-explicit variant: callable from `spawn_blocking` threads (no
/// implicit runtime context) — the manager tick runs there.
pub fn spawn_deferred_stamp_on(
runtime: &tokio::runtime::Handle,
message_id: [u8; 32],
cost: u8,
expand_rounds: usize,
) -> (
DeferredStampHandle,
tokio::sync::oneshot::Receiver<DeferredStampResult>,
) {
let cancel = Arc::new(AtomicBool::new(false));
let (tx, rx) = tokio::sync::oneshot::channel();
let cancel_flag = cancel.clone();
tokio::task::spawn_blocking(move || {
runtime.spawn_blocking(move || {
if cost == 0 {
let _ = tx.send(DeferredStampResult::Success {
stamp: [0u8; 32],
@@ -298,6 +277,8 @@ pub fn spawn_deferred_stamp(
}
let workblock = stamp_workblock(&message_id, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
loop {
@@ -309,8 +290,8 @@ pub fn spawn_deferred_stamp(
// Check cancellation every 1000 iterations.
for _ in 0..1000 {
let stamp = rand_bytes_from(&mut rng);
if stamp_valid(&stamp, cost, &workblock) {
let value = stamp_value(&workblock, &stamp);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
let _ = tx.send(DeferredStampResult::Success { stamp, value });
return;
}
@@ -332,7 +313,7 @@ fn rand_bytes_from(rng: &mut impl RngCore) -> [u8; 32] {
bytes
}
fn raw_stamp_value_from_base(base_hasher: &Sha256, stamp: &[u8; 32]) -> u32 {
fn stamp_value_from_base(base_hasher: &Sha256, stamp: &[u8; 32]) -> u32 {
let mut hasher = base_hasher.clone();
hasher.update(stamp);
let hash = hasher.finalize();
@@ -347,9 +328,10 @@ mod tests {
#[test]
fn test_workblock_deterministic() {
let id = sha256(b"test message id");
let wb1 = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let wb2 = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let wb1 = stamp_workblock(&id, 10);
let wb2 = stamp_workblock(&id, 10);
assert_eq!(wb1, wb2);
assert_eq!(wb1.len(), 10 * 256);
}
#[test]
@@ -360,6 +342,15 @@ mod tests {
assert_ne!(wb1, wb2);
}
/// Workblock for the default message expand rounds matches the Python
/// construction's size: 3000 rounds * 256 bytes.
#[test]
fn test_workblock_message_rounds_size() {
let id = sha256(b"size check");
let wb = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
assert_eq!(wb.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS * 256);
}
#[test]
fn test_leading_zero_bits() {
assert_eq!(leading_zero_bits(&[0xFF]), 0);
@@ -385,6 +376,23 @@ mod tests {
assert_eq!(value, 0);
}
/// T0-4: the stamp search is bounded — an unsatisfiable (hostile) cost
/// returns `None` immediately instead of pinning the thread forever.
#[test]
fn test_generate_stamp_capped_for_hostile_cost() {
assert_eq!(stamp_iteration_cap(1), Some(128));
assert_eq!(stamp_iteration_cap(26), Some(64u64 << 26));
assert!(stamp_iteration_cap(57).is_some());
assert_eq!(stamp_iteration_cap(58), None);
assert_eq!(stamp_iteration_cap(255), None);
let id = sha256(b"hostile cost");
// Cost 255 must fail fast (cap is None — no workblock spin at all).
assert!(generate_stamp(&id, 255, 20).is_none());
// Sane costs still succeed.
assert!(generate_stamp(&id, 4, 20).is_some());
}
#[test]
fn test_generate_and_validate_stamp() {
let id = sha256(b"test message for stamping");
@@ -416,13 +424,6 @@ mod tests {
assert!(result.is_none());
}
#[test]
fn test_stamp_value() {
let workblock = [0u8; 32];
let stamp = [0u8; 32];
let _value = stamp_value(&workblock, &stamp);
}
#[test]
fn test_stamp_value_consistency() {
let id = sha256(b"consistency test");
@@ -436,18 +437,41 @@ mod tests {
}
#[test]
fn test_workblock_handles_short_input() {
let short_input = b"short";
let wb = stamp_workblock(short_input, 10);
assert_ne!(wb, [0u8; 32]);
fn test_workblock_arbitrary_length_input() {
let short_material = b"short";
let wb = stamp_workblock(short_material, 5);
assert_eq!(wb.len(), 5 * 256);
let wb2 = stamp_workblock(short_material, 5);
assert_eq!(wb, wb2);
let wb3 = stamp_workblock(b"other", 5);
assert_ne!(wb, wb3);
}
#[test]
fn test_different_expand_round_constants() {
let id = sha256(b"test expand rounds");
let wb_default = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let wb_pn = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
assert_ne!(wb_default, wb_pn);
let wb_peering =
stamp_workblock(&id, crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
// Workblocks are prefix-stable per construction; only length differs.
assert_eq!(wb_pn[..wb_peering.len()], wb_peering[..]);
assert_eq!(wb_pn.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS_PN * 256);
assert_eq!(
wb_peering.len(),
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING * 256
);
}
/// The first 256-byte chunk of the workblock is identical regardless of
/// total round count — Python builds it incrementally the same way.
#[test]
fn test_workblock_prefix_stability() {
let id = sha256(b"prefix stability");
let wb_small = stamp_workblock(&id, 2);
let wb_large = stamp_workblock(&id, 5);
assert_eq!(wb_small[..], wb_large[..2 * 256]);
}
#[test]
@@ -509,33 +533,11 @@ mod tests {
}
#[test]
fn test_stamp_workblock_raw_deterministic() {
let id = sha256(b"test workblock raw");
let wb1 = stamp_workblock_raw(&id, 10);
let wb2 = stamp_workblock_raw(&id, 10);
assert_eq!(wb1, wb2);
assert_eq!(wb1.len(), 10 * 256);
}
#[test]
fn test_stamp_workblock_raw_arbitrary_length() {
let short_material = b"short";
let wb = stamp_workblock_raw(short_material, 5);
assert_eq!(wb.len(), 5 * 256);
let wb2 = stamp_workblock_raw(short_material, 5);
assert_eq!(wb, wb2);
let wb3 = stamp_workblock_raw(b"other", 5);
assert_ne!(wb, wb3);
}
#[test]
fn test_stamp_workblock_raw_peering_id_length() {
fn test_workblock_peering_id_length() {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(&[0xAA; 16]);
peering_id.extend_from_slice(&[0xBB; 16]);
let wb = stamp_workblock_raw(
let wb = stamp_workblock(
&peering_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
@@ -586,9 +588,9 @@ mod tests {
}
#[test]
fn test_raw_stamp_value_matches_direct_sha256_prefix_hash() {
fn test_stamp_value_matches_direct_sha256_of_workblock_and_stamp() {
let material = sha256(b"propagation transient id");
let workblock = stamp_workblock_raw(&material, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
let workblock = stamp_workblock(&material, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
let stamp = [0x5Au8; 32];
let mut direct = Vec::with_capacity(workblock.len() + stamp.len());
@@ -597,7 +599,7 @@ mod tests {
let direct_hash = sha256(&direct);
assert_eq!(
stamp_value_raw(&workblock, &stamp),
stamp_value(&workblock, &stamp),
leading_zero_bits(&direct_hash)
);
}
+257 -77
View File
@@ -4,7 +4,7 @@
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::time::{Duration, Instant};
use bytes::Bytes;
use clap::Parser;
@@ -46,6 +46,7 @@ use rns_identity::identity::Identity;
use rns_identity::ratchet::{
RatchetRing, ReceivedRatchet, clean_received_ratchets_dir, purge_expired_ratchets_in_memory,
};
use rns_runtime::lifecycle::ShutdownSignal;
use rns_transport::messages::{
AnnounceHandlerEvent, TransportMessage, TransportQuery, TransportQueryResponse,
};
@@ -95,6 +96,13 @@ fn now_f64() -> f64 {
.as_secs_f64()
}
async fn sleep_or_shutdown(shutdown: &ShutdownSignal, duration: Duration) -> bool {
tokio::select! {
_ = shutdown.wait() => true,
_ = tokio::time::sleep(duration) => false,
}
}
fn mark_delivery_attempt(message: &mut LxMessage) -> u32 {
let now = now_f64();
message.delivery_attempts += 1;
@@ -364,6 +372,56 @@ fn create_propagation_announce_packet_for(
Ok(raw)
}
/// Soft cap on announce-learned identity keys. Python bounds its equivalent
/// store via Transport's known-destinations cleanup; lxmd has no last-use
/// signal, so over the cap it evicts entries without a live ratchet first,
/// then oldest-ratchet entries. Evicted keys re-learn from the next announce.
const KNOWN_IDENTITIES_SOFT_CAP: usize = 10_000;
/// Full path-table resync cadence for `route_hops`. Announce events keep the
/// map fresh in between; this only re-baselines and prunes expired paths.
const ROUTE_HOPS_REFRESH_SECS: f64 = 300.0;
fn prune_known_identities(
known_identities: &mut HashMap<String, [u8; 64]>,
received_ratchets: &HashMap<String, ReceivedRatchet>,
) -> usize {
if known_identities.len() <= KNOWN_IDENTITIES_SOFT_CAP {
return 0;
}
let mut excess = known_identities.len() - KNOWN_IDENTITIES_SOFT_CAP;
let before = known_identities.len();
let no_ratchet: Vec<String> = known_identities
.keys()
.filter(|k| !received_ratchets.contains_key(*k))
.take(excess)
.cloned()
.collect();
for k in &no_ratchet {
known_identities.remove(k);
}
excess = known_identities
.len()
.saturating_sub(KNOWN_IDENTITIES_SOFT_CAP);
if excess > 0 {
let mut by_age: Vec<(String, f64)> = known_identities
.keys()
.filter_map(|k| {
received_ratchets
.get(k)
.map(|rr| (k.clone(), rr.received_at))
})
.collect();
by_age.sort_by(|a, b| a.1.total_cmp(&b.1));
for (k, _) in by_age.into_iter().take(excess) {
known_identities.remove(&k);
}
}
before - known_identities.len()
}
fn send_propagation_announce_try(
tx: &mpsc::Sender<TransportMessage>,
identity: &Identity,
@@ -430,6 +488,7 @@ struct LxmdRunner {
last_crypto_save: f64,
last_cull: f64,
last_ratchet_clean: f64,
last_route_refresh: f64,
received_ratchets_dir: PathBuf,
control_state: Arc<Mutex<ControlSnapshot>>,
control_command_rx: mpsc::Receiver<ControlCommand>,
@@ -564,8 +623,7 @@ impl LxmdRunner {
delivery_rx,
&identity,
LXMF_APP_NAME,
signing_key
.unwrap_or_else(|| panic!("Identity must have signing key for link management")),
signing_key,
);
link_mgr.set_link_packet_channel(link_packet_tx);
link_mgr.set_resource_completed_channel(resource_tx);
@@ -637,15 +695,19 @@ impl LxmdRunner {
}
};
let prop_signing_key = identity.get_signing_key().unwrap_or_else(|| {
panic!("Identity must have signing key for propagation link management")
});
// TODO(hardware-identity): route propagation link signing through the
// backend-aware Identity path before supporting hardware-backed lxmd.
let prop_signing_key = identity.get_signing_key().ok_or(
"identity has no signing key; propagation link management requires a \
locally stored signing key (hardware-backed identities are not yet \
supported by lxmd)",
)?;
let mut prop_link_mgr = rns_runtime::link_manager::LinkManager::with_destination(
transport_tx.clone(),
prop_delivery_rx,
&identity,
"lxmf.propagation",
prop_signing_key,
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);
@@ -659,7 +721,6 @@ impl LxmdRunner {
let link_identities = prop_link_mgr.link_identities_handle();
let local_identity_hash = identity.hash;
prop_link_mgr.set_request_handler(move |link_id, path_hash, data| {
let mut node = pn_for_handler.lock().ok()?;
let remote_identity_hash = link_identities
.lock()
.ok()
@@ -677,15 +738,21 @@ impl LxmdRunner {
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))
} else if path_hash == get_path_hash {
tracing::info!("propagation: handling get request");
Some(handler.handle_message_get_request(
remote_identity_ref,
&client_dest_hash,
&data,
&mut node,
))
let action = {
let mut node = pn_for_handler.lock().ok()?;
handler.handle_message_get_request(
remote_identity_ref,
&client_dest_hash,
&data,
&mut node,
)
};
// Phase-2 file reads happen here, after the node lock drops.
Some(action.into_response())
} else {
tracing::debug!(
path = hex::encode(path_hash),
@@ -722,15 +789,19 @@ impl LxmdRunner {
delivery_tx: Some(control_delivery_tx),
});
let control_signing_key = identity.get_signing_key().unwrap_or_else(|| {
panic!("Identity must have signing key for control link management")
});
// TODO(hardware-identity): route control link signing through the
// backend-aware Identity path before supporting hardware-backed lxmd.
let control_signing_key = identity.get_signing_key().ok_or(
"identity has no signing key; control link management requires a \
locally stored signing key (hardware-backed identities are not yet \
supported by lxmd)",
)?;
let mut control_link_mgr = rns_runtime::link_manager::LinkManager::with_destination(
transport_tx.clone(),
control_delivery_rx,
&identity,
CONTROL_APP_NAME,
control_signing_key,
Some(control_signing_key),
);
let control_link_identities = control_link_mgr.link_identities_handle();
let stats_path_hash =
@@ -876,6 +947,7 @@ impl LxmdRunner {
last_crypto_save: now,
last_cull: now,
last_ratchet_clean: now,
last_route_refresh: 0.0,
received_ratchets_dir: received_dir,
control_state,
control_command_rx,
@@ -1343,7 +1415,16 @@ impl LxmdRunner {
}
}
/// Resync `route_hops` from the transport path table: boot seed plus a
/// slow re-baseline that prunes destinations whose paths expired.
/// Freshness between resyncs comes from announce events
/// (`drain_announce_events`), so dumping the full table every tick was
/// pure clone churn. Gated internally; call sites stay per-tick.
async fn refresh_route_hops_from_transport(&mut self) {
let now = now_f64();
if now - self.last_route_refresh < ROUTE_HOPS_REFRESH_SECS && !self.route_hops.is_empty() {
return;
}
let (response_tx, response_rx) = tokio::sync::oneshot::channel();
if let Err(e) = self.transport_tx.try_send(TransportMessage::Rpc {
query: TransportQuery::GetPathTable,
@@ -1359,12 +1440,17 @@ impl LxmdRunner {
return;
};
let now = now_f64();
// Replace wholesale on success only — a failed query must not leave
// routing blind, and replacement (vs insert) is what evicts dests
// whose transport paths have expired.
let mut fresh: HashMap<[u8; 16], u8> = HashMap::with_capacity(entries.len());
for entry in entries {
if entry.expires > now {
self.route_hops.insert(entry.hash, entry.hops.max(1));
fresh.insert(entry.hash, entry.hops.max(1));
}
}
self.route_hops = fresh;
self.last_route_refresh = now;
}
fn tick(&mut self) {
@@ -1374,44 +1460,48 @@ impl LxmdRunner {
self.drain_backchannel_events();
self.router.process_deferred_stamps();
let known_identities = self
.known_identities
.keys()
.cloned()
.collect::<HashSet<_>>();
let route_hops = self.route_hops.clone();
let direct_destinations = self
// Per-destination plan inputs precomputed for pending Direct messages
// only — avoids cloning route_hops/known_identities every tick.
let direct_inputs = self
.router
.pending_outbound
.iter()
.filter(|message| message.method == DeliveryMethod::Direct)
.map(|message| message.destination_hash)
.collect::<HashSet<_>>();
let reusable_links = direct_destinations
.iter()
.copied()
.collect::<HashSet<_>>()
.into_iter()
.map(|dest| {
(
dest,
direct_reusable_link_state(self.link_delivery.as_ref(), dest),
DirectDeliveryPlanInput {
identity_known: self.known_identities.contains_key(&hex::encode(dest)),
route: direct_route_snapshot(&self.route_hops, dest),
reusable_link: direct_reusable_link_state(
self.link_delivery.as_ref(),
dest,
),
},
)
})
.collect::<HashMap<_, _>>();
let actions = self.router.process_outbound_with_direct(|message, _now| {
let dest = message.destination_hash;
DirectDeliveryPlanInput {
identity_known: known_identities.contains(&hex::encode(dest)),
route: direct_route_snapshot(&route_hops, dest),
reusable_link: reusable_links
.get(&dest)
.copied()
.unwrap_or(DirectReusableLinkState::None),
}
direct_inputs
.get(&message.destination_hash)
.cloned()
.unwrap_or(DirectDeliveryPlanInput {
identity_known: false,
route: None,
reusable_link: DirectReusableLinkState::None,
})
});
if !actions.is_empty() {
self.execute_encrypted_actions(actions);
self.drain_core_backchannel_send_commands();
}
// Advance the router jobloop counters (transient-cache cleaning, store
// cull, peer rotation at Python cadences). `process_outbound_with_direct`
// does not drive these.
self.router.run_jobs_tick();
if let Some(ref mut ld) = self.link_delivery {
ld.drain_events(&self.known_identities);
@@ -1513,8 +1603,15 @@ impl LxmdRunner {
if now - self.last_cull > 300.0 {
self.router.cull_stamp_costs();
self.router.cull_propagation();
self.router.rotate_peers();
// Store cull + peer rotation now run via `run_jobs_tick` at Python
// jobloop cadences. The propagation node's own store (separate
// from the router's) ages out expired messages and enforces the
// weight cap here — previously this never ran.
if let Some(ref pn) = self.propagation_node
&& let Ok(mut node) = pn.lock()
{
node.tick();
}
self.last_cull = now;
}
@@ -1530,11 +1627,14 @@ impl LxmdRunner {
if now - self.last_ratchet_clean > 900.0 {
let mem_dropped = purge_expired_ratchets_in_memory(&mut self.received_ratchets);
let disk_dropped = clean_received_ratchets_dir(&self.received_ratchets_dir);
if mem_dropped > 0 || disk_dropped > 0 {
let ids_dropped =
prune_known_identities(&mut self.known_identities, &self.received_ratchets);
if mem_dropped > 0 || disk_dropped > 0 || ids_dropped > 0 {
tracing::debug!(
mem_dropped,
disk_dropped,
"ratchet cleanup pass: removed expired entries"
ids_dropped,
"crypto cache cleanup pass: removed expired entries"
);
}
self.last_ratchet_clean = now;
@@ -1550,7 +1650,6 @@ impl LxmdRunner {
while let Ok(event) = self.announce_rx.try_recv() {
seen.push(event.destination_hash);
let dest_hex = hex::encode(event.destination_hash);
let mut crypto_dirty = false;
tracing::info!(
dest = %dest_hex,
hops = event.hops,
@@ -1612,17 +1711,30 @@ impl LxmdRunner {
&& self.known_identities.get(&dest_hex) != Some(&pub_key)
{
self.known_identities.insert(dest_hex.clone(), pub_key);
crypto_dirty = true;
tracing::debug!(dest = %dest_hex, "learned identity key from announce");
}
if let Some(ratchet_key) = event.ratchet {
self.received_ratchets
.insert(dest_hex.clone(), ReceivedRatchet::new(ratchet_key));
crypto_dirty = true;
// Python Identity._remember_ratchet: persist only the single
// changed ratchet, off the daemon loop. Identity keys and the
// ring stay on the periodic/shutdown saves.
if let Some(ratchet_key) = event.ratchet
&& self
.received_ratchets
.get(&dest_hex)
.is_none_or(|rr| rr.ratchet_pub != ratchet_key)
{
let rr = ReceivedRatchet::new(ratchet_key);
self.received_ratchets.insert(dest_hex.clone(), rr);
tracing::debug!(dest = %dest_hex, "learned ratchet from announce");
}
if crypto_dirty {
self.save_crypto_state();
let path = self
.received_ratchets_dir
.join(format!("{dest_hex}.ratchet"));
let dir = self.received_ratchets_dir.clone();
tokio::task::spawn_blocking(move || {
std::fs::create_dir_all(&dir).ok();
if let Err(e) = rr.save(&path) {
tracing::warn!("Failed to persist received ratchet: {e}");
}
});
}
}
seen
@@ -1706,13 +1818,17 @@ impl LxmdRunner {
return;
};
let (_remote_timebase, entries) = match LxMessage::unpack_propagation_wrapper(data) {
Ok(parsed) => parsed,
Err(e) => {
tracing::warn!("failed to unpack propagation wrapper: {e}");
return;
}
};
// Bounded against the configured propagation limit: rejects wrappers
// stuffed with junk entries before any per-entry workblock is built.
let max_transfer_bytes = self.config.propagation_limit_kb.saturating_mul(1024);
let (_remote_timebase, entries) =
match LxMessage::unpack_propagation_wrapper_bounded(data, max_transfer_bytes) {
Ok(parsed) => parsed,
Err(e) => {
tracing::warn!("failed to unpack propagation wrapper: {e}");
return;
}
};
let min_cost = self
.config
@@ -2713,7 +2829,7 @@ pub(crate) async fn main() {
Ok(r) => r,
Err(e) => {
tracing::error!("Failed to initialize LXMF daemon: {e}");
return;
std::process::exit(1);
}
};
@@ -2755,16 +2871,29 @@ pub(crate) async fn main() {
tracing::info!("Waiting for interfaces to come online before announcing...");
let mut announced = false;
for _ in 0..30 {
if shutdown.is_triggered() {
break;
}
let poll_started = Instant::now();
let (otx, orx) = tokio::sync::oneshot::channel();
let _ = runner
.transport_tx
.send(TransportMessage::Rpc {
tokio::select! {
_ = shutdown.wait() => break,
result = runner.transport_tx.send(TransportMessage::Rpc {
query: rns_transport::messages::TransportQuery::GetInterfaceStats,
response_tx: otx,
})
.await;
if let Ok(rns_transport::messages::TransportQueryResponse::InterfaceStats(stats)) =
orx.await
}) => {
if result.is_err() {
break;
}
}
}
let stats_result = tokio::select! {
_ = shutdown.wait() => break,
result = tokio::time::timeout(Duration::from_secs(1), orx) => result,
};
if let Ok(Ok(rns_transport::messages::TransportQueryResponse::InterfaceStats(stats))) =
stats_result
{
let any_online = stats
.iter()
@@ -2781,16 +2910,26 @@ pub(crate) async fn main() {
break;
}
}
tokio::time::sleep(Duration::from_secs(1)).await;
let elapsed = poll_started.elapsed();
if elapsed < Duration::from_secs(1)
&& sleep_or_shutdown(&shutdown, Duration::from_secs(1) - elapsed).await
{
break;
}
}
if !announced {
if shutdown.is_triggered() {
tracing::info!("Startup announce cancelled by shutdown");
} else if !announced {
tracing::warn!("No online interface detected after 30s, announcing anyway");
let _ = runner.send_announce().await;
runner.last_peer_announce = now_f64();
}
}
if daemon_config.node_announce_at_start && daemon_config.propagation_enabled {
if !shutdown.is_triggered()
&& daemon_config.node_announce_at_start
&& daemon_config.propagation_enabled
{
match runner.send_propagation_announce().await {
Ok(()) => {
tracing::info!("Startup propagation announce sent");
@@ -2810,7 +2949,9 @@ pub(crate) async fn main() {
tracing::info!("On-inbound command: {}", cmd);
}
if let Some(ref send_args) = args.send {
if !shutdown.is_triggered()
&& let Some(ref send_args) = args.send
{
let dest_hex = normalize_hash_hex(&send_args[0]);
let content = match args.send_file.as_ref() {
Some(path) => match std::fs::read_to_string(path) {
@@ -2857,7 +2998,10 @@ pub(crate) async fn main() {
if have_key && saw_dest_announce {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
if sleep_or_shutdown(&shutdown, Duration::from_millis(500)).await {
tracing::info!("message send interrupted by shutdown");
return;
}
}
if !have_key {
tracing::warn!(
@@ -2912,7 +3056,10 @@ pub(crate) async fn main() {
runner.refresh_route_hops_from_transport().await;
runner.drain_link_packets();
runner.tick();
tokio::time::sleep(Duration::from_secs(1)).await;
if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await {
tracing::info!("message send interrupted by shutdown");
return;
}
let stats = runner.router.stats();
if stats.pending_outbound == 0 && stats.pending_deferred_stamps == 0 {
@@ -2943,7 +3090,10 @@ pub(crate) async fn main() {
runner.refresh_route_hops_from_transport().await;
runner.drain_link_packets();
runner.tick();
tokio::time::sleep(Duration::from_secs(1)).await;
if sleep_or_shutdown(&shutdown, Duration::from_secs(1)).await {
tracing::info!("message send interrupted by shutdown");
return;
}
if runner
.link_delivery
@@ -2974,7 +3124,9 @@ pub(crate) async fn main() {
std::process::exit(0);
}
tracing::info!("LXMF Daemon running. Press Ctrl+C to stop.");
if !shutdown.is_triggered() {
tracing::info!("LXMF Daemon running. Press Ctrl+C to stop.");
}
// Event-driven for inbound, periodic for outbound and maintenance.
let mut tick_timer = tokio::time::interval(Duration::from_secs(4));
@@ -3020,6 +3172,34 @@ mod tests {
use super::*;
use lxmf_core::constants::DeliveryMethod;
/// Cap eviction prefers entries without a live ratchet, then oldest
/// ratchets; under the cap nothing is touched.
#[test]
fn prune_known_identities_respects_cap_and_recency() {
let mut ids: HashMap<String, [u8; 64]> = HashMap::new();
let mut ratchets: HashMap<String, ReceivedRatchet> = HashMap::new();
for i in 0..KNOWN_IDENTITIES_SOFT_CAP + 10 {
ids.insert(format!("id{i:05}"), [0u8; 64]);
}
// All but 4 of the overflow have ratchets; two ratchets are older.
for (i, key) in ids.keys().cloned().enumerate().collect::<Vec<_>>() {
if i >= 4 {
let mut rr = ReceivedRatchet::new([1u8; 32]);
rr.received_at = if i < 6 { 1.0 } else { 1000.0 };
ratchets.insert(key, rr);
}
}
let dropped = prune_known_identities(&mut ids, &ratchets);
assert_eq!(dropped, 10);
assert_eq!(ids.len(), KNOWN_IDENTITIES_SOFT_CAP);
let mut under: HashMap<String, [u8; 64]> = HashMap::new();
under.insert("only".into(), [0u8; 64]);
assert_eq!(prune_known_identities(&mut under, &ratchets), 0);
assert_eq!(under.len(), 1);
}
#[test]
fn path_request_requeue_sets_path_wait_deadline() {
let mut router = LxmRouter::new(Default::default());
+106
View File
@@ -1,6 +1,10 @@
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::{Child, Stdio};
use std::process::{Command, Output};
#[cfg(unix)]
use std::time::{Duration, Instant};
use std::time::{SystemTime, UNIX_EPOCH};
struct TestDir {
@@ -55,6 +59,20 @@ fn write_rust_identity(path: &Path) {
.expect("write Rust identity");
}
#[cfg(unix)]
fn wait_with_timeout(child: &mut Child, timeout: Duration) -> Option<std::process::ExitStatus> {
let deadline = Instant::now() + timeout;
loop {
if let Some(status) = child.try_wait().expect("poll lxmd-rs child") {
return Some(status);
}
if Instant::now() >= deadline {
return None;
}
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn help_lists_cli_surface_without_starting_runtime() {
let output = lxmd(&["--help"]);
@@ -76,6 +94,94 @@ fn help_lists_cli_surface_without_starting_runtime() {
assert!(text.contains("[possible values: opportunistic, direct, propagated]"));
}
#[cfg(unix)]
#[test]
fn ctrl_c_exits_during_startup_announce_wait() {
let lxmf_dir = TestDir::new("lxmf-ctrlc");
let rns_dir = TestDir::new("rns-ctrlc");
fs::write(
lxmf_dir.path().join("config"),
"\
[lxmf]
display_name = Test
announce_at_start = yes
[propagation]
enable_node = no
",
)
.expect("write LXMF config");
fs::write(
rns_dir.path().join("config"),
"\
[reticulum]
share_instance = No
enable_transport = No
respond_to_probes = No
panic_on_interface_error = No
discover_interfaces = No
[interfaces]
",
)
.expect("write no-interface Reticulum config");
let mut child = Command::new(env!("CARGO_BIN_EXE_lxmd-rs"))
.arg("--config")
.arg(lxmf_dir.path())
.arg("--rnsconfig")
.arg(rns_dir.path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("lxmd-rs subprocess should start");
let identity_path = lxmf_dir.path().join("identity");
let startup_deadline = Instant::now() + Duration::from_secs(5);
while !identity_path.exists() {
if let Some(status) = child.try_wait().expect("poll lxmd-rs startup") {
let output = child.wait_with_output().expect("collect lxmd-rs output");
panic!(
"lxmd-rs exited before startup announce wait ({status}):\n{}",
combined_output(&output)
);
}
assert!(
Instant::now() < startup_deadline,
"lxmd-rs did not reach startup announce wait"
);
std::thread::sleep(Duration::from_millis(50));
}
std::thread::sleep(Duration::from_millis(100));
let signal_status = Command::new("kill")
.arg("-INT")
.arg(child.id().to_string())
.status()
.expect("send SIGINT to lxmd-rs");
assert!(signal_status.success(), "kill -INT should succeed");
if wait_with_timeout(&mut child, Duration::from_secs(3)).is_none() {
let _ = child.kill();
let output = child.wait_with_output().expect("collect lxmd-rs output");
panic!(
"lxmd-rs did not exit after Ctrl+C during startup announce wait:\n{}",
combined_output(&output)
);
}
let output = child.wait_with_output().expect("collect lxmd-rs output");
assert!(
output.status.success(),
"expected clean shutdown after Ctrl+C, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Startup announce cancelled by shutdown"),
"expected startup announce cancellation log, got:\n{}",
combined_output(&output)
);
}
#[test]
fn version_reports_binary_name_and_package_version() {
let output = lxmd(&["--version"]);