mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-27 13:52:18 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
393478019b | ||
|
|
3e048eda1a | ||
|
|
b99c177f01 | ||
|
|
b08de427a9 | ||
|
|
22b1907d4c | ||
|
|
20ef834281 | ||
|
|
68ad7c8351 | ||
|
|
90e44916a4 | ||
|
|
134a17c704 | ||
|
|
89689fbdb4 | ||
|
|
c4f4a04dbb | ||
|
|
68d9d5541f | ||
|
|
1a2acd32f6 | ||
|
|
62f30baa0f | ||
|
|
167e571a3a | ||
|
|
06015ae181 | ||
|
|
9e44e8a407 | ||
|
|
2fc60703ea | ||
|
|
b61724d1f1 | ||
|
|
c7736b9d24 | ||
|
|
19187146c8 | ||
|
|
b41c7ac263 | ||
|
|
8f59b66854 | ||
|
|
5ea513bb95 | ||
|
|
6ac04f0311 | ||
|
|
b790ca91d3 | ||
|
|
511e0a77f1 | ||
|
|
fedba0bdfa | ||
|
|
c0bf58eb52 |
No files matched your search
@@ -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
+31
-51
@@ -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",
|
||||
@@ -1111,6 +1095,7 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-transport",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
@@ -1125,7 +1110,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"rand 0.8.5",
|
||||
@@ -1140,7 +1125,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1156,11 +1141,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 +1167,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1200,7 +1186,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "0.9.4"
|
||||
version = "1.0.1"
|
||||
dependencies = [
|
||||
"rns-crypto",
|
||||
"sha2",
|
||||
@@ -1353,12 +1339,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
@@ -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"
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://github.com/markqvist/LXMF)
|
||||
[](https://github.com/markqvist/LXMF)
|
||||
[](#feature-status)
|
||||
|
||||
[LXMF Reference](https://github.com/markqvist/LXMF) |
|
||||
@@ -264,7 +264,7 @@ Supported sections:
|
||||
| Section | Keys |
|
||||
| --- | --- |
|
||||
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
|
||||
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_ratchets`, `enforce_stamps` |
|
||||
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` |
|
||||
| `[control]` | `auth_required`, `allowed` |
|
||||
| `[logging]` | `loglevel` |
|
||||
|
||||
@@ -307,8 +307,8 @@ application envelopes.
|
||||
|
||||
| Area | Current behavior |
|
||||
| --- | --- |
|
||||
| Message format | Signed LXMF envelopes, custom field maps, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
|
||||
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, and opportunistic-to-direct downgrade. |
|
||||
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
|
||||
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct downgrade, and compression signalling in delivery announces. |
|
||||
| Propagation | Disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
|
||||
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, propagation tickets, and restart-safe ticket persistence. |
|
||||
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
|
||||
|
||||
@@ -9,6 +9,7 @@ pub const FIELD_ICON_APPEARANCE: u8 = 0x04;
|
||||
pub const FIELD_FILE_ATTACHMENTS: u8 = 0x05;
|
||||
pub const FIELD_IMAGE: u8 = 0x06;
|
||||
pub const FIELD_AUDIO: u8 = 0x07;
|
||||
/// Bytes, full thread ID hash.
|
||||
pub const FIELD_THREAD: u8 = 0x08;
|
||||
pub const FIELD_COMMANDS: u8 = 0x09;
|
||||
pub const FIELD_RESULTS: u8 = 0x0A;
|
||||
@@ -17,6 +18,22 @@ pub const FIELD_TICKET: u8 = 0x0C;
|
||||
pub const FIELD_EVENT: u8 = 0x0D;
|
||||
pub const FIELD_RNR_REFS: u8 = 0x0E;
|
||||
pub const FIELD_RENDERER: u8 = 0x0F;
|
||||
/// Bytes, full `LXMessage` hash. Python reference: LXMF.py:23.
|
||||
pub const FIELD_REPLY_TO: u8 = 0x30;
|
||||
/// Bytes, quoted content in UTF-8 encoding. Python reference: LXMF.py:24.
|
||||
pub const FIELD_REPLY_QUOTE: u8 = 0x31;
|
||||
/// Dict keyed by [`REACTION_TO`] / [`REACTION_CONTENT`]. Python reference: LXMF.py:25.
|
||||
pub const FIELD_REACTION: u8 = 0x40;
|
||||
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py:26.
|
||||
pub const FIELD_COMMENT: u8 = 0x41;
|
||||
/// Dict keyed by [`CONTINUATION_OF`]. Python reference: LXMF.py:27.
|
||||
pub const FIELD_CONTINUATION: u8 = 0x42;
|
||||
|
||||
// Unallocated fields between 0x00 and 0x80, both included, should be
|
||||
// considered reserved for future extensibility. For experimental and
|
||||
// unstable features, it is recommended to use fields above 0xFF.
|
||||
// Python reference: LXMF.py:29-32.
|
||||
|
||||
pub const FIELD_CUSTOM_TYPE: u8 = 0xFB;
|
||||
pub const FIELD_CUSTOM_DATA: u8 = 0xFC;
|
||||
pub const FIELD_CUSTOM_META: u8 = 0xFD;
|
||||
@@ -49,6 +66,27 @@ pub const RENDERER_MICRON: u8 = 0x01;
|
||||
pub const RENDERER_MARKDOWN: u8 = 0x02;
|
||||
pub const RENDERER_BBCODE: u8 = 0x03;
|
||||
|
||||
// Clients choose how to handle reaction content, if at all. While reactions
|
||||
// are typically a single unicode emoji or similar, the exact implementation
|
||||
// and sanitization is left up to the client. FIELD_REACTION dict keys —
|
||||
// Python reference: LXMF.py:104-110.
|
||||
/// Bytes, full `LXMessage` hash.
|
||||
pub const REACTION_TO: u8 = 0x00;
|
||||
/// Bytes, the reaction content in UTF-8 encoding.
|
||||
pub const REACTION_CONTENT: u8 = 0x01;
|
||||
|
||||
// Comment content is carried as the normal LXM content, so clients that do
|
||||
// not support comments display them as normal messages. FIELD_COMMENT dict
|
||||
// key — Python reference: LXMF.py:112-118.
|
||||
/// Bytes, full `LXMessage` hash.
|
||||
pub const COMMENT_FOR: u8 = 0x00;
|
||||
|
||||
// Continuation content is carried as the normal LXM content, so clients that
|
||||
// do not support continuations display them as normal messages.
|
||||
// FIELD_CONTINUATION dict key — Python reference: LXMF.py:120-126.
|
||||
/// Bytes, full `LXMessage` hash.
|
||||
pub const CONTINUATION_OF: u8 = 0x00;
|
||||
|
||||
pub const PN_META_VERSION: u8 = 0x00;
|
||||
pub const PN_META_NAME: u8 = 0x01;
|
||||
pub const PN_META_SYNC_STRATUM: u8 = 0x02;
|
||||
@@ -341,4 +379,18 @@ mod tests {
|
||||
assert_eq!(MAX_UNREACHABLE, 14 * 24 * 60 * 60);
|
||||
assert_eq!(SYNC_BACKOFF_STEP, 12 * 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_field_standards_match_python_101() {
|
||||
// LXMF.py:23-27 field allocations plus dict-key constants (LXMF.py:104-126).
|
||||
assert_eq!(FIELD_REPLY_TO, 0x30);
|
||||
assert_eq!(FIELD_REPLY_QUOTE, 0x31);
|
||||
assert_eq!(FIELD_REACTION, 0x40);
|
||||
assert_eq!(FIELD_COMMENT, 0x41);
|
||||
assert_eq!(FIELD_CONTINUATION, 0x42);
|
||||
assert_eq!(REACTION_TO, 0x00);
|
||||
assert_eq!(REACTION_CONTENT, 0x01);
|
||||
assert_eq!(COMMENT_FOR, 0x00);
|
||||
assert_eq!(CONTINUATION_OF, 0x00);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,17 @@ pub enum AnnounceResult {
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
/// Advertised delivery compression support from LXMF delivery-announce app data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompressionSupport {
|
||||
/// No explicit supported-functionality metadata was present or parseable.
|
||||
Unknown,
|
||||
/// A supported-functionality list was present and omitted `SF_COMPRESSION`.
|
||||
Unsupported,
|
||||
/// A supported-functionality list was present and included `SF_COMPRESSION`.
|
||||
Supported,
|
||||
}
|
||||
|
||||
/// Parsed propagation-node announce data.
|
||||
///
|
||||
/// Wire layout is a 7-element msgpack array:
|
||||
@@ -199,11 +210,13 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
parse_pn_announce_data(data).map(|p| p.stamp_cost)
|
||||
}
|
||||
|
||||
/// Encode delivery-announce `app_data` as msgpack `[display_name, stamp_cost]`.
|
||||
/// Encode delivery-announce `app_data` as msgpack
|
||||
/// `[display_name, stamp_cost, supported_functionality]` where the feature
|
||||
/// list advertises [`SF_COMPRESSION`](crate::constants::SF_COMPRESSION).
|
||||
///
|
||||
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
|
||||
///
|
||||
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1000.
|
||||
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1001 (1.0.1).
|
||||
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
|
||||
use rmpv::Value;
|
||||
|
||||
@@ -217,15 +230,18 @@ pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>)
|
||||
_ => Value::Nil,
|
||||
};
|
||||
|
||||
let peer_data = Value::Array(vec![name_val, cost_val]);
|
||||
let supported_functionality =
|
||||
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]);
|
||||
|
||||
let peer_data = Value::Array(vec![name_val, cost_val, supported_functionality]);
|
||||
|
||||
crate::encode_value(&peer_data)
|
||||
}
|
||||
|
||||
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
|
||||
///
|
||||
/// Accepts both Python LXMF 0.9.6's 2-element form and the optional 3-element
|
||||
/// feature-list form used by newer/extended peers.
|
||||
/// Accepts both Python LXMF <=0.9.8's 2-element form and the 3-element
|
||||
/// feature-list form emitted from 1.0.1 (and extended peers).
|
||||
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
|
||||
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
|
||||
let arr = value.as_array()?;
|
||||
@@ -257,27 +273,45 @@ pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
|
||||
parse_announce_app_data(data).and_then(|(_, cost)| cost)
|
||||
}
|
||||
|
||||
/// Parse advertised `SF_COMPRESSION` support in delivery-announce `app_data`.
|
||||
///
|
||||
/// Legacy 2-element app_data, malformed data, and missing feature lists are
|
||||
/// treated as unknown. A present feature list is authoritative.
|
||||
///
|
||||
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
|
||||
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
|
||||
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
|
||||
return CompressionSupport::Unknown;
|
||||
};
|
||||
let Some(arr) = value.as_array() else {
|
||||
return CompressionSupport::Unknown;
|
||||
};
|
||||
if arr.len() < 3 {
|
||||
return CompressionSupport::Unknown;
|
||||
}
|
||||
let Some(features) = arr[2].as_array() else {
|
||||
return CompressionSupport::Unknown;
|
||||
};
|
||||
|
||||
if features
|
||||
.iter()
|
||||
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
|
||||
{
|
||||
CompressionSupport::Supported
|
||||
} else {
|
||||
CompressionSupport::Unsupported
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
|
||||
///
|
||||
/// Returns `false` for legacy 2-element app_data or when the feature list is missing/empty.
|
||||
/// Fail-open like Python: legacy 2-element app_data, malformed data, and
|
||||
/// non-list feature entries all count as supported; only an explicit feature
|
||||
/// list that omits `SF_COMPRESSION` disables compression.
|
||||
///
|
||||
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
|
||||
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
|
||||
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
|
||||
return false;
|
||||
};
|
||||
let Some(arr) = value.as_array() else {
|
||||
return false;
|
||||
};
|
||||
if arr.len() < 3 {
|
||||
return false;
|
||||
}
|
||||
let Some(features) = arr[2].as_array() else {
|
||||
return false;
|
||||
};
|
||||
features
|
||||
.iter()
|
||||
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
|
||||
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
|
||||
}
|
||||
|
||||
/// Extract the advertised name from propagation-node announce data.
|
||||
@@ -422,7 +456,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 +467,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));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -704,6 +741,16 @@ mod tests {
|
||||
assert_eq!(cost, Some(12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_matches_python_101_bytes() {
|
||||
// Python 1.0.1 oracle: msgpack([b"Test", 16, [SF_COMPRESSION]]) — LXMRouter.py:999-1001.
|
||||
assert_eq!(
|
||||
hex::encode(get_announce_app_data(Some("Test"), Some(16))),
|
||||
"93c40454657374109100"
|
||||
);
|
||||
assert_eq!(hex::encode(get_announce_app_data(None, None)), "93c0c09100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delivery_announce_data_no_name() {
|
||||
let packed = get_announce_app_data(None, Some(8));
|
||||
@@ -768,8 +815,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_compression_support_from_app_data() {
|
||||
let python_096 = get_announce_app_data(Some("Alice"), Some(12));
|
||||
assert!(!compression_support_from_app_data(&python_096));
|
||||
// Legacy <=0.9.8 2-element app_data: unknown state, fail-open true
|
||||
// (Python returns True for len < 3 — LXMF.py:161).
|
||||
let python_098 = {
|
||||
use rmpv::Value;
|
||||
let arr = Value::Array(vec![Value::Binary(b"Alice".to_vec()), Value::from(12u64)]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&python_098),
|
||||
CompressionSupport::Unknown
|
||||
);
|
||||
assert!(compression_support_from_app_data(&python_098));
|
||||
|
||||
let supported = {
|
||||
use rmpv::Value;
|
||||
@@ -780,8 +837,30 @@ mod tests {
|
||||
]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&supported),
|
||||
CompressionSupport::Supported
|
||||
);
|
||||
assert!(compression_support_from_app_data(&supported));
|
||||
|
||||
let ratspeak_extended_supported = {
|
||||
use rmpv::Value;
|
||||
let arr = Value::Array(vec![
|
||||
Value::Binary(b"Alice".to_vec()),
|
||||
Value::from(12u64),
|
||||
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]),
|
||||
Value::Map(vec![]),
|
||||
]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&ratspeak_extended_supported),
|
||||
CompressionSupport::Supported
|
||||
);
|
||||
assert!(compression_support_from_app_data(
|
||||
&ratspeak_extended_supported
|
||||
));
|
||||
|
||||
// 3-element form with empty feature list -> unsupported.
|
||||
let empty_features = {
|
||||
use rmpv::Value;
|
||||
@@ -792,7 +871,26 @@ mod tests {
|
||||
]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&empty_features),
|
||||
CompressionSupport::Unsupported
|
||||
);
|
||||
assert!(!compression_support_from_app_data(&empty_features));
|
||||
|
||||
// Malformed data: unknown state, fail-open true (Python treats the
|
||||
// original non-msgpack announce format as supported — LXMF.py:167).
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&[0xc1]),
|
||||
CompressionSupport::Unknown
|
||||
);
|
||||
assert!(compression_support_from_app_data(&[0xc1]));
|
||||
|
||||
// Our own 1.0.1 emission round-trips as explicitly supported.
|
||||
let own = get_announce_app_data(Some("Alice"), Some(12));
|
||||
assert_eq!(
|
||||
compression_support_state_from_app_data(&own),
|
||||
CompressionSupport::Supported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -936,7 +1034,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 +1077,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 +1103,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());
|
||||
|
||||
@@ -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;
|
||||
|
||||
+158
-21
@@ -112,6 +112,14 @@ pub struct LxMessage {
|
||||
pub wire_payload: Option<Vec<u8>>,
|
||||
pub transport_encryption: Option<String>,
|
||||
pub incoming: bool,
|
||||
/// True when the source identity is blackholed at the transport layer.
|
||||
///
|
||||
/// Python sets this during `unpack_from_bytes` via `Reticulum.is_blackholed`
|
||||
/// (LXMessage.py:172, 803-805); `LXMRouter.lxmf_delivery` then drops such
|
||||
/// messages before processing (LXMRouter.py:1739-1741). Rust unpacking has
|
||||
/// no transport access, so embedders set it from the blackhole query
|
||||
/// surface before processing.
|
||||
pub source_blackholed: bool,
|
||||
/// Delivery progress in `0.0..=1.0`.
|
||||
pub progress: f64,
|
||||
/// Whether the direct-delivery resource should be bz2-compressed by the RNS layer.
|
||||
@@ -169,6 +177,7 @@ impl LxMessage {
|
||||
transport_encryption: None,
|
||||
wire_payload: None,
|
||||
incoming: false,
|
||||
source_blackholed: false,
|
||||
progress: 0.0,
|
||||
auto_compress: true,
|
||||
callbacks: MessageCallbacks::default(),
|
||||
@@ -177,12 +186,14 @@ impl LxMessage {
|
||||
|
||||
/// Update [`auto_compress`](Self::auto_compress) based on a peer's cached announce app_data.
|
||||
///
|
||||
/// Matches Python `LXMessage.determine_compression_support` — LXMessage.py:507-514.
|
||||
/// Legacy (pre-0.9.6) peers that omit the feature list will have compression disabled.
|
||||
/// Matches Python `LXMessage.determine_compression_support` — LXMessage.py:510-513.
|
||||
/// Fail-open: no cached app_data and legacy peers without a feature list
|
||||
/// default to compression enabled; only an explicit feature list omitting
|
||||
/// `SF_COMPRESSION` disables it.
|
||||
pub fn determine_compression_support(&mut self, peer_app_data: Option<&[u8]>) {
|
||||
self.auto_compress = peer_app_data
|
||||
.map(crate::handlers::compression_support_from_app_data)
|
||||
.unwrap_or(false);
|
||||
.unwrap_or(true);
|
||||
}
|
||||
|
||||
/// Register a callback fired when this message transitions to `Delivered`.
|
||||
@@ -383,7 +394,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 +408,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 +450,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
|
||||
@@ -499,6 +558,7 @@ impl LxMessage {
|
||||
transport_encryption: None,
|
||||
wire_payload: Some(payload_data.to_vec()),
|
||||
incoming: true,
|
||||
source_blackholed: false,
|
||||
progress: 0.0,
|
||||
auto_compress: true,
|
||||
callbacks: MessageCallbacks::default(),
|
||||
@@ -785,15 +845,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 +873,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;
|
||||
}
|
||||
|
||||
@@ -994,13 +1052,20 @@ impl LxMessage {
|
||||
}
|
||||
|
||||
/// Write the message to `directory_path`, named by the message hash.
|
||||
///
|
||||
/// Writes are atomic (unique tmp file + fsync + rename) so concurrent
|
||||
/// readers never observe a partial file — Python `write_to_directory`,
|
||||
/// LXMessage.py:674-696 (1.0.1). Python additionally serializes the write
|
||||
/// under a per-message persist lock; in Rust concurrent persists of one
|
||||
/// message are already exclusive-borrow serialized or hit unique tmp
|
||||
/// files, with the rename as the atomic last-writer-wins step.
|
||||
pub fn write_to_directory(&self, directory_path: &str) -> Result<String, MessageError> {
|
||||
let hash = self.hash.ok_or(MessageError::NotSigned)?;
|
||||
let file_name = rns_crypto::hex_encode(&hash);
|
||||
let file_path = format!("{directory_path}/{file_name}");
|
||||
|
||||
let container_data = self.pack_container()?;
|
||||
std::fs::write(&file_path, container_data)
|
||||
crate::persist::write_file_atomic(std::path::Path::new(&file_path), &container_data)
|
||||
.map_err(|e| MessageError::PackFailed(format!("write failed: {e}")))?;
|
||||
|
||||
Ok(file_path)
|
||||
@@ -1454,15 +1519,54 @@ mod tests {
|
||||
msg.determine_compression_support(Some(&supported));
|
||||
assert!(msg.auto_compress);
|
||||
|
||||
// Python LXMF 0.9.6 2-element announce has no feature list.
|
||||
let python_096 = crate::handlers::get_announce_app_data(Some("Peer"), Some(8));
|
||||
msg.determine_compression_support(Some(&python_096));
|
||||
// Explicit feature list omitting SF_COMPRESSION disables compression.
|
||||
let no_compression = {
|
||||
use rmpv::Value;
|
||||
let arr = Value::Array(vec![
|
||||
Value::Binary(b"Peer".to_vec()),
|
||||
Value::from(8u64),
|
||||
Value::Array(vec![]),
|
||||
]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
msg.determine_compression_support(Some(&no_compression));
|
||||
assert!(!msg.auto_compress);
|
||||
|
||||
// No peer data at all — auto_compress off (no announce == unknown).
|
||||
msg.auto_compress = true;
|
||||
// Legacy <=0.9.8 2-element announce has no feature list — fail-open
|
||||
// (Python compression_support_from_app_data returns True, LXMF.py:160).
|
||||
let python_098 = {
|
||||
use rmpv::Value;
|
||||
let arr = Value::Array(vec![Value::Binary(b"Peer".to_vec()), Value::from(8u64)]);
|
||||
crate::encode_value(&arr)
|
||||
};
|
||||
msg.determine_compression_support(Some(&python_098));
|
||||
assert!(msg.auto_compress);
|
||||
|
||||
// No peer data at all — defaults to compression on (LXMessage.py:513).
|
||||
msg.auto_compress = false;
|
||||
msg.determine_compression_support(None);
|
||||
assert!(!msg.auto_compress);
|
||||
assert!(msg.auto_compress);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_source_blackholed_defaults_false() {
|
||||
// LXMessage.py:172 — source_blackholed initialises false; embedders
|
||||
// flip it from the transport blackhole tables after unpacking.
|
||||
let msg = LxMessage::new([0xAA; 16], [0xBB; 16], "t", "c", DeliveryMethod::Direct);
|
||||
assert!(!msg.source_blackholed);
|
||||
|
||||
let mut outbound = LxMessage::new(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"Title",
|
||||
"Content",
|
||||
DeliveryMethod::Direct,
|
||||
);
|
||||
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
|
||||
outbound.sign(&key).unwrap();
|
||||
let packed = outbound.pack().unwrap();
|
||||
let unpacked = LxMessage::unpack(&packed).unwrap();
|
||||
assert!(!unpacked.source_blackholed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2050,6 +2154,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();
|
||||
|
||||
@@ -130,10 +130,13 @@ impl LxmPeer {
|
||||
peer
|
||||
}
|
||||
|
||||
/// Effective minimum stamp cost this peer will accept.
|
||||
/// Effective minimum stamp cost this peer will accept, using the peer's
|
||||
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
|
||||
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
|
||||
match self.stamp_cost {
|
||||
Some(cost) => cost.saturating_sub(PROPAGATION_COST_FLEX),
|
||||
Some(cost) => {
|
||||
cost.saturating_sub(self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX))
|
||||
}
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
@@ -291,18 +294,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,6 +468,27 @@ mod tests {
|
||||
// cost < flex must saturate at 0.
|
||||
peer.stamp_cost = Some(2);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
|
||||
|
||||
// Announced flexibility overrides the default.
|
||||
peer.stamp_cost = Some(16);
|
||||
peer.stamp_cost_flexibility = Some(5);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 11);
|
||||
peer.stamp_cost_flexibility = Some(0);
|
||||
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -24,6 +24,54 @@ pub const TICKETS_FILE: &str = "available_tickets";
|
||||
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
|
||||
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
|
||||
|
||||
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
|
||||
///
|
||||
/// Tmp name is `<path>.tmp.<pid>.<16 random hex>` so concurrent writers (or
|
||||
/// other processes) never collide; the tmp file is unlinked on error. An fsync
|
||||
/// failure is logged as a warning and is non-fatal, matching Python
|
||||
/// `LXMessage.write_to_directory` — LXMessage.py:674-696 (1.0.1).
|
||||
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
|
||||
let random: [u8; 8] = rand::random();
|
||||
let tmp_name = format!(
|
||||
"{}.tmp.{}.{}",
|
||||
path.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default(),
|
||||
std::process::id(),
|
||||
hex::encode(random)
|
||||
);
|
||||
let tmp = path.with_file_name(tmp_name);
|
||||
|
||||
let result = (|| {
|
||||
let mut file = fs::File::create(&tmp)?;
|
||||
file.write_all(data)?;
|
||||
file.flush()?;
|
||||
if let Err(e) = file.sync_all() {
|
||||
tracing::warn!(
|
||||
"Error while waiting for persist fsync for {}: {e}",
|
||||
tmp.display()
|
||||
);
|
||||
}
|
||||
drop(file);
|
||||
fs::rename(&tmp, path)
|
||||
})();
|
||||
|
||||
if result.is_err()
|
||||
&& tmp.exists()
|
||||
&& let Err(e) = fs::remove_file(&tmp)
|
||||
{
|
||||
tracing::error!(
|
||||
"Error while cleaning temporary file {} for {}: {e}",
|
||||
tmp.display(),
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
|
||||
let bytes =
|
||||
rmp_serde::to_vec(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
@@ -137,4 +185,42 @@ mod tests {
|
||||
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_file_atomic_writes_and_replaces_without_leftover_tmp() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("message");
|
||||
|
||||
write_file_atomic(&path, b"first").unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"first");
|
||||
|
||||
// Replaces existing content (os.replace semantics — LXMessage.py:687).
|
||||
write_file_atomic(&path, b"second").unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"second");
|
||||
|
||||
// No .tmp.* residue in the directory after successful writes.
|
||||
let leftovers: Vec<_> = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_file_atomic_cleans_tmp_on_error() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
// Destination is a directory: the final rename fails, and the tmp
|
||||
// file must be unlinked (LXMessage.py:691-693).
|
||||
let dir_path = tmp.path().join("collide");
|
||||
fs::create_dir(&dir_path).unwrap();
|
||||
|
||||
assert!(write_file_atomic(&dir_path, b"data").is_err());
|
||||
let leftovers: Vec<_> = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
+289
-58
@@ -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,10 +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,
|
||||
pub auth_required: bool,
|
||||
/// Generate outbound message PoW stamps through the router deferred-stamp queue.
|
||||
@@ -71,9 +67,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,
|
||||
auth_required: false,
|
||||
defer_stamp_generation: true,
|
||||
@@ -267,6 +260,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 +287,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 +333,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 +350,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 +457,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 +494,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());
|
||||
@@ -664,9 +695,9 @@ impl LxmRouter {
|
||||
.add(Ticket::new(token, destination_hash, expires));
|
||||
}
|
||||
|
||||
/// Returns the token of the most-recently-added valid ticket for `destination_hash`.
|
||||
/// Returns the token of the first valid ticket for `destination_hash`.
|
||||
///
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket` — LXMRouter.py:1115-1123.
|
||||
/// Python reference: `LXMRouter.get_outbound_ticket` — LXMRouter.py:1058-1064.
|
||||
pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> {
|
||||
let now = now_f64();
|
||||
self.ticket_store
|
||||
@@ -856,18 +887,23 @@ 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)?);
|
||||
// Python cleans tickets and stamp costs at load (LXMRouter.py:258-284).
|
||||
let now = now_f64();
|
||||
self.ticket_store.cull(now);
|
||||
self.outbound_stamp_costs
|
||||
.retain(|_, e| now - e.recorded_at < STAMP_COST_EXPIRY as f64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -875,29 +911,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 +967,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;
|
||||
}
|
||||
@@ -1080,14 +1107,6 @@ impl LxmRouter {
|
||||
self.config.propagation_stamp_flex = flex;
|
||||
}
|
||||
|
||||
pub fn set_enforce_ratchets(&mut self, enforce: bool) {
|
||||
self.config.ext.enforce_ratchets = enforce;
|
||||
}
|
||||
|
||||
pub fn set_enforce_stamps(&mut self, enforce: bool) {
|
||||
self.config.ext.enforce_stamps = enforce;
|
||||
}
|
||||
|
||||
/// Build propagation-node announce app_data (msgpack).
|
||||
///
|
||||
/// Python reference: LXMRouter.get_propagation_node_app_data — LXMRouter.py:306-318.
|
||||
@@ -1147,7 +1166,10 @@ impl LxmRouter {
|
||||
destination_hash: &[u8; 16],
|
||||
) -> bool {
|
||||
let now = now_f64();
|
||||
if let Some(ticket) = self.ticket_store.find(destination_hash, now) {
|
||||
for ticket in self.ticket_store.all() {
|
||||
if &ticket.destination_hash != destination_hash || !ticket.is_valid(now) {
|
||||
continue;
|
||||
}
|
||||
let mut material = Vec::with_capacity(16 + 32);
|
||||
material.extend_from_slice(&ticket.token);
|
||||
material.extend_from_slice(message_id);
|
||||
@@ -1718,10 +1740,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 +1864,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 +1888,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,9 +1937,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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2233,6 +2301,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();
|
||||
@@ -2297,6 +2434,24 @@ mod tests {
|
||||
assert_eq!(router.get_inbound_tickets().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_stamp_checks_all_tickets() {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
let dest = [0xAA; 16];
|
||||
let expires = now_f64() + 1000.0;
|
||||
router.remember_ticket(dest, [0x01; 16], expires);
|
||||
router.remember_ticket(dest, [0x02; 16], expires);
|
||||
|
||||
// Stamp derived from the SECOND ticket must still validate.
|
||||
let message_id = [0x33u8; 32];
|
||||
let mut material = Vec::with_capacity(16 + 32);
|
||||
material.extend_from_slice(&[0x02; 16]);
|
||||
material.extend_from_slice(&message_id);
|
||||
let stamp = rns_crypto::sha::truncated_hash(&material);
|
||||
|
||||
assert!(router.validate_stamp_with_tickets(&message_id, stamp.as_ref(), 16, &dest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cancel_outbound() {
|
||||
let mut router = LxmRouter::new(RouterConfig::default());
|
||||
@@ -2399,6 +2554,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 +3236,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
@@ -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(¤t);
|
||||
}
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! LXMF Ticket system: bypass PoW with pre-shared 16-byte tokens.
|
||||
//!
|
||||
//! Trusted peers may exchange tickets that bypass stamp requirements for a
|
||||
//! fixed expiry window. Tickets are single-use and renewable before expiry.
|
||||
//! fixed expiry window. Tickets are reusable until expiry and renewed once
|
||||
//! within `TICKET_RENEW` of expiring.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -33,10 +34,6 @@ impl Ticket {
|
||||
pub fn should_renew(&self, now: f64) -> bool {
|
||||
self.is_valid(now) && (self.expires - now) < TICKET_RENEW as f64
|
||||
}
|
||||
|
||||
pub fn use_ticket(&mut self) {
|
||||
self.used = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -59,17 +56,6 @@ impl TicketStore {
|
||||
.find(|t| &t.destination_hash == destination_hash && t.is_valid(now))
|
||||
}
|
||||
|
||||
/// Find and mark a ticket as used. Returns the token on success.
|
||||
pub fn use_for(&mut self, destination_hash: &[u8; 16], now: f64) -> Option<[u8; 16]> {
|
||||
for ticket in &mut self.tickets {
|
||||
if &ticket.destination_hash == destination_hash && ticket.is_valid(now) {
|
||||
ticket.use_ticket();
|
||||
return Some(ticket.token);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Drop expired and used tickets (past TICKET_GRACE).
|
||||
pub fn cull(&mut self, now: f64) {
|
||||
self.tickets
|
||||
@@ -104,9 +90,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_ticket_used() {
|
||||
// `used` survives only for persisted-state compat; is_valid must
|
||||
// still reject such entries.
|
||||
let mut ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
|
||||
assert!(ticket.is_valid(500.0));
|
||||
ticket.use_ticket();
|
||||
ticket.used = true;
|
||||
assert!(!ticket.is_valid(500.0));
|
||||
}
|
||||
|
||||
@@ -135,20 +123,6 @@ mod tests {
|
||||
assert!(found.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ticket_store_use() {
|
||||
let mut store = TicketStore::new();
|
||||
let dest = [0xBB; 16];
|
||||
|
||||
store.add(Ticket::new([0x01; 16], dest, 1000.0));
|
||||
|
||||
let token = store.use_for(&dest, 500.0);
|
||||
assert_eq!(token, Some([0x01; 16]));
|
||||
|
||||
let token = store.use_for(&dest, 500.0);
|
||||
assert!(token.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ticket_store_cull() {
|
||||
let mut store = TicketStore::new();
|
||||
|
||||
@@ -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,68 @@ 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;
|
||||
|
||||
/// Resolve a destination hash to its identity hash via the learned identity
|
||||
/// keys — the lxmd equivalent of `RNS.Identity.recall` (LXMessage.py:776).
|
||||
/// Identity hash = truncated hash of the 64-byte announce public key.
|
||||
fn recall_identity_hash(
|
||||
known_identities: &HashMap<String, [u8; 64]>,
|
||||
dest_hash: &[u8; 16],
|
||||
) -> Option<[u8; 16]> {
|
||||
known_identities
|
||||
.get(&hex::encode(dest_hash))
|
||||
.map(|pub_key| rns_crypto::sha::truncated_hash(pub_key))
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -402,6 +472,9 @@ struct LxmdRunner {
|
||||
received_ratchets: HashMap<String, ReceivedRatchet>,
|
||||
known_identities: HashMap<String, [u8; 64]>,
|
||||
route_hops: HashMap<[u8; 16], u8>,
|
||||
/// Transport blackhole table snapshot, refreshed per tick. Used to drop
|
||||
/// inbound LXMs from blackholed identities (LXMRouter.py:1739-1741).
|
||||
blackholed_identities: HashSet<[u8; 16]>,
|
||||
link_delivery: Option<lxmf_core::link_delivery::LinkDeliveryManager>,
|
||||
link_command_tx: mpsc::Sender<rns_runtime::link_manager::LinkManagerCommand>,
|
||||
link_identified_rx: mpsc::Receiver<([u8; 16], [u8; 16])>,
|
||||
@@ -430,6 +503,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 +638,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 +710,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 +736,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 +753,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 +804,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 =
|
||||
@@ -853,6 +939,7 @@ impl LxmdRunner {
|
||||
received_ratchets,
|
||||
known_identities,
|
||||
route_hops: HashMap::new(),
|
||||
blackholed_identities: HashSet::new(),
|
||||
link_delivery: None,
|
||||
link_command_tx,
|
||||
link_identified_rx,
|
||||
@@ -876,6 +963,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,
|
||||
@@ -960,13 +1048,6 @@ impl LxmdRunner {
|
||||
self.router.set_stamp_cost(self.lxmf_dest_hash, cost);
|
||||
}
|
||||
|
||||
if self.config.enforce_ratchets {
|
||||
self.router.set_enforce_ratchets(true);
|
||||
}
|
||||
if self.config.enforce_stamps {
|
||||
self.router.set_enforce_stamps(true);
|
||||
}
|
||||
|
||||
for configured in &self.config.control_allowed {
|
||||
match parse_destination_hash(configured) {
|
||||
Ok(hash) => self.router.allow_control(hash),
|
||||
@@ -1343,7 +1424,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 +1449,50 @@ 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;
|
||||
}
|
||||
|
||||
/// Snapshot the transport blackhole table. Ungated: the table is tiny and
|
||||
/// the per-tick roundtrip keeps drops close to Python's live
|
||||
/// `Reticulum.is_blackholed` query (LXMessage.py:803-805). Fail-open: on
|
||||
/// query failure the previous snapshot stays in effect.
|
||||
async fn refresh_blackholed_identities_from_transport(&mut self) {
|
||||
let (response_tx, response_rx) = tokio::sync::oneshot::channel();
|
||||
if let Err(e) = self.transport_tx.try_send(TransportMessage::Rpc {
|
||||
query: TransportQuery::GetBlackholedIdentities,
|
||||
response_tx,
|
||||
}) {
|
||||
tracing::warn!(error = %e, "could not determine message source blackhole status");
|
||||
return;
|
||||
}
|
||||
|
||||
let Ok(Ok(TransportQueryResponse::BlackholeList(entries))) =
|
||||
tokio::time::timeout(Duration::from_millis(100), response_rx).await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.blackholed_identities = entries.into_iter().map(|e| e.identity_hash).collect();
|
||||
}
|
||||
|
||||
/// True when the source destination resolves to a blackholed identity.
|
||||
/// Unknown identities are never dropped, mirroring Python's recall-gated
|
||||
/// check (LXMessage.py:804 only runs with a recalled source identity).
|
||||
fn source_blackholed(&self, source_hash: &[u8; 16]) -> bool {
|
||||
match recall_identity_hash(&self.known_identities, source_hash) {
|
||||
Some(identity_hash) => self.blackholed_identities.contains(&identity_hash),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self) {
|
||||
@@ -1374,44 +1502,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 +1645,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 +1669,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 +1692,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 +1753,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
|
||||
@@ -1682,13 +1836,22 @@ impl LxmdRunner {
|
||||
};
|
||||
|
||||
match LxMessage::unpack(&unpack_data) {
|
||||
Ok(msg) => {
|
||||
Ok(mut msg) => {
|
||||
tracing::info!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
title = %msg.title,
|
||||
len = msg.content.len(),
|
||||
"inbound LXMF message via link"
|
||||
);
|
||||
msg.source_blackholed = self.source_blackholed(&msg.source_hash);
|
||||
if msg.source_blackholed {
|
||||
// LXMRouter.py:1739-1741.
|
||||
tracing::debug!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
"Dropping LXM from blackholed identity"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if self.should_reject_for_stamp(&msg) {
|
||||
return;
|
||||
}
|
||||
@@ -1706,13 +1869,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
|
||||
@@ -1768,6 +1935,19 @@ impl LxmdRunner {
|
||||
len = msg.content.len(),
|
||||
"propagation: downloaded message"
|
||||
);
|
||||
msg.source_blackholed = self.source_blackholed(&msg.source_hash);
|
||||
if msg.source_blackholed {
|
||||
// LXMRouter.py:1739-1741.
|
||||
tracing::debug!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
"Dropping LXM from blackholed identity"
|
||||
);
|
||||
return;
|
||||
}
|
||||
// LXMRouter.py:1773-1775: enforcement covers propagated deliveries too.
|
||||
if self.should_reject_for_stamp(&msg) {
|
||||
return;
|
||||
}
|
||||
self.handle_inbound_message(msg);
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -1810,7 +1990,7 @@ impl LxmdRunner {
|
||||
};
|
||||
|
||||
match LxMessage::unpack(&unpack_data) {
|
||||
Ok(msg) => {
|
||||
Ok(mut msg) => {
|
||||
tracing::info!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
title = %msg.title,
|
||||
@@ -1818,6 +1998,16 @@ impl LxmdRunner {
|
||||
"inbound LXMF message received"
|
||||
);
|
||||
|
||||
msg.source_blackholed = self.source_blackholed(&msg.source_hash);
|
||||
if msg.source_blackholed {
|
||||
// LXMRouter.py:1739-1741.
|
||||
tracing::debug!(
|
||||
from = %hex::encode(msg.source_hash),
|
||||
"Dropping LXM from blackholed identity"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Reject on stamp failure BEFORE sending the delivery proof.
|
||||
if self.should_reject_for_stamp(&msg) {
|
||||
return;
|
||||
@@ -1913,12 +2103,13 @@ impl LxmdRunner {
|
||||
|
||||
// Pack synchronously (CPU-bound, no IO) and offload the disk write
|
||||
// to the blocking pool so a slow disk doesn't stall the lxmd runner
|
||||
// task between inbound messages.
|
||||
// task between inbound messages. Atomic tmp+rename write so readers
|
||||
// never see a partial file (LXMessage.py:674-696).
|
||||
match msg.pack() {
|
||||
Ok(packed) => {
|
||||
let write_path = msg_path.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Err(e) = std::fs::write(&write_path, &packed) {
|
||||
if let Err(e) = lxmf_core::persist::write_file_atomic(&write_path, &packed) {
|
||||
tracing::error!("failed to write message to {}: {e}", write_path.display());
|
||||
} else {
|
||||
tracing::info!("message saved to {}", write_path.display());
|
||||
@@ -2713,7 +2904,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 +2946,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 +2985,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 +3024,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 +3073,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 +3131,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 +3165,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 +3199,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));
|
||||
@@ -2985,6 +3212,7 @@ pub(crate) async fn main() {
|
||||
_ = tick_timer.tick() => {
|
||||
runner.drain_announce_events();
|
||||
runner.refresh_route_hops_from_transport().await;
|
||||
runner.refresh_blackholed_identities_from_transport().await;
|
||||
runner.drain_link_packets();
|
||||
runner.tick();
|
||||
}
|
||||
@@ -3020,6 +3248,60 @@ mod tests {
|
||||
use super::*;
|
||||
use lxmf_core::constants::DeliveryMethod;
|
||||
|
||||
/// Blackhole gating mirrors LXMessage.py:804: only a recallable source
|
||||
/// identity can be matched against the blackhole table; unknown sources
|
||||
/// never drop.
|
||||
#[test]
|
||||
fn recall_identity_hash_resolves_known_destinations_only() {
|
||||
let identity = Identity::new();
|
||||
let dest_hash =
|
||||
Destination::hash_from_name_and_identity(LXMF_APP_NAME, Some(&identity.hash));
|
||||
let pub_key = identity.get_public_key();
|
||||
|
||||
let mut known: HashMap<String, [u8; 64]> = HashMap::new();
|
||||
assert_eq!(recall_identity_hash(&known, &dest_hash), None);
|
||||
|
||||
known.insert(hex::encode(dest_hash), pub_key);
|
||||
assert_eq!(
|
||||
recall_identity_hash(&known, &dest_hash),
|
||||
Some(identity.hash)
|
||||
);
|
||||
|
||||
let mut blackholed: HashSet<[u8; 16]> = HashSet::new();
|
||||
blackholed.insert(identity.hash);
|
||||
let resolved = recall_identity_hash(&known, &dest_hash).unwrap();
|
||||
assert!(blackholed.contains(&resolved));
|
||||
assert_eq!(recall_identity_hash(&known, &[0xEE; 16]), None);
|
||||
}
|
||||
|
||||
/// 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());
|
||||
@@ -3180,6 +3462,60 @@ mod tests {
|
||||
assert_eq!(snapshot.hops, 5);
|
||||
}
|
||||
|
||||
/// Pins LXMRouter.py:1773-1775: stamp enforcement covers PROPAGATED
|
||||
/// deliveries, not just link-delivered messages.
|
||||
#[tokio::test]
|
||||
async fn propagation_downloaded_data_respects_stamp_enforcement() {
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let temp = std::env::temp_dir().join(format!(
|
||||
"lxmd-prop-stamp-gate-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
|
||||
let config = DaemonConfig {
|
||||
enforce_stamps: true,
|
||||
stamp_cost: Some(8),
|
||||
..Default::default()
|
||||
};
|
||||
let mut runner = LxmdRunner::new(config, &temp, tx).expect("runner");
|
||||
|
||||
let dest = [0xAB; 16];
|
||||
assert_ne!(dest, runner.lxmf_dest_hash);
|
||||
let mut msg = LxMessage::new(dest, [0xCD; 16], "t", "hello", DeliveryMethod::Propagated);
|
||||
msg.signature = Some([0u8; 64]);
|
||||
let data = msg.pack().expect("pack");
|
||||
let hash = LxMessage::unpack(&data)
|
||||
.expect("unpack")
|
||||
.hash
|
||||
.expect("hash");
|
||||
let msg_path = runner
|
||||
.messages_dir
|
||||
.join(format!("{}.lxm", hex::encode(hash)));
|
||||
|
||||
runner.handle_propagation_downloaded_data(&data);
|
||||
// Grace period: an (incorrectly) accepted message would be written on the blocking pool.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
assert!(
|
||||
!msg_path.exists(),
|
||||
"unstamped propagated message must be rejected"
|
||||
);
|
||||
|
||||
runner.config.enforce_stamps = false;
|
||||
runner.handle_propagation_downloaded_data(&data);
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while !msg_path.exists() && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(
|
||||
msg_path.exists(),
|
||||
"message must be stored once enforcement is off"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&temp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_reusable_link_state_uses_registered_backchannel() {
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
|
||||
@@ -161,7 +161,6 @@ pub struct DaemonConfig {
|
||||
pub control_allowed: Vec<String>,
|
||||
pub static_peers: Vec<String>,
|
||||
pub prioritise_destinations: Vec<String>,
|
||||
pub enforce_ratchets: bool,
|
||||
pub enforce_stamps: bool,
|
||||
pub message_storage_limit: Option<usize>,
|
||||
pub from_static_only: bool,
|
||||
@@ -196,7 +195,6 @@ impl Default for DaemonConfig {
|
||||
control_allowed: Vec::new(),
|
||||
static_peers: Vec::new(),
|
||||
prioritise_destinations: Vec::new(),
|
||||
enforce_ratchets: false,
|
||||
enforce_stamps: false,
|
||||
message_storage_limit: Some(500_000_000),
|
||||
from_static_only: false,
|
||||
@@ -221,8 +219,6 @@ impl DaemonConfig {
|
||||
autopeer_maxdepth: self.autopeer_maxdepth,
|
||||
peering_cost: self.peering_cost,
|
||||
max_peering_cost: self.max_peering_cost,
|
||||
enforce_ratchets: self.enforce_ratchets,
|
||||
enforce_stamps: self.enforce_stamps,
|
||||
auth_required: self.auth_required,
|
||||
message_storage_limit: self.message_storage_limit,
|
||||
name: self.node_name.clone(),
|
||||
@@ -301,7 +297,6 @@ impl DaemonConfig {
|
||||
{
|
||||
dc.propagation_limit_kb = limit as usize;
|
||||
}
|
||||
dc.enforce_ratchets = sec.get_bool_or("enforce_ratchets", false);
|
||||
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
|
||||
}
|
||||
|
||||
@@ -654,4 +649,18 @@ propagation_stamp_cost = 19
|
||||
assert_eq!(dc.propagation_stamp_cost, 19);
|
||||
assert_eq!(dc.to_router_config().propagation_stamp_cost, 19);
|
||||
}
|
||||
|
||||
/// Python lxmd exposes no enforce_ratchets option; the key must parse as a no-op.
|
||||
#[test]
|
||||
fn test_enforce_ratchets_key_ignored_matching_python_lxmd() {
|
||||
let input = r#"
|
||||
[propagation]
|
||||
enforce_ratchets = yes
|
||||
enforce_stamps = yes
|
||||
"#;
|
||||
let config = rns_runtime::config::Config::parse(input).unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
|
||||
assert!(dc.enforce_stamps);
|
||||
}
|
||||
}
|
||||
@@ -445,13 +445,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn delivery_announce_app_data_matches_python_msgpack() {
|
||||
// Python 1.0.1: msgpack([display_name, stamp_cost, [SF_COMPRESSION]])
|
||||
// — LXMRouter.py:999-1001.
|
||||
assert_eq!(
|
||||
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
|
||||
"92c4045465737410"
|
||||
"93c40454657374109100"
|
||||
);
|
||||
assert_eq!(
|
||||
hex::encode(delivery_announce_app_data(None, None)),
|
||||
"92c0c0"
|
||||
"93c0c09100"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
Reference in new issue
Block a user