Compare commits

...
Author SHA1 Message Date
DeFiDude 8a6316c635 lxmd: own announce discovery subscriptions 2026-08-16 20:18:31 -06:00
DeFiDude 0bd4220db6 docs: distinguish LXMF reference baselines 2026-08-16 18:41:23 -06:00
DeFiDude 44af77dc98 lxmd: follow current Python resource policy 2026-08-16 18:34:25 -06:00
DeFiDude 42355b4f46 lxmd: restore Python resource limit default 2026-08-16 17:32:26 -06:00
DeFiDude d100e3eae5 docs: explain established Link binding 2026-08-16 15:39:49 -06:00
DeFiDude 502795c70d link: observe typed endpoint send results 2026-08-16 15:37:13 -06:00
DeFiDude a530ad77c0 tools: map Link identity send errors 2026-08-16 15:19:59 -06:00
DeFiDude f91747b1d8 docs: record Link delivery hardening 2026-08-16 15:17:11 -06:00
DeFiDude 29804534ce propagation: pin Link sessions to proof interfaces 2026-08-16 15:17:08 -06:00
DeFiDude f89b6a2811 direct: bind Links and retain reverse proofs 2026-08-16 15:17:04 -06:00
DeFiDude 094bc95662 core: add native LXMF audio fields 2026-08-15 12:48:04 -06:00
DeFiDude b40dcd37f2 delivery: reconcile backchannel outcomes and reverse resources 2026-08-14 13:49:48 -06:00
DeFiDude 681c0f5961 delivery: reduce large message allocation 2026-08-13 12:42:35 -06:00
DeFiDude f9ed81e3ae docs: clarify Opportunistic proof lifecycle 2026-08-13 02:10:40 -06:00
DeFiDude 326022cae8 runtime: complete tickets and durable propagation 2026-08-12 23:58:24 -06:00
DeFiDude 27a49aed00 runtime: harden LXMF daemon parity 2026-08-12 20:15:30 -06:00
DeFiDude 2e124b1006 ci: enforce strict Clippy across supported targets 2026-08-06 18:49:06 -06:00
22 changed files with 9646 additions and 1875 deletions

No files matched your search

+29 -3
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install system deps
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace
- run: cargo test --workspace --locked
working-directory: rsLXMF
lint:
@@ -60,10 +60,36 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo fmt --all -- --check
working-directory: rsLXMF
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps
run: cargo doc --workspace --no-deps --locked
working-directory: rsLXMF
msrv:
name: Rust 1.85 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
with:
path: rsLXMF
- uses: actions/checkout@v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
path: rsReticulum
- uses: dtolnay/rust-toolchain@1.85.0
with:
components: clippy
- uses: Swatinem/rust-cache@v2
with:
workspaces: rsLXMF -> target
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
+31
View File
@@ -1,5 +1,36 @@
# Changelog
## Unreleased
- Replaced temporary aspect-wide announce handlers in remote-control lookup
with bounded validated destination recall, and made lxmd's delivery and
propagation observers exact owned subscriptions with deterministic cleanup.
- Matched current Python LXMF 1.1.0's fresh `lxmd` direct-delivery Resource
admission default of 1 decimal KB, while keeping the reusable router's
separate 1000 KB library default and preserving explicit configured limits.
- Bound Direct-delivery, propagation-download, and propagation-sync Link
initiators to the authenticated LRPROOF ingress interface before LRRTT,
routed all established-Link traffic through ordered typed endpoints, and
made reverse delivery proofs durable before plaintext publication.
- Bounded propagation-sync transport staging, scoped Link endpoint failures
to their owning operation, and prevented Resource responses from becoming
visible when their delivery proof cannot be retained.
- Made typed Link sends fail closed on rejected transport admission, delayed
reverse plaintext and propagation responses until their proofs are reliably
admitted, and made failed graceful closes unbind before deregistration.
- Added automatic pre-sign reply-ticket issue, signature-gated inbound
learning, directional migration-safe persistence, and proof-gated delivery
accounting, with live Python restart/reply interoperability.
- Made Opportunistic one-shot delivery wait for an authenticated Reticulum
proof, with atomic receipt-first dispatch and bounded retries.
- Moved propagation-store persistence off the daemon loop through
reserve/write/commit transactions so visibility, handled IDs and counters
advance only after durable writes.
- Added coalescing announce handoff, live allow-list rotation and split
peer-Resource convergence coverage.
- Made one-shot remote control commands wait for a real online Reticulum
interface before opening their Link, avoiding stale-path startup loss.
## 1.1.0 - 2026-07-26
- Added bounded propagation-node admission, exact inbound Resource ownership,
Generated
+1
View File
@@ -684,6 +684,7 @@ dependencies = [
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
+28 -5
View File
@@ -6,7 +6,8 @@
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![LXMF 1.0.1](https://img.shields.io/badge/target-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Compatibility floor: LXMF 1.0.1](https://img.shields.io/badge/compatibility%20floor-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Current reference: LXMF 1.1.0](https://img.shields.io/badge/current%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[LXMF Reference](https://github.com/markqvist/LXMF) |
@@ -239,7 +240,7 @@ Minimal config:
display_name = Rat
announce_at_start = no
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1000
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
[propagation]
@@ -259,6 +260,11 @@ auth_required = no
loglevel = 4
```
The standalone daemon follows current Python LXMF 1.1.0 and defaults this
setting to 1 decimal KB when it is omitted. This is intentionally distinct
from the reusable router library's 1000 KB default. Applications that accept
larger incoming messages should set their own explicit policy.
Supported sections:
| Section | Keys |
@@ -284,11 +290,18 @@ and, where network-backed, through `lxmd-rs --send-method`.
| Method | Behavior |
| --- | --- |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Oversized opportunistic messages are downgraded to Direct by the router. |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. Oversized opportunistic messages are downgraded to Direct by the router. |
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. |
| Propagated | Store-and-forward delivery through a propagation node, including deposit, retrieve, peer sync, stamps, and tickets. |
| Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
Direct and propagation Links use ordinary Reticulum path discovery only for
their initial LINKREQUEST. After a valid LRPROOF, rsLXMF pins the Link to that
proof's ingress interface and all later packets, Resources, proofs, keepalives,
and teardown use the same interface. A lost interface closes the Link instead
of silently rerouting it. Reverse Direct delivery is published only after its
role-correct proof has been admitted to that bound endpoint.
An ordinary direct or opportunistic LXMF message is a signed Reticulum payload:
```text
@@ -302,6 +315,10 @@ payload MessagePack([timestamp, title, content, fields, optional_stamp
application-defined data such as tickets, attachments, location data, or
application envelopes.
Library callers requesting a reply ticket set `include_ticket`, call
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a
requested ticket that would require changing an already-signed message.
## Feature Status
@@ -309,8 +326,8 @@ application envelopes.
| --- | --- |
| 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. |
| Propagation | Transactional 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, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
| Access lists | `ignored` and `allowed` hash-list files in the LXMF config directory. |
@@ -324,6 +341,12 @@ Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
`--send-timeout-secs`, and `--send-fields-json`.
The compatibility-floor corpus is Python LXMF 1.0.1 with Reticulum 1.3.8;
current daemon, delivery, Resource/proof, and propagation behavior is also
checked against exact LXMF 1.1.0 and Reticulum 1.4.2 sources. Version-specific
legacy vectors retain their original provenance instead of being silently
rewritten to current expectations.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
+2
View File
@@ -0,0 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.85"
+3
View File
@@ -175,6 +175,9 @@ pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
/// Delay before announcing propagation node (seconds).
pub const NODE_ANNOUNCE_DELAY: u64 = 20;
/// LXMF configuration and announce values use decimal kilobytes, matching
/// Python's `limit_kb * 1000` accounting.
pub const BYTES_PER_KILOBYTE: usize = 1000;
pub const PROPAGATION_LIMIT: usize = 256;
pub const DELIVERY_LIMIT: usize = 1000;
/// PROPAGATION_LIMIT * 40, in KB.
+21 -21
View File
@@ -159,15 +159,14 @@ impl DeliveryRatchetState {
}
}
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"
);
if control_file_trusted && (!control_existed || control_changed) {
if 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 {
@@ -211,12 +210,13 @@ impl DeliveryRatchetState {
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
&& let Some(packet) = self
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind {
if let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
{
return Ok(packet);
}
}
if !self.control_file_trusted {
@@ -292,15 +292,15 @@ impl DeliveryRatchetState {
/// 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.ring_file_trusted {
if 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");
if self.control_file_trusted {
if let Err(error) = self.control.save_verified(&self.control_path, identity) {
tracing::warn!(%error, "failed to save ratchet control state");
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+47 -21
View File
@@ -2,7 +2,7 @@
//!
//! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
//! * `available_tickets` — `Vec<Ticket>`
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//!
@@ -16,7 +16,7 @@ use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::Ticket;
use crate::ticket::{Ticket, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
@@ -68,15 +68,14 @@ pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
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()
);
if result.is_err() && tmp.exists() {
if let Err(e) = fs::remove_file(&tmp) {
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
}
}
result
@@ -111,12 +110,23 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &[Ticket]) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), &tickets)
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
}
pub fn load_tickets(dir: &Path) -> io::Result<Vec<Ticket>> {
Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default())
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PersistedTickets {
Directional(TicketStoreSnapshot),
Legacy(Vec<Ticket>),
}
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
None => (TicketStoreSnapshot::default(), None),
})
}
pub fn save_local_deliveries(
@@ -177,12 +187,26 @@ mod tests {
#[test]
fn tickets_roundtrip() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
let tickets = TicketStoreSnapshot {
version: 1,
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
};
save_tickets(tmp.path(), &tickets).unwrap();
let loaded = load_tickets(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].token, [0x01; 16]);
assert_eq!(loaded[0].destination_hash, [0x02; 16]);
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
assert!(legacy.is_none());
assert_eq!(loaded, tickets);
}
#[test]
fn legacy_flat_tickets_are_detected_for_migration() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(snapshot, TicketStoreSnapshot::default());
assert_eq!(legacy.unwrap(), tickets);
}
#[test]
@@ -199,7 +223,9 @@ mod tests {
fn missing_file_returns_default() {
let tmp = TempDir::new().unwrap();
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
assert!(load_tickets(tmp.path()).unwrap().is_empty());
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(tickets, TicketStoreSnapshot::default());
assert!(legacy.is_none());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
File diff suppressed because it is too large. Load diff
+348 -109
View File
@@ -39,8 +39,8 @@ impl Default for PropagationNodeConfig {
// Disabled by default; set to PROPAGATION_COST for production.
min_stamp_cost: 0,
peering_cost: PEERING_COST,
max_message_size: DELIVERY_LIMIT * 1024,
max_offer_size: SYNC_LIMIT * 1000,
max_message_size: DELIVERY_LIMIT * BYTES_PER_KILOBYTE,
max_offer_size: SYNC_LIMIT * BYTES_PER_KILOBYTE,
}
}
}
@@ -69,9 +69,16 @@ impl GetRequestAction {
/// Resolve to response bytes, performing any planned file reads inline.
/// Blocking; do not call while holding a shared node lock.
pub fn into_response(self) -> Vec<u8> {
self.into_response_with_served_count().0
}
/// Resolve the response and report how many messages were actually read
/// and admitted by the client's transfer limit. This lets the daemon keep
/// Python-compatible served-message accounting without repeating I/O.
pub fn into_response_with_served_count(self) -> (Vec<u8>, u64) {
match self {
GetRequestAction::Respond(bytes) => bytes,
GetRequestAction::ServeFiles(plan) => plan.serve(),
GetRequestAction::Respond(bytes) => (bytes, 0),
GetRequestAction::ServeFiles(plan) => plan.serve_with_count(),
}
}
}
@@ -98,6 +105,10 @@ impl GetServePlan {
/// over-limit entries skipped (not a transfer abort), stamps stripped
/// for client download. Unreadable files are skipped.
pub fn serve(&self) -> Vec<u8> {
self.serve_with_count().0
}
fn serve_with_count(&self) -> (Vec<u8>, u64) {
use rmpv::Value;
const PER_MESSAGE_OVERHEAD: f64 = 16.0;
@@ -121,7 +132,8 @@ impl GetServePlan {
messages.push(Value::Binary(payload));
}
crate::encode_value(&Value::Array(messages))
let served = messages.len() as u64;
(crate::encode_value(&Value::Array(messages)), served)
}
}
@@ -147,6 +159,45 @@ pub fn read_planned_messages(
.collect()
}
/// One propagation-store admission reserved under the node lock. Persist it
/// on a blocking worker, then commit the returned value under a short lock.
#[derive(Debug)]
pub struct PropagationStoreWritePlan {
entry: PropagationEntry,
data: Vec<u8>,
path: Option<PathBuf>,
}
impl PropagationStoreWritePlan {
pub fn transient_id(&self) -> PropagationTransientId {
self.entry.transient_id
}
pub fn size(&self) -> usize {
self.entry.size
}
/// Perform the potentially blocking durable write. Disk-backed nodes use
/// atomic temp-file replacement; in-memory nodes complete immediately.
pub fn persist(self) -> std::io::Result<PersistedPropagationStoreWrite> {
if let Some(ref path) = self.path {
crate::persist::write_file_atomic(path, &self.data)?;
}
Ok(PersistedPropagationStoreWrite {
entry: self.entry,
path: self.path,
})
}
}
/// Durable half of a propagation-store admission, ready for an in-memory
/// commit under the node lock.
#[derive(Debug)]
pub struct PersistedPropagationStoreWrite {
entry: PropagationEntry,
path: Option<PathBuf>,
}
#[derive(Debug, Clone)]
pub(crate) struct SyncOfferCandidateSnapshot {
transient_id: PropagationTransientId,
@@ -203,11 +254,12 @@ pub(crate) fn prepare_sync_offer_snapshot(
.propagation_sync_limit
.map(kilobytes_to_bytes_fail_closed);
let mut handled_messages = snapshot.policy.handled_messages.clone();
if let Some(path) = snapshot.peer_path.as_ref()
&& let Ok(data) = std::fs::read(path)
&& let Some(peer) = LxmPeer::from_bytes_with_handled(&data)
{
handled_messages.extend(peer.handled_messages);
if let Some(path) = snapshot.peer_path.as_ref() {
if let Ok(data) = std::fs::read(path) {
if let Some(peer) = LxmPeer::from_bytes_with_handled(&data) {
handled_messages.extend(peer.handled_messages);
}
}
}
let mut candidates = snapshot.candidates;
@@ -267,7 +319,7 @@ fn kilobytes_to_bytes_fail_closed(kilobytes: f64) -> usize {
if !kilobytes.is_finite() || kilobytes <= 0.0 {
return 0;
}
(kilobytes * 1000.0).floor() as usize
(kilobytes * BYTES_PER_KILOBYTE as f64).floor() as usize
}
pub struct PropagationNode {
@@ -283,6 +335,11 @@ pub struct PropagationNode {
/// scheduling and offer-preparation revalidation use this to avoid both
/// stale offers and repeated scans of an unchanged fully-handled store.
offer_generation: u64,
/// IDs and bytes reserved by off-lock store writes. Reservations prevent
/// duplicate acceptance and storage-cap oversubscription while I/O is in
/// flight.
pending_write_ids: HashSet<PropagationTransientId>,
pending_write_bytes: usize,
}
impl PropagationNode {
@@ -296,6 +353,8 @@ impl PropagationNode {
storage_path: None,
last_offer_times: HashMap::new(),
offer_generation: 0,
pending_write_ids: HashSet::new(),
pending_write_bytes: 0,
}
}
@@ -311,6 +370,31 @@ impl PropagationNode {
self.offer_generation
}
/// Apply the daemon's destination deny policy to the authoritative hosted
/// store. The reusable router has its own optional store, so production
/// wiring must configure this node explicitly as well.
pub fn ignore_destination(&mut self, dest_hash: [u8; 16]) {
self.store.ignore_destination(dest_hash);
}
pub fn unignore_destination(&mut self, dest_hash: &[u8; 16]) {
self.store.unignore_destination(dest_hash);
}
pub fn is_destination_ignored(&self, dest_hash: &[u8; 16]) -> bool {
self.store.is_destination_ignored(dest_hash)
}
/// Apply the daemon's culling-priority policy to the authoritative hosted
/// store.
pub fn prioritise_destination(&mut self, dest_hash: [u8; 16]) {
self.store.prioritise_destination(dest_hash);
}
pub fn unprioritise_destination(&mut self, dest_hash: &[u8; 16]) {
self.store.unprioritise_destination(dest_hash);
}
fn advance_offer_generation(&mut self) {
self.offer_generation = self.offer_generation.saturating_add(1);
}
@@ -330,11 +414,91 @@ impl PropagationNode {
storage_path: Some(storage_path),
last_offer_times: HashMap::new(),
offer_generation: 0,
pending_write_ids: HashSet::new(),
pending_write_bytes: 0,
};
node.load_from_disk()?;
Ok(node)
}
fn reserve_store_write(
&mut self,
entry: PropagationEntry,
data: Vec<u8>,
) -> Option<PropagationStoreWritePlan> {
let transient_id = entry.transient_id;
if self.store.contains(&transient_id) || self.pending_write_ids.contains(&transient_id) {
return None;
}
// Python checks the current store size before inserting and permits
// the message that crosses the cap; the next admission is rejected
// until culling makes room. Include reservations in that current-size
// view so concurrent writers cannot all pass the same preflight.
let occupied = self
.store
.total_size()
.saturating_add(self.pending_write_bytes);
if occupied > self.config.max_storage {
return None;
}
self.pending_write_ids.insert(transient_id);
self.pending_write_bytes = self.pending_write_bytes.saturating_add(data.len());
let path = self
.storage_path
.as_ref()
.map(|dir| dir.join(entry.filename()));
Some(PropagationStoreWritePlan { entry, data, path })
}
/// Release a reservation after a failed blocking write.
pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) {
if self.pending_write_ids.remove(transient_id) {
self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size);
}
}
/// Commit a successfully persisted admission. The normal path performs no
/// filesystem I/O while holding the node lock.
pub fn commit_store_write(&mut self, persisted: PersistedPropagationStoreWrite) -> bool {
let transient_id = persisted.entry.transient_id;
let size = persisted.entry.size;
if !self.pending_write_ids.remove(&transient_id) {
if let Some(path) = persisted.path {
let _ = std::fs::remove_file(path);
}
return false;
}
self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size);
let inserted = self.store.insert(persisted.entry);
if inserted {
self.advance_offer_generation();
} else if let Some(path) = persisted.path {
// Reservation loss/duplicate commit is exceptional; cleanup is a
// short best-effort operation and never occurs on normal traffic.
let _ = std::fs::remove_file(path);
}
inserted
}
fn persist_reserved(&mut self, plan: PropagationStoreWritePlan) -> bool {
let transient_id = plan.transient_id();
let size = plan.size();
match plan.persist() {
Ok(persisted) => self.commit_store_write(persisted),
Err(error) => {
self.abort_store_write(&transient_id, size);
tracing::warn!(
transient_id = %hex::encode(transient_id),
%error,
"failed to persist propagation message"
);
false
}
}
}
/// Returns `true` if the message was stored, `false` on duplicate, overflow,
/// pack failure, oversized message, or insufficient stamp.
#[tracing::instrument(
@@ -346,28 +510,22 @@ impl PropagationNode {
size = message.content.len(),
),
)]
pub fn accept_message(&mut self, message: &LxMessage) -> bool {
let hash = match message.hash {
Some(h) => h,
None => return false,
};
pub fn plan_accept_message(
&mut self,
message: &LxMessage,
) -> Option<PropagationStoreWritePlan> {
let hash = message.hash?;
let transient_id = message.transient_id.unwrap_or(hash);
if self.store.contains(&transient_id) {
return false;
}
if self.store.total_size() > self.config.max_storage {
return false;
return None;
}
let packed = match message.pack() {
Ok(p) => p,
Err(_) => return false,
};
let packed = message.pack().ok()?;
let msg_size = packed.len();
if msg_size > self.config.max_message_size {
return false;
return None;
}
// Compute stamp value via HKDF workblock over full_hash(packed) using
@@ -388,26 +546,21 @@ impl PropagationNode {
};
if self.config.min_stamp_cost > 0 && sv < self.config.min_stamp_cost {
return false;
return None;
}
let mut entry =
PropagationEntry::new(transient_id, hash, message.destination_hash, msg_size, sv);
entry.stored_at = message.timestamp;
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, &packed) {
// In-memory insert still proceeds on disk failure.
tracing::warn!(error = %e, "failed to persist propagation message");
}
}
self.reserve_store_write(entry, packed)
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_message(&mut self, message: &LxMessage) -> bool {
let Some(plan) = self.plan_accept_message(message) else {
return false;
};
self.persist_reserved(plan)
}
/// Store an already propagation-packed LXMF blob (`dest_hash || encrypted_data`).
@@ -416,23 +569,24 @@ impl PropagationNode {
/// [`Self::accept_message`], the node cannot decrypt or unpack this data;
/// it indexes by the transient ID and serves the raw blob back to the
/// destination client during `/get`.
pub fn accept_propagated_blob(&mut self, lxmf_data: &[u8], stamp_value: u8) -> bool {
pub fn plan_accept_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_value: u8,
) -> Option<PropagationStoreWritePlan> {
if lxmf_data.len() < DESTINATION_LENGTH + 1 {
return false;
return None;
}
if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost {
return false;
return None;
}
let transient_id = rns_crypto::sha::full_hash(lxmf_data);
if self.store.contains(&transient_id) {
return false;
}
if self.store.total_size() > self.config.max_storage {
return false;
return None;
}
if lxmf_data.len() > self.config.max_message_size {
return false;
return None;
}
let mut destination_hash = [0u8; 16];
@@ -446,18 +600,14 @@ impl PropagationNode {
stamp_value,
);
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, lxmf_data) {
tracing::warn!(error = %e, "failed to persist propagated message");
}
}
self.reserve_store_write(entry, lxmf_data.to_vec())
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_propagated_blob(&mut self, lxmf_data: &[u8], stamp_value: u8) -> bool {
let Some(plan) = self.plan_accept_propagated_blob(lxmf_data, stamp_value) else {
return false;
};
self.persist_reserved(plan)
}
/// Store a validated propagated LXMF blob with its propagation-node stamp.
@@ -466,33 +616,30 @@ impl PropagationNode {
/// `lxmf_data || stamp` on disk so peer sync can forward proof-carrying
/// data. Client `/get` strips the final 32-byte stamp before returning
/// messages to recipients.
pub fn accept_stamped_propagated_blob(
pub fn plan_accept_stamped_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_data: &[u8; 32],
stamp_value: u8,
) -> bool {
) -> Option<PropagationStoreWritePlan> {
if lxmf_data.len() < DESTINATION_LENGTH + 1 {
return false;
return None;
}
if self.config.min_stamp_cost > 0 && stamp_value < self.config.min_stamp_cost {
return false;
return None;
}
let transient_id = rns_crypto::sha::full_hash(lxmf_data);
if self.store.contains(&transient_id) {
return false;
return None;
}
let mut stored_data = Vec::with_capacity(lxmf_data.len() + stamp_data.len());
stored_data.extend_from_slice(lxmf_data);
stored_data.extend_from_slice(stamp_data);
if self.store.total_size() > self.config.max_storage {
return false;
}
if stored_data.len() > self.config.max_message_size {
return false;
return None;
}
let mut destination_hash = [0u8; 16];
@@ -506,18 +653,21 @@ impl PropagationNode {
stamp_value,
);
if let Some(ref dir) = self.storage_path {
let path = dir.join(entry.filename());
if let Err(e) = std::fs::write(&path, &stored_data) {
tracing::warn!(error = %e, "failed to persist stamped propagated message");
}
}
self.reserve_store_write(entry, stored_data)
}
let inserted = self.store.insert(entry);
if inserted {
self.advance_offer_generation();
}
inserted
pub fn accept_stamped_propagated_blob(
&mut self,
lxmf_data: &[u8],
stamp_data: &[u8; 32],
stamp_value: u8,
) -> bool {
let Some(plan) =
self.plan_accept_stamped_propagated_blob(lxmf_data, stamp_data, stamp_value)
else {
return false;
};
self.persist_reserved(plan)
}
fn load_from_disk(&mut self) -> std::io::Result<()> {
@@ -631,10 +781,10 @@ impl PropagationNode {
self.advance_offer_generation();
}
if before > after
&& let Some(ref dir) = self.storage_path
{
self.cleanup_orphaned_files(dir);
if before > after {
if let Some(ref dir) = self.storage_path {
self.cleanup_orphaned_files(dir);
}
}
}
@@ -652,10 +802,10 @@ impl PropagationNode {
if filename.ends_with(".peer") || filename.ends_with(".msgpack") {
continue;
}
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename)
&& !self.store.contains(&tid)
{
let _ = std::fs::remove_file(&path);
if let Some((tid, _, _)) = PropagationEntry::parse_filename(&filename) {
if !self.store.contains(&tid) {
let _ = std::fs::remove_file(&path);
}
}
}
}
@@ -696,6 +846,20 @@ impl PropagationNode {
self.store.len()
}
/// Count live store entries not yet handled by one peer. The daemon's
/// generation scheduler does not maintain `LxmPeer`'s legacy cached
/// unhandled counter, so control status must derive this from the same
/// authoritative store used to prepare offers.
pub fn unhandled_message_count(
&self,
handled_messages: &HashSet<PropagationTransientId>,
) -> usize {
self.store
.entries()
.filter(|entry| !handled_messages.contains(&entry.transient_id))
.count()
}
pub fn total_size(&self) -> usize {
self.store.total_size()
}
@@ -939,24 +1103,26 @@ impl PropagationNode {
let mut reads = Vec::new();
if let Some(wants_arr) = arr[0].as_array() {
for want_val in wants_arr {
if let Some(tid) = parse_store_id(want_val)
&& let Some(ref dir) = self.storage_path
&& let Some(entry) = self.store.get(&tid)
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
&& entry.destination_hash == *client_dest_hash
if let (Some(tid), Some(dir)) =
(parse_store_id(want_val), self.storage_path.as_ref())
{
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
if let Some(entry) = self.store.get(&tid) {
// Ownership gate (Python LXMRouter.py:1479): a client
// may only download messages addressed to itself.
if entry.destination_hash == *client_dest_hash {
reads.push(PlannedRead {
path: dir.join(entry.filename()),
stamped: entry.stamped,
});
}
}
}
}
}
// Wire value is kilobytes ×1000 (Python LXMRouter.py:1471).
// Wire value is decimal kilobytes (Python LXMRouter.py:1471).
let limit_bytes = if arr.len() > 2 {
arr[2].as_f64().map(|kb| kb * 1000.0)
arr[2].as_f64().map(|kb| kb * BYTES_PER_KILOBYTE as f64)
} else {
None
};
@@ -1111,10 +1277,11 @@ impl PropagationNode {
// Compatibility wrapper: production uses the staged task
// path and exposes this delta to the daemon for off-loop
// persistence.
if !terminal_handled_ids.is_empty()
&& let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
if !terminal_handled_ids.is_empty() {
if let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids)
{
tracing::warn!(%error, "failed to persist terminal offer dispositions");
}
}
return offer;
}
@@ -1228,12 +1395,13 @@ impl PropagationNode {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "peer").unwrap_or(false)
&& let Ok(data) = std::fs::read(&path)
&& let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data)
{
self.prune_handled_against_store(&mut peer);
peers.push(peer);
if path.extension().map(|e| e == "peer").unwrap_or(false) {
if let Ok(data) = std::fs::read(&path) {
if let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data) {
self.prune_handled_against_store(&mut peer);
peers.push(peer);
}
}
}
}
}
@@ -1326,7 +1494,9 @@ mod tests {
#[test]
fn test_new_propagation_node() {
let node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let config = PropagationNodeConfig::default();
assert_eq!(config.max_message_size, 1_000_000);
let node = PropagationNode::new(config, [0xAA; 16]);
assert_eq!(node.message_count(), 0);
assert_eq!(node.total_size(), 0);
assert_eq!(node.dest_hash, [0xAA; 16]);
@@ -1341,6 +1511,73 @@ mod tests {
assert_eq!(node.message_count(), 1);
}
#[test]
fn store_write_reservation_blocks_duplicates_until_durable_commit() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "reserved");
let plan = node.plan_accept_message(&msg).expect("first reservation");
assert_eq!(node.message_count(), 0, "reservation is not served state");
assert!(node.plan_accept_message(&msg).is_none());
let persisted = plan.persist().unwrap();
assert!(node.commit_store_write(persisted));
assert_eq!(node.message_count(), 1);
}
#[test]
fn failed_store_write_is_not_inserted_and_releases_reservation() {
let root = tempfile::tempdir().unwrap();
let store_dir = root.path().join("store");
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
store_dir.clone(),
)
.unwrap();
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "durable");
let plan = node.plan_accept_message(&msg).expect("reservation");
let transient_id = plan.transient_id();
let size = plan.size();
std::fs::remove_dir(&store_dir).unwrap();
assert!(plan.persist().is_err());
node.abort_store_write(&transient_id, size);
assert_eq!(node.message_count(), 0);
std::fs::create_dir(&store_dir).unwrap();
assert!(node.accept_message(&msg));
assert_eq!(node.message_count(), 1);
}
#[test]
fn hosted_node_applies_ignored_destination_policy() {
let destination = [0x44; 16];
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
node.ignore_destination(destination);
assert!(node.is_destination_ignored(&destination));
let mut blob = destination.to_vec();
blob.extend_from_slice(b"encrypted-lxmf");
assert!(!node.accept_stamped_propagated_blob(&blob, &[0; 32], 0));
assert_eq!(node.message_count(), 0);
node.unignore_destination(&destination);
assert!(node.accept_stamped_propagated_blob(&blob, &[0; 32], 0));
}
#[test]
fn unhandled_count_is_derived_from_live_store_and_peer_handled_set() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content");
let transient_id = msg.transient_id.or(msg.hash).unwrap();
assert!(node.accept_message(&msg));
let mut handled = HashSet::new();
assert_eq!(node.unhandled_message_count(&handled), 1);
handled.insert(transient_id);
assert_eq!(node.unhandled_message_count(&handled), 0);
}
#[test]
fn test_reject_duplicate() {
let mut node = PropagationNode::new(PropagationNodeConfig::default(), [0xAA; 16]);
@@ -2715,8 +2952,10 @@ mod tests {
};
// Reads resolve after the node borrow ends (embedder drops the lock).
drop(node);
let response: Value = rmpv::decode::read_value(&mut &plan.serve()[..]).unwrap();
let (response_bytes, served) = plan.serve_with_count();
let response: Value = rmpv::decode::read_value(&mut &response_bytes[..]).unwrap();
let messages = response.as_array().unwrap();
assert_eq!(served, 1);
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].as_slice().unwrap(), blob.as_slice());
File diff suppressed because it is too large. Load diff
+421 -112
View File
@@ -109,12 +109,17 @@ pub struct DeferredStampJob {
#[derive(Debug)]
pub enum SendError {
MissingOutboundPropagationNode(Box<LxMessage>),
TicketPreparation {
message: Box<LxMessage>,
source: TicketPreparationError,
},
}
impl SendError {
pub fn message(&self) -> &LxMessage {
match self {
Self::MissingOutboundPropagationNode(message) => message,
Self::TicketPreparation { message, .. } => message,
}
}
}
@@ -125,12 +130,21 @@ impl fmt::Display for SendError {
Self::MissingOutboundPropagationNode(_) => f.write_str(
"attempt to send propagated message with no outbound propagation node configured",
),
Self::TicketPreparation { source, .. } => source.fmt(f),
}
}
}
impl std::error::Error for SendError {}
#[derive(Debug, thiserror::Error)]
pub enum TicketPreparationError {
#[error("reply ticket must be added before the LXMF message is signed")]
AlreadySigned,
#[error("failed to encode LXMF reply ticket: {0}")]
Encode(String),
}
/// Current route metadata for an LXMF Direct delivery destination.
#[derive(Debug, Clone, PartialEq)]
pub struct DirectRouteSnapshot {
@@ -457,6 +471,7 @@ impl LxmRouter {
content_len = message.content.len(),
),
)]
#[deprecated(note = "use try_send() and handle the immediate routing result")]
pub fn send(&mut self, message: LxMessage) {
let _ = self.try_send(message);
}
@@ -479,11 +494,12 @@ impl LxmRouter {
return Err(SendError::MissingOutboundPropagationNode(Box::new(message)));
}
let now = now_f64();
if message.outbound_ticket.is_none()
&& let Some(ticket) = self.ticket_store.find(&message.destination_hash, now)
{
message.outbound_ticket = Some(ticket.token);
if let Err(source) = self.prepare_outbound(&mut message) {
message.mark_failed();
return Err(SendError::TicketPreparation {
message: Box::new(message),
source,
});
}
if message.stamp.is_none() && message.stamp_cost.is_none() {
@@ -514,16 +530,16 @@ impl LxmRouter {
}
}
if message.method == DeliveryMethod::Opportunistic
&& let Ok(packed) = message.pack_payload()
{
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
if message.method == DeliveryMethod::Opportunistic {
if let Ok(packed) = message.pack_payload() {
let content_size = packed
.len()
.saturating_sub(TIMESTAMP_SIZE + STRUCT_OVERHEAD);
// Approximates ENCRYPTED_PACKET_MAX_CONTENT for default RNS parameters.
let max_content = 295;
if content_size > max_content {
message.method = DeliveryMethod::Direct;
}
}
}
@@ -532,6 +548,53 @@ impl LxmRouter {
Ok(())
}
/// Apply router-owned ticket state before a caller signs `message`.
///
/// Learned outbound tickets do not change signed fields and can be
/// attached at any time. A requested reply ticket is a signed LXMF field,
/// so it must be inserted before signing. The method is deliberately
/// signer-agnostic: callers may subsequently use either `sign` or
/// `sign_with` without exposing private key material to the router.
pub fn prepare_outbound(
&mut self,
message: &mut LxMessage,
) -> Result<(), TicketPreparationError> {
let now = now_f64();
if message.outbound_ticket.is_none() {
if let Some(ticket) = self
.ticket_store
.find_outbound(&message.destination_hash, now)
{
message.outbound_ticket = Some(ticket.token);
}
}
if message.include_ticket && !message.fields.contains_key(&FIELD_TICKET) {
if message.signature.is_some() {
if self
.ticket_store
.should_issue_for(&message.destination_hash, now)
{
return Err(TicketPreparationError::AlreadySigned);
}
return Ok(());
}
if let Some(ticket) =
self.ticket_store
.issue_for(message.destination_hash, TICKET_EXPIRY, now)
{
let encoded = ticket
.encode_field()
.map_err(|error| TicketPreparationError::Encode(error.to_string()))?;
message
.set_msgpack_field(FIELD_TICKET, encoded)
.map_err(|error| TicketPreparationError::Encode(error.to_string()))?;
}
}
Ok(())
}
/// Queue `message` for off-thread stamp generation; it re-enters
/// `pending_outbound` with the stamp attached once the worker finishes.
/// Returns the message back when it carries no id to key the job on.
@@ -758,7 +821,7 @@ impl LxmRouter {
rand::thread_rng().fill_bytes(&mut token);
let expires = now_f64() + expiry_secs.unwrap_or(TICKET_EXPIRY) as f64;
self.ticket_store
.add(Ticket::new(token, destination_hash, expires));
.add_inbound(Ticket::new(token, destination_hash, expires));
token
}
@@ -767,7 +830,7 @@ impl LxmRouter {
/// Python reference: `LXMRouter.remember_ticket` — LXMRouter.py:1110-1113.
pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) {
self.ticket_store
.add(Ticket::new(token, destination_hash, expires));
.remember_outbound(Ticket::new(token, destination_hash, expires));
}
/// Returns the token of the first valid ticket for `destination_hash`.
@@ -776,7 +839,7 @@ impl LxmRouter {
pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> {
let now = now_f64();
self.ticket_store
.find(destination_hash, now)
.find_outbound(destination_hash, now)
.map(|t| t.token)
}
@@ -786,7 +849,7 @@ impl LxmRouter {
pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option<f64> {
let now = now_f64();
self.ticket_store
.find(destination_hash, now)
.find_outbound(destination_hash, now)
.map(|t| t.expires)
}
@@ -794,7 +857,7 @@ impl LxmRouter {
///
/// Python reference: `LXMRouter.get_inbound_tickets` — LXMRouter.py:1133-1136.
pub fn get_inbound_tickets(&self) -> &[Ticket] {
self.ticket_store.all()
self.ticket_store.inbound()
}
/// Cancel an outbound message before it is sent.
@@ -817,13 +880,14 @@ impl LxmRouter {
if let Some(mut msg) = self.pending_deferred_stamps.remove(message_hash) {
msg.cancel();
if self
let active_matches = self
.active_deferred_stamp
.as_ref()
.is_some_and(|job| job.message_hash == *message_hash)
&& let Some(job) = self.active_deferred_stamp.take()
{
job.handle.cancel();
.is_some_and(|job| job.message_hash == *message_hash);
if active_matches {
if let Some(job) = self.active_deferred_stamp.take() {
job.handle.cancel();
}
}
return true;
}
@@ -842,11 +906,26 @@ impl LxmRouter {
return false;
};
let mut msg = self.pending_outbound.remove(pos);
msg.mark_delivered();
let msg = self.pending_outbound.remove(pos);
self.complete_outbound_message(msg);
true
}
/// Complete an outbound message whose in-flight ownership moved from the
/// router queue into an embedding runtime.
///
/// Opportunistic packet delivery is asynchronous: the network accepts the
/// packet first and authenticates a delivery proof later. Embedders retain
/// the message between those events and return it here only after proof so
/// ticket-delivery accounting and callbacks reflect the observable result.
pub fn complete_outbound_message(&mut self, mut msg: LxMessage) {
if msg.include_ticket && msg.fields.contains_key(&FIELD_TICKET) {
self.ticket_store
.mark_ticket_delivered(msg.destination_hash, now_f64());
}
msg.mark_delivered();
}
/// Mark a pending outbound message failed and remove it from the outbound
/// queue.
pub fn mark_outbound_failed(&mut self, message_hash: &[u8; 32]) -> bool {
@@ -949,6 +1028,8 @@ impl LxmRouter {
/// distinct from its signed message hash; both identifiers are retained
/// so a later delivery through another representation is still deduped.
pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool {
self.learn_ticket_from_inbound(message);
let Some(message_id) = message.message_id.or(message.hash) else {
return false;
};
@@ -975,6 +1056,22 @@ impl LxmRouter {
true
}
/// Learn a reply ticket only from a cryptographically validated inbound
/// message. Returns whether valid outbound ticket state changed.
pub fn learn_ticket_from_inbound(&mut self, message: &LxMessage) -> bool {
if !message.signature_validated {
return false;
}
let Some(encoded) = message.fields.get(&FIELD_TICKET) else {
return false;
};
let Some(ticket) = Ticket::decode_field(message.source_hash, encoded, now_f64()) else {
return false;
};
self.ticket_store.remember_outbound(ticket);
true
}
/// Ingest an encrypted paper (`lxm://...`) URI and invoke the delivery callback as if the
/// message had arrived via the network.
///
@@ -1009,8 +1106,12 @@ impl LxmRouter {
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
self.ticket_store
.replace_all(persist::load_tickets(state_dir)?);
let (snapshot, legacy) = persist::load_tickets(state_dir)?;
if let Some(legacy) = legacy {
self.ticket_store.replace_legacy(legacy);
} else {
self.ticket_store.replace_snapshot(snapshot);
}
self.propagation_store
.replace_locally_delivered(persist::load_local_deliveries(state_dir)?);
self.propagation_store
@@ -1034,7 +1135,7 @@ impl LxmRouter {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, self.ticket_store.all())?;
persist::save_tickets(state_dir, &self.ticket_store.snapshot())?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
persist::save_node_stats(
@@ -1078,15 +1179,19 @@ impl LxmRouter {
/// The method does not mutate peer state, allowing a single shared sync
/// task to accept one policy before the daemon marks that peer started.
pub fn sync_peer_policies_for_store(&self, offer_generation: u64) -> Vec<OutboundOfferPolicy> {
let mut policies = self
let eligible = self
.peers
.values()
.filter(|peer| {
peer.alive
&& peer.state == PeerState::Idle
peer.state == PeerState::Idle
&& peer.should_sync()
&& peer.needs_offer_generation(offer_generation)
})
.collect::<Vec<_>>();
let has_alive = eligible.iter().any(|peer| peer.alive);
let mut policies = eligible
.into_iter()
.filter(|peer| peer.alive == has_alive)
.map(OutboundOfferPolicy::from)
.collect::<Vec<_>>();
policies.sort_by_key(|policy| policy.peer_hash);
@@ -1170,8 +1275,7 @@ impl LxmRouter {
return false;
}
if !configured_static
&& let Some(h) = hops
&& h as usize > self.config.ext.autopeer_maxdepth
&& hops.is_some_and(|h| h as usize > self.config.ext.autopeer_maxdepth)
{
return false;
}
@@ -1362,12 +1466,9 @@ impl LxmRouter {
destination_hash: &[u8; 16],
) -> bool {
let now = now_f64();
for ticket in self.ticket_store.all() {
if &ticket.destination_hash != destination_hash || !ticket.is_valid(now) {
continue;
}
for token in self.ticket_store.inbound_tokens(destination_hash, now) {
let mut material = Vec::with_capacity(16 + 32);
material.extend_from_slice(&ticket.token);
material.extend_from_slice(&token);
material.extend_from_slice(message_id);
let expected = rns_crypto::sha::truncated_hash(&material);
if stamp == expected.as_ref() {
@@ -1546,8 +1647,11 @@ impl LxmRouter {
let mut i = 0;
while i < self.pending_outbound.len() {
if let Some(limit) = self.config.ext.processing_limit
&& processed >= limit
if self
.config
.ext
.processing_limit
.is_some_and(|limit| processed >= limit)
{
break;
}
@@ -1592,7 +1696,8 @@ impl LxmRouter {
}
// State transitions match Python LXMessage.py:476-499:
// Opportunistic -> Sent immediately (single packet, fire-and-forget).
// Opportunistic -> Sent immediately; the embedding runtime keeps
// receipt ownership until an authenticated packet proof arrives.
// Direct / Propagated -> Sending (multi-step).
match msg.method {
DeliveryMethod::Direct => {
@@ -1665,8 +1770,11 @@ impl LxmRouter {
let mut i = 0;
while i < self.pending_outbound.len() {
if let Some(limit) = self.config.ext.processing_limit
&& processed >= limit
if self
.config
.ext
.processing_limit
.is_some_and(|limit| processed >= limit)
{
break;
}
@@ -1870,26 +1978,37 @@ impl LxmRouter {
let mut raw = header.pack();
raw.extend_from_slice(&packet_payload);
if transport_tx
let dispatched = transport_tx
.try_send(rns_transport::messages::TransportMessage::Outbound(
rns_transport::messages::OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest_hash,
},
))
.is_ok()
&& message.state == MessageState::Sending
.is_ok();
if dispatched
&& matches!(
message.state,
MessageState::Sending | MessageState::Sent
)
{
message.mark_sent();
message.progress = 1.0;
} else {
tracing::warn!(
dest = %hex::encode(dest_hash),
"transport backpressure deferred opportunistic LXMF delivery"
);
self.pending_outbound.push(message);
}
}
Err(err) => {
tracing::warn!(
dest = %hex::encode(dest_hash),
error = %err,
"cannot execute opportunistic LXMF action"
"cannot execute opportunistic LXMF action; re-queueing"
);
self.pending_outbound.push(message);
}
}
}
@@ -1955,20 +2074,16 @@ impl LxmRouter {
fn run_periodic_jobs(&mut self) {
// Job cadences match the Python LXMRouter jobloop.
if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) {
if self.processing_count % JOB_TRANSIENT_INTERVAL == 0 {
self.propagation_store.clean_transient_caches(now_f64());
}
if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL)
&& self.config.propagation_enabled
{
if self.processing_count % JOB_STORE_INTERVAL == 0 && self.config.propagation_enabled {
self.cull_propagation();
}
if self.processing_count.is_multiple_of(JOB_PEERSYNC_INTERVAL) {
if self.processing_count % JOB_PEERSYNC_INTERVAL == 0 {
self.clean_throttled_peers();
}
if self.processing_count.is_multiple_of(JOB_ROTATE_INTERVAL)
&& self.config.propagation_enabled
{
if self.processing_count % JOB_ROTATE_INTERVAL == 0 && self.config.propagation_enabled {
self.rotate_peers();
}
}
@@ -2293,7 +2408,7 @@ mod tests {
let msg = direct_policy_message();
let msg_hash = msg.hash;
let dest = msg.destination_hash;
router.send(msg);
router.try_send(msg).unwrap();
let actions =
router.process_outbound_with_direct(|message, _now| DirectDeliveryPlanInput {
@@ -2330,7 +2445,7 @@ mod tests {
let mut msg = direct_policy_message();
msg.next_delivery_attempt = now_f64() + 3600.0;
let msg_hash = msg.hash;
router.send(msg);
router.try_send(msg).unwrap();
let actions =
router.process_outbound_with_direct(|_message, _now| DirectDeliveryPlanInput {
@@ -2355,7 +2470,7 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let first = direct_policy_message();
let first_hash = first.hash.expect("first hash");
router.send(first);
router.try_send(first).unwrap();
assert!(router.defer_outbound_for_path_request(&first_hash, 1000.0));
assert_eq!(
@@ -2369,7 +2484,7 @@ mod tests {
let second = direct_policy_message();
let second_hash = second.hash.expect("second hash");
router.send(second);
router.try_send(second).unwrap();
assert!(router.mark_outbound_failed(&second_hash));
assert!(router.pending_outbound.is_empty());
}
@@ -2458,7 +2573,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_deferred_stamps.is_empty());
assert_eq!(router.pending_outbound.len(), 1);
@@ -2467,6 +2582,114 @@ mod tests {
assert_eq!(queued.stamp_value, Some(COST_TICKET));
}
#[test]
fn prepare_outbound_issues_native_reply_ticket_before_signing() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAA; 16];
let mut msg = LxMessage::new(dest, [0xBB; 16], "ticket", "reply", DeliveryMethod::Direct);
msg.include_ticket = true;
router.prepare_outbound(&mut msg).unwrap();
assert!(msg.msgpack_field_ids.contains(&FIELD_TICKET));
let field = msg.fields.get(&FIELD_TICKET).unwrap();
let value = rmpv::decode::read_value(&mut field.as_slice()).unwrap();
assert_eq!(value.as_array().unwrap().len(), 2);
msg.sign(&key).unwrap();
router.try_send(msg).unwrap();
let hash = router.pending_outbound[0].hash.unwrap();
assert!(router.mark_outbound_delivered(&hash));
let mut next = LxMessage::new(dest, [0xBB; 16], "ticket", "later", DeliveryMethod::Direct);
next.include_ticket = true;
router.prepare_outbound(&mut next).unwrap();
assert!(!next.fields.contains_key(&FIELD_TICKET));
}
#[test]
fn externally_retained_message_updates_ticket_only_when_completed() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAC; 16];
let mut in_flight = LxMessage::new(
dest,
[0xBD; 16],
"ticket",
"proof",
DeliveryMethod::Opportunistic,
);
in_flight.include_ticket = true;
router.prepare_outbound(&mut in_flight).unwrap();
in_flight.sign(&key).unwrap();
let mut before_proof =
LxMessage::new(dest, [0xBD; 16], "ticket", "before", DeliveryMethod::Direct);
before_proof.include_ticket = true;
router.prepare_outbound(&mut before_proof).unwrap();
assert!(before_proof.fields.contains_key(&FIELD_TICKET));
router.complete_outbound_message(in_flight);
let mut after_proof =
LxMessage::new(dest, [0xBD; 16], "ticket", "after", DeliveryMethod::Direct);
after_proof.include_ticket = true;
router.prepare_outbound(&mut after_proof).unwrap();
assert!(!after_proof.fields.contains_key(&FIELD_TICKET));
}
#[test]
fn signed_message_requesting_ticket_fails_instead_of_invalidating_signature() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut router = LxmRouter::new(RouterConfig::default());
let mut msg = LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"ticket",
"late",
DeliveryMethod::Direct,
);
msg.include_ticket = true;
msg.sign(&key).unwrap();
assert!(matches!(
router.try_send(msg),
Err(SendError::TicketPreparation {
source: TicketPreparationError::AlreadySigned,
..
})
));
assert!(router.pending_outbound.is_empty());
}
#[test]
fn deliver_inbound_learns_ticket_only_after_signature_validation() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let public = key.public_key();
let source = [0xBB; 16];
let mut sender = LxmRouter::new(RouterConfig::default());
let mut msg = LxMessage::new(
[0xAA; 16],
source,
"ticket",
"learn",
DeliveryMethod::Direct,
);
msg.include_ticket = true;
sender.prepare_outbound(&mut msg).unwrap();
msg.sign(&key).unwrap();
let mut unsigned_receiver = LxmRouter::new(RouterConfig::default());
assert!(unsigned_receiver.deliver_inbound(&msg, false));
assert!(unsigned_receiver.get_outbound_ticket(&source).is_none());
let mut verified = msg.clone();
assert!(verified.verify(&public));
let mut receiver = LxmRouter::new(RouterConfig::default());
assert!(receiver.deliver_inbound(&verified, false));
assert!(receiver.get_outbound_ticket(&source).is_some());
}
#[tokio::test]
async fn test_deferred_stamp_queue_completes_before_outbound_processing() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
@@ -2477,7 +2700,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "defer", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_outbound.is_empty());
assert!(router.pending_deferred_stamps.contains_key(&message_id));
@@ -2521,7 +2744,7 @@ mod tests {
);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.pending_deferred_stamps.contains_key(&message_id));
// Drive entirely from a blocking thread (no implicit runtime).
@@ -2576,7 +2799,7 @@ mod tests {
let mut msg = LxMessage::new(dest, [0xBB; 16], "cancel", "stamp", DeliveryMethod::Direct);
msg.sign(&key).unwrap();
let message_id = msg.message_id.unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.process_deferred_stamps();
assert!(router.active_deferred_stamp.is_some());
@@ -2621,13 +2844,16 @@ mod tests {
assert!(router.get_inbound_tickets().is_empty());
let token = router.generate_ticket(dest, None);
assert_eq!(router.get_outbound_ticket(&dest), Some(token));
assert!(router.get_outbound_ticket_expiry(&dest).unwrap() > now_f64());
assert!(router.get_outbound_ticket(&dest).is_none());
assert_eq!(router.get_inbound_tickets().len(), 1);
assert_eq!(router.get_inbound_tickets()[0].token, token);
// remember_ticket adds another entry for the same dest.
// A remembered peer ticket is outbound and does not alter the
// locally-issued inbound set.
router.remember_ticket(dest, [0x55; 16], now_f64() + 1000.0);
assert_eq!(router.get_inbound_tickets().len(), 2);
assert_eq!(router.get_inbound_tickets().len(), 1);
assert_eq!(router.get_outbound_ticket(&dest), Some([0x55; 16]));
assert!(router.get_outbound_ticket_expiry(&dest).unwrap() > now_f64());
}
#[test]
@@ -2635,8 +2861,12 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let dest = [0xAA; 16];
let expires = now_f64() + 1000.0;
router.remember_ticket(dest, [0x01; 16], expires);
router.remember_ticket(dest, [0x02; 16], expires);
router
.ticket_store
.add_inbound(Ticket::new([0x01; 16], dest, expires));
router
.ticket_store
.add_inbound(Ticket::new([0x02; 16], dest, expires));
// Stamp derived from the SECOND ticket must still validate.
let message_id = [0x33u8; 32];
@@ -2934,6 +3164,38 @@ mod tests {
assert_eq!(router.sync_peer_policies_for_store(6).len(), 1);
}
#[test]
fn store_generation_scheduler_falls_back_to_backoff_expired_unresponsive_peers() {
let alive_hash = [0x21; 16];
let fallback_hash = [0x22; 16];
let mut router = LxmRouter::new(RouterConfig::default());
let alive = LxmPeer::new(alive_hash);
let mut fallback = LxmPeer::new(fallback_hash);
fallback.alive = false;
fallback.next_sync_attempt = 0.0;
assert!(router.add_peer(alive));
assert!(router.add_peer(fallback));
let policies = router.sync_peer_policies_for_store(1);
assert_eq!(
policies
.iter()
.map(|policy| policy.peer_hash)
.collect::<Vec<_>>(),
vec![alive_hash]
);
router.peers.get_mut(&alive_hash).unwrap().begin_sync();
let policies = router.sync_peer_policies_for_store(1);
assert_eq!(
policies
.iter()
.map(|policy| policy.peer_hash)
.collect::<Vec<_>>(),
vec![fallback_hash]
);
}
#[test]
fn test_validate_stamp() {
let router = LxmRouter::new(RouterConfig::default());
@@ -2955,7 +3217,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
assert_eq!(router.pending_outbound.len(), 1);
assert_eq!(router.pending_outbound[0].state, MessageState::Outbound);
}
@@ -2990,7 +3252,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS + 1;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3010,7 +3272,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.delivery_attempts = MAX_DELIVERY_ATTEMPTS;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3064,7 +3326,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_direct = actions
@@ -3088,7 +3350,7 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_propagated = actions
@@ -3107,7 +3369,7 @@ mod tests {
"Content",
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
let has_opportunistic = actions
@@ -3126,7 +3388,10 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
assert!(matches!(
router.try_send(msg),
Err(SendError::MissingOutboundPropagationNode(_))
));
assert!(
router.pending_outbound.is_empty(),
@@ -3148,7 +3413,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1);
@@ -3174,7 +3439,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
assert_eq!(router.trigger_outbound_for_delivery_announce(dest), 1);
@@ -3199,7 +3464,7 @@ mod tests {
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64();
msg.next_delivery_attempt = now_f64() + PATH_REQUEST_WAIT as f64;
router.send(msg);
router.try_send(msg).unwrap();
assert!(router.process_outbound().is_empty());
@@ -3221,13 +3486,15 @@ mod tests {
let mut router = LxmRouter::new(RouterConfig::default());
let node = [0xCC; 16];
router.set_outbound_propagation_node(Some(node));
router.send(LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"Propagated",
"Content",
DeliveryMethod::Propagated,
));
router
.try_send(LxMessage::new(
[0xAA; 16],
[0xBB; 16],
"Propagated",
"Content",
DeliveryMethod::Propagated,
))
.unwrap();
assert_eq!(
router.trigger_outbound_for_propagation_node_announce([0xDD; 16], b"not-msgpack"),
@@ -3255,7 +3522,7 @@ mod tests {
);
// Anchor the timestamp comfortably past the expiry window.
msg.timestamp = now_f64() - (MESSAGE_EXPIRY as f64) - 60.0;
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3287,7 +3554,7 @@ mod tests {
// Simulate one failed attempt very recently.
msg.delivery_attempts = 1;
msg.last_delivery_attempt = now_f64() - 1.0; // 1 s ago, inside the 10 s window.
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert!(
@@ -3317,7 +3584,7 @@ mod tests {
);
msg.last_delivery_attempt = now_f64() - 1.0;
router.set_outbound_propagation_node(Some([0xCC; 16]));
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert!(
@@ -3343,7 +3610,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3374,12 +3641,16 @@ mod tests {
DeliveryMethod::Opportunistic,
);
msg.sign(&signing_key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.tick_with_encryptor(|_dest, plaintext| Ok(plaintext.to_vec()));
let received = rx.try_recv();
assert!(received.is_ok(), "expected outbound packet from tick()");
assert!(
router.pending_outbound.is_empty(),
"a successful fire-and-forget tick must not requeue the sent packet"
);
}
#[test]
@@ -3451,6 +3722,40 @@ mod tests {
);
}
#[test]
fn opportunistic_transport_backpressure_requeues_instead_of_dropping() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let dest_hash = [0xA1; 16];
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
tx.try_send(
rns_transport::messages::TransportMessage::DeregisterDestination { hash: [0xF0; 16] },
)
.unwrap();
let mut router = LxmRouter::new(RouterConfig::default());
router.set_transport(tx);
let mut message = LxMessage::new(
dest_hash,
[0xB1; 16],
"defer",
"payload",
DeliveryMethod::Opportunistic,
);
message.sign(&key).unwrap();
let message_hash = message.hash;
router.execute_actions_with_encryptor(
vec![OutboundAction::DeliverOpportunistic { message, dest_hash }],
|_dest, plaintext| Ok(plaintext.to_vec()),
);
assert!(matches!(
rx.try_recv().unwrap(),
rns_transport::messages::TransportMessage::DeregisterDestination { .. }
));
assert_eq!(router.pending_outbound.len(), 1);
assert_eq!(router.pending_outbound.first().unwrap().hash, message_hash);
}
#[test]
fn test_execute_actions_without_encryptor_does_not_send_opportunistic_plaintext() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
@@ -3802,20 +4107,24 @@ mod tests {
config.ext.processing_limit = Some(1);
let mut router = LxmRouter::new(config);
router.send(LxMessage::new(
[0x01; 16],
[0; 16],
"a",
"b",
DeliveryMethod::Direct,
));
router.send(LxMessage::new(
[0x02; 16],
[0; 16],
"c",
"d",
DeliveryMethod::Direct,
));
router
.try_send(LxMessage::new(
[0x01; 16],
[0; 16],
"a",
"b",
DeliveryMethod::Direct,
))
.unwrap();
router
.try_send(LxMessage::new(
[0x02; 16],
[0; 16],
"c",
"d",
DeliveryMethod::Direct,
))
.unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3843,7 +4152,7 @@ mod tests {
&large_content,
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
assert_eq!(router.pending_outbound[0].method, DeliveryMethod::Direct);
}
@@ -3858,7 +4167,7 @@ mod tests {
"Content",
DeliveryMethod::Direct,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3885,7 +4194,7 @@ mod tests {
"Content",
DeliveryMethod::Propagated,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3907,7 +4216,7 @@ mod tests {
"Content",
DeliveryMethod::Opportunistic,
);
router.send(msg);
router.try_send(msg).unwrap();
let actions = router.process_outbound();
assert_eq!(actions.len(), 1);
@@ -3935,7 +4244,7 @@ mod tests {
DeliveryMethod::Direct,
);
msg.sign(&signing_key).unwrap();
router.send(msg);
router.try_send(msg).unwrap();
router.tick();
+245 -66
View File
@@ -1,20 +1,22 @@
//! LXMF Ticket system: bypass PoW with pre-shared 16-byte tokens.
//! LXMF ticket lifecycle and persistence state.
//!
//! Trusted peers may exchange tickets that bypass stamp requirements for a
//! fixed expiry window. Tickets are reusable until expiry and renewed once
//! within `TICKET_RENEW` of expiring.
//! A ticket issued to a peer is an *inbound* ticket: it validates that peer's
//! future stamps. A ticket learned from a peer is an *outbound* ticket: it is
//! used to stamp future messages to that peer. Keeping those directions
//! separate is required for Python LXMF compatibility.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::constants::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ticket {
pub token: [u8; 16],
pub destination_hash: [u8; 16],
/// Expiry timestamp (Unix epoch seconds).
pub expires: f64,
pub used: bool,
}
impl Ticket {
@@ -23,22 +25,90 @@ impl Ticket {
token,
destination_hash,
expires,
used: false,
}
}
pub fn is_valid(&self, now: f64) -> bool {
!self.used && now < self.expires
now < self.expires
}
pub fn should_renew(&self, now: f64) -> bool {
self.is_valid(now) && (self.expires - now) < TICKET_RENEW as f64
self.is_valid(now) && (self.expires - now) <= TICKET_RENEW as f64
}
/// Encode Python's native MessagePack ticket field `[expires, token]`.
pub fn encode_field(&self) -> Result<Vec<u8>, rmpv::encode::Error> {
let value = rmpv::Value::Array(vec![
rmpv::Value::F64(self.expires),
rmpv::Value::Binary(self.token.to_vec()),
]);
let mut encoded = Vec::new();
rmpv::encode::write_value(&mut encoded, &value)?;
Ok(encoded)
}
/// Decode a signed inbound Python-compatible ticket field.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
if cursor.position() != encoded.len() as u64 {
return None;
}
let values = value.as_array()?;
if values.len() != 2 {
return None;
}
let expires = values[0].as_f64()?;
let token = values[1].as_slice()?;
if !expires.is_finite() || expires <= now || token.len() != TICKET_LENGTH {
return None;
}
let mut token_array = [0u8; TICKET_LENGTH];
token_array.copy_from_slice(token);
Some(Self::new(token_array, destination_hash, expires))
}
}
/// Versioned, serializable ticket state.
///
/// Version 1 replaces the former flat `Vec<Ticket>` representation. The flat
/// form could not distinguish tickets issued to peers from tickets learned
/// from peers and therefore could not implement Python's reply semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TicketStoreSnapshot {
#[serde(default = "ticket_store_version")]
pub version: u8,
#[serde(default)]
pub outbound: Vec<Ticket>,
#[serde(default)]
pub inbound: Vec<Ticket>,
#[serde(default)]
pub last_deliveries: HashMap<[u8; 16], f64>,
}
const fn ticket_store_version() -> u8 {
1
}
impl Default for TicketStoreSnapshot {
fn default() -> Self {
Self {
version: ticket_store_version(),
outbound: Vec::new(),
inbound: Vec::new(),
last_deliveries: HashMap::new(),
}
}
}
#[derive(Debug, Default)]
pub struct TicketStore {
tickets: Vec<Ticket>,
/// One learned ticket per destination, matching Python's outbound map.
outbound: HashMap<[u8; 16], Ticket>,
/// Multiple locally issued tickets may overlap during renewal/grace.
inbound: Vec<Ticket>,
/// Last successful delivery of a message containing a ticket.
last_deliveries: HashMap<[u8; 16], f64>,
}
impl TicketStore {
@@ -46,34 +116,130 @@ impl TicketStore {
Self::default()
}
pub fn add(&mut self, ticket: Ticket) {
self.tickets.push(ticket);
/// Store a ticket issued locally for `destination_hash`.
pub fn add_inbound(&mut self, ticket: Ticket) {
if self.inbound.iter().any(|existing| {
existing.destination_hash == ticket.destination_hash && existing.token == ticket.token
}) {
return;
}
self.inbound.push(ticket);
}
pub fn find(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.tickets
/// Store or replace the ticket learned from `destination_hash`.
pub fn remember_outbound(&mut self, ticket: Ticket) {
self.outbound.insert(ticket.destination_hash, ticket);
}
/// Return the valid ticket learned from `destination_hash`.
pub fn find_outbound(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.outbound
.get(destination_hash)
.filter(|ticket| ticket.is_valid(now))
}
/// Return every valid ticket issued locally for `destination_hash`.
pub fn inbound_tokens(&self, destination_hash: &[u8; 16], now: f64) -> Vec<[u8; 16]> {
self.inbound
.iter()
.find(|t| &t.destination_hash == destination_hash && t.is_valid(now))
.filter(|ticket| &ticket.destination_hash == destination_hash && ticket.is_valid(now))
.map(|ticket| ticket.token)
.collect()
}
/// Drop expired and used tickets (past TICKET_GRACE).
/// Generate or reuse a ticket for a peer, respecting Python's delivery
/// interval and renewal window. `None` means a ticket was delivered too
/// recently and should not be included in this message.
pub fn issue_for(
&mut self,
destination_hash: [u8; 16],
expiry_secs: u64,
now: f64,
) -> Option<Ticket> {
if !self.should_issue_for(&destination_hash, now) {
return None;
}
if let Some(ticket) = self.inbound.iter().find(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
}) {
return Some(ticket.clone());
}
let token: [u8; TICKET_LENGTH] = rand::random();
let ticket = Ticket::new(token, destination_hash, now + expiry_secs as f64);
self.inbound.push(ticket.clone());
Some(ticket)
}
pub fn should_issue_for(&self, destination_hash: &[u8; 16], now: f64) -> bool {
!self
.last_deliveries
.get(destination_hash)
.is_some_and(|last| now - *last < TICKET_INTERVAL as f64)
}
pub fn mark_ticket_delivered(&mut self, destination_hash: [u8; 16], delivered_at: f64) {
self.last_deliveries.insert(destination_hash, delivered_at);
}
/// Drop expired outbound tickets and inbound tickets after their grace
/// period. Delivery timestamps need only survive one interval.
pub fn cull(&mut self, now: f64) {
self.tickets
.retain(|t| !t.used && now < t.expires + TICKET_GRACE as f64);
self.outbound.retain(|_, ticket| ticket.is_valid(now));
self.inbound
.retain(|ticket| now < ticket.expires + TICKET_GRACE as f64);
self.last_deliveries
.retain(|_, delivered| now - *delivered < TICKET_INTERVAL as f64);
}
pub fn count_valid(&self, now: f64) -> usize {
self.tickets.iter().filter(|t| t.is_valid(now)).count()
self.outbound
.values()
.filter(|ticket| ticket.is_valid(now))
.count()
+ self
.inbound
.iter()
.filter(|ticket| ticket.is_valid(now))
.count()
}
/// Snapshot of all stored tickets (including expired / used).
pub fn all(&self) -> &[Ticket] {
&self.tickets
pub fn inbound(&self) -> &[Ticket] {
&self.inbound
}
/// Replace the entire ticket set — used when restoring from persisted state.
pub fn replace_all(&mut self, tickets: Vec<Ticket>) {
self.tickets = tickets;
pub fn snapshot(&self) -> TicketStoreSnapshot {
TicketStoreSnapshot {
version: ticket_store_version(),
outbound: self.outbound.values().cloned().collect(),
inbound: self.inbound.clone(),
last_deliveries: self.last_deliveries.clone(),
}
}
pub fn replace_snapshot(&mut self, snapshot: TicketStoreSnapshot) {
self.outbound = snapshot
.outbound
.into_iter()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = snapshot.inbound;
self.last_deliveries = snapshot.last_deliveries;
}
/// Migrate the legacy flat representation conservatively. Old Rust used
/// every entry for both directions, so retaining entries in both stores
/// preserves working stamps while all new state is direction-correct.
pub fn replace_legacy(&mut self, tickets: Vec<Ticket>) {
self.outbound = tickets
.iter()
.cloned()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = tickets;
self.last_deliveries.clear();
}
}
@@ -82,54 +248,67 @@ mod tests {
use super::*;
#[test]
fn test_ticket_validity() {
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(999.0));
assert!(!ticket.is_valid(1001.0));
}
#[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.used = true;
assert!(!ticket.is_valid(500.0));
}
#[test]
fn test_ticket_renew() {
let expires = 2_000_000.0;
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], expires);
// TICKET_RENEW is ~1 week; close to expiry should trigger, far should not.
assert!(ticket.should_renew(expires - 1.0));
assert!(!ticket.should_renew(0.0));
}
#[test]
fn test_ticket_store() {
fn direction_state_is_separate() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
store.add_inbound(Ticket::new([0x01; 16], dest, 2_000.0));
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
assert!(store.find_outbound(&dest, 1_000.0).is_none());
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.add(Ticket::new([0x02; 16], dest, 2000.0));
store.add(Ticket::new([0x03; 16], [0xCC; 16], 1500.0));
assert_eq!(store.count_valid(500.0), 3);
assert_eq!(store.count_valid(1500.0), 1);
let found = store.find(&dest, 500.0);
assert!(found.is_some());
store.remember_outbound(Ticket::new([0x02; 16], dest, 2_000.0));
assert_eq!(
store.find_outbound(&dest, 1_000.0).unwrap().token,
[0x02; 16]
);
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
}
#[test]
fn test_ticket_store_cull() {
fn issuance_reuses_then_renews_and_throttles_after_delivery() {
let mut store = TicketStore::new();
store.add(Ticket::new([0x01; 16], [0xBB; 16], 100.0));
store.add(Ticket::new([0x02; 16], [0xBB; 16], 99999.0));
let dest = [0xBB; 16];
let first = store.issue_for(dest, TICKET_EXPIRY, 1_000.0).unwrap();
let reused = store.issue_for(dest, TICKET_EXPIRY, 2_000.0).unwrap();
assert_eq!(reused.token, first.token);
store.cull(100.0 + TICKET_GRACE as f64 + 1.0);
assert_eq!(store.count_valid(99999.0 - 1.0), 1);
store.mark_ticket_delivered(dest, 2_000.0);
assert!(store.issue_for(dest, TICKET_EXPIRY, 2_001.0).is_none());
let renewed = store
.issue_for(dest, TICKET_EXPIRY, 2_000.0 + TICKET_INTERVAL as f64)
.unwrap();
assert_eq!(renewed.token, first.token);
let near_expiry = first.expires - TICKET_RENEW as f64 + 1.0;
let replacement = store.issue_for(dest, TICKET_EXPIRY, near_expiry).unwrap();
assert_ne!(replacement.token, first.token);
}
#[test]
fn snapshot_roundtrip_preserves_directions_and_delivery_gate() {
let mut store = TicketStore::new();
let dest = [0xCC; 16];
store.add_inbound(Ticket::new([1; 16], dest, 9_999.0));
store.remember_outbound(Ticket::new([2; 16], dest, 9_999.0));
store.mark_ticket_delivered(dest, 100.0);
let mut restored = TicketStore::new();
restored.replace_snapshot(store.snapshot());
assert_eq!(restored.inbound_tokens(&dest, 200.0), vec![[1; 16]]);
assert_eq!(restored.find_outbound(&dest, 200.0).unwrap().token, [2; 16]);
assert!(restored.issue_for(dest, TICKET_EXPIRY, 200.0).is_none());
}
#[test]
fn ticket_field_is_native_python_shape_and_rejects_expired_values() {
let ticket = Ticket::new([0x42; 16], [0x11; 16], 2_000.0);
let encoded = ticket.encode_field().unwrap();
let value = rmpv::decode::read_value(&mut encoded.as_slice()).unwrap();
let values = value.as_array().unwrap();
assert_eq!(values[0].as_f64(), Some(2_000.0));
assert_eq!(values[1].as_slice(), Some(&[0x42; 16][..]));
let decoded = Ticket::decode_field([0x11; 16], &encoded, 1_000.0).unwrap();
assert_eq!(decoded, ticket);
assert!(Ticket::decode_field([0x11; 16], &encoded, 2_000.0).is_none());
}
}
+3
View File
@@ -23,6 +23,9 @@ base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
[[bin]]
name = "lxmd-rs"
path = "src/bin/lxmd-rs.rs"
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -106,6 +106,7 @@ pub(super) enum PnValidationOutcome {
pub(super) struct PnValidationClaim {
link_id: LinkId,
outcome: PnValidationOutcome,
peer_destination_hash: Option<[u8; 16]>,
}
impl PnValidationClaim {
@@ -117,6 +118,10 @@ impl PnValidationClaim {
self.outcome
}
pub(super) fn peer_destination_hash(self) -> Option<[u8; 16]> {
self.peer_destination_hash
}
pub(super) fn should_close_link(self) -> bool {
matches!(
self.outcome,
@@ -590,7 +595,11 @@ impl PnInboundRuntime {
self.install_untracked_invalid_throttle(pending.peer_destination_hash, now);
}
Some(PnValidationClaim { link_id, outcome })
Some(PnValidationClaim {
link_id,
outcome,
peer_destination_hash: pending.peer_destination_hash,
})
}
fn install_untracked_invalid_throttle(
+166 -21
View File
@@ -71,7 +71,7 @@ impl PythonLxmdConfig {
delivery_transfer_max_accepted_size: get_float_or_floor(
lxmf,
"delivery_transfer_max_accepted_size",
1000.0,
1.0,
0.38,
),
on_inbound: lxmf
@@ -227,7 +227,10 @@ impl Default for DaemonConfig {
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
delivery_transfer_max_accepted_size: 1000.0,
// Current Python LXMF 1.1.0's standalone lxmd defaults
// direct-delivery Resource admission to 1 decimal KB when the
// setting is omitted. LXMRouter's library default is separate.
delivery_transfer_max_accepted_size: 1.0,
}
}
}
@@ -321,16 +324,17 @@ impl DaemonConfig {
dc.outbound_propagation_node = Some(trimmed.to_string());
}
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none()
&& let Some(cost) = sec.get_uint("propagation_stamp_cost")
{
dc.propagation_stamp_cost = cost as u8;
if get_int(Some(sec), "propagation_stamp_cost_target").is_none() {
if let Some(cost) = sec.get_uint("propagation_stamp_cost") {
dc.propagation_stamp_cost = cost as u8;
}
}
if get_float(Some(sec), "propagation_message_max_accepted_size").is_none()
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
&& let Some(limit) = sec.get_uint("propagation_limit")
{
dc.propagation_limit_kb = limit as usize;
if let Some(limit) = sec.get_uint("propagation_limit") {
dc.propagation_limit_kb = limit as usize;
}
}
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -339,14 +343,14 @@ impl DaemonConfig {
if !dc.auth_required {
dc.auth_required = sec.get_bool_or("auth_required", false);
}
if dc.control_allowed.is_empty()
&& let Some(allowed) = sec.get("allowed")
{
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if dc.control_allowed.is_empty() {
if let Some(allowed) = sec.get("allowed") {
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
}
@@ -403,12 +407,12 @@ pub fn create_router_with_transport(
pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> {
use std::process::Command;
let parts: Vec<&str> = command.split_whitespace().collect();
let parts = split_command_line(command)?;
if parts.is_empty() {
return Ok(());
}
let mut cmd = Command::new(parts[0]);
let mut cmd = Command::new(&parts[0]);
for arg in &parts[1..] {
cmd.arg(arg);
}
@@ -421,10 +425,151 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
Ok(())
}
/// Parse the configured hook using the shell-like quoting supported by
/// Python's `shlex.split()`, without invoking a shell.
fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
use std::io::{Error, ErrorKind};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut parts = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut escaped = false;
let mut started = false;
for ch in command.chars() {
if escaped {
current.push(ch);
escaped = false;
started = true;
continue;
}
match quote {
Quote::Single => {
if ch == '\'' {
quote = Quote::None;
} else {
current.push(ch);
}
started = true;
}
Quote::Double => {
if ch == '"' {
quote = Quote::None;
} else if ch == '\\' {
escaped = true;
} else {
current.push(ch);
}
started = true;
}
Quote::None => match ch {
'\'' => {
quote = Quote::Single;
started = true;
}
'"' => {
quote = Quote::Double;
started = true;
}
'\\' => {
escaped = true;
started = true;
}
c if c.is_whitespace() => {
if started {
parts.push(std::mem::take(&mut current));
started = false;
}
}
_ => {
current.push(ch);
started = true;
}
},
}
}
if escaped || quote != Quote::None {
return Err(Error::new(
ErrorKind::InvalidInput,
"unterminated quote or escape in on_inbound command",
));
}
if started {
parts.push(current);
}
Ok(parts)
}
/// Persist a received message before invoking the configured hook. Keeping
/// both operations in one blocking job prevents the hook from racing the
/// atomic file write and keeps process execution off the async daemon loop.
pub fn persist_inbound_and_execute(
message_path: &std::path::Path,
packed: &[u8],
command: Option<&str>,
) -> std::io::Result<()> {
lxmf_core::persist::write_file_atomic(message_path, packed)?;
if let Some(command) = command {
execute_on_inbound(command, &message_path.to_string_lossy())?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_inbound_parser_matches_shell_like_quoting_without_a_shell() {
assert_eq!(
split_command_line("/tmp/a\\ b --label 'two words' \"\" --quoted=\"x y\"").unwrap(),
["/tmp/a b", "--label", "two words", "", "--quoted=x y"]
);
assert!(split_command_line("hook 'unterminated").is_err());
assert!(split_command_line("hook trailing\\").is_err());
}
#[cfg(unix)]
#[test]
fn inbound_hook_observes_fully_persisted_message() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let hook = dir.path().join("hook with spaces.sh");
let message = dir.path().join("message.lxm");
let observed = dir.path().join("observed");
std::fs::write(
&hook,
"#!/bin/sh\nexpected=$1\nobserved=$2\nmessage=$3\ncmp \"$expected\" \"$message\" && printf ok > \"$observed\"\n",
)
.unwrap();
let mut permissions = std::fs::metadata(&hook).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&hook, permissions).unwrap();
let expected = dir.path().join("expected");
std::fs::write(&expected, b"complete payload").unwrap();
let command = format!(
"'{}' '{}' '{}'",
hook.display(),
expected.display(),
observed.display()
);
persist_inbound_and_execute(&message, b"complete payload", Some(&command)).unwrap();
assert_eq!(std::fs::read(&message).unwrap(), b"complete payload");
assert_eq!(std::fs::read(&observed).unwrap(), b"ok");
}
#[test]
fn test_default_config() {
let dc = DaemonConfig::default();
@@ -452,7 +597,7 @@ mod tests {
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.0);
assert_eq!(dc.delivery_transfer_max_accepted_size, 1.0);
assert!(!dc.from_static_only);
}
@@ -465,7 +610,7 @@ mod tests {
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.delivery_transfer_max_accepted_size, 1.0);
assert_eq!(py.on_inbound, None);
assert!(!py.enable_propagation_node);
assert_eq!(py.node_name, None);
@@ -588,7 +733,7 @@ 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.0);
assert_eq!(rc.delivery_limit_kb, 1.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);
+1 -1
View File
@@ -224,7 +224,7 @@ announce_at_start = no
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1000
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
+89 -49
View File
@@ -10,8 +10,11 @@ use lxmf_core::propagation_node::PropagationNode;
use lxmf_core::router::LxmRouter;
use rmpv::Value;
use rns_identity::identity::Identity;
use rns_runtime::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_transport::messages::{AnnounceHandlerEvent, TransportMessage};
use rns_transport::messages::TransportMessage;
use tokio::sync::mpsc;
pub const CONTROL_APP_NAME: &str = "lxmf.propagation.control";
@@ -68,50 +71,22 @@ pub async fn resolve_remote_identity_hash(
remote_destination_hash: [u8; 16],
timeout_secs: f64,
) -> Result<[u8; 16], LinkClientError> {
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
transport_tx
.send(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
let send_result = transport_tx
.send(TransportMessage::RequestPath {
destination_hash: remote_destination_hash,
})
.await;
if send_result.is_err() {
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
return Err(LinkClientError::TransportUnavailable);
}
let wait = async {
while let Some(event) = ann_rx.recv().await {
if event.destination_hash == remote_destination_hash
&& let Some(identity_hash) = event.identity_hash
{
return Ok(identity_hash);
}
let recalled = resolve_destination_on_transport(
&transport_tx,
remote_destination_hash,
DestinationResolveOptions::new(Duration::from_secs_f64(timeout_secs.max(0.0))),
)
.await;
let recalled = recalled.map_err(|error| match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("remote identity resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
let result =
match tokio::time::timeout(Duration::from_secs_f64(timeout_secs.max(0.0)), wait).await {
Ok(result) => result,
Err(_) => Err(LinkClientError::Timeout("remote identity resolution")),
};
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
result
})?;
Identity::from_public_key(&recalled.public_key)
.map(|identity| identity.hash)
.map_err(|error| LinkClientError::UnexpectedResponse(error.to_string()))
}
pub fn decode_control_response(response: &[u8]) -> ControlResponse {
@@ -123,10 +98,10 @@ pub fn decode_control_response(response: &[u8]) -> ControlResponse {
return ControlResponse::Success;
};
if let Some(code) = value.as_u64()
&& let Some(error) = peer_error_from_code(code as u8)
{
return ControlResponse::Error(error);
if let Some(code) = value.as_u64() {
if let Some(error) = peer_error_from_code(code as u8) {
return ControlResponse::Error(error);
}
}
if value.is_nil() {
@@ -193,6 +168,9 @@ pub fn encode_router_control_stats(
.as_ref()
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.handled_messages))
.unwrap_or_else(|| peer.unhandled_messages() as usize);
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -269,7 +247,7 @@ pub fn encode_router_control_stats(
(Value::String("incoming".into()), Value::from(peer.incoming)),
(
Value::String("unhandled".into()),
Value::from(peer.unhandled_messages() as u64),
Value::from(unhandled as u64),
),
]),
),
@@ -866,6 +844,68 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[tokio::test]
async fn remote_identity_resolution_uses_recall_and_path_request_without_handlers() {
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportQuery, TransportQueryResponse,
};
let remote_destination_hash = [0x41; 16];
let remote_identity = Identity::new();
let public_key = remote_identity.get_public_key();
let expected_identity_hash = remote_identity.hash;
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("initial recall")
else {
panic!("expected initial recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.expect("return cache miss");
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::RequestPath { destination_hash })
if destination_hash == remote_destination_hash
));
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("post-request recall")
else {
panic!("expected post-request recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(
RecalledDestinationRpcEntry {
dest_hash: remote_destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
},
)))
.expect("return resolved identity");
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_remote_identity_hash(transport_tx, remote_destination_hash, 1.0)
.await
.expect("resolve remote identity");
assert_eq!(resolved, expected_identity_hash);
responder.await.expect("transport responder");
}
fn decode_value(data: &[u8]) -> Value {
rmpv::decode::read_value(&mut &data[..]).unwrap()
}
+6 -5
View File
@@ -228,7 +228,7 @@ fn example_config_exits_before_runtime_initialisation() {
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("delivery_transfer_max_accepted_size = 1"));
assert!(text.contains("[propagation]"));
assert!(text.contains("enable_node = no"));
assert!(text.contains("announce_interval = 360"));
@@ -289,7 +289,7 @@ fn clap_requires_send_argument() {
}
#[test]
fn status_and_peers_query_control_and_timeout_without_daemon() {
fn status_and_peers_fail_before_link_without_an_online_interface() {
let lxmf_dir = TestDir::new("lxmf");
let rns_dir = TestDir::new("rns");
write_rust_identity(&lxmf_dir.path().join("identity"));
@@ -323,12 +323,13 @@ discover_interfaces = No
assert_eq!(
output.status.code(),
Some(200),
"expected Python-compatible control timeout, got:\n{}",
"expected interface-readiness failure, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Getting lxmd statistics timed out, exiting now"),
"expected Python-compatible control timeout text, got:\n{}",
combined_output(&output)
.contains("No online Reticulum interface became available, exiting now"),
"expected specific interface-readiness error, got:\n{}",
combined_output(&output)
);
assert!(