mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-27 13:52:18 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0bd1ef82f | ||
|
|
a1c3a29603 | ||
|
|
830db46735 | ||
|
|
b4c2e09ca6 | ||
|
|
7dfe9c18bd | ||
|
|
4350dd1a88 | ||
|
|
e38bab9d16 | ||
|
|
115c9dd17c | ||
|
|
3070484a5f | ||
|
|
c52c0a254f | ||
|
|
42e3907835 | ||
|
|
5c37690bd6 | ||
|
|
703942ecf5 | ||
|
|
d22fa362fa | ||
|
|
b47a2d29b9 | ||
|
|
bd9d51b6b7 | ||
|
|
356ba6a305 | ||
|
|
3a17ca6845 | ||
|
|
e55074595c | ||
|
|
e0257d6fd6 | ||
|
|
663bfb6066 | ||
|
|
68f84ce0a6 | ||
|
|
93f4257068 | ||
|
|
90606fdb3f | ||
|
|
393478019b | ||
|
|
3e048eda1a | ||
|
|
b99c177f01 | ||
|
|
b08de427a9 | ||
|
|
22b1907d4c | ||
|
|
20ef834281 | ||
|
|
68ad7c8351 | ||
|
|
90e44916a4 | ||
|
|
134a17c704 | ||
|
|
89689fbdb4 | ||
|
|
c4f4a04dbb | ||
|
|
68d9d5541f | ||
|
|
1a2acd32f6 | ||
|
|
62f30baa0f | ||
|
|
167e571a3a | ||
|
|
06015ae181 | ||
|
|
9e44e8a407 | ||
|
|
2fc60703ea | ||
|
|
b61724d1f1 | ||
|
|
c7736b9d24 | ||
|
|
19187146c8 | ||
|
|
b41c7ac263 | ||
|
|
8f59b66854 | ||
|
|
5ea513bb95 |
No files matched your search
@@ -62,3 +62,8 @@ jobs:
|
||||
working-directory: rsLXMF
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
working-directory: rsLXMF
|
||||
- name: Check public API documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
run: cargo doc --workspace --no-deps
|
||||
working-directory: rsLXMF
|
||||
@@ -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.1.0
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
- Added bounded propagation-node admission, exact inbound Resource ownership,
|
||||
asynchronous validation, and peer-specific throttling.
|
||||
- Completed live peer offer preparation, encrypted Resource synchronization,
|
||||
cancellation, and proof-gated convergence.
|
||||
- Added public inbound Resource tracking and cancellation plus restart-safe
|
||||
persistence and packet/Resource deduplication.
|
||||
- Unified safe name presentation and authoritative propagation transfer
|
||||
status, including restart protection.
|
||||
- Aligned `lxmd-rs` delivery and stamp defaults with the proven Python LXMF
|
||||
compatibility target.
|
||||
Generated
+40
-10
@@ -643,13 +643,14 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "lxmf-core"
|
||||
version = "0.9.2"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"hex",
|
||||
"proptest",
|
||||
"rand 0.8.5",
|
||||
"rmp",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"rns-crypto",
|
||||
@@ -664,11 +665,12 @@ dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lxmf-tools"
|
||||
version = "0.9.2"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -1049,7 +1051,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1067,7 +1069,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"rand 0.8.5",
|
||||
@@ -1076,25 +1078,29 @@ dependencies = [
|
||||
"rns-crypto",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
"if-addrs",
|
||||
"jni",
|
||||
"libc",
|
||||
"md-5",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-transport",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
@@ -1109,7 +1115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"rand 0.8.5",
|
||||
@@ -1124,7 +1130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1140,7 +1146,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1166,7 +1172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1185,7 +1191,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "0.9.4"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"rns-crypto",
|
||||
"sha2",
|
||||
@@ -1478,6 +1484,21 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
||||
dependencies = [
|
||||
"tinyvec_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec_macros"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.50.0"
|
||||
@@ -1590,6 +1611,15 @@ version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.6"
|
||||
|
||||
+13
-11
@@ -6,30 +6,31 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.9.2"
|
||||
version = "1.1.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Reticulum crates from a sibling rsReticulum checkout during development.
|
||||
rns-crypto = { path = "../rsReticulum/crates/rns-crypto" }
|
||||
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.1.0" }
|
||||
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.1.0" }
|
||||
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.1.0" }
|
||||
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.1.0" }
|
||||
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.1.0" }
|
||||
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.1.0" }
|
||||
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.1.0" }
|
||||
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.1.0" }
|
||||
|
||||
# Workspace LXMF crates
|
||||
lxmf-core = { path = "crates/lxmf-core" }
|
||||
lxmf-tools = { path = "crates/lxmf-tools" }
|
||||
lxmf-core = { path = "crates/lxmf-core", version = "1.1.0" }
|
||||
lxmf-tools = { path = "crates/lxmf-tools", version = "1.1.0" }
|
||||
|
||||
# Encoding
|
||||
base64 = "0.22"
|
||||
|
||||
# Serialization
|
||||
rmp = "0.8"
|
||||
rmp-serde = "1"
|
||||
rmpv = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -56,6 +57,7 @@ thiserror = "2"
|
||||
# Misc
|
||||
hex = "0.4"
|
||||
tempfile = "3"
|
||||
unicode-normalization = "0.1"
|
||||
|
||||
# Testing
|
||||
proptest = "1"
|
||||
@@ -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) |
|
||||
@@ -238,8 +238,8 @@ Minimal config:
|
||||
[lxmf]
|
||||
display_name = Rat
|
||||
announce_at_start = no
|
||||
# stamp_cost = 12
|
||||
delivery_transfer_max_accepted_size = 1000
|
||||
# stamp_cost = 8
|
||||
# on_inbound = /path/to/handler
|
||||
|
||||
[propagation]
|
||||
@@ -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. |
|
||||
|
||||
@@ -17,12 +17,14 @@ thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
rmp = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
unicode-normalization = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = { workspace = true }
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Crash-safe ratchet ownership for an LXMF delivery destination.
|
||||
//!
|
||||
//! A delivery announce is returned only after any candidate private ratchet
|
||||
//! and the associated announce-ordering state are durably committed. The
|
||||
//! propagation destination intentionally does not use this type.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rns_identity::announce_state::RatchetControlState;
|
||||
use rns_identity::destination::{AnnounceTime, DestType, Destination, Direction};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Reticulum aspect used by an LXMF delivery destination.
|
||||
pub const DELIVERY_APP_NAME: &str = "lxmf.delivery";
|
||||
|
||||
/// Whether a delivery announce is a normal broadcast or a tagged path reply.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DeliveryAnnounceKind<'a> {
|
||||
Broadcast,
|
||||
PathResponse { tag: Option<&'a [u8]> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum DeliveryRatchetError {
|
||||
#[error("LXMF delivery destination does not match the supplied identity")]
|
||||
DestinationMismatch,
|
||||
#[error("ratchet control state at {path} is untrusted; refusing to overwrite it")]
|
||||
UntrustedControl { path: PathBuf },
|
||||
#[error("announce coalesced until wall time advances")]
|
||||
Coalesced,
|
||||
#[error("failed to plan announce time: {0}")]
|
||||
Plan(#[source] std::io::Error),
|
||||
#[error("failed to persist announce ordering state at {path}: {source}")]
|
||||
PersistControl {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error(transparent)]
|
||||
Destination(#[from] rns_identity::destination::DestinationError),
|
||||
#[error("internal ratchet invariant failed: {0}")]
|
||||
Invariant(&'static str),
|
||||
}
|
||||
|
||||
/// Owns the private-key ring, signed control sidecar, and exact tagged-response
|
||||
/// cache for one `lxmf.delivery` destination.
|
||||
pub struct DeliveryRatchetState {
|
||||
destination: Destination,
|
||||
ring: RatchetRing,
|
||||
control: RatchetControlState,
|
||||
ring_path: PathBuf,
|
||||
control_path: PathBuf,
|
||||
ring_file_trusted: bool,
|
||||
control_file_trusted: bool,
|
||||
}
|
||||
|
||||
impl DeliveryRatchetState {
|
||||
/// Load verified state, preserving any invalid existing files in place.
|
||||
///
|
||||
/// A missing ring is generated and persisted before it becomes live. A
|
||||
/// ring that cannot be stored leaves delivery available but unratcheted.
|
||||
/// An invalid control sidecar defers new announces because their ordering
|
||||
/// cannot be proven safely.
|
||||
pub fn load_or_initialize(
|
||||
identity: &Identity,
|
||||
destination_hash: [u8; 16],
|
||||
ring_path: PathBuf,
|
||||
control_path: PathBuf,
|
||||
wall_now: u64,
|
||||
) -> Result<Self, DeliveryRatchetError> {
|
||||
let destination = Destination::new(
|
||||
Some(identity),
|
||||
Direction::In,
|
||||
DestType::Single,
|
||||
DELIVERY_APP_NAME,
|
||||
)?;
|
||||
if destination.hash != destination_hash {
|
||||
return Err(DeliveryRatchetError::DestinationMismatch);
|
||||
}
|
||||
|
||||
let ring_existed = ring_path.exists();
|
||||
let (mut ring, ring_file_trusted) = if ring_existed {
|
||||
match RatchetRing::load_verified(&ring_path, identity) {
|
||||
Ok(loaded) => {
|
||||
let format = loaded.format();
|
||||
let ring = loaded.into_ring();
|
||||
if format == RatchetRingFormat::LegacyRust {
|
||||
match ring.save_verified(&ring_path, identity) {
|
||||
Ok(()) => tracing::info!(
|
||||
path = %ring_path.display(),
|
||||
"migrated legacy Rust ratchet ring to canonical format"
|
||||
),
|
||||
Err(error) => tracing::warn!(
|
||||
path = %ring_path.display(),
|
||||
%error,
|
||||
"legacy ratchet ring is valid but canonical rewrite failed"
|
||||
),
|
||||
}
|
||||
}
|
||||
(ring, true)
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
path = %ring_path.display(),
|
||||
%error,
|
||||
"ratchet ring is untrusted; preserving it and announcing without a ratchet"
|
||||
);
|
||||
(RatchetRing::new(), false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(RatchetRing::new(), true)
|
||||
};
|
||||
|
||||
let control_existed = control_path.exists();
|
||||
let (mut control, control_file_trusted) = if control_existed {
|
||||
match RatchetControlState::load_verified(&control_path, identity, destination_hash) {
|
||||
Ok(state) => (state, true),
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
path = %control_path.display(),
|
||||
%error,
|
||||
"ratchet control state is untrusted; preserving it and deferring new announces"
|
||||
);
|
||||
(
|
||||
RatchetControlState::new(identity.hash, destination_hash),
|
||||
false,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(
|
||||
RatchetControlState::new(identity.hash, destination_hash),
|
||||
true,
|
||||
)
|
||||
};
|
||||
|
||||
let mut control_changed = false;
|
||||
if control_file_trusted && control.last_rotation_wall().is_none() {
|
||||
control.anchor_rotation_if_unknown(wall_now);
|
||||
control_changed = true;
|
||||
}
|
||||
|
||||
if ring.is_empty() && ring_file_trusted && control_file_trusted {
|
||||
let prepared = ring.prepare_rotation_at(wall_now as f64);
|
||||
match prepared.ring().save_verified(&ring_path, identity) {
|
||||
Ok(()) => {
|
||||
ring.commit_prepared_rotation(prepared);
|
||||
control = control.with_rotation_at(wall_now);
|
||||
control_changed = true;
|
||||
}
|
||||
Err(error) => tracing::error!(
|
||||
path = %ring_path.display(),
|
||||
%error,
|
||||
"could not durably initialise ratchet ring; delivery announces will be unratcheted"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
if control_file_trusted
|
||||
&& (!control_existed || control_changed)
|
||||
&& let Err(error) = control.save_verified(&control_path, identity)
|
||||
{
|
||||
tracing::warn!(
|
||||
path = %control_path.display(),
|
||||
%error,
|
||||
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
destination,
|
||||
ring,
|
||||
control,
|
||||
ring_path,
|
||||
control_path,
|
||||
ring_file_trusted,
|
||||
control_file_trusted,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn destination_hash(&self) -> [u8; 16] {
|
||||
self.destination.hash
|
||||
}
|
||||
|
||||
pub fn ring(&self) -> &RatchetRing {
|
||||
&self.ring
|
||||
}
|
||||
|
||||
pub fn control(&self) -> &RatchetControlState {
|
||||
&self.control
|
||||
}
|
||||
|
||||
/// Build an announce after committing all state that its wire bytes claim.
|
||||
///
|
||||
/// `wall_now` supplies both rotation age and the 40-bit wire ordering
|
||||
/// value. `cache_now` is a separate local elapsed-time domain used only for
|
||||
/// tagged path-response expiry.
|
||||
pub fn create_announce(
|
||||
&mut self,
|
||||
identity: &Identity,
|
||||
app_data: &[u8],
|
||||
wall_now: u64,
|
||||
cache_now: f64,
|
||||
kind: DeliveryAnnounceKind<'_>,
|
||||
) -> Result<Vec<u8>, DeliveryRatchetError> {
|
||||
if identity.hash != self.control.identity_hash() {
|
||||
return Err(DeliveryRatchetError::DestinationMismatch);
|
||||
}
|
||||
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
|
||||
|
||||
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
|
||||
&& let Some(packet) = self
|
||||
.destination
|
||||
.cached_path_response_packet(tag, cache_now)?
|
||||
{
|
||||
return Ok(packet);
|
||||
}
|
||||
|
||||
if !self.control_file_trusted {
|
||||
return Err(DeliveryRatchetError::UntrustedControl {
|
||||
path: self.control_path.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let Some(mut candidate_control) = self
|
||||
.control
|
||||
.prepare_announce(wall_now)
|
||||
.map_err(DeliveryRatchetError::Plan)?
|
||||
else {
|
||||
return Err(DeliveryRatchetError::Coalesced);
|
||||
};
|
||||
|
||||
let rotation_due = self.ring.is_empty()
|
||||
|| self
|
||||
.control
|
||||
.rotation_due(wall_now, self.ring.ratchet_interval());
|
||||
let mut prepared_rotation = None;
|
||||
let mut ratchet_public = self.ring.current_public_key();
|
||||
if rotation_due && self.ring_file_trusted {
|
||||
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
|
||||
match prepared.ring().save_verified(&self.ring_path, identity) {
|
||||
Ok(()) => {
|
||||
ratchet_public = Some(prepared.public_key());
|
||||
candidate_control = candidate_control.with_rotation_at(wall_now);
|
||||
prepared_rotation = Some(prepared);
|
||||
}
|
||||
Err(error) => tracing::error!(
|
||||
path = %self.ring_path.display(),
|
||||
%error,
|
||||
"ratchet rotation was not persisted; reusing the last durable ratchet"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
candidate_control
|
||||
.save_verified(&self.control_path, identity)
|
||||
.map_err(|source| DeliveryRatchetError::PersistControl {
|
||||
path: self.control_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let wire_now =
|
||||
candidate_control
|
||||
.last_announce_wire()
|
||||
.ok_or(DeliveryRatchetError::Invariant(
|
||||
"prepared announce has no wire-order value",
|
||||
))?;
|
||||
if let Some(prepared) = prepared_rotation {
|
||||
self.ring.commit_prepared_rotation(prepared);
|
||||
}
|
||||
self.control = candidate_control;
|
||||
|
||||
let (path_response, tag) = match kind {
|
||||
DeliveryAnnounceKind::Broadcast => (false, None),
|
||||
DeliveryAnnounceKind::PathResponse { tag } => (true, tag),
|
||||
};
|
||||
self.destination
|
||||
.announce_packet_at(
|
||||
identity,
|
||||
Some(app_data),
|
||||
ratchet_public.as_ref(),
|
||||
path_response,
|
||||
tag,
|
||||
AnnounceTime::new(wire_now, announce_time.cache)?,
|
||||
)
|
||||
.map_err(DeliveryRatchetError::from)
|
||||
}
|
||||
|
||||
/// Best-effort shutdown checkpoint. Invalid files detected during load are
|
||||
/// never overwritten by this operation.
|
||||
pub fn save(&self, identity: &Identity) {
|
||||
if self.ring_file_trusted
|
||||
&& let Err(error) = self.ring.save_verified(&self.ring_path, identity)
|
||||
{
|
||||
tracing::warn!(%error, "failed to save ratchet ring");
|
||||
}
|
||||
if self.control_file_trusted
|
||||
&& let Err(error) = self.control.save_verified(&self.control_path, identity)
|
||||
{
|
||||
tracing::warn!(%error, "failed to save ratchet control state");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ring_path(&self) -> &Path {
|
||||
&self.ring_path
|
||||
}
|
||||
|
||||
pub fn control_path(&self) -> &Path {
|
||||
&self.control_path
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_identity::ratchet::ratchet_public_bytes;
|
||||
|
||||
fn unpack_announce(
|
||||
raw: &[u8],
|
||||
) -> (
|
||||
rns_wire::header::PacketHeader,
|
||||
rns_identity::announce::AnnounceData,
|
||||
) {
|
||||
let (header, header_len) = rns_wire::header::PacketHeader::unpack(raw).unwrap();
|
||||
let announce = rns_identity::announce::AnnounceData::unpack(
|
||||
&raw[header_len..],
|
||||
header.flags.context_flag,
|
||||
)
|
||||
.unwrap();
|
||||
(header, announce)
|
||||
}
|
||||
|
||||
fn state_at(dir: &Path, identity: &Identity, wall_now: u64) -> DeliveryRatchetState {
|
||||
let destination_hash =
|
||||
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
|
||||
DeliveryRatchetState::load_or_initialize(
|
||||
identity,
|
||||
destination_hash,
|
||||
dir.join("ring"),
|
||||
dir.join("ring.control"),
|
||||
wall_now,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn survives_restart_rotates_and_retains_the_previous_private_key() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut state = state_at(dir.path(), &identity, 100);
|
||||
let initial_public = state.ring.current_public_key().unwrap();
|
||||
|
||||
let raw = state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
101,
|
||||
101.0,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
let (header, announce) = unpack_announce(&raw);
|
||||
assert!(header.flags.context_flag);
|
||||
assert_eq!(announce.ratchet, Some(initial_public));
|
||||
let committed_wire_time = state.control.last_announce_wire();
|
||||
assert!(matches!(
|
||||
state.create_announce(
|
||||
&identity,
|
||||
b"changed",
|
||||
101,
|
||||
101.5,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
),
|
||||
Err(DeliveryRatchetError::Coalesced)
|
||||
));
|
||||
assert_eq!(state.control.last_announce_wire(), committed_wire_time);
|
||||
|
||||
let mut restarted = state_at(dir.path(), &identity, 102);
|
||||
assert_eq!(restarted.ring.current_public_key(), Some(initial_public));
|
||||
let raw = restarted
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
102,
|
||||
102.0,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(unpack_announce(&raw).1.ratchet, Some(initial_public));
|
||||
|
||||
let rotate_at = 100 + restarted.ring.ratchet_interval();
|
||||
let raw = restarted
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
rotate_at,
|
||||
rotate_at as f64,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
let rotated_public = unpack_announce(&raw).1.ratchet.unwrap();
|
||||
assert_ne!(rotated_public, initial_public);
|
||||
assert_eq!(restarted.ring.len(), 2);
|
||||
assert!(
|
||||
restarted
|
||||
.ring
|
||||
.private_keys()
|
||||
.iter()
|
||||
.any(|private| ratchet_public_bytes(private) == initial_public)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_ring_storage_can_only_emit_an_unratcheted_announce() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let destination =
|
||||
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
|
||||
let mut state = DeliveryRatchetState::load_or_initialize(
|
||||
&identity,
|
||||
destination,
|
||||
dir.path().join("missing/ring"),
|
||||
dir.path().join("ring.control"),
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(state.ring.is_empty());
|
||||
|
||||
let raw = state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
101,
|
||||
101.0,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
let (header, announce) = unpack_announce(&raw);
|
||||
assert!(!header.flags.context_flag);
|
||||
assert_eq!(announce.ratchet, None);
|
||||
assert!(state.ring.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_ring_is_preserved_and_never_advertised() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ring_path = dir.path().join("ring");
|
||||
let corrupt = b"not-a-ratchet-ring";
|
||||
std::fs::write(&ring_path, corrupt).unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut state = state_at(dir.path(), &identity, 100);
|
||||
|
||||
let raw = state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
101,
|
||||
101.0,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!unpack_announce(&raw).0.flags.context_flag);
|
||||
assert_eq!(std::fs::read(ring_path).unwrap(), corrupt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_control_commit_cannot_publish_or_commit_a_prepared_rotation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut state = state_at(dir.path(), &identity, 100);
|
||||
state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
101,
|
||||
101.0,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
)
|
||||
.unwrap();
|
||||
let live_public = state.ring.current_public_key();
|
||||
let live_wire_time = state.control.last_announce_wire();
|
||||
state.control_path = dir.path().join("missing/ring.control");
|
||||
let rotate_at = 100 + state.ring.ratchet_interval();
|
||||
|
||||
assert!(matches!(
|
||||
state.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
rotate_at,
|
||||
rotate_at as f64,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
),
|
||||
Err(DeliveryRatchetError::PersistControl { .. })
|
||||
));
|
||||
assert_eq!(state.ring.current_public_key(), live_public);
|
||||
assert_eq!(state.control.last_announce_wire(), live_wire_time);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_tag_replays_exact_packet_without_consuming_announce_time() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut state = state_at(dir.path(), &identity, 100);
|
||||
let tag = b"path-request-tag";
|
||||
let first = state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"first",
|
||||
101,
|
||||
101.0,
|
||||
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
|
||||
)
|
||||
.unwrap();
|
||||
let committed_wire = state.control.last_announce_wire();
|
||||
|
||||
let replay = state
|
||||
.create_announce(
|
||||
&identity,
|
||||
b"changed",
|
||||
101,
|
||||
102.0,
|
||||
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
replay, first,
|
||||
"removing the cache lookup changes signed bytes"
|
||||
);
|
||||
assert_eq!(state.control.last_announce_wire(), committed_wire);
|
||||
assert_eq!(
|
||||
unpack_announce(&replay).0.context,
|
||||
rns_wire::context::PacketContext::PathResponse
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_cache_clock_cannot_commit_announce_state() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let identity = Identity::new();
|
||||
let mut state = state_at(dir.path(), &identity, 100);
|
||||
let live_wire = state.control.last_announce_wire();
|
||||
let live_public = state.ring.current_public_key();
|
||||
|
||||
assert!(matches!(
|
||||
state.create_announce(
|
||||
&identity,
|
||||
b"app",
|
||||
101,
|
||||
f64::NAN,
|
||||
DeliveryAnnounceKind::Broadcast,
|
||||
),
|
||||
Err(DeliveryRatchetError::Destination(_))
|
||||
));
|
||||
assert_eq!(state.control.last_announce_wire(), live_wire);
|
||||
assert_eq!(state.ring.current_public_key(), live_public);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::constants::*;
|
||||
use crate::presentation::{MAX_ADVERTISED_NAME_CHARS, sanitize_name};
|
||||
|
||||
/// Announce handler type.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -37,6 +38,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:
|
||||
@@ -88,7 +100,12 @@ impl PropagationNodeAnnounceData {
|
||||
}
|
||||
|
||||
pub fn set_name(&mut self, name: &str) {
|
||||
self.metadata.insert(PN_META_NAME, name.as_bytes().to_vec());
|
||||
let name = sanitize_name(name, MAX_ADVERTISED_NAME_CHARS);
|
||||
if name.is_empty() {
|
||||
self.metadata.remove(&PN_META_NAME);
|
||||
} else {
|
||||
self.metadata.insert(PN_META_NAME, name.into_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +150,17 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
|
||||
/// dropped because it duplicated this function's checks and every
|
||||
/// in-tree caller called both back-to-back.
|
||||
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
|
||||
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
|
||||
value
|
||||
.as_u64()
|
||||
.or_else(|| value.as_i64().and_then(|number| number.try_into().ok()))
|
||||
.or_else(|| {
|
||||
value.as_f64().and_then(|number| {
|
||||
(number.is_finite() && number >= 0.0).then_some(number as u64)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
|
||||
let arr = value.as_array()?;
|
||||
if arr.len() < 7 {
|
||||
@@ -144,38 +172,27 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
|
||||
.or_else(|| arr[1].as_u64().map(|u| u as i64))
|
||||
.or_else(|| arr[1].as_f64().map(|f| f as i64))?;
|
||||
let node_state = arr[2].as_bool()?;
|
||||
let transfer_limit = arr[3]
|
||||
.as_u64()
|
||||
.or_else(|| arr[3].as_i64().map(|i| i as u64))
|
||||
.or_else(|| arr[3].as_f64().map(|f| f as u64))?;
|
||||
let sync_limit = arr[4]
|
||||
.as_u64()
|
||||
.or_else(|| arr[4].as_i64().map(|i| i as u64))
|
||||
.or_else(|| arr[4].as_f64().map(|f| f as u64))?;
|
||||
let transfer_limit = nonnegative_u64(&arr[3])?;
|
||||
let sync_limit = nonnegative_u64(&arr[4])?;
|
||||
|
||||
let costs = arr[5].as_array()?;
|
||||
if costs.len() < 3 {
|
||||
return None;
|
||||
}
|
||||
let stamp_cost = costs[0]
|
||||
.as_u64()
|
||||
.or_else(|| costs[0].as_i64().map(|i| i as u64))? as u8;
|
||||
let stamp_flex = costs[1]
|
||||
.as_u64()
|
||||
.or_else(|| costs[1].as_i64().map(|i| i as u64))? as u8;
|
||||
let peering_cost = costs[2]
|
||||
.as_u64()
|
||||
.or_else(|| costs[2].as_i64().map(|i| i as u64))? as u8;
|
||||
let stamp_cost = u8::try_from(nonnegative_u64(&costs[0])?).ok()?;
|
||||
let stamp_flex = u8::try_from(nonnegative_u64(&costs[1])?).ok()?;
|
||||
let peering_cost = u8::try_from(nonnegative_u64(&costs[2])?).ok()?;
|
||||
|
||||
// Python's `pn_announce_data_is_valid()` requires the metadata element to
|
||||
// be a map. Unknown keys and non-binary values are ignored here because
|
||||
// the typed Rust API can only retain metadata it can represent safely.
|
||||
let mut metadata = HashMap::new();
|
||||
if let Some(map) = arr[6].as_map() {
|
||||
for (k, v) in map {
|
||||
if let (Some(key), Some(val)) = (
|
||||
k.as_u64().map(|u| u as u8),
|
||||
v.as_slice().map(|s| s.to_vec()),
|
||||
) {
|
||||
metadata.insert(key, val);
|
||||
}
|
||||
for (k, v) in arr[6].as_map()? {
|
||||
if let (Some(key), Some(val)) = (
|
||||
k.as_u64().and_then(|number| number.try_into().ok()),
|
||||
v.as_slice().map(|s| s.to_vec()),
|
||||
) {
|
||||
metadata.insert(key, val);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,33 +216,38 @@ 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`].
|
||||
///
|
||||
/// `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;
|
||||
|
||||
let name_val = match display_name {
|
||||
Some(name) => Value::Binary(name.as_bytes().to_vec()),
|
||||
None => Value::Nil,
|
||||
};
|
||||
let name_val = display_name
|
||||
.map(|name| sanitize_name(name, MAX_ADVERTISED_NAME_CHARS))
|
||||
.filter(|name| !name.is_empty())
|
||||
.map_or(Value::Nil, |name| Value::Binary(name.into_bytes()));
|
||||
|
||||
let cost_val = match stamp_cost {
|
||||
Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64),
|
||||
_ => 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()?;
|
||||
@@ -236,7 +258,8 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
|
||||
let display_name = arr[0]
|
||||
.as_slice()
|
||||
.and_then(|b| String::from_utf8(b.to_vec()).ok())
|
||||
.map(|name| name.replace('\0', "").trim().to_string());
|
||||
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
|
||||
.filter(|name| !name.is_empty());
|
||||
|
||||
let stamp_cost = arr[1].as_u64().map(|c| c as u8);
|
||||
|
||||
@@ -257,27 +280,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.
|
||||
@@ -288,7 +329,10 @@ pub fn compression_support_from_app_data(data: &[u8]) -> bool {
|
||||
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
|
||||
let parsed = parse_pn_announce_data(data)?;
|
||||
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
|
||||
String::from_utf8(name_bytes.clone()).ok()
|
||||
String::from_utf8(name_bytes.clone())
|
||||
.ok()
|
||||
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
|
||||
.filter(|name| !name.is_empty())
|
||||
}
|
||||
|
||||
/// Outcome of a resource transfer, matching Python `resource_concluded` /
|
||||
@@ -407,12 +451,10 @@ impl PropagationRequestHandler {
|
||||
true
|
||||
};
|
||||
|
||||
let peer_hash = remote_identity_hash.copied().unwrap_or([0u8; 16]);
|
||||
|
||||
node.handle_offer_request(
|
||||
request_data,
|
||||
crate::propagation_node::OfferRequestContext {
|
||||
peer_hash,
|
||||
peer_hash: remote_identity_hash.copied().unwrap_or([0u8; 16]),
|
||||
identity_known,
|
||||
is_throttled,
|
||||
access_allowed,
|
||||
@@ -422,7 +464,10 @@ 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`](crate::propagation_node::GetRequestAction::ServeFiles)
|
||||
/// plan — the embedder resolves it after releasing the node lock.
|
||||
///
|
||||
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499.
|
||||
pub fn handle_message_get_request(
|
||||
@@ -431,14 +476,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));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -680,6 +726,47 @@ mod tests {
|
||||
assert!(parse_pn_announce_data(&[]).is_none());
|
||||
assert!(parse_pn_announce_data(&[0x91, 0xC2]).is_none());
|
||||
assert!(parse_pn_announce_data(&[0x01]).is_none());
|
||||
|
||||
let non_map_metadata = rmpv::Value::Array(vec![
|
||||
rmpv::Value::Boolean(false),
|
||||
rmpv::Value::from(1_777_716_440u64),
|
||||
rmpv::Value::Boolean(true),
|
||||
rmpv::Value::from(10_240),
|
||||
rmpv::Value::from(10_240),
|
||||
rmpv::Value::Array(vec![
|
||||
rmpv::Value::from(16),
|
||||
rmpv::Value::from(3),
|
||||
rmpv::Value::from(18),
|
||||
]),
|
||||
rmpv::Value::Array(Vec::new()),
|
||||
]);
|
||||
assert!(
|
||||
parse_pn_announce_data(&crate::encode_value(&non_map_metadata)).is_none(),
|
||||
"Python rejects propagation announces whose metadata is not a map"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pn_announce_data_rejects_wrapping_policy_values() {
|
||||
use rmpv::Value;
|
||||
|
||||
let encode = |transfer_limit: Value, stamp_cost: Value| {
|
||||
let value = Value::Array(vec![
|
||||
Value::Boolean(false),
|
||||
Value::from(1_777_716_440u64),
|
||||
Value::Boolean(true),
|
||||
transfer_limit,
|
||||
Value::from(10240),
|
||||
Value::Array(vec![stamp_cost, Value::from(3), Value::from(18)]),
|
||||
Value::Map(vec![]),
|
||||
]);
|
||||
let mut packed = Vec::new();
|
||||
rmpv::encode::write_value(&mut packed, &value).unwrap();
|
||||
packed
|
||||
};
|
||||
|
||||
assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none());
|
||||
assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -704,6 +791,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));
|
||||
@@ -757,6 +854,18 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_name_from_app_data_sanitizes_untrusted_unicode() {
|
||||
let packed = get_announce_app_data(
|
||||
Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "),
|
||||
Some(12),
|
||||
);
|
||||
assert_eq!(
|
||||
display_name_from_app_data(&packed),
|
||||
Some("AliceNetwork".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stamp_cost_from_app_data() {
|
||||
let packed = get_announce_app_data(Some("Alice"), Some(12));
|
||||
@@ -768,8 +877,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 +899,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 +933,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 +1096,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 +1139,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 +1165,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());
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Actor-owned tracking for inbound LXMF delivery Resources.
|
||||
//!
|
||||
//! The Reticulum runtime owns the actual transfers. Embedders project its
|
||||
//! lifecycle notifications into [`InboundResourceEvent`] and forward bounded
|
||||
//! [`InboundResourceCancelRequest`] values back to that owner. This keeps the
|
||||
//! public LXMF API independent of a concrete Reticulum runtime while retaining
|
||||
//! exact `(link_id, logical_resource_id)` cancellation authority.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
/// Exact owner key for one logical inbound Resource.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct InboundResourceKey {
|
||||
pub link_id: [u8; 16],
|
||||
pub resource_id: [u8; 32],
|
||||
}
|
||||
|
||||
impl InboundResourceKey {
|
||||
pub const fn new(link_id: [u8; 16], resource_id: [u8; 32]) -> Self {
|
||||
Self {
|
||||
link_id,
|
||||
resource_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Terminal result of an inbound Resource transfer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum InboundResourceConclusion {
|
||||
Complete,
|
||||
Cancelled,
|
||||
Rejected,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Current public state of an inbound Resource.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum InboundResourceStatus {
|
||||
Receiving,
|
||||
Complete,
|
||||
Cancelled,
|
||||
Rejected,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl InboundResourceStatus {
|
||||
pub const fn is_closed(self) -> bool {
|
||||
!matches!(self, Self::Receiving)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InboundResourceConclusion> for InboundResourceStatus {
|
||||
fn from(value: InboundResourceConclusion) -> Self {
|
||||
match value {
|
||||
InboundResourceConclusion::Complete => Self::Complete,
|
||||
InboundResourceConclusion::Cancelled => Self::Cancelled,
|
||||
InboundResourceConclusion::Rejected => Self::Rejected,
|
||||
InboundResourceConclusion::Failed => Self::Failed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned, non-sensitive snapshot of one inbound transfer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InboundResourceSnapshot {
|
||||
pub key: InboundResourceKey,
|
||||
pub data_size: usize,
|
||||
pub transferred: usize,
|
||||
pub total_segments: usize,
|
||||
pub status: InboundResourceStatus,
|
||||
}
|
||||
|
||||
impl InboundResourceSnapshot {
|
||||
pub const fn is_closed(&self) -> bool {
|
||||
self.status.is_closed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Transport-neutral lifecycle input consumed by [`InboundResourceTracker`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InboundResourceEvent {
|
||||
Started {
|
||||
key: InboundResourceKey,
|
||||
data_size: usize,
|
||||
total_segments: usize,
|
||||
},
|
||||
Progress {
|
||||
key: InboundResourceKey,
|
||||
transferred: usize,
|
||||
total: usize,
|
||||
},
|
||||
Concluded {
|
||||
key: InboundResourceKey,
|
||||
conclusion: InboundResourceConclusion,
|
||||
},
|
||||
LinkClosed {
|
||||
link_id: [u8; 16],
|
||||
},
|
||||
}
|
||||
|
||||
/// Exact cancellation request for the embedding runtime's Resource owner.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InboundResourceCancelRequest {
|
||||
key: InboundResourceKey,
|
||||
}
|
||||
|
||||
impl InboundResourceCancelRequest {
|
||||
pub const fn new(key: InboundResourceKey) -> Self {
|
||||
Self { key }
|
||||
}
|
||||
|
||||
pub const fn key(self) -> InboundResourceKey {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloneable live handle retained by a caller after the active list changes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct InboundResourceHandle {
|
||||
key: InboundResourceKey,
|
||||
snapshot_rx: watch::Receiver<InboundResourceSnapshot>,
|
||||
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
|
||||
}
|
||||
|
||||
impl InboundResourceHandle {
|
||||
pub const fn key(&self) -> InboundResourceKey {
|
||||
self.key
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> InboundResourceSnapshot {
|
||||
self.snapshot_rx.borrow().clone()
|
||||
}
|
||||
|
||||
/// Wait for the next lifecycle/progress update.
|
||||
///
|
||||
/// Returns `None` after the terminal snapshot has been published and the
|
||||
/// actor owner has dropped its sender.
|
||||
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
|
||||
if self.snapshot_rx.changed().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
Some(self.snapshot())
|
||||
}
|
||||
|
||||
/// Queue exact inbound cancellation without blocking the actor owner.
|
||||
///
|
||||
/// `false` means the transfer is already closed, cancellation is not
|
||||
/// wired by the embedder, or the bounded command channel cannot accept the
|
||||
/// request. Authoritative closure arrives through the lifecycle stream.
|
||||
pub fn cancel(&self) -> bool {
|
||||
if self.snapshot().is_closed() {
|
||||
return false;
|
||||
}
|
||||
self.cancel_tx.as_ref().is_some_and(|tx| {
|
||||
tx.try_send(InboundResourceCancelRequest::new(self.key))
|
||||
.is_ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveInboundResource {
|
||||
snapshot_tx: watch::Sender<InboundResourceSnapshot>,
|
||||
}
|
||||
|
||||
/// Single-owner active Resource registry.
|
||||
///
|
||||
/// Terminal records are removed immediately, so the registry is bounded by
|
||||
/// concurrent transfers. Previously returned handles retain the final owned
|
||||
/// snapshot without keeping actor state alive.
|
||||
#[derive(Default)]
|
||||
pub struct InboundResourceTracker {
|
||||
active: HashMap<InboundResourceKey, ActiveInboundResource>,
|
||||
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
|
||||
}
|
||||
|
||||
impl InboundResourceTracker {
|
||||
pub fn new(cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) -> Self {
|
||||
Self {
|
||||
active: HashMap::new(),
|
||||
cancel_tx: Some(cancel_tx),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_cancel_sender(&mut self, cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) {
|
||||
self.cancel_tx = Some(cancel_tx);
|
||||
}
|
||||
|
||||
/// Number of currently active inbound Resources.
|
||||
pub fn inbound_count(&self) -> usize {
|
||||
self.active.len()
|
||||
}
|
||||
|
||||
/// Deterministic snapshot of all active Resource handles.
|
||||
pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> {
|
||||
let mut keys = self.active.keys().copied().collect::<Vec<_>>();
|
||||
keys.sort_unstable();
|
||||
keys.into_iter()
|
||||
.filter_map(|key| self.handle_for(key))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Return the active Resource matching `resource_id`.
|
||||
///
|
||||
/// A cryptographic ID collision across two Links fails closed instead of
|
||||
/// choosing the wrong cancellation authority.
|
||||
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
|
||||
let mut matches = self
|
||||
.active
|
||||
.keys()
|
||||
.filter(|key| &key.resource_id == resource_id)
|
||||
.copied();
|
||||
let key = matches.next()?;
|
||||
if matches.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
self.handle_for(key)
|
||||
}
|
||||
|
||||
/// Return one exact active Resource.
|
||||
pub fn inbound_resource_exact(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
|
||||
self.handle_for(key)
|
||||
}
|
||||
|
||||
/// Queue cancellation for one unique active logical Resource.
|
||||
pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool {
|
||||
self.inbound_resource(resource_id)
|
||||
.is_some_and(|handle| handle.cancel())
|
||||
}
|
||||
|
||||
/// Queue cancellation for one exact active Resource.
|
||||
pub fn cancel_inbound_exact(&self, key: InboundResourceKey) -> bool {
|
||||
self.handle_for(key).is_some_and(|handle| handle.cancel())
|
||||
}
|
||||
|
||||
/// Queue cancellation for a stable snapshot of every active Resource.
|
||||
///
|
||||
/// The returned count is the number accepted by the bounded command
|
||||
/// channel, matching Python's count-oriented `cancel_all_inbound` API.
|
||||
pub fn cancel_all_inbound(&self) -> usize {
|
||||
self.inbound_resources()
|
||||
.into_iter()
|
||||
.filter(InboundResourceHandle::cancel)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Apply one lifecycle update from the embedding runtime.
|
||||
pub fn handle_event(&mut self, event: InboundResourceEvent) {
|
||||
match event {
|
||||
InboundResourceEvent::Started {
|
||||
key,
|
||||
data_size,
|
||||
total_segments,
|
||||
} => self.started(key, data_size, total_segments),
|
||||
InboundResourceEvent::Progress {
|
||||
key,
|
||||
transferred,
|
||||
total,
|
||||
} => self.progress(key, transferred, total),
|
||||
InboundResourceEvent::Concluded { key, conclusion } => self.concluded(key, conclusion),
|
||||
InboundResourceEvent::LinkClosed { link_id } => self.link_closed(link_id),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_for(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
|
||||
let active = self.active.get(&key)?;
|
||||
Some(InboundResourceHandle {
|
||||
key,
|
||||
snapshot_rx: active.snapshot_tx.subscribe(),
|
||||
cancel_tx: self.cancel_tx.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn started(&mut self, key: InboundResourceKey, data_size: usize, total_segments: usize) {
|
||||
if let Some(active) = self.active.get(&key) {
|
||||
let mut snapshot = active.snapshot_tx.borrow().clone();
|
||||
snapshot.data_size = snapshot.data_size.max(data_size);
|
||||
snapshot.total_segments = snapshot.total_segments.max(total_segments.max(1));
|
||||
active.snapshot_tx.send_replace(snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
let snapshot = InboundResourceSnapshot {
|
||||
key,
|
||||
data_size,
|
||||
transferred: 0,
|
||||
total_segments: total_segments.max(1),
|
||||
status: InboundResourceStatus::Receiving,
|
||||
};
|
||||
let (snapshot_tx, _snapshot_rx) = watch::channel(snapshot);
|
||||
self.active
|
||||
.insert(key, ActiveInboundResource { snapshot_tx });
|
||||
}
|
||||
|
||||
fn progress(&mut self, key: InboundResourceKey, transferred: usize, total: usize) {
|
||||
let Some(active) = self.active.get(&key) else {
|
||||
return;
|
||||
};
|
||||
let mut snapshot = active.snapshot_tx.borrow().clone();
|
||||
snapshot.data_size = snapshot.data_size.max(total);
|
||||
snapshot.transferred = transferred.min(snapshot.data_size);
|
||||
active.snapshot_tx.send_replace(snapshot);
|
||||
}
|
||||
|
||||
fn concluded(&mut self, key: InboundResourceKey, conclusion: InboundResourceConclusion) {
|
||||
let Some(active) = self.active.remove(&key) else {
|
||||
return;
|
||||
};
|
||||
let mut snapshot = active.snapshot_tx.borrow().clone();
|
||||
snapshot.status = conclusion.into();
|
||||
if conclusion == InboundResourceConclusion::Complete {
|
||||
snapshot.transferred = snapshot.data_size;
|
||||
}
|
||||
active.snapshot_tx.send_replace(snapshot);
|
||||
}
|
||||
|
||||
fn link_closed(&mut self, link_id: [u8; 16]) {
|
||||
let keys = self
|
||||
.active
|
||||
.keys()
|
||||
.filter(|key| key.link_id == link_id)
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
for key in keys {
|
||||
self.concluded(key, InboundResourceConclusion::Failed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn key(link: u8, resource: u8) -> InboundResourceKey {
|
||||
InboundResourceKey::new([link; 16], [resource; 32])
|
||||
}
|
||||
|
||||
fn started(key: InboundResourceKey, size: usize) -> InboundResourceEvent {
|
||||
InboundResourceEvent::Started {
|
||||
key,
|
||||
data_size: size,
|
||||
total_segments: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_handle_tracks_progress_and_terminal_snapshot() {
|
||||
let (cancel_tx, _cancel_rx) = mpsc::channel(4);
|
||||
let mut tracker = InboundResourceTracker::new(cancel_tx);
|
||||
let resource = key(1, 2);
|
||||
|
||||
tracker.handle_event(started(resource, 100));
|
||||
let mut handle = tracker.inbound_resource(&resource.resource_id).unwrap();
|
||||
assert_eq!(tracker.inbound_count(), 1);
|
||||
assert_eq!(handle.snapshot().transferred, 0);
|
||||
|
||||
tracker.handle_event(InboundResourceEvent::Progress {
|
||||
key: resource,
|
||||
transferred: 40,
|
||||
total: 100,
|
||||
});
|
||||
assert_eq!(handle.changed().await.unwrap().transferred, 40);
|
||||
|
||||
tracker.handle_event(InboundResourceEvent::Concluded {
|
||||
key: resource,
|
||||
conclusion: InboundResourceConclusion::Complete,
|
||||
});
|
||||
let terminal = handle.changed().await.unwrap();
|
||||
assert_eq!(terminal.status, InboundResourceStatus::Complete);
|
||||
assert_eq!(terminal.transferred, 100);
|
||||
assert!(terminal.is_closed());
|
||||
assert_eq!(tracker.inbound_count(), 0);
|
||||
assert!(!handle.cancel());
|
||||
assert!(handle.changed().await.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_is_exact_bounded_and_snapshot_based() {
|
||||
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
|
||||
let mut tracker = InboundResourceTracker::new(cancel_tx);
|
||||
let first = key(1, 3);
|
||||
let second = key(2, 4);
|
||||
tracker.handle_event(started(first, 10));
|
||||
tracker.handle_event(started(second, 20));
|
||||
|
||||
assert!(tracker.cancel_inbound(&first.resource_id));
|
||||
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
|
||||
assert_eq!(tracker.cancel_all_inbound(), 2);
|
||||
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
|
||||
assert_eq!(cancel_rx.try_recv().unwrap().key(), second);
|
||||
assert!(!tracker.cancel_inbound(&[9; 32]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_cancel_channel_fails_without_removing_active_state() {
|
||||
let (cancel_tx, _cancel_rx) = mpsc::channel(1);
|
||||
let mut tracker = InboundResourceTracker::new(cancel_tx);
|
||||
let first = key(1, 5);
|
||||
let second = key(1, 6);
|
||||
tracker.handle_event(started(first, 10));
|
||||
tracker.handle_event(started(second, 10));
|
||||
|
||||
assert!(tracker.cancel_inbound_exact(first));
|
||||
assert!(!tracker.cancel_inbound_exact(second));
|
||||
assert_eq!(tracker.inbound_count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_start_preserves_one_logical_handle() {
|
||||
let (cancel_tx, _cancel_rx) = mpsc::channel(2);
|
||||
let mut tracker = InboundResourceTracker::new(cancel_tx);
|
||||
let split = key(3, 7);
|
||||
tracker.handle_event(InboundResourceEvent::Started {
|
||||
key: split,
|
||||
data_size: 100,
|
||||
total_segments: 3,
|
||||
});
|
||||
tracker.handle_event(InboundResourceEvent::Started {
|
||||
key: split,
|
||||
data_size: 100,
|
||||
total_segments: 3,
|
||||
});
|
||||
|
||||
assert_eq!(tracker.inbound_count(), 1);
|
||||
let snapshot = tracker.inbound_resource_exact(split).unwrap().snapshot();
|
||||
assert_eq!(snapshot.total_segments, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_or_unknown_resources_never_become_visible() {
|
||||
let mut tracker = InboundResourceTracker::default();
|
||||
let unknown = key(4, 8);
|
||||
tracker.handle_event(InboundResourceEvent::Progress {
|
||||
key: unknown,
|
||||
transferred: 5,
|
||||
total: 10,
|
||||
});
|
||||
tracker.handle_event(InboundResourceEvent::Concluded {
|
||||
key: unknown,
|
||||
conclusion: InboundResourceConclusion::Rejected,
|
||||
});
|
||||
assert_eq!(tracker.inbound_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn link_close_fails_only_resources_owned_by_that_link() {
|
||||
let mut tracker = InboundResourceTracker::default();
|
||||
let closed = key(5, 9);
|
||||
let retained = key(6, 10);
|
||||
tracker.handle_event(started(closed, 10));
|
||||
tracker.handle_event(started(retained, 20));
|
||||
let mut closed_handle = tracker.inbound_resource_exact(closed).unwrap();
|
||||
|
||||
tracker.handle_event(InboundResourceEvent::LinkClosed {
|
||||
link_id: closed.link_id,
|
||||
});
|
||||
assert_eq!(
|
||||
closed_handle.changed().await.unwrap().status,
|
||||
InboundResourceStatus::Failed
|
||||
);
|
||||
assert!(tracker.inbound_resource_exact(closed).is_none());
|
||||
assert!(tracker.inbound_resource_exact(retained).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_then_complete_is_terminal_and_not_requeued() {
|
||||
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
|
||||
let mut tracker = InboundResourceTracker::new(cancel_tx);
|
||||
let resource = key(7, 11);
|
||||
tracker.handle_event(started(resource, 10));
|
||||
let handle = tracker.inbound_resource_exact(resource).unwrap();
|
||||
|
||||
assert!(handle.cancel());
|
||||
assert_eq!(cancel_rx.try_recv().unwrap().key(), resource);
|
||||
tracker.handle_event(InboundResourceEvent::Concluded {
|
||||
key: resource,
|
||||
conclusion: InboundResourceConclusion::Complete,
|
||||
});
|
||||
assert_eq!(handle.snapshot().status, InboundResourceStatus::Complete);
|
||||
assert!(!handle.cancel());
|
||||
assert_eq!(tracker.inbound_count(), 0);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@
|
||||
//! | Module | What it does |
|
||||
//! | --------------------- | -------------------------------------------------- |
|
||||
//! | [`message`] | Message object: fields, packing, stamp, encryption |
|
||||
//! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction |
|
||||
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
|
||||
//! | [`presentation`] | Safe bounded presentation of untrusted names |
|
||||
//! | [`router`] | Actor-driven routing and delivery state machine |
|
||||
//! | [`peer`] | Propagation-peer state and sync bookkeeping |
|
||||
//! | [`propagation`] | On-disk store-and-forward message pool |
|
||||
@@ -32,16 +35,29 @@
|
||||
//!
|
||||
//! [`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 delivery_ratchet;
|
||||
pub mod discovery_stamper;
|
||||
pub mod handlers;
|
||||
pub mod inbound_resource;
|
||||
pub mod link_delivery;
|
||||
pub mod message;
|
||||
pub mod peer;
|
||||
pub mod persist;
|
||||
pub mod presentation;
|
||||
pub mod propagation;
|
||||
pub mod propagation_admission;
|
||||
pub mod propagation_client;
|
||||
pub mod propagation_node;
|
||||
pub mod propagation_offer;
|
||||
pub mod propagation_sync;
|
||||
pub mod router;
|
||||
pub mod stamper;
|
||||
|
||||
@@ -447,7 +447,9 @@ pub struct LinkDeliveryManager {
|
||||
backchannel_links: HashMap<[u8; 16], [u8; 16]>,
|
||||
pending: HashMap<[u8; 16], PendingDelivery>,
|
||||
backchannel_tx: Option<mpsc::Sender<BackchannelSendCommand>>,
|
||||
inbound_packet_tx: Option<mpsc::Sender<(Vec<u8>, [u8; 16])>>,
|
||||
/// Unbounded: inbound link data is proved to the peer on receipt, so
|
||||
/// local delivery must not drop.
|
||||
inbound_packet_tx: Option<mpsc::UnboundedSender<(Vec<u8>, [u8; 16])>>,
|
||||
pending_backchannel_starts: Vec<PendingBackchannelStart>,
|
||||
pending_backchannel_deliveries: HashMap<BackchannelProofKey, PendingBackchannelDelivery>,
|
||||
identity_pub: Option<[u8; 64]>,
|
||||
@@ -492,7 +494,7 @@ impl LinkDeliveryManager {
|
||||
/// backchannels: the outbound Direct manager owns the link_id destination,
|
||||
/// so ordinary link DATA replies route back here rather than to the
|
||||
/// responder-side LinkManager.
|
||||
pub fn set_inbound_packet_sender(&mut self, tx: mpsc::Sender<(Vec<u8>, [u8; 16])>) {
|
||||
pub fn set_inbound_packet_sender(&mut self, tx: mpsc::UnboundedSender<(Vec<u8>, [u8; 16])>) {
|
||||
self.inbound_packet_tx = Some(tx);
|
||||
}
|
||||
|
||||
@@ -1227,7 +1229,7 @@ impl LinkDeliveryManager {
|
||||
};
|
||||
|
||||
if let Some(ref tx) = self.inbound_packet_tx {
|
||||
let _ = tx.try_send((plaintext, *link_id));
|
||||
let _ = tx.send((plaintext, *link_id));
|
||||
}
|
||||
|
||||
let packet_hash = rns_wire::hash::packet_hash(raw, header_type);
|
||||
@@ -3157,6 +3159,7 @@ mod tests {
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: proof_raw.into(),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
mgr.drain_events(&HashMap::new());
|
||||
@@ -3744,7 +3747,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_outbound_direct_link_accepts_backchannel_packet() {
|
||||
let (tx, mut rx) = mpsc::channel(128);
|
||||
let (inbound_tx, mut inbound_rx) = mpsc::channel(4);
|
||||
let (inbound_tx, mut inbound_rx) = mpsc::unbounded_channel();
|
||||
let mut mgr = LinkDeliveryManager::new(tx, None, None);
|
||||
mgr.set_inbound_packet_sender(inbound_tx);
|
||||
|
||||
@@ -3780,6 +3783,7 @@ mod tests {
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -3810,7 +3814,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_outbound_direct_backchannel_proof_uses_received_header_type() {
|
||||
let (tx, mut rx) = mpsc::channel(128);
|
||||
let (inbound_tx, mut inbound_rx) = mpsc::channel(4);
|
||||
let (inbound_tx, mut inbound_rx) = mpsc::unbounded_channel();
|
||||
let mut mgr = LinkDeliveryManager::new(tx, None, None);
|
||||
mgr.set_inbound_packet_sender(inbound_tx);
|
||||
|
||||
@@ -3850,6 +3854,7 @@ mod tests {
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: raw.clone(),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -4279,6 +4284,7 @@ mod tests {
|
||||
&close_body,
|
||||
),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -4320,6 +4326,7 @@ mod tests {
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -4411,6 +4418,7 @@ mod tests {
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: proof_raw.into(),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
mgr.drain_events(&HashMap::new());
|
||||
@@ -4460,6 +4468,7 @@ mod tests {
|
||||
&close_body,
|
||||
),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
|
||||
+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();
|
||||
|
||||
+523
-29
@@ -2,12 +2,15 @@
|
||||
//!
|
||||
//! Python reference: LXMF/LXMPeer.py.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::constants::*;
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
type StoredPeer = (
|
||||
type LegacyStoredPeer = (
|
||||
Vec<u8>,
|
||||
f64,
|
||||
u32,
|
||||
@@ -19,6 +22,133 @@ type StoredPeer = (
|
||||
Vec<Vec<u8>>,
|
||||
);
|
||||
|
||||
const STORED_PEER_VERSION: u8 = 2;
|
||||
const MAX_PEER_METADATA_ENTRIES: usize = 16;
|
||||
const MAX_PEER_METADATA_VALUE_BYTES: usize = 1024;
|
||||
const MAX_PEER_METADATA_BYTES: usize = 4096;
|
||||
|
||||
fn bounded_peer_metadata(metadata: Option<HashMap<u8, Vec<u8>>>) -> Option<HashMap<u8, Vec<u8>>> {
|
||||
let metadata = metadata?;
|
||||
let mut entries = metadata.into_iter().collect::<Vec<_>>();
|
||||
entries.sort_by_key(|(key, _)| *key);
|
||||
|
||||
let mut retained = HashMap::new();
|
||||
let mut retained_bytes = 0usize;
|
||||
for (key, value) in entries.into_iter().take(MAX_PEER_METADATA_ENTRIES) {
|
||||
if value.len() > MAX_PEER_METADATA_VALUE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let entry_bytes = 1usize.saturating_add(value.len());
|
||||
if retained_bytes.saturating_add(entry_bytes) > MAX_PEER_METADATA_BYTES {
|
||||
continue;
|
||||
}
|
||||
retained_bytes += entry_bytes;
|
||||
retained.insert(key, value);
|
||||
}
|
||||
|
||||
Some(retained)
|
||||
}
|
||||
|
||||
/// Versioned peer persistence used by propagation sync.
|
||||
///
|
||||
/// The original Rust format was a nine-element tuple. Readers continue to
|
||||
/// accept that tuple, while new writes retain the announce-derived policy
|
||||
/// needed to prepare a correct outbound offer after restart.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct StoredPeerV2 {
|
||||
version: u8,
|
||||
destination_hash: Vec<u8>,
|
||||
last_sync: f64,
|
||||
unreachable_count: u32,
|
||||
peering_cost: u8,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_cost_flexibility: Option<u8>,
|
||||
autopeered: bool,
|
||||
is_static: bool,
|
||||
handled_ids: Vec<Vec<u8>>,
|
||||
peering_timebase: f64,
|
||||
propagation_transfer_limit: Option<f64>,
|
||||
propagation_sync_limit: Option<f64>,
|
||||
peering_key: Option<(Vec<u8>, u32)>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
last_heard: f64,
|
||||
alive: bool,
|
||||
}
|
||||
|
||||
/// Immutable inputs for one outbound propagation offer.
|
||||
///
|
||||
/// `LxmPeer` remains the authoritative mutable owner. The network task gets a
|
||||
/// clone of this snapshot so offer selection cannot silently fall back to a
|
||||
/// newly-created peer that lacks announce or handled-message state.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OutboundOfferPolicy {
|
||||
pub peer_hash: [u8; 16],
|
||||
pub handled_messages: HashSet<PropagationTransientId>,
|
||||
pub stamp_cost: Option<u8>,
|
||||
pub stamp_cost_flexibility: Option<u8>,
|
||||
pub minimum_stamp_cost: u8,
|
||||
pub peering_cost: u8,
|
||||
pub propagation_transfer_limit: Option<f64>,
|
||||
pub propagation_sync_limit: Option<f64>,
|
||||
pub peering_key: Vec<u8>,
|
||||
pub peering_key_value: Option<u32>,
|
||||
pub peering_timebase: f64,
|
||||
pub autopeered: bool,
|
||||
pub is_static: bool,
|
||||
pub metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl OutboundOfferPolicy {
|
||||
/// Compatibility policy for callers that only know a peer hash.
|
||||
///
|
||||
/// This preserves the old unbounded selection behavior. Production
|
||||
/// callers should construct a snapshot from the authoritative `LxmPeer`.
|
||||
pub fn unrestricted(peer_hash: [u8; 16]) -> Self {
|
||||
Self {
|
||||
peer_hash,
|
||||
handled_messages: HashSet::new(),
|
||||
stamp_cost: None,
|
||||
stamp_cost_flexibility: None,
|
||||
minimum_stamp_cost: 0,
|
||||
peering_cost: PEERING_COST,
|
||||
propagation_transfer_limit: None,
|
||||
propagation_sync_limit: None,
|
||||
peering_key: Vec::new(),
|
||||
peering_key_value: None,
|
||||
peering_timebase: 0.0,
|
||||
autopeered: false,
|
||||
is_static: false,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_peer(&self) -> LxmPeer {
|
||||
let mut peer = LxmPeer::new(self.peer_hash);
|
||||
self.apply_to_peer(&mut peer);
|
||||
peer
|
||||
}
|
||||
|
||||
pub(crate) fn apply_to_peer(&self, peer: &mut LxmPeer) {
|
||||
if self.peering_timebase >= peer.peering_timebase {
|
||||
peer.peering_timebase = self.peering_timebase;
|
||||
peer.stamp_cost = self.stamp_cost;
|
||||
peer.stamp_cost_flexibility = self.stamp_cost_flexibility;
|
||||
peer.peering_cost = self.peering_cost;
|
||||
peer.propagation_transfer_limit = self.propagation_transfer_limit;
|
||||
peer.propagation_sync_limit = self.propagation_sync_limit;
|
||||
peer.peering_key = self.peering_key_value.and_then(|value| {
|
||||
let stamp: [u8; 32] = self.peering_key.clone().try_into().ok()?;
|
||||
Some((stamp, value))
|
||||
});
|
||||
peer.autopeered = self.autopeered;
|
||||
peer.is_static = self.is_static;
|
||||
peer.metadata = self.metadata.clone();
|
||||
}
|
||||
peer.handled_messages
|
||||
.extend(self.handled_messages.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
/// An LXMF peer propagation node.
|
||||
#[derive(Debug)]
|
||||
pub struct LxmPeer {
|
||||
@@ -58,11 +188,15 @@ pub struct LxmPeer {
|
||||
pub last_sync_attempt: f64,
|
||||
pub next_sync_attempt: f64,
|
||||
pub sync_backoff: f64,
|
||||
pub metadata: Option<Vec<u8>>,
|
||||
pub metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
/// Last local propagation-store revision conclusively processed by this
|
||||
/// peer. This is intentionally process-local because node revisions reset
|
||||
/// when the store is reconstructed at startup.
|
||||
pub last_offer_generation: u64,
|
||||
/// Static peers are operator-configured; autopeered peers come from announces.
|
||||
pub is_static: bool,
|
||||
/// Message hashes already handled by this peer, for sync filtering.
|
||||
pub handled_messages: std::collections::HashSet<PropagationTransientId>,
|
||||
pub handled_messages: HashSet<PropagationTransientId>,
|
||||
}
|
||||
|
||||
impl LxmPeer {
|
||||
@@ -100,8 +234,9 @@ impl LxmPeer {
|
||||
next_sync_attempt: 0.0,
|
||||
sync_backoff: 0.0,
|
||||
metadata: None,
|
||||
last_offer_generation: 0,
|
||||
is_static: false,
|
||||
handled_messages: std::collections::HashSet::new(),
|
||||
handled_messages: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,22 +253,122 @@ impl LxmPeer {
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
) -> Self {
|
||||
Self::from_announce_with_metadata(
|
||||
destination_hash,
|
||||
timebase,
|
||||
transfer_limit,
|
||||
sync_limit,
|
||||
stamp_cost,
|
||||
stamp_flexibility,
|
||||
peering_cost,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct a peer from announce data, retaining bounded metadata.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_announce_with_metadata(
|
||||
destination_hash: [u8; 16],
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
) -> Self {
|
||||
let mut peer = Self::new(destination_hash);
|
||||
peer.peering_timebase = timebase;
|
||||
peer.propagation_transfer_limit = transfer_limit;
|
||||
peer.propagation_sync_limit = sync_limit;
|
||||
peer.propagation_sync_limit = sync_limit.or(transfer_limit);
|
||||
peer.stamp_cost = stamp_cost;
|
||||
peer.stamp_cost_flexibility = stamp_flexibility;
|
||||
peer.peering_cost = peering_cost.unwrap_or(PEERING_COST);
|
||||
peer.metadata = bounded_peer_metadata(metadata);
|
||||
peer.autopeered = true;
|
||||
peer
|
||||
}
|
||||
|
||||
/// Effective minimum stamp cost this peer will accept.
|
||||
/// Refresh announce-derived policy only when `timebase` is newer.
|
||||
///
|
||||
/// Returns `true` when the peer was updated. Runtime counters, handled
|
||||
/// messages and static-peer status remain owned by the existing peer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_from_announce(
|
||||
&mut self,
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
) -> bool {
|
||||
let metadata = self.metadata.clone();
|
||||
self.refresh_from_announce_with_metadata(
|
||||
timebase,
|
||||
transfer_limit,
|
||||
sync_limit,
|
||||
stamp_cost,
|
||||
stamp_flexibility,
|
||||
peering_cost,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
/// Refresh announce-derived policy and bounded metadata only when newer.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn refresh_from_announce_with_metadata(
|
||||
&mut self,
|
||||
timebase: f64,
|
||||
transfer_limit: Option<f64>,
|
||||
sync_limit: Option<f64>,
|
||||
stamp_cost: Option<u8>,
|
||||
stamp_flexibility: Option<u8>,
|
||||
peering_cost: Option<u8>,
|
||||
metadata: Option<HashMap<u8, Vec<u8>>>,
|
||||
) -> bool {
|
||||
if timebase <= self.peering_timebase {
|
||||
return false;
|
||||
}
|
||||
|
||||
let offer_constraints_changed = self.propagation_transfer_limit != transfer_limit
|
||||
|| self.propagation_sync_limit != sync_limit.or(transfer_limit)
|
||||
|| self.stamp_cost != stamp_cost
|
||||
|| self.stamp_cost_flexibility != stamp_flexibility
|
||||
|| self.peering_cost != peering_cost.unwrap_or(PEERING_COST);
|
||||
self.peering_timebase = timebase;
|
||||
self.propagation_transfer_limit = transfer_limit;
|
||||
self.propagation_sync_limit = sync_limit.or(transfer_limit);
|
||||
self.stamp_cost = stamp_cost;
|
||||
self.stamp_cost_flexibility = stamp_flexibility;
|
||||
self.peering_cost = peering_cost.unwrap_or(PEERING_COST);
|
||||
self.metadata = bounded_peer_metadata(metadata);
|
||||
if offer_constraints_changed {
|
||||
self.last_offer_generation = 0;
|
||||
}
|
||||
|
||||
// A key remains usable when it still meets the new target. Otherwise
|
||||
// the daemon must generate a replacement before taking a snapshot.
|
||||
if self
|
||||
.peering_key
|
||||
.is_some_and(|(_, value)| value < self.peering_cost as u32)
|
||||
{
|
||||
self.peering_key = None;
|
||||
}
|
||||
|
||||
self.heard();
|
||||
self.next_sync_attempt = 0.0;
|
||||
true
|
||||
}
|
||||
|
||||
/// Effective minimum stamp cost this peer will accept, using the peer's
|
||||
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
|
||||
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -142,6 +377,11 @@ impl LxmPeer {
|
||||
self.stamp_cost.is_some() && self.stamp_cost_flexibility.is_some()
|
||||
}
|
||||
|
||||
/// Snapshot the complete immutable policy for one outbound sync offer.
|
||||
pub fn outbound_offer_policy(&self) -> OutboundOfferPolicy {
|
||||
OutboundOfferPolicy::from(self)
|
||||
}
|
||||
|
||||
pub fn add_unhandled_message(&mut self) {
|
||||
self.unhandled_count_cached = false;
|
||||
self.unhandled_count += 1;
|
||||
@@ -171,27 +411,50 @@ impl LxmPeer {
|
||||
self.handled_messages.contains(hash)
|
||||
}
|
||||
|
||||
pub fn needs_offer_generation(&self, generation: u64) -> bool {
|
||||
generation > self.last_offer_generation
|
||||
}
|
||||
|
||||
pub fn mark_offer_generation_processed(&mut self, generation: u64) {
|
||||
self.last_offer_generation = self.last_offer_generation.max(generation);
|
||||
}
|
||||
|
||||
/// Serialize peer state, including handled messages, for persistence.
|
||||
pub fn to_bytes_with_handled(&self) -> Vec<u8> {
|
||||
let handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
|
||||
let data = (
|
||||
self.destination_hash.to_vec(),
|
||||
self.last_sync,
|
||||
self.unreachable_count,
|
||||
self.peering_cost,
|
||||
self.stamp_cost,
|
||||
self.stamp_cost_flexibility,
|
||||
self.autopeered,
|
||||
self.is_static,
|
||||
handled,
|
||||
);
|
||||
rmp_serde::to_vec(&data).unwrap_or_default()
|
||||
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
|
||||
handled.sort();
|
||||
let data = StoredPeerV2 {
|
||||
version: STORED_PEER_VERSION,
|
||||
destination_hash: self.destination_hash.to_vec(),
|
||||
last_sync: self.last_sync,
|
||||
unreachable_count: self.unreachable_count,
|
||||
peering_cost: self.peering_cost,
|
||||
stamp_cost: self.stamp_cost,
|
||||
stamp_cost_flexibility: self.stamp_cost_flexibility,
|
||||
autopeered: self.autopeered,
|
||||
is_static: self.is_static,
|
||||
handled_ids: handled,
|
||||
peering_timebase: self.peering_timebase,
|
||||
propagation_transfer_limit: self.propagation_transfer_limit,
|
||||
propagation_sync_limit: self.propagation_sync_limit,
|
||||
peering_key: self
|
||||
.peering_key
|
||||
.map(|(stamp, value)| (stamp.to_vec(), value)),
|
||||
metadata: self.metadata.clone(),
|
||||
last_heard: self.last_heard,
|
||||
alive: self.alive,
|
||||
};
|
||||
rmp_serde::to_vec_named(&data).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Deserialize peer state, including handled messages, from [`to_bytes_with_handled`] output.
|
||||
///
|
||||
/// [`to_bytes_with_handled`]: Self::to_bytes_with_handled
|
||||
pub fn from_bytes_with_handled(data: &[u8]) -> Option<Self> {
|
||||
if let Ok(stored) = rmp_serde::from_slice::<StoredPeerV2>(data) {
|
||||
return Self::from_stored_v2(stored);
|
||||
}
|
||||
|
||||
let (
|
||||
dest_hash_vec,
|
||||
last_sync,
|
||||
@@ -202,7 +465,7 @@ impl LxmPeer {
|
||||
autopeered,
|
||||
is_static,
|
||||
handled_vec,
|
||||
): StoredPeer = rmp_serde::from_slice(data).ok()?;
|
||||
): LegacyStoredPeer = rmp_serde::from_slice(data).ok()?;
|
||||
if dest_hash_vec.len() != 16 {
|
||||
return None;
|
||||
}
|
||||
@@ -231,6 +494,39 @@ impl LxmPeer {
|
||||
Some(peer)
|
||||
}
|
||||
|
||||
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
|
||||
if stored.version != STORED_PEER_VERSION || stored.destination_hash.len() != 16 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut destination_hash = [0u8; 16];
|
||||
destination_hash.copy_from_slice(&stored.destination_hash);
|
||||
let mut peer = Self::new(destination_hash);
|
||||
peer.last_sync = stored.last_sync;
|
||||
peer.unreachable_count = stored.unreachable_count;
|
||||
peer.peering_cost = stored.peering_cost;
|
||||
peer.stamp_cost = stored.stamp_cost;
|
||||
peer.stamp_cost_flexibility = stored.stamp_cost_flexibility;
|
||||
peer.autopeered = stored.autopeered;
|
||||
peer.is_static = stored.is_static;
|
||||
peer.peering_timebase = stored.peering_timebase;
|
||||
peer.propagation_transfer_limit = stored.propagation_transfer_limit;
|
||||
peer.propagation_sync_limit = stored.propagation_sync_limit;
|
||||
peer.peering_key = stored.peering_key.and_then(|(stamp, value)| {
|
||||
let stamp: [u8; 32] = stamp.try_into().ok()?;
|
||||
Some((stamp, value))
|
||||
});
|
||||
peer.metadata = stored.metadata;
|
||||
peer.last_heard = stored.last_heard;
|
||||
peer.alive = stored.alive;
|
||||
peer.handled_messages = stored
|
||||
.handled_ids
|
||||
.into_iter()
|
||||
.filter_map(|value| value.try_into().ok())
|
||||
.collect();
|
||||
Some(peer)
|
||||
}
|
||||
|
||||
pub fn mark_unreachable(&mut self) {
|
||||
self.unreachable_count += 1;
|
||||
let now = now_f64();
|
||||
@@ -291,18 +587,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,6 +668,32 @@ impl LxmPeer {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&LxmPeer> for OutboundOfferPolicy {
|
||||
fn from(peer: &LxmPeer) -> Self {
|
||||
let peering_key = peer
|
||||
.peering_key
|
||||
.filter(|(_, value)| *value >= peer.peering_cost as u32)
|
||||
.map(|(stamp, _)| stamp.to_vec())
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
peer_hash: peer.destination_hash,
|
||||
handled_messages: peer.handled_messages.clone(),
|
||||
stamp_cost: peer.stamp_cost,
|
||||
stamp_cost_flexibility: peer.stamp_cost_flexibility,
|
||||
minimum_stamp_cost: peer.minimum_accepted_stamp_cost(),
|
||||
peering_cost: peer.peering_cost,
|
||||
propagation_transfer_limit: peer.propagation_transfer_limit,
|
||||
propagation_sync_limit: peer.propagation_sync_limit,
|
||||
peering_key,
|
||||
peering_key_value: peer.peering_key.map(|(_, value)| value),
|
||||
peering_timebase: peer.peering_timebase,
|
||||
autopeered: peer.autopeered,
|
||||
is_static: peer.is_static,
|
||||
metadata: peer.metadata.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the best peer to sync with from a set of candidates.
|
||||
///
|
||||
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
|
||||
@@ -465,6 +787,178 @@ 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outbound_offer_policy_captures_authoritative_peer_state() {
|
||||
let mut peer = LxmPeer::new([0xAA; 16]);
|
||||
peer.stamp_cost = Some(16);
|
||||
peer.stamp_cost_flexibility = Some(3);
|
||||
peer.propagation_transfer_limit = Some(1.5);
|
||||
peer.propagation_sync_limit = Some(4.5);
|
||||
peer.peering_cost = 18;
|
||||
peer.peering_key = Some(([0x77; 32], 18));
|
||||
peer.add_handled_message(&tid(0x11));
|
||||
|
||||
let policy = peer.outbound_offer_policy();
|
||||
|
||||
assert_eq!(policy.peer_hash, [0xAA; 16]);
|
||||
assert_eq!(policy.minimum_stamp_cost, 13);
|
||||
assert_eq!(policy.propagation_transfer_limit, Some(1.5));
|
||||
assert_eq!(policy.propagation_sync_limit, Some(4.5));
|
||||
assert_eq!(policy.peering_key, vec![0x77; 32]);
|
||||
assert!(policy.handled_messages.contains(&tid(0x11)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_announce_cannot_overwrite_newer_peer_policy() {
|
||||
let mut peer = LxmPeer::from_announce(
|
||||
[0xAA; 16],
|
||||
200.0,
|
||||
Some(2.0),
|
||||
Some(8.0),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
);
|
||||
|
||||
assert!(!peer.refresh_from_announce(
|
||||
199.0,
|
||||
Some(1.0),
|
||||
Some(4.0),
|
||||
Some(8),
|
||||
Some(1),
|
||||
Some(4),
|
||||
));
|
||||
assert_eq!(peer.peering_timebase, 200.0);
|
||||
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
|
||||
assert_eq!(peer.stamp_cost, Some(16));
|
||||
|
||||
peer.peering_key = Some(([0x55; 32], 18));
|
||||
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
|
||||
assert_eq!(peer.propagation_sync_limit, Some(3.0));
|
||||
assert_eq!(peer.stamp_cost, Some(20));
|
||||
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_persistence_retains_offer_policy_and_reads_legacy_tuple() {
|
||||
let mut peer = LxmPeer::from_announce(
|
||||
[0xAA; 16],
|
||||
1234.0,
|
||||
Some(1.25),
|
||||
Some(9.5),
|
||||
Some(16),
|
||||
Some(3),
|
||||
Some(18),
|
||||
);
|
||||
peer.peering_key = Some(([0x66; 32], 19));
|
||||
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
|
||||
peer.add_handled_message(&tid(0x22));
|
||||
|
||||
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
|
||||
assert_eq!(restored.peering_timebase, 1234.0);
|
||||
assert_eq!(restored.propagation_transfer_limit, Some(1.25));
|
||||
assert_eq!(restored.propagation_sync_limit, Some(9.5));
|
||||
assert_eq!(restored.peering_key, Some(([0x66; 32], 19)));
|
||||
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
|
||||
assert!(restored.has_handled(&tid(0x22)));
|
||||
|
||||
let legacy: LegacyStoredPeer = (
|
||||
vec![0xBB; 16],
|
||||
42.0,
|
||||
2,
|
||||
18,
|
||||
Some(12),
|
||||
Some(2),
|
||||
true,
|
||||
false,
|
||||
vec![tid(0x33).to_vec()],
|
||||
);
|
||||
let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap();
|
||||
let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap();
|
||||
assert_eq!(restored_legacy.destination_hash, [0xBB; 16]);
|
||||
assert_eq!(restored_legacy.stamp_cost, Some(12));
|
||||
assert!(restored_legacy.has_handled(&tid(0x33)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_metadata_is_typed_bounded_and_persisted() {
|
||||
let mut metadata = HashMap::new();
|
||||
metadata.insert(0, b"node name".to_vec());
|
||||
metadata.insert(1, vec![0xAA; MAX_PEER_METADATA_VALUE_BYTES + 1]);
|
||||
for key in 2..=30 {
|
||||
metadata.insert(key, vec![key; 8]);
|
||||
}
|
||||
|
||||
let peer = LxmPeer::from_announce_with_metadata(
|
||||
[0xAA; 16],
|
||||
10.0,
|
||||
Some(1.0),
|
||||
Some(2.0),
|
||||
Some(12),
|
||||
Some(3),
|
||||
Some(18),
|
||||
Some(metadata),
|
||||
);
|
||||
let retained = peer.metadata.as_ref().unwrap();
|
||||
assert_eq!(retained.get(&0), Some(&b"node name".to_vec()));
|
||||
assert!(!retained.contains_key(&1));
|
||||
assert!(retained.len() <= MAX_PEER_METADATA_ENTRIES);
|
||||
|
||||
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
|
||||
assert_eq!(restored.metadata, peer.metadata);
|
||||
|
||||
let empty = LxmPeer::from_announce_with_metadata(
|
||||
[0xBB; 16],
|
||||
10.0,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(HashMap::new()),
|
||||
);
|
||||
assert_eq!(empty.metadata, Some(HashMap::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_policy_invalidates_processed_store_generation() {
|
||||
let mut peer =
|
||||
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None);
|
||||
peer.mark_offer_generation_processed(7);
|
||||
assert!(!peer.needs_offer_generation(7));
|
||||
|
||||
assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None));
|
||||
assert!(peer.needs_offer_generation(7));
|
||||
|
||||
peer.mark_offer_generation_processed(7);
|
||||
assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None));
|
||||
assert!(
|
||||
!peer.needs_offer_generation(7),
|
||||
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
|
||||
);
|
||||
}
|
||||
|
||||
/// T0-4: an absurd announce-supplied peering cost must fail the bounded
|
||||
/// key search instead of spinning forever; sane costs still succeed.
|
||||
#[test]
|
||||
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]
|
||||
|
||||
@@ -23,6 +23,64 @@ pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
|
||||
pub const TICKETS_FILE: &str = "available_tickets";
|
||||
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
|
||||
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
|
||||
pub const NODE_STATS_FILE: &str = "node_stats";
|
||||
|
||||
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedNodeStats {
|
||||
pub client_propagation_messages_received: u64,
|
||||
pub client_propagation_messages_served: u64,
|
||||
pub unpeered_propagation_incoming: u64,
|
||||
pub unpeered_propagation_rx_bytes: u64,
|
||||
}
|
||||
|
||||
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
|
||||
///
|
||||
/// 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 =
|
||||
@@ -30,10 +88,7 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let tmp = path.with_extension("tmp");
|
||||
fs::write(&tmp, &bytes)?;
|
||||
fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
write_file_atomic(path, &bytes)
|
||||
}
|
||||
|
||||
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
|
||||
@@ -86,6 +141,17 @@ pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTrans
|
||||
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
|
||||
let bytes = rmp_serde::to_vec_named(stats)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
fs::create_dir_all(dir)?;
|
||||
write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes)
|
||||
}
|
||||
|
||||
pub fn load_node_stats(dir: &Path) -> io::Result<PersistedNodeStats> {
|
||||
Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -136,5 +202,133 @@ mod tests {
|
||||
assert!(load_tickets(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
|
||||
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
load_node_stats(tmp.path()).unwrap(),
|
||||
PersistedNodeStats::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_stats_roundtrip_uses_named_python_fields() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let expected = PersistedNodeStats {
|
||||
client_propagation_messages_received: 11,
|
||||
client_propagation_messages_served: 12,
|
||||
unpeered_propagation_incoming: 13,
|
||||
unpeered_propagation_rx_bytes: 14,
|
||||
};
|
||||
|
||||
save_node_stats(tmp.path(), &expected).unwrap();
|
||||
assert_eq!(load_node_stats(tmp.path()).unwrap(), expected);
|
||||
|
||||
let encoded = fs::read(tmp.path().join(NODE_STATS_FILE)).unwrap();
|
||||
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(encoded)).unwrap();
|
||||
let keys = value
|
||||
.as_map()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|(key, _)| key.as_str())
|
||||
.collect::<std::collections::HashSet<_>>();
|
||||
assert!(keys.contains("client_propagation_messages_received"));
|
||||
assert!(keys.contains("client_propagation_messages_served"));
|
||||
assert!(keys.contains("unpeered_propagation_incoming"));
|
||||
assert!(keys.contains("unpeered_propagation_rx_bytes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialization_failure_preserves_existing_file_without_temp_residue() {
|
||||
struct FailsToSerialize;
|
||||
|
||||
impl serde::Serialize for FailsToSerialize {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
Err(serde::ser::Error::custom("intentional failure"))
|
||||
}
|
||||
}
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = tmp.path().join("state");
|
||||
fs::write(&path, b"previous-good-state").unwrap();
|
||||
|
||||
assert!(write_mpk(&path, &FailsToSerialize).is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous-good-state");
|
||||
assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writers_never_publish_torn_data_or_collide_on_temp_names() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let path = Arc::new(tmp.path().join("shared"));
|
||||
let barrier = Arc::new(Barrier::new(8));
|
||||
let payloads = (0u8..8)
|
||||
.map(|value| vec![value; 16 * 1024])
|
||||
.collect::<Vec<_>>();
|
||||
let threads = payloads
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|payload| {
|
||||
let path = Arc::clone(&path);
|
||||
let barrier = Arc::clone(&barrier);
|
||||
std::thread::spawn(move || {
|
||||
barrier.wait();
|
||||
write_file_atomic(path.as_ref(), &payload).unwrap();
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for thread in threads {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
|
||||
let published = fs::read(path.as_ref()).unwrap();
|
||||
assert!(payloads.contains(&published));
|
||||
let leftovers = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
|
||||
.count();
|
||||
assert_eq!(leftovers, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Safe presentation helpers for untrusted announce metadata.
|
||||
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
/// Maximum retained characters for an advertised LXMF display/node name.
|
||||
pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
|
||||
|
||||
/// Normalize and bound an untrusted display name.
|
||||
///
|
||||
/// The result is NFKC-normalized, contains no control or presentation-control
|
||||
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is
|
||||
/// truncated by Unicode scalar values rather than UTF-8 bytes.
|
||||
pub fn sanitize_name(input: &str, max_chars: usize) -> String {
|
||||
if max_chars == 0 {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut output = String::new();
|
||||
let mut pending_space = false;
|
||||
let mut retained = 0usize;
|
||||
|
||||
for character in input.nfkc() {
|
||||
if is_filtered_name_character(character) {
|
||||
continue;
|
||||
}
|
||||
if character.is_whitespace() {
|
||||
pending_space = !output.is_empty();
|
||||
continue;
|
||||
}
|
||||
if pending_space {
|
||||
// A collapsed separator is useful only when the current visible
|
||||
// character also fits. Never consume the final slot with a
|
||||
// trailing space that disappears on the next sanitization pass.
|
||||
if max_chars.saturating_sub(retained) < 2 {
|
||||
break;
|
||||
}
|
||||
output.push(' ');
|
||||
retained += 1;
|
||||
pending_space = false;
|
||||
}
|
||||
if retained == max_chars {
|
||||
break;
|
||||
}
|
||||
output.push(character);
|
||||
retained += 1;
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
fn is_filtered_name_character(character: char) -> bool {
|
||||
let codepoint = character as u32;
|
||||
character.is_control()
|
||||
|| is_bidi_control(codepoint)
|
||||
|| is_private_use(codepoint)
|
||||
|| is_zero_width(codepoint)
|
||||
|| is_variation_selector(codepoint)
|
||||
|| is_emoji(codepoint)
|
||||
}
|
||||
|
||||
fn is_bidi_control(codepoint: u32) -> bool {
|
||||
matches!(
|
||||
codepoint,
|
||||
0x061C
|
||||
| 0x200E
|
||||
| 0x200F
|
||||
| 0x202A..=0x202E
|
||||
| 0x2066..=0x2069
|
||||
| 0x206A..=0x206F
|
||||
)
|
||||
}
|
||||
|
||||
fn is_private_use(codepoint: u32) -> bool {
|
||||
matches!(
|
||||
codepoint,
|
||||
0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD
|
||||
)
|
||||
}
|
||||
|
||||
fn is_zero_width(codepoint: u32) -> bool {
|
||||
matches!(
|
||||
codepoint,
|
||||
0x034F | 0x180E | 0x200B..=0x200D | 0x2060 | 0xFEFF
|
||||
)
|
||||
}
|
||||
|
||||
fn is_variation_selector(codepoint: u32) -> bool {
|
||||
matches!(codepoint, 0xFE00..=0xFE0F | 0xE0100..=0xE01EF)
|
||||
}
|
||||
|
||||
// Bounded presentation policy, intentionally broader than a font-dependent
|
||||
// emoji lookup. It covers the Unicode emoji blocks and legacy symbol ranges
|
||||
// that gain emoji presentation through variation selectors.
|
||||
fn is_emoji(codepoint: u32) -> bool {
|
||||
matches!(
|
||||
codepoint,
|
||||
0x00A9
|
||||
| 0x00AE
|
||||
| 0x203C
|
||||
| 0x2049
|
||||
| 0x2122
|
||||
| 0x2139
|
||||
| 0x2190..=0x21FF
|
||||
| 0x2300..=0x23FF
|
||||
| 0x2460..=0x24FF
|
||||
| 0x25A0..=0x27BF
|
||||
| 0x2934..=0x2935
|
||||
| 0x2B00..=0x2BFF
|
||||
| 0x3030
|
||||
| 0x303D
|
||||
| 0x3297
|
||||
| 0x3299
|
||||
| 0x1F000..=0x1FAFF
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes_nfkc_and_collapses_unicode_whitespace() {
|
||||
assert_eq!(
|
||||
sanitize_name(" RNS\u{00A0}\tCommunity ", 128),
|
||||
"RNS Community"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removes_controls_bidi_private_use_emoji_variants_and_zero_width() {
|
||||
let hostile = "safe\n\u{202E}txt\u{E000}\u{1F680}\u{FE0F}\u{200D} name";
|
||||
assert_eq!(sanitize_name(hostile, 128), "safetxt name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncates_multibyte_text_by_characters_without_panicking() {
|
||||
assert_eq!(sanitize_name("Ångström東京", 8), "Ångström");
|
||||
assert_eq!(sanitize_name("東京通信", 3), "東京通");
|
||||
assert_eq!(sanitize_name("anything", 0), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncation_never_retains_a_separator_without_following_text() {
|
||||
assert_eq!(sanitize_name("¡ A", 2), "¡");
|
||||
assert_eq!(sanitize_name("A B", 3), "A B");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
|
||||
let sanitized = sanitize_name(&input, limit);
|
||||
prop_assert!(sanitized.chars().count() <= limit);
|
||||
prop_assert_eq!(sanitize_name(&sanitized, limit), sanitized);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -40,12 +40,35 @@ pub enum PropagationClientState {
|
||||
ListRequested,
|
||||
/// `/get` with `[wants, haves, limit]` sent.
|
||||
GetRequested,
|
||||
/// A Resource response is actively transferring.
|
||||
Receiving,
|
||||
/// `/get` with `[None, received_ids]` sent.
|
||||
PurgeRequested,
|
||||
Complete,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// One coherent public snapshot of a propagation-node download.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PropagationTransferStatus {
|
||||
pub state: PropagationClientState,
|
||||
pub progress: f64,
|
||||
pub data_size: Option<usize>,
|
||||
/// Number of message blobs decoded from the completed response.
|
||||
pub result: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for PropagationTransferStatus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
state: PropagationClientState::Idle,
|
||||
progress: 0.0,
|
||||
data_size: None,
|
||||
result: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SegmentRoute {
|
||||
original_hash: [u8; 32],
|
||||
segment_index: usize,
|
||||
@@ -58,7 +81,9 @@ pub struct PropagationClient {
|
||||
outbound_propagation_node: Option<[u8; 16]>,
|
||||
link: Option<Link>,
|
||||
link_id: Option<[u8; 16]>,
|
||||
pub state: PropagationClientState,
|
||||
status: PropagationTransferStatus,
|
||||
/// Request phase whose response is currently arriving as a Resource.
|
||||
receiving_for: Option<PropagationClientState>,
|
||||
identity_pub: Option<[u8; 64]>,
|
||||
identity_key: Option<Ed25519PrivateKey>,
|
||||
/// Phase 1 response: transient IDs the server has.
|
||||
@@ -93,7 +118,8 @@ impl PropagationClient {
|
||||
outbound_propagation_node: None,
|
||||
link: None,
|
||||
link_id: None,
|
||||
state: PropagationClientState::Idle,
|
||||
status: PropagationTransferStatus::default(),
|
||||
receiving_for: None,
|
||||
identity_pub,
|
||||
identity_key,
|
||||
available_messages: Vec::new(),
|
||||
@@ -135,11 +161,47 @@ impl PropagationClient {
|
||||
std::mem::take(&mut self.received_messages)
|
||||
}
|
||||
|
||||
pub const fn state(&self) -> PropagationClientState {
|
||||
self.status.state
|
||||
}
|
||||
|
||||
pub const fn transfer_status(&self) -> PropagationTransferStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
/// Clear a terminal presentation snapshot after the caller has consumed
|
||||
/// its result. Active transfers are never reset by acknowledgement.
|
||||
pub fn acknowledge_transfer(&mut self) -> bool {
|
||||
if !matches!(
|
||||
self.status.state,
|
||||
PropagationClientState::Complete | PropagationClientState::Failed
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
self.cleanup();
|
||||
self.status = PropagationTransferStatus::default();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn start_download(&mut self) -> bool {
|
||||
let node_hash = match self.outbound_propagation_node {
|
||||
Some(h) => h,
|
||||
None => return false,
|
||||
};
|
||||
if !matches!(
|
||||
self.status.state,
|
||||
PropagationClientState::Idle
|
||||
| PropagationClientState::Complete
|
||||
| PropagationClientState::Failed
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if matches!(
|
||||
self.status.state,
|
||||
PropagationClientState::Complete | PropagationClientState::Failed
|
||||
) {
|
||||
self.cleanup();
|
||||
}
|
||||
|
||||
let (link, request_data) = Link::new_initiator(node_hash, 1);
|
||||
let link_id = link.link_id;
|
||||
@@ -180,9 +242,13 @@ impl PropagationClient {
|
||||
destination_hash: node_hash,
|
||||
}));
|
||||
|
||||
self.status = PropagationTransferStatus {
|
||||
state: PropagationClientState::LinkEstablishing,
|
||||
..PropagationTransferStatus::default()
|
||||
};
|
||||
self.receiving_for = None;
|
||||
self.link = Some(link);
|
||||
self.link_id = Some(link_id);
|
||||
self.state = PropagationClientState::LinkEstablishing;
|
||||
self.started_at = Some(Instant::now());
|
||||
self.identified = false;
|
||||
self.available_messages.clear();
|
||||
@@ -225,7 +291,7 @@ impl PropagationClient {
|
||||
if header.flags.packet_type == rns_wire::flags::PacketType::Proof
|
||||
|| header.context == rns_wire::context::PacketContext::Lrproof =>
|
||||
{
|
||||
if self.state != PropagationClientState::LinkEstablishing {
|
||||
if self.status.state != PropagationClientState::LinkEstablishing {
|
||||
continue;
|
||||
}
|
||||
let node_hex = self.outbound_propagation_node.map(|h| hex_encode(&h));
|
||||
@@ -293,7 +359,7 @@ impl PropagationClient {
|
||||
self.inbound_resources.clear();
|
||||
self.inbound_split_resources.clear();
|
||||
self.segment_routing.clear();
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
|
||||
verified
|
||||
@@ -336,16 +402,26 @@ impl PropagationClient {
|
||||
destination_hash: link_id,
|
||||
}));
|
||||
}
|
||||
self.state = PropagationClientState::LinkEstablished;
|
||||
self.status.state = PropagationClientState::LinkEstablished;
|
||||
}
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_response_data(&mut self, response_data: &[u8]) {
|
||||
match self.state {
|
||||
let response_phase = if self.status.state == PropagationClientState::Receiving {
|
||||
let Some(phase) = self.receiving_for.take() else {
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
};
|
||||
phase
|
||||
} else {
|
||||
self.status.state
|
||||
};
|
||||
|
||||
match response_phase {
|
||||
PropagationClientState::ListRequested => {
|
||||
self.handle_list_response(response_data);
|
||||
}
|
||||
@@ -364,11 +440,11 @@ impl PropagationClient {
|
||||
return;
|
||||
};
|
||||
let Ok(plaintext) = link.decrypt(data) else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
};
|
||||
let Ok(adv) = ResourceAdvertisement::unpack(&plaintext) else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -376,12 +452,29 @@ impl PropagationClient {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.status.state != PropagationClientState::Receiving {
|
||||
if !matches!(
|
||||
self.status.state,
|
||||
PropagationClientState::ListRequested
|
||||
| PropagationClientState::GetRequested
|
||||
| PropagationClientState::PurgeRequested
|
||||
) {
|
||||
return;
|
||||
}
|
||||
self.receiving_for = Some(self.status.state);
|
||||
} else if self.receiving_for.is_none() {
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
self.status.state = PropagationClientState::Receiving;
|
||||
self.status.data_size = Some(self.status.data_size.unwrap_or_default().max(adv.data_size));
|
||||
|
||||
if adv.total_segments > 1 {
|
||||
if adv.total_segments > MAX_SEGMENTS
|
||||
|| adv.segment_index == 0
|
||||
|| adv.segment_index > adv.total_segments
|
||||
{
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -390,7 +483,7 @@ impl PropagationClient {
|
||||
.entry(adv.original_hash)
|
||||
.or_insert_with(|| MultiSegmentInbound::new(adv.total_segments, adv.original_hash));
|
||||
if entry.total_segments != adv.total_segments {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
self.segment_routing.insert(
|
||||
@@ -422,7 +515,7 @@ impl PropagationClient {
|
||||
map_hashes,
|
||||
rtt,
|
||||
) else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -442,6 +535,7 @@ impl PropagationClient {
|
||||
fn handle_resource_part(&mut self, data: &[u8]) {
|
||||
let mut control_actions = Vec::new();
|
||||
let mut completed = None;
|
||||
let mut observed_progress = None;
|
||||
|
||||
for (resource_hash, transfer) in &mut self.inbound_resources {
|
||||
let action = transfer.receive_part(data.to_vec());
|
||||
@@ -453,7 +547,7 @@ impl PropagationClient {
|
||||
control_actions.push((rns_wire::context::PacketContext::ResourceReq, req));
|
||||
}
|
||||
TransferAction::Failed(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
@@ -462,6 +556,7 @@ impl PropagationClient {
|
||||
if transfer.resource.is_complete() {
|
||||
completed = Some(*resource_hash);
|
||||
}
|
||||
observed_progress = Some((*resource_hash, transfer.resource.progress()));
|
||||
|
||||
if completed.is_some() || !control_actions.is_empty() {
|
||||
break;
|
||||
@@ -472,6 +567,23 @@ impl PropagationClient {
|
||||
self.send_encrypted_resource_control(context, &payload);
|
||||
}
|
||||
|
||||
if let Some((resource_hash, segment_progress)) = observed_progress {
|
||||
let progress = self
|
||||
.segment_routing
|
||||
.get(&resource_hash)
|
||||
.and_then(|route| {
|
||||
self.inbound_split_resources
|
||||
.get(&route.original_hash)
|
||||
.map(|coordinator| {
|
||||
(coordinator.assembled_count() as f64 + segment_progress)
|
||||
/ coordinator.total_segments.max(1) as f64
|
||||
})
|
||||
})
|
||||
.unwrap_or(segment_progress);
|
||||
self.status.state = PropagationClientState::Receiving;
|
||||
self.status.progress = self.status.progress.max(progress.clamp(0.0, 1.0));
|
||||
}
|
||||
|
||||
if let Some(resource_hash) = completed {
|
||||
self.complete_resource(resource_hash);
|
||||
}
|
||||
@@ -518,7 +630,7 @@ impl PropagationClient {
|
||||
);
|
||||
}
|
||||
TransferAction::Failed(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -543,7 +655,7 @@ impl PropagationClient {
|
||||
if let Some(link) = self.link.as_mut() {
|
||||
link.untrack_resource(&resource_hash);
|
||||
}
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
|
||||
fn complete_resource(&mut self, resource_hash: [u8; 32]) {
|
||||
@@ -564,7 +676,7 @@ impl PropagationClient {
|
||||
assembled
|
||||
}
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -587,7 +699,7 @@ impl PropagationClient {
|
||||
.set_segment_data(route.segment_index, assembled)
|
||||
.is_err()
|
||||
{
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
if let Some(meta) = metadata {
|
||||
@@ -597,7 +709,7 @@ impl PropagationClient {
|
||||
match coord.reassemble() {
|
||||
Ok(payload) => complete_payload = Some(payload),
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -620,7 +732,7 @@ impl PropagationClient {
|
||||
match link.handle_response_plaintext(payload) {
|
||||
Ok((_request_id, response_data)) => response_data,
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -685,7 +797,7 @@ impl PropagationClient {
|
||||
let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -701,12 +813,14 @@ impl PropagationClient {
|
||||
}
|
||||
|
||||
if self.available_messages.is_empty() {
|
||||
self.state = PropagationClientState::Complete;
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
self.status.progress = 1.0;
|
||||
self.status.result = Some(0);
|
||||
} else {
|
||||
self.send_get_request();
|
||||
}
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,47 +829,52 @@ impl PropagationClient {
|
||||
let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(arr) = value.as_array() {
|
||||
let mut received = 0usize;
|
||||
for item in arr {
|
||||
if let Some(msg_data) = item.as_slice() {
|
||||
let tid = rns_crypto::sha::full_hash(msg_data);
|
||||
self.received_ids.push(tid.to_vec());
|
||||
self.received_messages.push(msg_data.to_vec());
|
||||
received += 1;
|
||||
}
|
||||
}
|
||||
self.status.progress = 1.0;
|
||||
self.status.result = Some(received);
|
||||
|
||||
if !self.received_ids.is_empty() {
|
||||
self.send_purge_request();
|
||||
} else {
|
||||
self.state = PropagationClientState::Complete;
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
}
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase 3: mark the download complete.
|
||||
fn handle_purge_response(&mut self) {
|
||||
self.state = PropagationClientState::Complete;
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
self.status.progress = 1.0;
|
||||
}
|
||||
|
||||
pub fn tick(&mut self) {
|
||||
if let Some(started) = self.started_at
|
||||
&& started.elapsed() > self.timeout
|
||||
&& self.state != PropagationClientState::Idle
|
||||
&& self.state != PropagationClientState::Complete
|
||||
&& self.status.state != PropagationClientState::Idle
|
||||
&& self.status.state != PropagationClientState::Complete
|
||||
{
|
||||
self.cleanup();
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
return;
|
||||
}
|
||||
|
||||
match self.state {
|
||||
match self.status.state {
|
||||
PropagationClientState::Idle => {}
|
||||
PropagationClientState::LinkEstablishing => {}
|
||||
PropagationClientState::LinkEstablished => {
|
||||
@@ -767,10 +886,10 @@ impl PropagationClient {
|
||||
}
|
||||
PropagationClientState::ListRequested
|
||||
| PropagationClientState::GetRequested
|
||||
| PropagationClientState::Receiving
|
||||
| PropagationClientState::PurgeRequested => {}
|
||||
PropagationClientState::Complete | PropagationClientState::Failed => {
|
||||
self.cleanup();
|
||||
self.state = PropagationClientState::Idle;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -808,15 +927,16 @@ impl PropagationClient {
|
||||
fn send_list_request(&mut self) {
|
||||
use rmpv::Value;
|
||||
|
||||
self.receiving_for = None;
|
||||
let request_data = {
|
||||
let array = Value::Array(vec![Value::Nil, Value::Nil]);
|
||||
crate::encode_value(&array)
|
||||
};
|
||||
|
||||
if self.send_get_path_request(&request_data) {
|
||||
self.state = PropagationClientState::ListRequested;
|
||||
self.status.state = PropagationClientState::ListRequested;
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,6 +944,11 @@ impl PropagationClient {
|
||||
fn send_get_request(&mut self) {
|
||||
use rmpv::Value;
|
||||
|
||||
self.status.progress = 0.0;
|
||||
self.status.data_size = None;
|
||||
self.status.result = None;
|
||||
self.receiving_for = None;
|
||||
|
||||
let wants: Vec<Value> = self
|
||||
.available_messages
|
||||
.iter()
|
||||
@@ -841,15 +966,17 @@ impl PropagationClient {
|
||||
|
||||
if wants.is_empty() {
|
||||
if haves.is_empty() {
|
||||
self.state = PropagationClientState::Complete;
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
self.status.progress = 1.0;
|
||||
self.status.result = Some(0);
|
||||
return;
|
||||
}
|
||||
let array = Value::Array(vec![Value::Nil, Value::Array(haves)]);
|
||||
let buf = crate::encode_value(&array);
|
||||
if self.send_get_path_request(&buf) {
|
||||
self.state = PropagationClientState::PurgeRequested;
|
||||
self.status.state = PropagationClientState::PurgeRequested;
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -863,9 +990,9 @@ impl PropagationClient {
|
||||
let buf = crate::encode_value(&array);
|
||||
|
||||
if self.send_get_path_request(&buf) {
|
||||
self.state = PropagationClientState::GetRequested;
|
||||
self.status.state = PropagationClientState::GetRequested;
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -873,6 +1000,7 @@ impl PropagationClient {
|
||||
fn send_purge_request(&mut self) {
|
||||
use rmpv::Value;
|
||||
|
||||
self.receiving_for = None;
|
||||
let received: Vec<Value> = self
|
||||
.received_ids
|
||||
.iter()
|
||||
@@ -883,9 +1011,9 @@ impl PropagationClient {
|
||||
let buf = crate::encode_value(&array);
|
||||
|
||||
if self.send_get_path_request(&buf) {
|
||||
self.state = PropagationClientState::PurgeRequested;
|
||||
self.status.state = PropagationClientState::PurgeRequested;
|
||||
} else {
|
||||
self.state = PropagationClientState::Failed;
|
||||
self.status.state = PropagationClientState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -946,6 +1074,7 @@ impl PropagationClient {
|
||||
self.inbound_resources.clear();
|
||||
self.inbound_split_resources.clear();
|
||||
self.segment_routing.clear();
|
||||
self.receiving_for = None;
|
||||
self.started_at = None;
|
||||
}
|
||||
|
||||
@@ -978,6 +1107,7 @@ impl PropagationClient {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_protocol::resource::OutboundTransfer;
|
||||
|
||||
fn active_link_pair(dest_hash: [u8; 16]) -> (Link, Link) {
|
||||
let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
|
||||
@@ -1019,7 +1149,7 @@ mod tests {
|
||||
fn test_client_creation() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let client = PropagationClient::new(tx, None, None);
|
||||
assert_eq!(client.state, PropagationClientState::Idle);
|
||||
assert_eq!(client.status.state, PropagationClientState::Idle);
|
||||
assert_eq!(client.received_count(), 0);
|
||||
}
|
||||
|
||||
@@ -1038,7 +1168,7 @@ mod tests {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
assert!(!client.start_download());
|
||||
assert_eq!(client.state, PropagationClientState::Idle);
|
||||
assert_eq!(client.status.state, PropagationClientState::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1048,7 +1178,10 @@ mod tests {
|
||||
client.set_propagation_node([0xBB; 16]);
|
||||
|
||||
assert!(client.start_download());
|
||||
assert_eq!(client.state, PropagationClientState::LinkEstablishing);
|
||||
assert_eq!(
|
||||
client.status.state,
|
||||
PropagationClientState::LinkEstablishing
|
||||
);
|
||||
assert!(client.link_id.is_some());
|
||||
|
||||
let reg = rx.try_recv();
|
||||
@@ -1060,6 +1193,20 @@ mod tests {
|
||||
assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_start_download_rejects_an_active_transfer() {
|
||||
let (tx, mut rx) = mpsc::channel(64);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.set_propagation_node([0xBC; 16]);
|
||||
|
||||
assert!(client.start_download());
|
||||
while rx.try_recv().is_ok() {}
|
||||
|
||||
assert!(!client.start_download());
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(client.state(), PropagationClientState::LinkEstablishing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_add_local_messages() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
@@ -1099,30 +1246,30 @@ mod tests {
|
||||
fn test_handle_list_response_empty() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &rmpv::Value::Array(vec![])).unwrap();
|
||||
|
||||
client.handle_list_response(&buf);
|
||||
assert_eq!(client.state, PropagationClientState::Complete);
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_list_response_invalid() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
|
||||
client.handle_list_response(&[0xFF, 0xFF]);
|
||||
assert_eq!(client.state, PropagationClientState::Failed);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_list_response_accepts_python_full_hash_ids() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
|
||||
let id32 = vec![0xAB; 32];
|
||||
let response = rmpv::Value::Array(vec![rmpv::Value::Binary(id32.clone())]);
|
||||
@@ -1133,14 +1280,14 @@ mod tests {
|
||||
assert_eq!(client.available_messages, vec![id32]);
|
||||
// It accepted the 32-byte ID, then failed only because this unit test
|
||||
// has no live link on which to send the follow-up `/get`.
|
||||
assert_eq!(client.state, PropagationClientState::Failed);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_list_response_rejects_pre_fix_16_byte_ids() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
|
||||
let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAB; 16])]);
|
||||
let mut buf = Vec::new();
|
||||
@@ -1148,7 +1295,7 @@ mod tests {
|
||||
|
||||
client.handle_list_response(&buf);
|
||||
assert!(client.available_messages.is_empty());
|
||||
assert_eq!(client.state, PropagationClientState::Complete);
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1157,7 +1304,7 @@ mod tests {
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.set_propagation_node([0xBB; 16]);
|
||||
client.start_download();
|
||||
client.state = PropagationClientState::GetRequested;
|
||||
client.status.state = PropagationClientState::GetRequested;
|
||||
|
||||
let msg1 = vec![0xAA; 100];
|
||||
let msg2 = vec![0xBB; 200];
|
||||
@@ -1178,30 +1325,105 @@ mod tests {
|
||||
rns_crypto::sha::full_hash(&msg1).to_vec()
|
||||
);
|
||||
assert_eq!(client.received_ids[0].len(), 32);
|
||||
assert_eq!(client.transfer_status().progress, 1.0);
|
||||
assert_eq!(client.transfer_status().result, Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_get_response_empty() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::GetRequested;
|
||||
client.status.state = PropagationClientState::GetRequested;
|
||||
|
||||
let response = rmpv::Value::Array(vec![]);
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &response).unwrap();
|
||||
|
||||
client.handle_get_response(&buf);
|
||||
assert_eq!(client.state, PropagationClientState::Complete);
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_response_retains_the_request_phase() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.status.state = PropagationClientState::Receiving;
|
||||
client.receiving_for = Some(PropagationClientState::GetRequested);
|
||||
|
||||
let response = rmpv::Value::Array(vec![]);
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &response).unwrap();
|
||||
client.handle_response_data(&buf);
|
||||
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
assert_eq!(client.status.progress, 1.0);
|
||||
assert_eq!(client.status.result, Some(0));
|
||||
assert!(client.receiving_for.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_response_reports_size_and_monotonic_progress() {
|
||||
let (tx, mut rx) = mpsc::channel(64);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
let (initiator, responder) = active_link_pair([0xE3; 16]);
|
||||
client.link_id = Some(initiator.link_id);
|
||||
client.link = Some(initiator);
|
||||
client.status.state = PropagationClientState::GetRequested;
|
||||
|
||||
let payload = vec![0xAB; 3_000];
|
||||
let mut sender = OutboundTransfer::new_encrypted(
|
||||
payload.clone(),
|
||||
false,
|
||||
Duration::from_millis(50),
|
||||
responder.session_keys().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
sender.resource.flags.is_response = true;
|
||||
let advertisement = match sender.tick() {
|
||||
TransferAction::SendAdvertisement(data) => data,
|
||||
other => panic!("expected Resource advertisement, got {other:?}"),
|
||||
};
|
||||
let encrypted_advertisement = responder.encrypt(&advertisement).unwrap();
|
||||
|
||||
client.handle_resource_advertisement(&encrypted_advertisement);
|
||||
assert_eq!(client.status.state, PropagationClientState::Receiving);
|
||||
assert_eq!(client.status.data_size, Some(payload.len()));
|
||||
assert_eq!(
|
||||
client.receiving_for,
|
||||
Some(PropagationClientState::GetRequested)
|
||||
);
|
||||
|
||||
let request = match rx.try_recv().unwrap() {
|
||||
TransportMessage::Outbound(request) => request,
|
||||
other => panic!("expected Resource request, got {other:?}"),
|
||||
};
|
||||
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
let request_data = responder.decrypt(&request.raw[offset..]).unwrap();
|
||||
let first_part = sender
|
||||
.handle_request(&request_data)
|
||||
.into_iter()
|
||||
.find_map(|action| match action {
|
||||
TransferAction::SendPart(_, data) => Some(data),
|
||||
_ => None,
|
||||
})
|
||||
.expect("sender emits at least one requested part");
|
||||
|
||||
client.handle_resource_part(&first_part);
|
||||
assert!(client.status.progress > 0.0);
|
||||
assert!(client.status.progress < 1.0);
|
||||
let first_progress = client.status.progress;
|
||||
client.handle_resource_part(&first_part);
|
||||
assert!(client.status.progress >= first_progress);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_purge_response() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.state = PropagationClientState::PurgeRequested;
|
||||
client.status.state = PropagationClientState::PurgeRequested;
|
||||
|
||||
client.handle_purge_response();
|
||||
assert_eq!(client.state, PropagationClientState::Complete);
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1210,15 +1432,20 @@ mod tests {
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.set_propagation_node([0xCC; 16]);
|
||||
client.start_download();
|
||||
assert_eq!(client.state, PropagationClientState::LinkEstablishing);
|
||||
assert_eq!(
|
||||
client.status.state,
|
||||
PropagationClientState::LinkEstablishing
|
||||
);
|
||||
|
||||
client.timeout = Duration::ZERO;
|
||||
|
||||
client.tick();
|
||||
assert_eq!(client.state, PropagationClientState::Failed);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
|
||||
client.tick();
|
||||
assert_eq!(client.state, PropagationClientState::Idle);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
assert!(client.acknowledge_transfer());
|
||||
assert_eq!(client.status.state, PropagationClientState::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1229,7 +1456,7 @@ mod tests {
|
||||
client.start_download();
|
||||
while rx.try_recv().is_ok() {}
|
||||
|
||||
client.state = PropagationClientState::Complete;
|
||||
client.status.state = PropagationClientState::Complete;
|
||||
client.tick();
|
||||
|
||||
let dereg = rx.try_recv();
|
||||
@@ -1248,7 +1475,7 @@ mod tests {
|
||||
let link_id = link.link_id;
|
||||
client.link = Some(link);
|
||||
client.link_id = Some(link_id);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
client.started_at = Some(Instant::now());
|
||||
|
||||
let close_body = responder_link
|
||||
@@ -1263,19 +1490,22 @@ mod tests {
|
||||
&close_body,
|
||||
),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
client.drain_events(&std::collections::HashMap::new());
|
||||
assert_eq!(client.state, PropagationClientState::Failed);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
|
||||
client.tick();
|
||||
assert_eq!(client.state, PropagationClientState::Idle);
|
||||
assert_eq!(client.status.state, PropagationClientState::Failed);
|
||||
assert!(client.link.is_none());
|
||||
assert!(matches!(
|
||||
rx.try_recv().unwrap(),
|
||||
TransportMessage::DeregisterDestination { hash } if hash == link_id
|
||||
));
|
||||
assert!(client.acknowledge_transfer());
|
||||
assert_eq!(client.status.state, PropagationClientState::Idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1287,18 +1517,19 @@ mod tests {
|
||||
let link_id = link.link_id;
|
||||
client.link = Some(link);
|
||||
client.link_id = Some(link_id);
|
||||
client.state = PropagationClientState::ListRequested;
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
|
||||
client
|
||||
.event_tx
|
||||
.try_send(DestinationEvent::InboundPacket {
|
||||
raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
client.drain_events(&std::collections::HashMap::new());
|
||||
assert_eq!(client.state, PropagationClientState::ListRequested);
|
||||
assert_eq!(client.status.state, PropagationClientState::ListRequested);
|
||||
assert!(client.link.is_some());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,327 @@
|
||||
//! Typed evaluation of an inbound propagation-node `/offer` request.
|
||||
//!
|
||||
//! Admission policy and lifecycle accounting deliberately live in
|
||||
//! [`crate::propagation_admission`]. Callers must pass that cheap preflight
|
||||
//! before performing the peering-key work in this module, then commit the
|
||||
//! returned wanted outcome to the same admission candidate.
|
||||
|
||||
use crate::propagation_admission::PnOfferResponse;
|
||||
use crate::stamper;
|
||||
use crate::sync::OfferResponse;
|
||||
use crate::types::PropagationTransientId;
|
||||
|
||||
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
|
||||
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
|
||||
|
||||
/// A peering-key-validated offer and the subset not present in local storage.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PnOfferEvaluation {
|
||||
HaveAll,
|
||||
WantAll,
|
||||
WantSome(Vec<PropagationTransientId>),
|
||||
}
|
||||
|
||||
impl PnOfferEvaluation {
|
||||
/// Lifecycle outcome recorded by [`crate::propagation_admission`].
|
||||
pub fn admission_response(&self) -> PnOfferResponse {
|
||||
match self {
|
||||
Self::HaveAll => PnOfferResponse::HaveAll,
|
||||
Self::WantAll => PnOfferResponse::WantAll,
|
||||
Self::WantSome(_) => PnOfferResponse::WantSome,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python-compatible response value for the `/offer` request.
|
||||
pub fn into_wire_response(self) -> OfferResponse {
|
||||
match self {
|
||||
Self::HaveAll => OfferResponse::HaveAll,
|
||||
Self::WantAll => OfferResponse::WantAll,
|
||||
Self::WantSome(ids) => {
|
||||
OfferResponse::WantSome(ids.into_iter().map(Vec::from).collect())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure before an offer can be committed to admission accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PnOfferEvaluationError {
|
||||
InvalidData,
|
||||
InvalidKey,
|
||||
}
|
||||
|
||||
impl PnOfferEvaluationError {
|
||||
pub fn wire_response(self) -> OfferResponse {
|
||||
match self {
|
||||
Self::InvalidData => OfferResponse::ErrorInvalidData,
|
||||
Self::InvalidKey => OfferResponse::ErrorInvalidKey,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum DecodedPeeringKey {
|
||||
Empty,
|
||||
Key([u8; 32]),
|
||||
InvalidLength,
|
||||
}
|
||||
|
||||
pub(crate) struct DecodedOffer {
|
||||
peering_key: DecodedPeeringKey,
|
||||
transient_ids: Vec<PropagationTransientId>,
|
||||
}
|
||||
|
||||
/// Decode, validate, and determine the wanted subset without mutating
|
||||
/// admission state.
|
||||
pub(crate) fn evaluate<F>(
|
||||
request_data: &[u8],
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
max_offer_size: usize,
|
||||
contains: F,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
|
||||
where
|
||||
F: FnMut(&PropagationTransientId) -> bool,
|
||||
{
|
||||
let offer = decode(request_data, max_offer_size)?;
|
||||
evaluate_decoded(
|
||||
offer,
|
||||
local_identity_hash,
|
||||
remote_identity_hash,
|
||||
peering_cost,
|
||||
contains,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate_decoded<F>(
|
||||
offer: DecodedOffer,
|
||||
local_identity_hash: &[u8; 16],
|
||||
remote_identity_hash: &[u8; 16],
|
||||
peering_cost: u8,
|
||||
mut contains: F,
|
||||
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
|
||||
where
|
||||
F: FnMut(&PropagationTransientId) -> bool,
|
||||
{
|
||||
let peering_key_valid = match offer.peering_key {
|
||||
DecodedPeeringKey::Empty => peering_cost == 0,
|
||||
DecodedPeeringKey::Key(key) => {
|
||||
let mut peering_id = [0u8; 32];
|
||||
peering_id[..16].copy_from_slice(local_identity_hash);
|
||||
peering_id[16..].copy_from_slice(remote_identity_hash);
|
||||
stamper::validate_peering_key(&peering_id, &key, peering_cost)
|
||||
}
|
||||
DecodedPeeringKey::InvalidLength => false,
|
||||
};
|
||||
|
||||
if !peering_key_valid {
|
||||
return Err(PnOfferEvaluationError::InvalidKey);
|
||||
}
|
||||
|
||||
let wanted: Vec<PropagationTransientId> = offer
|
||||
.transient_ids
|
||||
.iter()
|
||||
.filter(|transient_id| !contains(transient_id))
|
||||
.copied()
|
||||
.collect();
|
||||
|
||||
if wanted.is_empty() {
|
||||
Ok(PnOfferEvaluation::HaveAll)
|
||||
} else if wanted.len() == offer.transient_ids.len() {
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
} else {
|
||||
Ok(PnOfferEvaluation::WantSome(wanted))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(
|
||||
data: &[u8],
|
||||
max_offer_size: usize,
|
||||
) -> Result<DecodedOffer, PnOfferEvaluationError> {
|
||||
use std::io::Read;
|
||||
|
||||
if data.len() > max_offer_size {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let mut remaining = data;
|
||||
let field_count = rmp::decode::read_array_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
|
||||
if field_count != 2 {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let peering_key_len = rmp::decode::read_bin_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if peering_key_len > remaining.len() {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
let peering_key = match peering_key_len {
|
||||
0 => DecodedPeeringKey::Empty,
|
||||
32 => {
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&remaining[..32]);
|
||||
DecodedPeeringKey::Key(key)
|
||||
}
|
||||
_ => DecodedPeeringKey::InvalidLength,
|
||||
};
|
||||
remaining = &remaining[peering_key_len..];
|
||||
|
||||
let transient_id_count = rmp::decode::read_array_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if transient_id_count > remaining.len() / ENCODED_TRANSIENT_ID_MIN_BYTES {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
let mut transient_ids = Vec::with_capacity(transient_id_count);
|
||||
for _ in 0..transient_id_count {
|
||||
let encoded_len = rmp::decode::read_bin_len(&mut remaining)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
|
||||
if encoded_len != 32 {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
let mut transient_id = [0u8; 32];
|
||||
remaining
|
||||
.read_exact(&mut transient_id)
|
||||
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
|
||||
transient_ids.push(transient_id);
|
||||
}
|
||||
|
||||
if !remaining.is_empty() {
|
||||
return Err(PnOfferEvaluationError::InvalidData);
|
||||
}
|
||||
|
||||
Ok(DecodedOffer {
|
||||
peering_key,
|
||||
transient_ids,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rmpv::Value;
|
||||
|
||||
fn encode_offer(key: Value, ids: Value) -> Vec<u8> {
|
||||
crate::encode_value(&Value::Array(vec![key, ids]))
|
||||
}
|
||||
|
||||
fn id(value: u8) -> PropagationTransientId {
|
||||
[value; 32]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_decode_rejects_malformed_fields_and_trailing_bytes() {
|
||||
let malformed = [
|
||||
vec![0xc1],
|
||||
crate::encode_value(&Value::Array(vec![])),
|
||||
crate::encode_value(&Value::Array(vec![
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![]),
|
||||
Value::Nil,
|
||||
])),
|
||||
encode_offer(Value::Nil, Value::Array(vec![])),
|
||||
encode_offer(Value::String("key".into()), Value::Array(vec![])),
|
||||
encode_offer(Value::Binary(vec![]), Value::Nil),
|
||||
encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::Binary(vec![1; 31])]),
|
||||
),
|
||||
encode_offer(Value::Binary(vec![]), Value::Array(vec![Value::from(1)])),
|
||||
encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::String(
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
|
||||
)]),
|
||||
),
|
||||
];
|
||||
|
||||
for request in malformed {
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![]));
|
||||
trailing.push(0xc0);
|
||||
assert_eq!(
|
||||
evaluate(&trailing, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_requests_over_the_bounded_sync_budget() {
|
||||
let request = vec![0xc0; 65];
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 64, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_declared_id_count_before_allocating_entries() {
|
||||
let mut request = Vec::new();
|
||||
rmp::encode::write_array_len(&mut request, 2).unwrap();
|
||||
rmp::encode::write_bin_len(&mut request, 0).unwrap();
|
||||
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidData)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_key_is_valid_only_when_peering_work_is_disabled() {
|
||||
let request = encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![Value::Binary(id(3).to_vec())]),
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
|
||||
Ok(PnOfferEvaluation::WantAll)
|
||||
);
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false),
|
||||
Err(PnOfferEvaluationError::InvalidKey)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wanted_evaluation_preserves_offer_order_and_duplicates() {
|
||||
let request = encode_offer(
|
||||
Value::Binary(vec![]),
|
||||
Value::Array(vec![
|
||||
Value::Binary(id(1).to_vec()),
|
||||
Value::Binary(id(2).to_vec()),
|
||||
Value::Binary(id(2).to_vec()),
|
||||
Value::Binary(id(3).to_vec()),
|
||||
]),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]),
|
||||
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outcomes_map_to_admission_and_wire_types() {
|
||||
assert_eq!(
|
||||
PnOfferEvaluation::HaveAll.admission_response(),
|
||||
PnOfferResponse::HaveAll
|
||||
);
|
||||
assert_eq!(
|
||||
PnOfferEvaluation::WantAll.admission_response(),
|
||||
PnOfferResponse::WantAll
|
||||
);
|
||||
let some = PnOfferEvaluation::WantSome(vec![id(7)]);
|
||||
assert_eq!(some.admission_response(), PnOfferResponse::WantSome);
|
||||
assert_eq!(
|
||||
some.into_wire_response(),
|
||||
OfferResponse::WantSome(vec![id(7).to_vec()])
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+768
-74
File diff suppressed because it is too large.
Load diff
+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();
|
||||
|
||||
+1719
-227
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+139
-20
@@ -3,6 +3,9 @@
|
||||
//! Python reference: LXMF/Utilities/lxmd.py.
|
||||
|
||||
use lxmf_core::constants::*;
|
||||
use lxmf_core::propagation_admission::{
|
||||
PN_DEFAULT_MAX_INBOUND_SYNCS, PN_MIN_MAX_INBOUND_SYNCS, PnInboundAdmissionConfig,
|
||||
};
|
||||
use lxmf_core::router::{LxmRouter, RouterConfig, RouterConfigExt};
|
||||
use rns_runtime::config::{Config, ConfigSection};
|
||||
|
||||
@@ -16,6 +19,7 @@ pub struct PythonLxmdConfig {
|
||||
pub display_name: String,
|
||||
pub peer_announce_at_start: bool,
|
||||
pub peer_announce_interval: Option<i64>,
|
||||
pub peer_stamp_cost: i64,
|
||||
pub delivery_transfer_max_accepted_size: f64,
|
||||
pub on_inbound: Option<String>,
|
||||
pub enable_propagation_node: bool,
|
||||
@@ -24,6 +28,9 @@ pub struct PythonLxmdConfig {
|
||||
pub node_announce_at_start: bool,
|
||||
pub autopeer: bool,
|
||||
pub autopeer_maxdepth: Option<i64>,
|
||||
pub sequential_pn_stamp_validation: bool,
|
||||
pub static_peers_bypass_sequential: bool,
|
||||
pub max_inbound_syncs: i64,
|
||||
pub node_announce_interval: Option<i64>,
|
||||
pub message_storage_limit: f64,
|
||||
pub propagation_transfer_max_accepted_size: f64,
|
||||
@@ -58,6 +65,9 @@ impl PythonLxmdConfig {
|
||||
.to_string(),
|
||||
peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false),
|
||||
peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60),
|
||||
peer_stamp_cost: get_int(lxmf, "stamp_cost")
|
||||
.map(|value| value.max(1))
|
||||
.unwrap_or(12),
|
||||
delivery_transfer_max_accepted_size: get_float_or_floor(
|
||||
lxmf,
|
||||
"delivery_transfer_max_accepted_size",
|
||||
@@ -75,6 +85,19 @@ impl PythonLxmdConfig {
|
||||
node_announce_at_start: get_bool_or(propagation, "announce_at_start", false),
|
||||
autopeer: get_bool_or(propagation, "autopeer", true),
|
||||
autopeer_maxdepth: get_int(propagation, "autopeer_maxdepth"),
|
||||
sequential_pn_stamp_validation: get_bool_or(
|
||||
propagation,
|
||||
"sequential_pn_stamp_validation",
|
||||
true,
|
||||
),
|
||||
static_peers_bypass_sequential: get_bool_or(
|
||||
propagation,
|
||||
"static_peers_bypass_sequential",
|
||||
true,
|
||||
),
|
||||
max_inbound_syncs: get_int(propagation, "max_inbound_syncs")
|
||||
.map(|value| value.max(PN_MIN_MAX_INBOUND_SYNCS as i64))
|
||||
.unwrap_or(PN_DEFAULT_MAX_INBOUND_SYNCS as i64),
|
||||
node_announce_interval: get_int(propagation, "announce_interval").map(|v| v * 60),
|
||||
message_storage_limit: get_float_or_floor(
|
||||
propagation,
|
||||
@@ -152,6 +175,9 @@ pub struct DaemonConfig {
|
||||
pub max_peers: usize,
|
||||
pub autopeer: bool,
|
||||
pub autopeer_maxdepth: usize,
|
||||
pub sequential_pn_stamp_validation: bool,
|
||||
pub static_peers_bypass_sequential: bool,
|
||||
pub max_inbound_syncs: usize,
|
||||
pub propagation_limit_kb: usize,
|
||||
pub sync_limit_kb: usize,
|
||||
pub on_inbound_command: Option<String>,
|
||||
@@ -161,13 +187,12 @@ 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,
|
||||
/// Max accepted inbound delivery transfer size in KB. Python reference:
|
||||
/// `delivery_transfer_max_accepted_size` in `lxmd.py`.
|
||||
pub delivery_transfer_max_accepted_size: usize,
|
||||
pub delivery_transfer_max_accepted_size: f64,
|
||||
}
|
||||
|
||||
impl Default for DaemonConfig {
|
||||
@@ -177,7 +202,7 @@ impl Default for DaemonConfig {
|
||||
node_name: None,
|
||||
announce_at_start: false,
|
||||
announce_interval: None,
|
||||
stamp_cost: None,
|
||||
stamp_cost: Some(12),
|
||||
propagation_enabled: false,
|
||||
outbound_propagation_node: None,
|
||||
propagation_stamp_cost: PROPAGATION_COST,
|
||||
@@ -187,6 +212,9 @@ impl Default for DaemonConfig {
|
||||
max_peers: MAX_PEERS,
|
||||
autopeer: true,
|
||||
autopeer_maxdepth: AUTOPEER_MAXDEPTH,
|
||||
sequential_pn_stamp_validation: true,
|
||||
static_peers_bypass_sequential: true,
|
||||
max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS,
|
||||
propagation_limit_kb: PROPAGATION_LIMIT,
|
||||
sync_limit_kb: SYNC_LIMIT,
|
||||
on_inbound_command: None,
|
||||
@@ -196,11 +224,10 @@ 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,
|
||||
delivery_transfer_max_accepted_size: DELIVERY_LIMIT,
|
||||
delivery_transfer_max_accepted_size: 1000.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -221,8 +248,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(),
|
||||
@@ -232,6 +257,16 @@ impl DaemonConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the long-lived inbound propagation admission policy.
|
||||
pub fn to_inbound_admission_config(&self) -> PnInboundAdmissionConfig {
|
||||
PnInboundAdmissionConfig {
|
||||
sequential_validation: self.sequential_pn_stamp_validation,
|
||||
static_sequential: !self.static_peers_bypass_sequential,
|
||||
max_inbound_syncs: self.max_inbound_syncs,
|
||||
from_static_only: self.from_static_only,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse from `[lxmf]`, `[propagation]`, and `[control]` sections.
|
||||
pub fn from_config(config: &Config) -> Self {
|
||||
let py = PythonLxmdConfig::from_config(config);
|
||||
@@ -240,6 +275,7 @@ impl DaemonConfig {
|
||||
node_name: py.node_name,
|
||||
announce_at_start: py.peer_announce_at_start,
|
||||
announce_interval: seconds_to_u64(py.peer_announce_interval),
|
||||
stamp_cost: normalize_peer_stamp_cost(py.peer_stamp_cost),
|
||||
propagation_enabled: py.enable_propagation_node,
|
||||
propagation_stamp_cost: clamp_python_cost_to_u8(
|
||||
py.propagation_stamp_cost_target,
|
||||
@@ -260,6 +296,9 @@ impl DaemonConfig {
|
||||
.autopeer_maxdepth
|
||||
.and_then(|value| usize::try_from(value).ok())
|
||||
.unwrap_or(AUTOPEER_MAXDEPTH),
|
||||
sequential_pn_stamp_validation: py.sequential_pn_stamp_validation,
|
||||
static_peers_bypass_sequential: py.static_peers_bypass_sequential,
|
||||
max_inbound_syncs: usize::try_from(py.max_inbound_syncs).unwrap_or(usize::MAX),
|
||||
propagation_limit_kb: kb_to_usize_ceil(py.propagation_transfer_max_accepted_size),
|
||||
sync_limit_kb: kb_to_usize_ceil(py.propagation_sync_max_accepted_size),
|
||||
on_inbound_command: py.on_inbound,
|
||||
@@ -271,18 +310,10 @@ impl DaemonConfig {
|
||||
prioritise_destinations: py.prioritised_lxmf_destinations,
|
||||
message_storage_limit: megabytes_to_bytes(py.message_storage_limit),
|
||||
from_static_only: py.from_static_only,
|
||||
delivery_transfer_max_accepted_size: kb_to_usize_ceil(
|
||||
py.delivery_transfer_max_accepted_size,
|
||||
),
|
||||
delivery_transfer_max_accepted_size: py.delivery_transfer_max_accepted_size,
|
||||
..DaemonConfig::default()
|
||||
};
|
||||
|
||||
if let Some(sec) = config.section("lxmf")
|
||||
&& let Some(cost) = sec.get_uint("stamp_cost")
|
||||
{
|
||||
dc.stamp_cost = Some(cost as u8);
|
||||
}
|
||||
|
||||
if let Some(sec) = config.section("propagation") {
|
||||
if let Some(node) = sec.get("outbound_node") {
|
||||
let trimmed = node.trim();
|
||||
@@ -301,7 +332,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);
|
||||
}
|
||||
|
||||
@@ -328,6 +358,13 @@ fn clamp_python_cost_to_u8(value: i64, floor: i64) -> u8 {
|
||||
value.max(floor).min(u8::MAX as i64) as u8
|
||||
}
|
||||
|
||||
/// Apply Python lxmd's signed floor, then mirror `set_inbound_stamp_cost`:
|
||||
/// delivery stamp costs are valid only in `1..=254`.
|
||||
fn normalize_peer_stamp_cost(value: i64) -> Option<u8> {
|
||||
let cost = u8::try_from(value.max(1)).ok()?;
|
||||
(cost < u8::MAX).then_some(cost)
|
||||
}
|
||||
|
||||
fn get_float(section: Option<&ConfigSection>, key: &str) -> Option<f64> {
|
||||
section.and_then(|sec| sec.get_float(key))
|
||||
}
|
||||
@@ -394,6 +431,7 @@ mod tests {
|
||||
assert_eq!(dc.display_name.as_deref(), Some("Anonymous Peer"));
|
||||
assert!(!dc.announce_at_start);
|
||||
assert_eq!(dc.announce_interval, None);
|
||||
assert_eq!(dc.stamp_cost, Some(12));
|
||||
assert!(!dc.propagation_enabled);
|
||||
assert_eq!(dc.propagation_stamp_cost, 16);
|
||||
assert_eq!(dc.propagation_stamp_flex, 3);
|
||||
@@ -402,12 +440,19 @@ mod tests {
|
||||
assert_eq!(dc.max_peers, 20);
|
||||
assert!(dc.autopeer);
|
||||
assert_eq!(dc.autopeer_maxdepth, AUTOPEER_MAXDEPTH);
|
||||
assert!(dc.sequential_pn_stamp_validation);
|
||||
assert!(dc.static_peers_bypass_sequential);
|
||||
assert_eq!(dc.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS);
|
||||
assert_eq!(
|
||||
dc.to_inbound_admission_config(),
|
||||
PnInboundAdmissionConfig::default()
|
||||
);
|
||||
assert_eq!(dc.propagation_limit_kb, 256);
|
||||
assert_eq!(dc.sync_limit_kb, 10_240);
|
||||
assert!(!dc.node_announce_at_start);
|
||||
assert_eq!(dc.node_announce_interval, None);
|
||||
assert_eq!(dc.message_storage_limit, Some(500_000_000));
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 1000);
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 1000.0);
|
||||
assert!(!dc.from_static_only);
|
||||
}
|
||||
|
||||
@@ -419,6 +464,7 @@ mod tests {
|
||||
assert_eq!(py.display_name, "Anonymous Peer");
|
||||
assert!(!py.peer_announce_at_start);
|
||||
assert_eq!(py.peer_announce_interval, None);
|
||||
assert_eq!(py.peer_stamp_cost, 12);
|
||||
assert_eq!(py.delivery_transfer_max_accepted_size, 1000.0);
|
||||
assert_eq!(py.on_inbound, None);
|
||||
assert!(!py.enable_propagation_node);
|
||||
@@ -427,6 +473,9 @@ mod tests {
|
||||
assert!(!py.node_announce_at_start);
|
||||
assert!(py.autopeer);
|
||||
assert_eq!(py.autopeer_maxdepth, None);
|
||||
assert!(py.sequential_pn_stamp_validation);
|
||||
assert!(py.static_peers_bypass_sequential);
|
||||
assert_eq!(py.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS as i64);
|
||||
assert_eq!(py.node_announce_interval, None);
|
||||
assert_eq!(py.message_storage_limit, 500.0);
|
||||
assert_eq!(py.propagation_transfer_max_accepted_size, 256.0);
|
||||
@@ -460,9 +509,13 @@ prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
|
||||
control_allowed = 11111111111111111111111111111111
|
||||
from_static_only = yes
|
||||
max_peers = 7
|
||||
sequential_pn_stamp_validation = no
|
||||
static_peers_bypass_sequential = no
|
||||
max_inbound_syncs = 0
|
||||
|
||||
[lxmf]
|
||||
announce_interval = 3
|
||||
stamp_cost = -9
|
||||
delivery_transfer_max_accepted_size = 0.1
|
||||
|
||||
[logging]
|
||||
@@ -473,6 +526,7 @@ loglevel = 6
|
||||
|
||||
assert_eq!(py.peer_announce_interval, Some(180));
|
||||
assert_eq!(py.node_announce_interval, Some(120));
|
||||
assert_eq!(py.peer_stamp_cost, 1);
|
||||
assert_eq!(py.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(py.message_storage_limit, 0.005);
|
||||
assert_eq!(py.propagation_transfer_max_accepted_size, 0.38);
|
||||
@@ -491,6 +545,9 @@ loglevel = 6
|
||||
["11111111111111111111111111111111"]
|
||||
);
|
||||
assert_eq!(py.max_peers, Some(7));
|
||||
assert!(!py.sequential_pn_stamp_validation);
|
||||
assert!(!py.static_peers_bypass_sequential);
|
||||
assert_eq!(py.max_inbound_syncs, PN_MIN_MAX_INBOUND_SYNCS as i64);
|
||||
assert!(py.from_static_only);
|
||||
assert_eq!(py.target_loglevel, Some(6));
|
||||
}
|
||||
@@ -531,7 +588,8 @@ propagation_transfer_max_accepted_size = 12
|
||||
let rc = dc.to_router_config();
|
||||
assert!(!rc.propagation_enabled);
|
||||
assert_eq!(rc.max_peers, 20);
|
||||
assert_eq!(rc.delivery_limit_kb, 1000);
|
||||
assert_eq!(rc.delivery_limit_kb, 1000.0);
|
||||
assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0);
|
||||
assert_eq!(rc.propagation_limit_kb, 256);
|
||||
assert_eq!(rc.sync_limit_kb, 10_240);
|
||||
assert_eq!(rc.propagation_stamp_cost, 16);
|
||||
@@ -587,6 +645,9 @@ remote_peering_cost_max = -2
|
||||
max_peers = 10
|
||||
autopeer = no
|
||||
autopeer_maxdepth = 2
|
||||
sequential_pn_stamp_validation = no
|
||||
static_peers_bypass_sequential = no
|
||||
max_inbound_syncs = 5
|
||||
static_peers = 00112233445566778899aabbccddeeff
|
||||
prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
|
||||
control_allowed = 11111111111111111111111111111111
|
||||
@@ -597,7 +658,7 @@ from_static_only = yes
|
||||
assert_eq!(dc.display_name.as_deref(), Some("TestNode"));
|
||||
assert!(dc.announce_at_start);
|
||||
assert_eq!(dc.announce_interval, Some(180));
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 1);
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(dc.stamp_cost, Some(8));
|
||||
assert!(dc.propagation_enabled);
|
||||
assert_eq!(dc.node_name.as_deref(), Some("PropNode"));
|
||||
@@ -617,6 +678,18 @@ from_static_only = yes
|
||||
assert_eq!(dc.max_peers, 10);
|
||||
assert!(!dc.autopeer);
|
||||
assert_eq!(dc.autopeer_maxdepth, 2);
|
||||
assert!(!dc.sequential_pn_stamp_validation);
|
||||
assert!(!dc.static_peers_bypass_sequential);
|
||||
assert_eq!(dc.max_inbound_syncs, 5);
|
||||
assert_eq!(
|
||||
dc.to_inbound_admission_config(),
|
||||
PnInboundAdmissionConfig {
|
||||
sequential_validation: false,
|
||||
static_sequential: true,
|
||||
max_inbound_syncs: 5,
|
||||
from_static_only: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(dc.static_peers, ["00112233445566778899aabbccddeeff"]);
|
||||
assert_eq!(
|
||||
dc.prioritise_destinations,
|
||||
@@ -626,6 +699,38 @@ from_static_only = yes
|
||||
assert!(dc.from_static_only);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_stamp_cost_matches_python_floor_and_destination_range() {
|
||||
for (configured, normalized, expected) in [
|
||||
(-7, 1, Some(1)),
|
||||
(0, 1, Some(1)),
|
||||
(254, 254, Some(254)),
|
||||
(255, 255, None),
|
||||
(256, 256, None),
|
||||
(1000, 1000, None),
|
||||
] {
|
||||
let input = format!("[lxmf]\nstamp_cost = {configured}\n");
|
||||
let config = rns_runtime::config::Config::parse(&input).unwrap();
|
||||
let py = PythonLxmdConfig::from_config(&config);
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
|
||||
assert_eq!(py.peer_stamp_cost, normalized, "configured {configured}");
|
||||
assert_eq!(dc.stamp_cost, expected, "configured {configured}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_delivery_limit_survives_daemon_and_router_config() {
|
||||
let config = rns_runtime::config::Config::parse(
|
||||
"[lxmf]\ndelivery_transfer_max_accepted_size = 0.38\n",
|
||||
)
|
||||
.unwrap();
|
||||
let dc = DaemonConfig::from_config(&config);
|
||||
|
||||
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
|
||||
assert_eq!(dc.to_router_config().delivery_limit_kb, 0.38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_python_stamp_target_key_with_floor() {
|
||||
let input = r#"
|
||||
@@ -654,4 +759,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);
|
||||
}
|
||||
}
|
||||
@@ -94,7 +94,7 @@ pub struct Args {
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub identity: Option<PathBuf>,
|
||||
|
||||
/// Send a single message and exit: --send <dest_hash> <content>
|
||||
/// Send a single message and exit: `--send <dest_hash> <content>`.
|
||||
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
|
||||
pub send: Option<Vec<String>>,
|
||||
|
||||
@@ -180,6 +180,15 @@ autopeer = yes
|
||||
|
||||
autopeer_maxdepth = 6
|
||||
|
||||
# Validate inbound propagation stamp batches sequentially by default.
|
||||
# sequential_pn_stamp_validation = yes
|
||||
|
||||
# Let configured static peers bypass sequential validation and inbound limits.
|
||||
# static_peers_bypass_sequential = yes
|
||||
|
||||
# Maximum concurrent inbound propagation sync transfers.
|
||||
# max_inbound_syncs = 3
|
||||
|
||||
# message_storage_limit = 500
|
||||
|
||||
# propagation_message_max_accepted_size = 256
|
||||
@@ -213,6 +222,8 @@ announce_at_start = no
|
||||
|
||||
# announce_interval = 360
|
||||
|
||||
# stamp_cost = 12
|
||||
|
||||
delivery_transfer_max_accepted_size = 1000
|
||||
|
||||
# on_inbound = /path/to/handler
|
||||
|
||||
@@ -300,7 +300,7 @@ pub fn encode_router_control_stats(
|
||||
(Value::String("uptime".into()), Value::F64(uptime)),
|
||||
(
|
||||
Value::String("delivery_limit".into()),
|
||||
Value::from(router.config.delivery_limit_kb as u64),
|
||||
Value::F64(router.config.delivery_limit_kb),
|
||||
),
|
||||
(
|
||||
Value::String("propagation_limit".into()),
|
||||
@@ -612,12 +612,10 @@ pub fn format_remote_status(
|
||||
}
|
||||
_ => "never synced".to_string(),
|
||||
};
|
||||
let name = map_str(peer, "name")
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.replace(['\n', '\r'], "");
|
||||
let display_name = if name.len() > 45 {
|
||||
format!("{}...", &name[..45])
|
||||
let name =
|
||||
lxmf_core::presentation::sanitize_name(map_str(peer, "name").unwrap_or(""), 46);
|
||||
let display_name = if name.chars().count() > 45 {
|
||||
format!("{}...", name.chars().take(45).collect::<String>())
|
||||
} else {
|
||||
name
|
||||
};
|
||||
@@ -955,6 +953,34 @@ mod tests {
|
||||
assert!(out.contains("4 propagation messages served to clients"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_formatter_bounds_multibyte_untrusted_peer_names() {
|
||||
let hostile_name = format!("{}\u{202e}\u{1f680}", "界".repeat(50));
|
||||
let peer = Value::Map(vec![
|
||||
(
|
||||
Value::String("name".into()),
|
||||
Value::String(hostile_name.into()),
|
||||
),
|
||||
(Value::String("alive".into()), Value::Boolean(true)),
|
||||
]);
|
||||
let stats = Value::Map(vec![
|
||||
(
|
||||
Value::String("destination_hash".into()),
|
||||
Value::Binary(vec![0x01; 16]),
|
||||
),
|
||||
(
|
||||
Value::String("peers".into()),
|
||||
Value::Map(vec![(Value::Binary(vec![0x02; 16]), peer)]),
|
||||
),
|
||||
]);
|
||||
|
||||
let out = format_remote_status(&stats, false, true, 0.0);
|
||||
let expected = format!("Name : {}...", "界".repeat(45));
|
||||
assert!(out.contains(&expected));
|
||||
assert!(!out.contains('\u{202e}'));
|
||||
assert!(!out.contains('\u{1f680}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stats_encoder_uses_python_compile_stats_shape() {
|
||||
use lxmf_core::peer::LxmPeer;
|
||||
@@ -964,6 +990,7 @@ mod tests {
|
||||
propagation_enabled: true,
|
||||
..Default::default()
|
||||
};
|
||||
config.delivery_limit_kb = 0.38;
|
||||
config.ext.message_storage_limit = Some(500_000_000);
|
||||
let mut router = LxmRouter::new(config);
|
||||
router.propagation_start_time = Some(1_700_000_000.0);
|
||||
@@ -1022,6 +1049,7 @@ mod tests {
|
||||
assert_eq!(map_u64(&stats, "static_peers"), Some(1));
|
||||
assert_eq!(map_u64(&stats, "discovered_peers"), Some(0));
|
||||
assert_eq!(map_u64(&stats, "total_peers"), Some(1));
|
||||
assert_eq!(map_f64(&stats, "delivery_limit"), Some(0.38));
|
||||
|
||||
let peers = map_value(&stats, "peers").unwrap().as_map().unwrap();
|
||||
let peer_stats = &peers[0].1;
|
||||
|
||||
@@ -18,6 +18,7 @@ pub struct LxmdPaths {
|
||||
pub propagation_store_dir: PathBuf,
|
||||
pub ratchets_dir: PathBuf,
|
||||
pub ratchet_ring_path: PathBuf,
|
||||
pub ratchet_control_path: PathBuf,
|
||||
pub received_ratchets_dir: PathBuf,
|
||||
pub known_identities_path: PathBuf,
|
||||
pub legacy_lxmf_dir: PathBuf,
|
||||
@@ -38,6 +39,7 @@ impl LxmdPaths {
|
||||
let propagation_store_dir = lxmf_storage_dir.join("messagestore");
|
||||
let ratchets_dir = lxmf_storage_dir.join("ratchets");
|
||||
let ratchet_ring_path = ratchets_dir.join("ring");
|
||||
let ratchet_control_path = ratchets_dir.join("ring.control");
|
||||
let received_ratchets_dir = ratchets_dir.join("received");
|
||||
let known_identities_path = ratchets_dir.join("known_identities");
|
||||
|
||||
@@ -57,6 +59,7 @@ impl LxmdPaths {
|
||||
propagation_store_dir,
|
||||
ratchets_dir,
|
||||
ratchet_ring_path,
|
||||
ratchet_control_path,
|
||||
received_ratchets_dir,
|
||||
known_identities_path,
|
||||
legacy_lxmf_dir,
|
||||
@@ -333,6 +336,10 @@ mod tests {
|
||||
paths.ratchet_ring_path,
|
||||
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring")
|
||||
);
|
||||
assert_eq!(
|
||||
paths.ratchet_control_path,
|
||||
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring.control")
|
||||
);
|
||||
assert_eq!(
|
||||
paths.received_ratchets_dir,
|
||||
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/received")
|
||||
@@ -445,13 +452,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"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -227,11 +227,15 @@ fn example_config_exits_before_runtime_initialisation() {
|
||||
assert!(text.contains("[lxmf]"));
|
||||
assert!(text.contains("display_name = Anonymous Peer"));
|
||||
assert!(text.contains("announce_at_start = no"));
|
||||
assert!(text.contains("# stamp_cost = 12"));
|
||||
assert!(text.contains("delivery_transfer_max_accepted_size = 1000"));
|
||||
assert!(text.contains("[propagation]"));
|
||||
assert!(text.contains("enable_node = no"));
|
||||
assert!(text.contains("announce_interval = 360"));
|
||||
assert!(text.contains("announce_at_start = yes"));
|
||||
assert!(text.contains("# sequential_pn_stamp_validation = yes"));
|
||||
assert!(text.contains("# static_peers_bypass_sequential = yes"));
|
||||
assert!(text.contains("# max_inbound_syncs = 3"));
|
||||
assert!(text.contains("[logging]"));
|
||||
assert!(text.contains("loglevel = 4"));
|
||||
assert!(!text.contains("[control]"));
|
||||
|
||||
Reference in new issue
Block a user