docs: refresh guides and reference help

This commit is contained in:
DeFiDude committed 2026-11-02 11:13:50 -07:00
1 parent b5c3365b57
commit 18b99b8932
42 files changed
+955 -649

No files matched your search

+4 -1
View File
@@ -12,12 +12,15 @@
## 1.4.0 - 2026-10-12 ## 1.4.0 - 2026-10-12
This section records the source-version transition. It is not a standalone
1.4.0 binary release; the published standalone release remains 1.3.0.
- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions. - Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions.
- Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry. - Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry.
- Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available. - Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available.
- Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext. - Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext.
- Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods. - Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods.
- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. This source-breaking release uses the `~1.4.0` compatibility line. - Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. Use the `~1.4.0` compatibility line for these source-breaking APIs.
## 1.3.0 - 2026-10-12 ## 1.3.0 - 2026-10-12
+50 -38
View File
@@ -7,7 +7,7 @@
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE) [![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.89+](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org) [![Rust 1.89+](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org)
[![Compatibility floor: LXMF 1.0.1](https://img.shields.io/badge/compatibility%20floor-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) [![Supplementary release reference: LXMF 1.1.0](https://img.shields.io/badge/supplementary%20release%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status) [![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[LXMF Reference](https://github.com/markqvist/LXMF) | [LXMF Reference](https://github.com/markqvist/LXMF) |
@@ -38,6 +38,8 @@ LXMF daemons on `PATH` without worry.
## Build It ## Build It
This guide describes the 1.4.0 source line at `b5c3365b5715f1f36f74963a9d2136238d956467`, used by Ratspeak 1.0.37 with rsReticulum 1.4.0. The published standalone daemon download is [v1.3.0](https://github.com/ratspeak/rsLXMF/releases/tag/v1.3.0); use [its README](https://github.com/ratspeak/rsLXMF/blob/v1.3.0/README.md) and bundled `--help` for that build. The 1.4 message and durable relay APIs require a coordinated source migration.
The current development layout for rsLXMF requires The current development layout for rsLXMF requires
rsReticulum as a sibling directory/repo next to it, such as: rsReticulum as a sibling directory/repo next to it, such as:
@@ -52,9 +54,13 @@ mkdir ratspeak-src
cd ratspeak-src cd ratspeak-src
git clone https://github.com/ratspeak/rsReticulum git clone https://github.com/ratspeak/rsReticulum
git clone https://github.com/ratspeak/rsLXMF git clone https://github.com/ratspeak/rsLXMF
git -C rsReticulum checkout --detach 5b38cae702a5b3984adf12a435f6d3012fcf90e1
git -C rsLXMF checkout --detach b5c3365b5715f1f36f74963a9d2136238d956467
cd rsLXMF cd rsLXMF
``` ```
Run the build commands below from that `rsLXMF` directory. The host crates require Rust 1.89 or newer.
### macOS ### macOS
Install Rust with `rustup`, then install Apple's build tools: Install Rust with `rustup`, then install Apple's build tools:
@@ -66,7 +72,6 @@ xcode-select --install
Build from the sibling checkout: Build from the sibling checkout:
```bash ```bash
cd rsLXMF
cargo build --release --locked cargo build --release --locked
``` ```
@@ -78,25 +83,24 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash ```bash
sudo apt update sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev sudo apt install -y build-essential pkg-config
``` ```
Fedora: Fedora:
```bash ```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel sudo dnf install gcc make pkgconf-pkg-config
``` ```
Arch: Arch:
```bash ```bash
sudo pacman -S --needed base-devel pkgconf systemd sudo pacman -S --needed base-devel pkgconf
``` ```
#### Build the daemon: #### Build the daemon:
```bash ```bash
cd rsLXMF
cargo build --release --locked cargo build --release --locked
``` ```
@@ -108,7 +112,6 @@ Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell: Build from PowerShell:
```powershell ```powershell
cd rsLXMF
cargo build --release --locked cargo build --release --locked
``` ```
@@ -125,7 +128,7 @@ macOS/Linux or `.\target\release\lxmd-rs.exe` on Windows.
Generate the example config: Print the example configuration to standard output:
```bash ```bash
lxmd-rs --exampleconfig lxmd-rs --exampleconfig
@@ -143,11 +146,11 @@ Run a propagation node:
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --propagation-node lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --propagation-node
``` ```
Send a message and exit: Send a message and exit. Replace uppercase hash placeholders with the appropriate 32-character hexadecimal destination hash:
```bash ```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \ lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> "message body" --send "DELIVERY_DESTINATION_HASH" "message body"
``` ```
The `--send` flag is an rsLXMF convenience. Normal The `--send` flag is an rsLXMF convenience. Normal
@@ -157,7 +160,7 @@ Send UTF-8 file content or select a delivery method:
```bash ```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \ lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> --send-file ./message.txt --send-method direct --send "DELIVERY_DESTINATION_HASH" --send-file ./message.txt --send-method direct
``` ```
Supported `--send-method` values are `opportunistic`, `direct`, and Supported `--send-method` values are `opportunistic`, `direct`, and
@@ -167,20 +170,23 @@ Attach custom LXMF fields from scripts:
```bash ```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \ lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> "with fields" \ --send "DELIVERY_DESTINATION_HASH" "with fields" \
--send-fields-json '{"1":"aGVsbG8=","42":"AAECAw=="}' --send-fields-json '{"200":"aGVsbG8=","201":"AAECAw=="}'
``` ```
The JSON object maps field IDs to base64-encoded bytes. It is only a shell The CLI JSON object maps IDs from 0 to 255 to base64-encoded binary values.
convenience; LXMF fields remain MessagePack field maps on the wire. Choose IDs and schemas agreed with the receiving application. This option
does not construct structured MessagePack fields such as an LRGP envelope;
use the library’s typed field API for those. The library supports a wider
integer ID range than this CLI convenience.
Control a propagation node: Control a propagation node:
```bash ```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --status lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --status
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --peers lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --peers
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync <peer_hash> lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync "PEER_PROPAGATION_HASH"
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break <peer_hash> lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break "PEER_PROPAGATION_HASH"
``` ```
These commands query an `lxmf.propagation.control` endpoint over Reticulum. These commands query an `lxmf.propagation.control` endpoint over Reticulum.
@@ -192,7 +198,7 @@ For a remote propagation node, pass the node's propagation destination hash:
```bash ```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \ lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--status --peers --remote <propagation_destination_hash> --timeout 5 --status --peers --remote "PROPAGATION_DESTINATION_HASH" --timeout 5
``` ```
Control queries use `<config-dir>/identity` by default. Use `--identity PATH` Control queries use `<config-dir>/identity` by default. Use `--identity PATH`
@@ -218,6 +224,8 @@ If no LXMF config directory is supplied, the default is:
| Linux/macOS | `/etc/rsLXMF/config`, then `~/.config/rsLXMF/config`, then `~/.rsLXMF/config` | | Linux/macOS | `/etc/rsLXMF/config`, then `~/.config/rsLXMF/config`, then `~/.rsLXMF/config` |
| Windows | `%APPDATA%\rsLXMF\config` | | Windows | `%APPDATA%\rsLXMF\config` |
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
If `--rnsconfig` is omitted, Reticulum config resolution follows If `--rnsconfig` is omitted, Reticulum config resolution follows
rsReticulum-specific defaults. rsReticulum-specific defaults.
@@ -251,8 +259,8 @@ autopeer = yes
autopeer_maxdepth = 6 autopeer_maxdepth = 6
auth_required = no auth_required = no
# node_name = Rat Nest # node_name = Rat Nest
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d # static_peers = 0123456789abcdef0123456789abcdef
# outbound_node = e17f833c4ddf8890dd3a79a6fea8161d # outbound_node = 0123456789abcdef0123456789abcdef
# max_peers = 20 # max_peers = 20
# propagation_stamp_cost_target = 16 # propagation_stamp_cost_target = 16
# propagation_stamp_cost_flexibility = 3 # propagation_stamp_cost_flexibility = 3
@@ -261,17 +269,16 @@ auth_required = no
loglevel = 4 loglevel = 4
``` ```
The standalone daemon follows current Python LXMF 1.1.0 and defaults this `delivery_transfer_max_accepted_size` limits incoming Direct Resource data
setting to 1 decimal KB when it is omitted. This is intentionally distinct in decimal KB and defaults to 1 when omitted. The reusable router library has a separate 1000 KB default. Applications that accept
from the reusable router library's 1000 KB default. Applications that accept
larger incoming messages should set their own explicit policy. larger incoming messages should set their own explicit policy.
Supported sections: Common sections and supported keys (see `--exampleconfig` for annotated defaults):
| Section | Keys | | Section | Keys |
| --- | --- | | --- | --- |
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` | | `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` | | `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `sequential_pn_stamp_validation`, `static_peers_bypass_sequential`, `max_inbound_syncs`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` |
| `[control]` | `auth_required`, `allowed` | | `[control]` | `auth_required`, `allowed` |
| `[logging]` | `loglevel` | | `[logging]` | `loglevel` |
@@ -279,10 +286,10 @@ Optional hash-list files live next to `<config-dir>/config`:
| File | Meaning | | File | Meaning |
| --- | --- | | --- | --- |
| `ignored` | Hashes loaded into the router ignored list. | | `ignored` | LXMF destination hashes to ignore. |
| `allowed` | Hashes loaded into the router delivery allow-list. Empty means no allow-list restriction. | | `allowed` | Reticulum **identity hashes** permitted to retrieve messages when propagation `auth_required = yes`. An empty list then admits no clients. |
Hash-list files accept one raw 32-character hex destination hash per line. Each file accepts one raw 32-character hex hash per line. The two files use different hash types. Propagation administration is separate: `control_allowed` contains authorized control identity hashes; the daemon’s own identity is also authorized. Client retrieval authorization does not make the node’s stored messages readable to other clients.
## Delivery Model ## Delivery Model
@@ -291,7 +298,7 @@ and, where network-backed, through `lxmd-rs --send-method`.
| Method | Behavior | | Method | Behavior |
| --- | --- | | --- | --- |
| 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. | | 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. The router switches oversized opportunistic messages to Direct. |
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. | | 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. | | 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. | | Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
@@ -312,13 +319,17 @@ signature 64 bytes
payload MessagePack([timestamp, title, content, fields, optional_stamp]) payload MessagePack([timestamp, title, content, fields, optional_stamp])
``` ```
`title` and `content` are bytes on the wire. `fields` is a `map<u8, bytes>` for `title` and `content` are bytes on the wire. `fields` maps integer IDs to
application-defined data such as tickets, attachments, location data, or MessagePack values, which can be binary, text, arrays, maps or other supported
application envelopes. values. Standard fields have defined schemas. The 1.4 library preserves signed
and unsigned integer IDs beyond the CLI’s 0–255 range and rejects duplicate
outer IDs. Encoding a structured field as a binary blob changes its meaning.
Library callers requesting a reply ticket set `include_ticket`, call In the 1.4 API, construct `LxMessageDraft` and set `include_ticket` before
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a calling `LxmRouter::prepare_outbound`. Persist the returned ticket intent before
requested ticket that would require changing an already-signed message. signing; a pending intent blocks signing. Signing consumes the draft, and
finalization produces an immutable message. See the [1.4 migration guide](api/migrations/1.4.md)
for stamp work, typed fields, inbound verification and propagation storage.
## Feature Status ## Feature Status
@@ -326,7 +337,7 @@ requested ticket that would require changing an already-signed message.
| Area | Current behavior | | Area | Current behavior |
| --- | --- | | --- | --- |
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. | | 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. | | Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct fallback, and compression signalling in delivery announces. |
| Propagation | Transactional disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. | | 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. | | 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. | | Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
@@ -342,11 +353,12 @@ Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`, Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
`--send-timeout-secs`, and `--send-fields-json`. `--send-timeout-secs`, and `--send-fields-json`.
The complete release-baseline corpus and live matrix use Python LXMF 1.0.1 The complete corpus and live matrix for standalone 1.3.0 use Python LXMF 1.0.1
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery, with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
same Reticulum 1.4.2 source. Historical vectors retain their original same Reticulum 1.4.2 source. Historical vectors retain their original
provenance, and RNS 1.5.0 is intentionally deferred. provenance. Later source changes include selected LXMF 1.2.0 behavior; that
does not establish complete compatibility with every later Python release.
## Contributing ## Contributing
+10 -8
View File
@@ -1,9 +1,11 @@
# Rust API # Rust API
Application code that constructs or inspects LXMF messages should use This guide describes the 1.4.0 source API, not the published standalone
`lxmf_core::message_api`. It re-exports the existing message, status, and 1.3.0 daemon. Application code should use `lxmf_core::message_api`, which
identifier types without wrapping or replacing them. The original re-exports the message types without wrappers. The equivalent module-qualified
module-qualified paths remain supported. paths remain available. The [1.4 migration guide](migrations/1.4.md) explains
the source-breaking change from mutable messages to drafts, signed messages
and immutable finalized messages.
The compiled `lxmf-core` `message` example demonstrates message construction, The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path. signing, packing, and unpacking through this path.
@@ -20,10 +22,10 @@ provisional module-qualified APIs.
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library `lxmf-tools` supports the `lxmd-rs` binary and is not a public library
integration target. integration target.
The message facade changes no wire fields, signatures, serialization, Choosing the facade instead of the equivalent module-qualified path does not
delivery methods, proofs, persistence, or runtime behavior. Later reductions change behavior. Upgrading from 1.3 to 1.4 does change message and persistence
to the broader module tree require a reviewed API diff, downstream migration, APIs; follow the migration guide. Further reductions to the broader module tree
and an explicit version decision. require a reviewed API diff, downstream migration and an explicit version decision.
## Delivery-owner integration ## Delivery-owner integration
+9 -4
View File
@@ -1,4 +1,8 @@
# 1.4 source migration (unreleased) # Migrating to the 1.4 source API
The 1.4 source line is used by Ratspeak 1.0.37. The published standalone
command-line download remains 1.3.0; these APIs and migration commands require
a matching 1.4 source build.
Messages now retain the exact signed bytes received or finalized for sending. Messages now retain the exact signed bytes received or finalized for sending.
Verification, storage, and delivery metadata cannot change those bytes. The Verification, storage, and delivery metadata cannot change those bytes. The
@@ -6,6 +10,8 @@ Verification, storage, and delivery metadata cannot change those bytes. The
## Construct, sign, then finalize ## Construct, sign, then finalize
This fragment uses `?` to propagate `MessageError` from the enclosing function.
```rust ```rust
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft}; use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
use rns_crypto::ed25519::Ed25519PrivateKey; use rns_crypto::ed25519::Ed25519PrivateKey;
@@ -19,7 +25,6 @@ let signed = draft.sign(&Ed25519PrivateKey::generate())?;
let stamp = signed.generate_recipient_stamp()?; let stamp = signed.generate_recipient_stamp()?;
let message = signed.finalize(stamp)?; let message = signed.finalize(stamp)?;
let bytes = message.wire_bytes(); let bytes = message.wire_bytes();
# Ok::<(), lxmf_core::message_api::MessageError>(())
``` ```
Use `sign_with` for an external or hardware signer. Both signing methods consume Use `sign_with` for an external or hardware signer. Both signing methods consume
@@ -85,7 +90,7 @@ wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit
count and exact size before signing and finalization, including stamp framing. count and exact size before signing and finalization, including stamp framing.
These are parser/construction ceilings, not transport promises: Resource segment These are parser/construction ceilings, not transport promises: Resource segment
limits, metadata, encryption and propagation wrapping impose separate admission limits, metadata, encryption and propagation wrapping impose separate admission
checks. The embedded profile retains 64 fields and depth8; host-valid custom checks. The embedded profile retains 64 fields and depth 8; host-valid custom
messages are not automatically compatible with every device. messages are not automatically compatible with every device.
Old corrupted files are never silently repaired or re-signed. A hash-shaped Old corrupted files are never silently repaired or re-signed. A hash-shaped
@@ -176,7 +181,7 @@ copy that was already delivered.
`submit_signed` now refuses a message whose id is already queued, awaiting its `submit_signed` now refuses a message whose id is already queued, awaiting its
stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as
already sent. already queued; it is not evidence of transmission or recipient delivery.
## Retaining delivered destinations ## Retaining delivered destinations
+5 -1
View File
@@ -1,5 +1,9 @@
# Relay store migration # Relay store migration
This guide applies to the 1.4 source API and daemon. Build the matching
source before using these commands; the standalone 1.3.0 binary does not
provide this migration.
Relay nodes now admit only validated opaque propagation data to a durable store. Relay nodes now admit only validated opaque propagation data to a durable store.
A packet proof follows complete validation and acknowledged durable admission. A packet proof follows complete validation and acknowledged durable admission.
Resource completion still means transport completion; it does not certify the Resource completion still means transport completion; it does not certify the
@@ -20,7 +24,7 @@ whole message bodies; every read verifies the full body, and a body that fails
is not served. is not served.
Stop every process that can write the store, including service supervisors and Stop every process that can write the store, including service supervisors and
scheduled restarts. Then run the candidate daemon against the correct config: scheduled restarts. Then run the 1.4 source-built daemon against the correct config:
```sh ```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped
+3
View File
@@ -1,4 +1,7 @@
//! Construct, sign, freeze, and inspect a message through the canonical API. //! Construct, sign, freeze, and inspect a message through the canonical API.
//! The hashes below are placeholders: this local packing example does not
//! authenticate a sender or transmit a message. Real source hashes must bind
//! the signing identity to its lxmf.delivery destination.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState}; use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState};
use rns_crypto::ed25519::Ed25519PrivateKey; use rns_crypto::ed25519::Ed25519PrivateKey;
+20 -8
View File
@@ -46,8 +46,10 @@ pub struct AdmissionRecord {
pub committed_at: u64, pub committed_at: u64,
} }
/// Verified local purge authority with its finite policy lifetime. Adapters /// Local purge authority with an optional expiry. Policy-discard and user-deleted
/// supply these only after checking the referenced durable effect. /// receipts expire after [`POLICY_RECEIPT_LIFETIME`]; committed/duplicate receipts
/// have no time expiry. Adapters must check the referenced durable effect before
/// supplying this value; constructing it does not perform that verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DurableHave { pub struct DurableHave {
pub transient_id: [u8; 32], pub transient_id: [u8; 32],
@@ -84,8 +86,9 @@ pub enum AdmissionError {
/// Trusted persistence adapter boundary. Implementations must atomically commit /// Trusted persistence adapter boundary. Implementations must atomically commit
/// the receipt with the message/effect, or reference a previously durable effect. /// the receipt with the message/effect, or reference a previously durable effect.
/// In particular, returning a record after a failed/uncertain filesystem or SQL /// In particular, returning a record after a failed/uncertain filesystem or SQL
/// commit violates this contract. SQLite implementations use the dedicated FULL /// commit violates this contract. SQL adapters must establish their transaction
/// connection; file implementations use the intent/body/commit journal. /// and durability guarantees. [`crate::admission_store::FileAdmissionStore`]
/// uses an intent/body/commit journal.
pub trait DurableAdmissionBackend { pub trait DurableAdmissionBackend {
fn commit(self) -> Result<AdmissionRecord, AdmissionError>; fn commit(self) -> Result<AdmissionRecord, AdmissionError>;
} }
@@ -320,8 +323,9 @@ pub(crate) struct AdmissionResolution {
pub outcome: DownloadAdmissionOutcome, pub outcome: DownloadAdmissionOutcome,
} }
/// Single-use, generation-bound authority. Dropping it reports a retryable /// Single-use, generation-bound authority. Dropping an unresolved token attempts
/// failure; cancelling its client generation cannot cancel a blocking commit. /// to send a Cancelled rejection to its consumer. Cancelling the client generation
/// cannot cancel a blocking commit.
pub struct DownloadAdmissionToken { pub struct DownloadAdmissionToken {
scope: AdmissionScope, scope: AdmissionScope,
generation: u64, generation: u64,
@@ -355,11 +359,19 @@ impl DownloadAdmissionToken {
pub fn scope(&self) -> AdmissionScope { pub fn scope(&self) -> AdmissionScope {
self.scope self.scope
} }
/// Check immediately after durable commit before publishing current-generation effects. /// Read whether this token still belongs to the current client generation.
/// Cancellation cannot stop an in-flight commit or release its memory lease. ///
/// This is a snapshot, not a lock: the generation can change immediately.
/// Check after durable commit and use the adapter's lifecycle gate around
/// current-generation UI effects. Cancellation cannot stop an in-flight
/// commit or release its memory lease.
pub fn is_current(&self) -> bool { pub fn is_current(&self) -> bool {
self.current_generation.load(Ordering::Acquire) == self.generation self.current_generation.load(Ordering::Acquire) == self.generation
} }
/// Enqueue one outcome for this token's scope and current generation.
/// Success reports enqueueing, not remote deletion or an atomic lifecycle
/// transition; the consumer rechecks the generation before applying it.
/// A mismatched scope, revoked generation or closed consumer returns an error.
pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> { pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> {
if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome
&& receipt.record.scope != self.scope && receipt.record.scope != self.scope
+12 -2
View File
@@ -1,5 +1,8 @@
//! File adapter for lxmd's durable download receipts and hook outbox. //! File adapter for lxmd's durable download receipts and hook outbox.
//! The original ciphertext TID is journaled before publishing decrypted bytes. //! The original ciphertext TID is journaled before publishing decrypted bytes.
//! Keep exclusive ownership of the journal and body paths while the store is
//! open; its mutex coordinates clones of one store, not independent open calls
//! or external file writers.
use crate::admission::*; use crate::admission::*;
use bytes::Bytes; use bytes::Bytes;
use rns_identity::persistence::{ use rns_identity::persistence::{
@@ -109,6 +112,11 @@ impl FileAdmissionStore {
}) })
} }
/// Prepare a persistence operation for an already authenticated message and
/// caller-selected disposition. The scope must retain the original ciphertext
/// TID; this method recomputes only the received plaintext wire hash.
/// Neither preparation nor commit authenticates the sender. Preparation writes
/// no files; commit performs persistence.
pub fn prepare( pub fn prepare(
&self, &self,
mut record: AdmissionRecord, mut record: AdmissionRecord,
@@ -125,8 +133,10 @@ impl FileAdmissionStore {
} }
} }
/// Durable visible receipts remain while their referenced message exists; /// Return live receipts from committed or recovered state for this identity/node.
/// invisible policy/TID accelerators expire after the local90-day policy. /// Visible receipts have no time expiry; invisible policy/TID receipts expire
/// after 90 days. This query does not re-read archive files. Use the store's
/// deletion API to revoke visible receipts when deleting a message.
pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec<Vec<u8>> { pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec<Vec<u8>> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner()); let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner inner
+11 -10
View File
@@ -173,7 +173,7 @@ pub const PATH_REQUEST_WAIT: u64 = 7;
pub const MAX_PATHLESS_TRIES: u32 = 1; pub const MAX_PATHLESS_TRIES: u32 = 1;
/// Maximum link inactivity before teardown (seconds). /// Maximum link inactivity before teardown (seconds).
pub const LINK_MAX_INACTIVITY: u64 = 10 * 60; pub const LINK_MAX_INACTIVITY: u64 = 10 * 60;
/// Maximum propagation link inactivity (seconds). /// Python propagation-link inactivity limit, in seconds; retained as a reference value.
pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60; pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60;
pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60; pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60; pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
@@ -196,7 +196,7 @@ pub const PN_STAMP_THROTTLE: u64 = 180;
pub const AUTOPEER: bool = true; pub const AUTOPEER: bool = true;
pub const AUTOPEER_MAXDEPTH: usize = 4; pub const AUTOPEER_MAXDEPTH: usize = 4;
/// When selecting peers for sync, pick from the N fastest. /// Size of the fastest-peer pool considered alongside unknown-speed peers.
pub const FASTEST_N_RANDOM_POOL: usize = 2; pub const FASTEST_N_RANDOM_POOL: usize = 2;
/// Percentage of max_peers kept as headroom for rotation. /// Percentage of max_peers kept as headroom for rotation.
pub const ROTATION_HEADROOM_PCT: usize = 10; pub const ROTATION_HEADROOM_PCT: usize = 10;
@@ -213,12 +213,12 @@ pub const DUPLICATE_SIGNAL: &str = "lxmf_duplicate";
pub const OFFER_REQUEST_PATH: &str = "/offer"; pub const OFFER_REQUEST_PATH: &str = "/offer";
pub const MESSAGE_GET_PATH: &str = "/get"; pub const MESSAGE_GET_PATH: &str = "/get";
/// Maximum time a peer can be unreachable before removal (14 days). /// Age since last contact after which `mark_unreachable` marks a peer not alive (14 days).
pub const MAX_UNREACHABLE: u64 = 14 * 24 * 60 * 60; pub const MAX_UNREACHABLE: u64 = 14 * 24 * 60 * 60;
/// Sync backoff step per consecutive failure (12 minutes). /// Sync backoff step per consecutive failure (12 minutes).
pub const SYNC_BACKOFF_STEP: u64 = 12 * 60; pub const SYNC_BACKOFF_STEP: u64 = 12 * 60;
pub const PATH_REQUEST_GRACE: f64 = 7.5; pub const PATH_REQUEST_GRACE: f64 = 7.5;
/// Maximum time a peer can be stale before rotation (14 days). /// Age since last contact used by the peer staleness check (14 days).
pub const PEER_STALE_TIME: u64 = 14 * 24 * 60 * 60; pub const PEER_STALE_TIME: u64 = 14 * 24 * 60 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -263,22 +263,23 @@ pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PN: usize = 1000;
pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING: usize = 25; pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING: usize = 25;
/// SHA-256 output length. /// SHA-256 output length.
pub const STAMP_SIZE: usize = 32; pub const STAMP_SIZE: usize = 32;
/// Minimum batch size before using parallel validation pool. /// Python propagation-validation pool threshold, retained as a reference constant.
pub const PN_VALIDATION_POOL_MIN_SIZE: usize = 256; pub const PN_VALIDATION_POOL_MIN_SIZE: usize = 256;
/// Interval (in ticks) for processing outbound messages. /// Python outbound-processing cadence in ticks; retained as a reference constant.
pub const JOB_OUTBOUND_INTERVAL: u64 = 1; pub const JOB_OUTBOUND_INTERVAL: u64 = 1;
/// Interval (in ticks) for processing deferred stamps. /// Python deferred-stamp cadence in ticks; retained as a reference constant.
pub const JOB_STAMPS_INTERVAL: u64 = 1; pub const JOB_STAMPS_INTERVAL: u64 = 1;
/// Interval (in ticks) for cleaning inactive links. /// Python inactive-link cleanup cadence in ticks; retained as a reference constant.
pub const JOB_LINKS_INTERVAL: u64 = 1; pub const JOB_LINKS_INTERVAL: u64 = 1;
/// Interval (in ticks) for cleaning transient ID caches. /// Interval (in ticks) for cleaning transient ID caches.
pub const JOB_TRANSIENT_INTERVAL: u64 = 60; pub const JOB_TRANSIENT_INTERVAL: u64 = 60;
/// Interval (in ticks) for cleaning the message store. /// Interval (in ticks) for cleaning the message store.
pub const JOB_STORE_INTERVAL: u64 = 120; pub const JOB_STORE_INTERVAL: u64 = 120;
/// Interval (in ticks) for syncing peers. /// Tick interval for cleaning throttled-peer entries, named for Python
/// peer-sync cadence. Peer synchronization is driven by the embedding runtime.
pub const JOB_PEERSYNC_INTERVAL: u64 = 6; pub const JOB_PEERSYNC_INTERVAL: u64 = 6;
/// Interval (in ticks) for ingesting peer distribution queues. /// Python peer-distribution ingestion cadence in ticks; retained as a reference constant.
pub const JOB_PEERINGEST_INTERVAL: u64 = 6; pub const JOB_PEERINGEST_INTERVAL: u64 = 6;
/// 56 * JOB_PEERINGEST_INTERVAL. /// 56 * JOB_PEERINGEST_INTERVAL.
pub const JOB_ROTATE_INTERVAL: u64 = 56 * 6; pub const JOB_ROTATE_INTERVAL: u64 = 56 * 6;
+5 -1
View File
@@ -57,7 +57,11 @@ pub struct DeliveryRatchetState {
} }
impl DeliveryRatchetState { impl DeliveryRatchetState {
/// Load verified state, preserving any invalid existing files in place. /// Load canonical or legacy Rust state, preserving rejected files in place.
/// Canonical signatures cover the packed key list. Accepted legacy signatures
/// cover only the current public key, not retained old keys; canonical rewrite
/// is best-effort and does not establish their historical authenticity.
/// A failed rewrite does not prevent use of the accepted legacy ring.
/// ///
/// A missing ring is generated and persisted before it becomes live. A /// A missing ring is generated and persisted before it becomes live. A
/// ring that cannot be stored leaves delivery available but unratcheted. /// ring that cannot be stored leaves delivery available but unratcheted.
+14 -17
View File
@@ -2,15 +2,15 @@
//! //!
//! # Layering //! # Layering
//! //!
//! Python `RNS/Discovery.py:41` imports `LXMF.LXStamper` directly; the //! Python `RNS.Discovery.InterfaceAnnouncer` loads `LXMF.LXStamper` when
//! discovery subsystem cannot work without LXMF installed. Rust keeps //! initialized, requiring LXMF for on-network discovery. Rust keeps
//! Reticulum below LXMF, so `rns-transport` depends on a trait object and //! Reticulum below LXMF, so `rns-transport` depends on a trait object and
//! the concrete implementation lives here. //! the concrete implementation lives here.
//! //!
//! # Workblock: Python parity //! # Workblock: Python parity
//! //!
//! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)` //! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)`
//! (RNS/Discovery.py:220), where `stamp_workblock` is the //! in `InterfaceAnnouncer`, where `stamp_workblock` is the
//! HKDF-expanded construction: one HKDF expand per round, each round //! HKDF-expanded construction: one HKDF expand per round, each round
//! producing 256 bytes, total `expand_rounds * 256` bytes. //! producing 256 bytes, total `expand_rounds * 256` bytes.
//! [`crate::stamper::stamp_workblock`] is the same construction. //! [`crate::stamper::stamp_workblock`] is the same construction.
@@ -26,14 +26,10 @@ use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
/// interface, so this path has to stay cheap enough for periodic announces. /// interface, so this path has to stay cheap enough for periodic announces.
pub const DISCOVERY_WORKBLOCK_EXPAND_ROUNDS: usize = 20; pub const DISCOVERY_WORKBLOCK_EXPAND_ROUNDS: usize = 20;
/// Upper bound on the random-stamp search before we give up on a given /// Default attempt budget for one discovery stamp search. Exhaustion returns
/// tick. If the cap is hit, the announcer skips this cycle and tries again /// `None`, allowing the announcer to skip this preparation attempt and retry.
/// rather than pinning a blocking worker indefinitely. /// The budget limits attempts, not elapsed time. The requested generation cost
/// /// comes from the per-interface announce configuration.
/// Python has no equivalent cap (it blocks until success); we cap so
/// `spawn_blocking` threads cannot be stuck forever if the user
/// misconfigures `discover_interfaces_required_value` to something
/// unreasonable.
pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000; pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000;
/// PoW stamper for on-network discovery announces. Thin wrapper around /// PoW stamper for on-network discovery announces. Thin wrapper around
@@ -50,8 +46,9 @@ pub struct LxmfDiscoveryStamper {
} }
impl LxmfDiscoveryStamper { impl LxmfDiscoveryStamper {
/// Build a stamper with a custom iteration cap. Most callers want /// Build a stamper with a custom iteration cap. Zero selects
/// [`LxmfDiscoveryStamper::default`]. /// [`DISCOVERY_MAX_ITERATIONS`], as does [`LxmfDiscoveryStamper::default`].
/// This differs from [`generate_discovery_stamp`], where zero allows no attempts.
pub fn with_max_iterations(max_iterations: u64) -> Self { pub fn with_max_iterations(max_iterations: u64) -> Self {
Self { max_iterations } Self { max_iterations }
} }
@@ -107,10 +104,10 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
} }
} }
/// Validation helper: synchronous wrapper mirroring /// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
/// [`crate::stamper::generate_stamp_limited`] but using the HKDF /// explicit attempt limit. Uses the same construction as
/// workblock construction. Public so interop tests and downstream validation /// [`crate::stamper::generate_stamp_limited`], without a transport runtime.
/// can exercise discovery stamping without a transport runtime. /// For nonzero cost, a zero iteration limit returns `None`.
pub fn generate_discovery_stamp( pub fn generate_discovery_stamp(
infohash: &[u8; 32], infohash: &[u8; 32],
target_value: u8, target_value: u8,
+55 -43
View File
@@ -1,7 +1,8 @@
//! Announce handlers for `lxmf.delivery` and `lxmf.propagation` destinations, plus the //! Announce handlers for `lxmf.delivery` and `lxmf.propagation` destinations, plus the
//! propagation-node control endpoint dispatcher. //! propagation-node control endpoint dispatcher.
//! //!
//! Python reference: LXMF/Handlers.py, LXMF.py:172-198, LXMRouter.py:306-318, LXMRouter.py:985-1000. //! Related Python code: LXMF/Handlers.py, the announce helpers in LXMF.py,
//! and the request handlers in LXMRouter.py.
use std::collections::HashMap; use std::collections::HashMap;
@@ -55,18 +56,19 @@ pub enum CompressionSupport {
/// `[false, timebase, node_state, transfer_limit_kb, sync_limit_kb, /// `[false, timebase, node_state, transfer_limit_kb, sync_limit_kb,
/// [stamp_cost, stamp_flex, peering_cost], metadata]`. /// [stamp_cost, stamp_flex, peering_cost], metadata]`.
/// ///
/// Python reference: LXMRouter.py:306-318. /// Python reference: `LXMRouter.get_propagation_node_app_data`.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PropagationNodeAnnounceData { pub struct PropagationNodeAnnounceData {
/// Legacy LXMF PN-support flag, always false. /// Compatibility field. The constructor/parser set it to false, and the
/// encoder always writes false regardless of this field.
pub legacy: bool, pub legacy: bool,
/// Node timebase as Unix seconds. /// Node timebase as Unix seconds.
pub timebase: i64, pub timebase: i64,
/// True when the node is actively serving propagation. /// True when the node is actively serving propagation.
pub node_state: bool, pub node_state: bool,
/// Per-transfer limit in kilobytes. /// Per-transfer limit in decimal kilobytes (1 kB = 1000 bytes).
pub transfer_limit: u64, pub transfer_limit: u64,
/// Per-sync limit in kilobytes. /// Per-sync limit in decimal kilobytes (1 kB = 1000 bytes).
pub sync_limit: u64, pub sync_limit: u64,
pub stamp_cost: u8, pub stamp_cost: u8,
pub stamp_flex: u8, pub stamp_flex: u8,
@@ -111,7 +113,7 @@ impl PropagationNodeAnnounceData {
/// Encode propagation-node announce `app_data` as msgpack. /// Encode propagation-node announce `app_data` as msgpack.
/// ///
/// Python reference: LXMRouter.py:306-318. /// Python reference: `LXMRouter.get_propagation_node_app_data`.
pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<u8> { pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<u8> {
use rmpv::Value; use rmpv::Value;
@@ -142,13 +144,16 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
crate::encode_value(&announce_data) crate::encode_value(&announce_data)
} }
/// Parse propagation-node announce data. Returns `None` if the data is /// Parse a propagation-node announce array with at least seven elements.
/// malformed (not msgpack, not an array, fewer than 7 elements, or any ///
/// element of the wrong type) — same rejection criteria as Python's /// Requires a boolean state, numeric timebase, nonnegative finite limits/costs,
/// `pn_announce_data_is_valid` at `LXMF.py:172-198`. The validator and /// a cost array with at least three values, and a metadata map. Rust casts apply; costs must
/// the parser used to be two separate functions; the validator was /// fit in `u8` after conversion. The legacy slot is ignored. Only metadata with
/// dropped because it duplicated this function's checks and every /// `u8` keys and binary values is retained. Extra array elements and trailing
/// in-tree caller called both back-to-back. /// MessagePack bytes are not rejected.
///
/// This parser does not authenticate the announce or enforce timebase freshness.
/// Its coercion and filtering rules differ from Python `pn_announce_data_is_valid`.
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> { pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> { fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
value value
@@ -211,7 +216,7 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
/// Extract stamp cost from propagation-node announce data. /// Extract stamp cost from propagation-node announce data.
/// ///
/// Python reference: `pn_stamp_cost_from_app_data` — LXMF.py:163-170. /// Uses [`parse_pn_announce_data`] and its numeric conversion rules.
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> { pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_pn_announce_data(data).map(|p| p.stamp_cost) parse_pn_announce_data(data).map(|p| p.stamp_cost)
} }
@@ -222,7 +227,8 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
/// ///
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil. /// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
/// ///
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1001 (1.0.1). /// Names are sanitized and limited to [`MAX_ADVERTISED_NAME_CHARS`] characters.
/// Python reference: `LXMRouter.get_announce_app_data`.
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> { pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
use rmpv::Value; use rmpv::Value;
@@ -246,8 +252,10 @@ pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>)
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`. /// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
/// ///
/// Accepts both Python LXMF <=0.9.8's 2-element form and the 3-element /// Requires an array with at least two elements; later elements are ignored.
/// feature-list form emitted from 1.0.1 (and extended peers). /// A binary UTF-8 name is sanitized and bounded. Unsigned stamp costs are cast
/// to `u8`, retaining the low byte; this does not apply the encoder's `1..=254`
/// filter. Original raw-text announce names are not parsed by this helper.
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> { pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?; let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?; let arr = value.as_array()?;
@@ -268,14 +276,14 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
/// Extract just the display name from delivery-announce `app_data`. /// Extract just the display name from delivery-announce `app_data`.
/// ///
/// Python reference: `display_name_from_app_data` — LXMF.py:131-143. /// Uses [`parse_announce_app_data`], including its name sanitization and array-only format.
pub fn display_name_from_app_data(data: &[u8]) -> Option<String> { pub fn display_name_from_app_data(data: &[u8]) -> Option<String> {
parse_announce_app_data(data).and_then(|(name, _)| name) parse_announce_app_data(data).and_then(|(name, _)| name)
} }
/// Extract just the stamp cost from delivery-announce `app_data`. /// Extract just the stamp cost from delivery-announce `app_data`.
/// ///
/// Python reference: `stamp_cost_from_app_data` — LXMF.py:145-152. /// Uses [`parse_announce_app_data`], including its unsigned-to-`u8` cast.
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> { pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_announce_app_data(data).and_then(|(_, cost)| cost) parse_announce_app_data(data).and_then(|(_, cost)| cost)
} }
@@ -285,7 +293,7 @@ pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
/// Legacy 2-element app_data, malformed data, and missing feature lists are /// Legacy 2-element app_data, malformed data, and missing feature lists are
/// treated as unknown. A present feature list is authoritative. /// treated as unknown. A present feature list is authoritative.
/// ///
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164. /// Related Python helper: `compression_support_from_app_data`.
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport { pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else { let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return CompressionSupport::Unknown; return CompressionSupport::Unknown;
@@ -312,20 +320,18 @@ pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSuppor
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`. /// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
/// ///
/// Fail-open like Python: legacy 2-element app_data, malformed data, and /// Returns true for Supported or Unknown, including empty/malformed input and
/// non-list feature entries all count as supported; only an explicit feature /// missing or non-list feature metadata. Only a present feature list without
/// list that omits `SF_COMPRESSION` disables compression. /// `SF_COMPRESSION` returns false. This boolean default differs from Python
/// /// helper cases that return `None` or raise a decode error.
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
pub fn compression_support_from_app_data(data: &[u8]) -> bool { pub fn compression_support_from_app_data(data: &[u8]) -> bool {
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
} }
/// Extract the advertised name from propagation-node announce data. /// Extract the advertised name from propagation-node announce data.
/// ///
/// Reads the [`PN_META_NAME`] metadata entry and decodes it as UTF-8. /// Reads binary [`PN_META_NAME`] metadata, decodes UTF-8, then sanitizes and
/// /// bounds the name. Returns `None` if parsing fails or the result is empty.
/// Python reference: `pn_name_from_app_data` — LXMF.py:172-181.
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> { pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
let parsed = parse_pn_announce_data(data)?; let parsed = parse_pn_announce_data(data)?;
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?; let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
@@ -374,21 +380,24 @@ pub enum ControlResult {
/// Propagation-node request handler. /// Propagation-node request handler.
/// ///
/// Owns the access-control state and dispatches the three request paths (`/pn/get/stats`, /// Provides handlers for `/pn/get/stats`, `/offer`, `/get`, `/pn/peer/sync` and
/// `/offer`, `/get`) to [`crate::propagation_node::PropagationNode`]. Python reference: /// `/pn/peer/unpeer`. The embedder must supply identities already verified by
/// LXMRouter.py:650-657. /// the Link; these methods accept identity hashes and do not authenticate them.
/// Sync/unpeer handlers authorize a request; the caller performs those actions.
pub struct PropagationRequestHandler { pub struct PropagationRequestHandler {
pub local_identity_hash: [u8; 16], pub local_identity_hash: [u8; 16],
pub control_allowed: Vec<[u8; 16]>, pub control_allowed: Vec<[u8; 16]>,
/// When true, only peers in [`static_peers`](Self::static_peers) may submit offers. /// When true, offers require the supplied remote identity hash to be in
/// [`static_peers`](Self::static_peers). This helper uses identity hashes.
pub from_static_only: bool, pub from_static_only: bool,
pub static_peers: std::collections::HashSet<[u8; 16]>, pub static_peers: std::collections::HashSet<[u8; 16]>,
/// Throttled peers mapped to their expiry Unix timestamp. /// Supplied remote identity hashes mapped to throttle-expiry Unix timestamps.
pub throttled_peers: HashMap<[u8; 16], f64>, pub throttled_peers: HashMap<[u8; 16], f64>,
} }
impl PropagationRequestHandler { impl PropagationRequestHandler {
/// Create a handler seeded with the local identity hash, which is always control-allowed. /// Create a handler with the local identity hash in its initial control allowlist.
/// The allowlist remains mutable, including removal of that identity.
pub fn new(identity_hash: [u8; 16]) -> Self { pub fn new(identity_hash: [u8; 16]) -> Self {
Self { Self {
local_identity_hash: identity_hash, local_identity_hash: identity_hash,
@@ -399,9 +408,9 @@ impl PropagationRequestHandler {
} }
} }
/// Handle a `/pn/get/stats` request: validates identity and access, then returns msgpack stats. /// Return MessagePack stats when the supplied verified identity is control-allowed.
/// ///
/// Python reference: `LXMRouter.stats_get_request` — LXMRouter.py:819-822. /// Related Python handler: `LXMRouter.stats_get_request`.
pub fn handle_stats_request( pub fn handle_stats_request(
&self, &self,
remote_identity_hash: Option<&[u8; 16]>, remote_identity_hash: Option<&[u8; 16]>,
@@ -423,9 +432,10 @@ impl PropagationRequestHandler {
/// Handle an `/offer` request from a syncing peer. /// Handle an `/offer` request from a syncing peer.
/// ///
/// Validates identity, throttle status, access, and peering key, then delegates to /// Build identity-presence, throttle and static-access context, then delegate
/// [`crate::propagation_node::PropagationNode::handle_offer_request`]. Python reference: /// decoding and peering-key checks to
/// `LXMRouter.offer_request` — LXMRouter.py:2139-2189. /// [`crate::propagation_node::PropagationNode::handle_offer_request`].
/// Supply an already verified remote identity; this helper does not verify it.
pub fn handle_offer_request( pub fn handle_offer_request(
&self, &self,
remote_identity_hash: Option<&[u8; 16]>, remote_identity_hash: Option<&[u8; 16]>,
@@ -469,7 +479,9 @@ impl PropagationRequestHandler {
/// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles) /// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles)
/// plan — the embedder resolves it after releasing the node lock. /// plan — the embedder resolves it after releasing the node lock.
/// ///
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499. /// The caller must derive `client_dest_hash` from the verified remote identity
/// and enforce its access policy. This helper checks only that an identity
/// was supplied; it does not bind the two arguments.
pub fn handle_message_get_request( pub fn handle_message_get_request(
&self, &self,
remote_identity_hash: Option<&[u8; 16]>, remote_identity_hash: Option<&[u8; 16]>,
@@ -494,7 +506,7 @@ impl PropagationRequestHandler {
/// Handle a `/pn/peer/sync` request. Returns msgpack `true` on success; the caller performs /// Handle a `/pn/peer/sync` request. Returns msgpack `true` on success; the caller performs
/// the actual sync trigger. /// the actual sync trigger.
/// ///
/// Python reference: `LXMRouter.peer_sync_request` — LXMRouter.py:824-834. /// Related Python handler: `LXMRouter.peer_sync_request`.
pub fn handle_peer_sync_request( pub fn handle_peer_sync_request(
&self, &self,
remote_identity_hash: Option<&[u8; 16]>, remote_identity_hash: Option<&[u8; 16]>,
@@ -527,7 +539,7 @@ impl PropagationRequestHandler {
/// Handle a `/pn/peer/unpeer` request. Returns msgpack `true` on success; the caller performs /// Handle a `/pn/peer/unpeer` request. Returns msgpack `true` on success; the caller performs
/// the actual peer removal. /// the actual peer removal.
/// ///
/// Python reference: `LXMRouter.peer_unpeer_request` — LXMRouter.py:836-846. /// Related Python handler: `LXMRouter.peer_unpeer_request`.
pub fn handle_peer_unpeer_request( pub fn handle_peer_unpeer_request(
&self, &self,
remote_identity_hash: Option<&[u8; 16]>, remote_identity_hash: Option<&[u8; 16]>,
@@ -564,7 +576,7 @@ impl PropagationRequestHandler {
/// Throttle `peer_hash` for `duration_secs` starting now. /// Throttle `peer_hash` for `duration_secs` starting now.
/// ///
/// Python reference: `LXMRouter.propagation_resource_concluded` — LXMRouter.py:2277-2278. /// Related Python handler: `LXMRouter.propagation_resource_concluded`.
pub fn throttle_peer(&mut self, peer_hash: [u8; 16], duration_secs: f64) { pub fn throttle_peer(&mut self, peer_hash: [u8; 16], duration_secs: f64) {
let expiry = now_f64() + duration_secs; let expiry = now_f64() + duration_secs;
self.throttled_peers.insert(peer_hash, expiry); self.throttled_peers.insert(peer_hash, expiry);
+15 -10
View File
@@ -62,7 +62,8 @@ impl From<InboundResourceConclusion> for InboundResourceStatus {
} }
} }
/// Owned, non-sensitive snapshot of one inbound transfer. /// Owned snapshot containing link/Resource IDs, sizes, progress and status.
/// It contains no transferred payload bytes.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct InboundResourceSnapshot { pub struct InboundResourceSnapshot {
pub key: InboundResourceKey, pub key: InboundResourceKey,
@@ -133,10 +134,12 @@ impl InboundResourceHandle {
self.snapshot_rx.borrow().clone() self.snapshot_rx.borrow().clone()
} }
/// Wait for the next lifecycle/progress update. /// Wait for an unseen lifecycle/progress state. Intermediate updates may
/// be coalesced by the watch channel.
/// ///
/// Returns `None` after the terminal snapshot has been published and the /// Returns `None` once the sender is gone and its latest value has been seen.
/// actor owner has dropped its sender. /// Dropping the tracker can close the channel without publishing a terminal
/// state; terminal states require the corresponding lifecycle event.
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> { pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
if self.snapshot_rx.changed().await.is_err() { if self.snapshot_rx.changed().await.is_err() {
return None; return None;
@@ -166,9 +169,10 @@ struct ActiveInboundResource {
/// Single-owner active Resource registry. /// Single-owner active Resource registry.
/// ///
/// Terminal records are removed immediately, so the registry is bounded by /// Concluded and LinkClosed events remove records immediately. The embedder
/// concurrent transfers. Previously returned handles retain the final owned /// must forward those events to keep the registry limited to active transfers;
/// snapshot without keeping actor state alive. /// the tracker has no independent entry cap or timeout. Previously returned
/// handles retain their latest snapshot without keeping tracker state alive.
#[derive(Default)] #[derive(Default)]
pub struct InboundResourceTracker { pub struct InboundResourceTracker {
active: HashMap<InboundResourceKey, ActiveInboundResource>, active: HashMap<InboundResourceKey, ActiveInboundResource>,
@@ -203,8 +207,8 @@ impl InboundResourceTracker {
/// Return the active Resource matching `resource_id`. /// Return the active Resource matching `resource_id`.
/// ///
/// A cryptographic ID collision across two Links fails closed instead of /// If the same Resource ID is active on more than one Link, returns `None`.
/// choosing the wrong cancellation authority. /// Use [`Self::inbound_resource_exact`] with the full key to disambiguate.
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> { pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
let mut matches = self let mut matches = self
.active .active
@@ -237,7 +241,8 @@ impl InboundResourceTracker {
/// Queue cancellation for a stable snapshot of every active Resource. /// Queue cancellation for a stable snapshot of every active Resource.
/// ///
/// The returned count is the number accepted by the bounded command /// The returned count is the number accepted by the bounded command
/// channel, matching Python's count-oriented `cancel_all_inbound` API. /// channel, not the number of completed cancellations. Closure is reported
/// by subsequent lifecycle events.
pub fn cancel_all_inbound(&self) -> usize { pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resources() self.inbound_resources()
.into_iter() .into_iter()
+14 -7
View File
@@ -4,20 +4,20 @@
//! //!
//! This crate implements the LXMF wire model and is the core LXMF building //! This crate implements the LXMF wire model and is the core LXMF building
//! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications. //! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications.
//! Its Reticulum dependency is `rns-transport` from rsReticulum; LXMF sits one //! It uses rsReticulum for transport, links, identities and Resources; LXMF
//! layer above the Reticulum stack. //! sits one layer above the Reticulum stack.
//! //!
//! # Module map //! # Module map
//! //!
//! | Module | What it does | //! | Module | What it does |
//! | --------------------- | -------------------------------------------------- | //! | --------------------- | -------------------------------------------------- |
//! | [`message`] | Message object: fields, packing, stamp, encryption | //! | [`message`] | Message types, packing, verification and encryption hooks |
//! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction | //! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction |
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation | //! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
//! | [`presentation`] | Safe bounded presentation of untrusted names | //! | [`presentation`] | Safe bounded presentation of untrusted names |
//! | [`router`] | Actor-driven routing and delivery state machine | //! | [`router`] | Caller-driven routing and delivery state machine |
//! | [`peer`] | Propagation-peer state and sync bookkeeping | //! | [`peer`] | Propagation-peer state and sync bookkeeping |
//! | [`propagation`] | On-disk store-and-forward message pool | //! | [`propagation`] | In-memory propagation message index and selection |
//! | [`propagation_node`] | Propagation-node role logic | //! | [`propagation_node`] | Propagation-node role logic |
//! | [`propagation_client`]| Client side of propagation sync | //! | [`propagation_client`]| Client side of propagation sync |
//! | [`propagation_sync`] | Wire-level peer sync exchange | //! | [`propagation_sync`] | Wire-level peer sync exchange |
@@ -25,9 +25,16 @@
//! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery | //! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery |
//! | [`sync`] | Shared peer-to-peer sync primitives | //! | [`sync`] | Shared peer-to-peer sync primitives |
//! | [`link_delivery`] | Reticulum-link-based delivery path | //! | [`link_delivery`] | Reticulum-link-based delivery path |
//! | [`handlers`] | Callback trait surface for delivery events | //! | [`handlers`] | Announce parsing and propagation control handlers |
//! | [`ticket`] | Small typed identifier for propagation workflows | //! | [`ticket`] | Directional tickets for bypassing recipient stamp work |
//! | [`persist`] | MessagePack-based on-disk state | //! | [`persist`] | MessagePack-based on-disk state |
//! | [`admission`] | Durable inbox admission and receipt state |
//! | [`admission_store`] | Admission-store interface and file-backed adapter |
//! | [`propagation_admission`] | Inbound propagation offer and transfer states |
//! | [`propagation_offer`] | Propagation-offer evaluation outcomes |
//! | [`propagation_send`] | Outbound propagation payload preparation |
//! | [`propagation_store_v2`] | Durable propagation store and recovery |
//! | [`types`] | Message, destination and identity hash aliases |
//! | [`constants`] | Wire constants: STATE, METHOD, field IDs, etc. | //! | [`constants`] | Wire constants: STATE, METHOD, field IDs, etc. |
//! //!
//! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum` //! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum`
+96 -73
View File
@@ -1,9 +1,11 @@
//! Link-based LXMF message delivery (Python's Direct delivery mode). //! Caller-driven LXMF delivery over Reticulum Links.
//! //!
//! Establishes a link to the recipient, identifies the sender, and transfers the message either //! Sends a message as an encrypted Link packet or as segmented Resources and
//! as a single encrypted link packet or as a Resource over the link. Enables larger-than-MDU //! tracks Link-level proofs. Reusable Direct Links identify the sender after a
//! messages via resource segmentation, delivery confirmation via link-level proofs, and sender //! successful delivery when local identity keys are configured. One-shot packed
//! identity verification via link identification. //! deliveries, used for propagation deposits, identify before sending when those
//! keys are available. Link proofs confirm transport receipt, not application
//! validation or durable storage at the recipient.
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::fmt; use std::fmt;
@@ -57,23 +59,21 @@ const LINK_PACKET_DISPATCH_TIMEOUT: Duration = LINK_ENDPOINT_ADMISSION_TIMEOUT_M
/// Authority-derived first-hop timing for an outbound Link. /// Authority-derived first-hop timing for an outbound Link.
/// ///
/// Python Reticulum computes an initiator's establishment deadline as the /// The initiator's establishment timeout is the first-hop timeout plus six
/// first-hop timeout plus six seconds for every hop to the destination. The /// seconds times `max(hops, 1)`. With the canonical 500-byte MTU, first-hop
/// first-hop timeout is one full Reticulum MTU at the next-hop interface's /// serialization time is `500 * 8 / bitrate` seconds plus a six-second baseline,
/// bitrate, plus the same six-second baseline. When no authoritative bitrate /// as in Python Reticulum. An unknown or zero bitrate uses the baseline alone.
/// is available, Reticulum falls back to the baseline alone.
/// ///
/// Keeping this input independent of interface type is intentional: BLE, /// This input is independent of interface type. An interface going offline
/// serial, TCP and every future adapter use the same Link timing rule. It does /// does not pause or reset the establishment clock.
/// not pause or reset the protocol clock when an interface goes offline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkEstablishmentTiming { pub struct LinkEstablishmentTiming {
first_hop_timeout: Duration, first_hop_timeout: Duration,
} }
impl LinkEstablishmentTiming { impl LinkEstablishmentTiming {
/// Construct timing from an already-authoritative Reticulum first-hop /// Store an authoritative Reticulum first-hop timeout without validation
/// timeout (for example `ReticulumHandle::first_hop_timeout`). /// (for example, a value from `ReticulumHandle::first_hop_timeout`).
pub const fn from_first_hop_timeout(first_hop_timeout: Duration) -> Self { pub const fn from_first_hop_timeout(first_hop_timeout: Duration) -> Self {
Self { first_hop_timeout } Self { first_hop_timeout }
} }
@@ -84,14 +84,13 @@ impl LinkEstablishmentTiming {
Self::from_first_hop_bitrate_and_mtu(bitrate, rns_wire::constants::MTU as u32) Self::from_first_hop_bitrate_and_mtu(bitrate, rns_wire::constants::MTU as u32)
} }
/// Derive first-hop timing from the effective next-hop bitrate and an /// Derive timing as six seconds plus `min(normalised_mtu, 500) * 8 / bitrate`.
/// already-normalised Reticulum protocol MTU. /// A zero bitrate contributes no serialization time.
/// ///
/// Callers normally want [`Self::from_first_hop_bitrate`], which uses the /// Normally use [`Self::from_first_hop_bitrate`] for the canonical 500-byte
/// canonical 500-byte Reticulum MTU exactly like Python Reticulum and the /// Reticulum MTU used by Python Reticulum and the rsReticulum runtime.
/// trusted rsReticulum runtime. `normalised_mtu` exists for callers that /// `normalised_mtu` must be a protocol MTU, not a BLE ATT MTU, RNode serial
/// already have an authoritative *protocol* MTU. It must never be a BLE /// chunk size, or raw hardware-interface MTU.
/// ATT MTU, an RNode serial chunk size, or a raw hardware-interface MTU.
pub fn from_first_hop_bitrate_and_mtu(bitrate: u64, normalised_mtu: u32) -> Self { pub fn from_first_hop_bitrate_and_mtu(bitrate: u64, normalised_mtu: u32) -> Self {
let serialization_secs = if bitrate == 0 { let serialization_secs = if bitrate == 0 {
0.0 0.0
@@ -360,7 +359,8 @@ pub struct PendingDelivery {
pub link: Link, pub link: Link,
pub state: DeliveryState, pub state: DeliveryState,
pub started_at: Instant, pub started_at: Instant,
/// Resource transfer, populated after the link establishes. /// Current Resource transfer when the payload requires one; single-packet
/// and idle deliveries have no Resource transfer.
pub transfer: Option<OutboundTransfer>, pub transfer: Option<OutboundTransfer>,
/// Sequential Reticulum Resource plan for payloads larger than one /// Sequential Reticulum Resource plan for payloads larger than one
/// efficient resource. Segment 1 is stored in `transfer`; later segments /// efficient resource. Segment 1 is stored in `transfer`; later segments
@@ -375,8 +375,10 @@ pub struct PendingDelivery {
link_request_result: Option< link_request_result: Option<
oneshot::Receiver<Result<(), rns_transport::link_messages::LinkRequestDispatchError>>, oneshot::Receiver<Result<(), rns_transport::link_messages::LinkRequestDispatchError>>,
>, >,
/// Ordinary Link-packet proof window, installed when the packet is /// Current Link-packet admission or proof wait. Exact driver receipts
/// locally admitted. Resource transfers use their own progress watchdog. /// replace the staging window with the proof window after admission;
/// legacy queued acknowledgements include an admission allowance.
/// Resource transfers use their own progress watchdog.
pub timeout: Duration, pub timeout: Duration,
pub msg_hash: Option<[u8; 32]>, pub msg_hash: Option<[u8; 32]>,
pub failure_reason: Option<String>, pub failure_reason: Option<String>,
@@ -390,8 +392,8 @@ pub struct PendingDelivery {
/// Keep successful Direct links open for additional messages. Propagation /// Keep successful Direct links open for additional messages. Propagation
/// deposits currently keep the old one-shot behavior. /// deposits currently keep the old one-shot behavior.
pub reusable: bool, pub reusable: bool,
/// Upstream identifies the initiator after the first successful Direct /// Whether local Link identification was staged after a successful Direct
/// delivery, making the link usable as a peer backchannel. /// delivery. Requires configured identity keys; it is not a peer acknowledgement.
pub backchannel_identified: bool, pub backchannel_identified: bool,
queued: VecDeque<QueuedDelivery>, queued: VecDeque<QueuedDelivery>,
/// Resources arriving in the reverse direction on this initiator-owned /// Resources arriving in the reverse direction on this initiator-owned
@@ -575,7 +577,9 @@ pub struct DirectLinkStartReport {
pub in_flight_deliveries: usize, pub in_flight_deliveries: usize,
} }
/// A proof-tracked send over an already-authenticated inbound delivery Link. /// Adapter receipt identifying a proof-tracked send over an authenticated
/// inbound Link. The embedding runtime must establish that authentication;
/// this publicly constructible value is not itself a proof of delivery.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum BackchannelSendReceipt { pub enum BackchannelSendReceipt {
Packet { Packet {
@@ -632,9 +636,9 @@ impl fmt::Display for BackchannelSendError {
impl std::error::Error for BackchannelSendError {} impl std::error::Error for BackchannelSendError {}
/// Whether a link-delivery failure should be treated like upstream LXMF's /// Classify known local link-delivery failure strings as eligible for Direct
/// closed/pending Link path, where the message remains eligible for Direct /// rediscovery. This matches the intended closed/pending-Link retry policy;
/// rediscovery instead of being terminally failed. /// it is an explicit string whitelist, not a classifier for arbitrary peer errors.
pub fn is_retryable_link_delivery_failure(reason: &str) -> bool { pub fn is_retryable_link_delivery_failure(reason: &str) -> bool {
// Only concrete local endpoint terminal outcomes, not malformed packet, // Only concrete local endpoint terminal outcomes, not malformed packet,
// role mismatch or arbitrary peer rejection text, trigger rediscovery. // role mismatch or arbitrary peer rejection text, trigger rediscovery.
@@ -1058,10 +1062,11 @@ impl LinkDeliveryManager {
self.backchannel_cancellation_aware = false; self.backchannel_cancellation_aware = false;
} }
/// Install an adapter that fences closed receipt publication and retains /// Install an adapter whose caller contract fences closed receipt publication
/// exact cleanup ownership. New starts close/drain their receipt immediately /// and retains exact cleanup ownership. New starts close/drain their receipt
/// on user cancellation; existing starts retain their captured policy. /// on user cancellation; existing starts retain their captured policy.
/// Legacy adapters must continue using `set_backchannel_sender` instead. /// This setter records that contract without verifying the adapter. Legacy
/// adapters must use [`Self::set_backchannel_sender`].
pub fn set_cancellation_aware_backchannel_sender( pub fn set_cancellation_aware_backchannel_sender(
&mut self, &mut self,
tx: mpsc::Sender<BackchannelSendCommand>, tx: mpsc::Sender<BackchannelSendCommand>,
@@ -1109,8 +1114,9 @@ impl LinkDeliveryManager {
self.inbound_resource_completion_handler = Some(Arc::new(handler)); self.inbound_resource_completion_handler = Some(Arc::new(handler));
} }
/// Register an inbound authenticated Link as a reusable backchannel for a /// Cache a reusable inbound Link for a remote LXMF delivery destination.
/// remote LXMF delivery destination. /// The caller must already have authenticated the Link identity and verified
/// its binding to `dest_hash`; this method only records the mapping.
pub fn register_backchannel(&mut self, dest_hash: [u8; 16], link_id: [u8; 16]) { pub fn register_backchannel(&mut self, dest_hash: [u8; 16], link_id: [u8; 16]) {
self.backchannel_links.insert(dest_hash, link_id); self.backchannel_links.insert(dest_hash, link_id);
tracing::info!( tracing::info!(
@@ -1151,8 +1157,9 @@ impl LinkDeliveryManager {
result result
} }
/// Remove cached backchannel state for a closed Link and fail any /// Remove a closed Link from the backchannel cache and fail its installed sends.
/// in-flight backchannel sends that were using it. /// Pending starts with an early settlement or cancellation remain until their
/// exact receipt can be reconciled; closure does not discard that ownership.
pub fn fail_backchannel_link( pub fn fail_backchannel_link(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -1304,10 +1311,11 @@ impl LinkDeliveryManager {
self.start_direct_delivery(message, dest_hash, hops, timing) self.start_direct_delivery(message, dest_hash, hops, timing)
} }
/// Start a link delivery with an already-packed payload. /// Start a one-shot Link delivery with a caller-supplied packed payload.
/// ///
/// This is used for LXMF propagation deposits, whose link payload is the /// Propagation deposits use their propagation wrapper here rather than the
/// propagation wrapper rather than the regular signed LXMF representation. /// regular signed LXMF representation. This method does not validate that
/// wrapper or its correspondence to the supplied message metadata.
pub fn start_packed_delivery( pub fn start_packed_delivery(
&mut self, &mut self,
message: LxMessage, message: LxMessage,
@@ -2044,10 +2052,12 @@ impl LinkDeliveryManager {
} }
} }
/// Drain inbound transport events and dispatch by packet context. /// Process up to 32 inbound destination events and pending local acknowledgements.
/// ///
/// Call before [`Self::tick`] each cycle. Routes `LRPROOF`, `ResourceHmu`, `ResourceReq`, /// Call before [`Self::tick`] each cycle and continue polling when more input
/// and `ResourcePrf` contexts to their handlers. /// is ready. Routes Link establishment, packets, Resources, proofs and lifecycle
/// events. `known_identities` must contain trusted destination-to-public-key
/// bindings for establishment-proof validation.
pub fn drain_events(&mut self, known_identities: &HashMap<String, [u8; 64]>) { pub fn drain_events(&mut self, known_identities: &HashMap<String, [u8; 64]>) {
self.poll_link_requests(); self.poll_link_requests();
self.poll_endpoint_control(); self.poll_endpoint_control();
@@ -2266,8 +2276,9 @@ impl LinkDeliveryManager {
} }
} }
/// Validate an inbound `LRPROOF`, complete the handshake, and transition to /// Validate `LRPROOF` and stage endpoint binding and RTT acknowledgement.
/// [`DeliveryState::Identifying`]. /// `true` means that plan was accepted. The binding acknowledgement must be
/// processed and RTT send staged before entering [`DeliveryState::Identifying`].
pub fn handle_link_proof( pub fn handle_link_proof(
&mut self, &mut self,
link_id: &[u8; 16], link_id: &[u8; 16],
@@ -3688,11 +3699,11 @@ impl LinkDeliveryManager {
} }
} }
/// Handle an inbound `RESOURCE_REQ` (receiver's `request_next`). /// Handle a decrypted, authenticated `RESOURCE_REQ` from the receiver.
/// ///
/// The request returns a list of parts the receiver still needs; dispatch the resulting /// This method immediately dispatches the requested parts rather than waiting
/// `SendPart` actions immediately rather than waiting for the next [`Self::tick`], since /// for [`Self::tick`]. Direct callers must authenticate and decrypt the request;
/// the receiver may time out and retry first. /// [`Self::drain_events`] performs that step for routed transport events.
pub fn handle_request(&mut self, link_id: &[u8; 16], request_data: &[u8]) { pub fn handle_request(&mut self, link_id: &[u8; 16], request_data: &[u8]) {
let event = { let event = {
let Some(delivery) = self.pending.get_mut(link_id) else { let Some(delivery) = self.pending.get_mut(link_id) else {
@@ -3766,7 +3777,9 @@ impl LinkDeliveryManager {
} }
} }
/// Apply an inbound resource proof; returns `true` when the proof was accepted. /// Validate a Resource proof; `true` means the current segment's proof was
/// accepted. A split Resource may then advance to another segment, so this is
/// not necessarily whole-message completion.
pub fn handle_resource_proof(&mut self, link_id: &[u8; 16], proof_data: &[u8]) -> bool { pub fn handle_resource_proof(&mut self, link_id: &[u8; 16], proof_data: &[u8]) -> bool {
let mut event = None; let mut event = None;
let accepted = if let Some(delivery) = self.pending.get_mut(link_id) { let accepted = if let Some(delivery) = self.pending.get_mut(link_id) {
@@ -3828,7 +3841,9 @@ impl LinkDeliveryManager {
accepted accepted
} }
/// Apply an inbound receiver-cancel/reject for the current outbound resource. /// Apply a decrypted, authenticated receiver-cancel body for the current
/// outbound Resource. Matches its first 32 bytes against the Resource hash;
/// this method does not authenticate raw input. The next tick reports rejection.
pub fn handle_resource_reject(&mut self, link_id: &[u8; 16], reject_data: &[u8]) -> bool { pub fn handle_resource_reject(&mut self, link_id: &[u8; 16], reject_data: &[u8]) -> bool {
if reject_data.len() < 32 { if reject_data.len() < 32 {
return false; return false;
@@ -3912,6 +3927,10 @@ impl LinkDeliveryManager {
false false
} }
/// Record a packet proof already verified by the authenticated Link owner.
/// This method accepts only identifiers and performs no cryptographic check.
/// Returns a completion result for an installed send. Otherwise, records an
/// early observation only when a start is pending on that Link.
pub fn handle_backchannel_packet_proof( pub fn handle_backchannel_packet_proof(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -3920,11 +3939,12 @@ impl LinkDeliveryManager {
self.complete_backchannel_delivery(BackchannelProofKey::Packet(link_id, packet_hash)) self.complete_backchannel_delivery(BackchannelProofKey::Packet(link_id, packet_hash))
} }
/// Mirror the exact bounded packet wait observed by the authenticated Link /// Mirror a packet wait supplied by the authenticated Link owner.
/// owner. `awaiting_admission` separates local staging from the RTT proof /// `awaiting_admission` separates local staging from the RTT proof window
/// window installed after endpoint acceptance. Call before or after its send receipt; /// installed after endpoint acceptance. Call before or after the send receipt;
/// delayed observations retain the original start instant. Unowned, /// delayed observations retain the supplied start instant. Requires an installed
/// cancelled and completed sends cannot be installed by this method. /// send or a pending start on that Link; its receipt later confirms the exact hash.
/// The caller must supply a valid bounded window; its duration is not clamped.
pub fn observe_backchannel_packet_wait( pub fn observe_backchannel_packet_wait(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -3972,14 +3992,14 @@ impl LinkDeliveryManager {
) )
} }
/// Mirror an exact bounded Resource wait from its protocol owner. The /// Mirror a Resource wait supplied by its authenticated protocol owner.
/// owner must drive advertisement/window/proof exhaustion and report /// The caller must supply a valid bounded window, drive protocol exhaustion,
/// terminal results. Only real protocol progress/retry may update this /// and report terminal results; this method does not clamp the duration.
/// window; keepalives or generic UI progress must not extend it. This /// Only real protocol progress or retry may update the window, not keepalives
/// replaces the finite legacy adapter fallback for this exact send only. /// or generic UI progress. This replaces the legacy fallback for this send.
/// A bounded 180-second observation grace follows the original deadline to /// A 180-second observation grace follows the supplied deadline. Terminal
/// tolerate asynchronous accounting delivery; terminal results still settle /// results still settle immediately; repeating an identical observation does
/// immediately and duplicate observations do not restart that envelope. /// not restart the window.
pub fn observe_backchannel_resource_wait( pub fn observe_backchannel_resource_wait(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -4036,6 +4056,10 @@ impl LinkDeliveryManager {
true true
} }
/// Record a Resource proof already verified by the authenticated Link owner.
/// This method accepts only identifiers and performs no cryptographic check.
/// Returns a completion result for an installed send. Otherwise, records an
/// early observation only when a start is pending on that Link.
pub fn handle_backchannel_resource_proof( pub fn handle_backchannel_resource_proof(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -4667,15 +4691,14 @@ impl LinkDeliveryManager {
.collect() .collect()
} }
/// Return the finite delivery-owner envelope currently owning this message. /// Return the recorded delivery-owner wait for this message, when available.
/// ///
/// Queued messages have no independent clock. Packet waits start at local /// Messages queued behind another delivery on a reusable Direct Link have no
/// admission; Resource waits belong to the progress engine, not total /// independent clock. Packet waits cover local staging and then proof receipt;
/// message age. Observed backchannel bounds preserve the external owner's /// Resource waits belong to the progress engine, not total message age. Backchannel observations preserve the external owner's
/// original instant, with a 180-second accounting observation grace for /// supplied instant and duration, adding 180 seconds of accounting grace only
/// externally owned Resources only. Direct Resource and packet protocol /// for Resources. Without an observation, legacy backchannels use the finite
/// clocks are unchanged. Legacy adapters without observations retain the /// fallback. Callers supplying observations are responsible for valid bounds.
/// finite fallback, never an unlimited exemption from an orphan watchdog.
pub fn message_timeout_window(&self, msg_hash: [u8; 32]) -> Option<(Instant, Duration)> { pub fn message_timeout_window(&self, msg_hash: [u8; 32]) -> Option<(Instant, Duration)> {
for delivery in self.pending.values() { for delivery in self.pending.values() {
if delivery.msg_hash != Some(msg_hash) { if delivery.msg_hash != Some(msg_hash) {
+42 -34
View File
@@ -450,7 +450,7 @@ impl LxMessage {
} }
/// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data. /// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data.
/// ///
/// Matches Python `LXMessage.determine_compression_support` — LXMessage.py:510-513. /// Follows Python `LXMessage.determine_compression_support`.
/// Fail-open: no cached app_data and legacy peers without a feature list /// Fail-open: no cached app_data and legacy peers without a feature list
/// default to compression enabled; only an explicit feature list omitting /// default to compression enabled; only an explicit feature list omitting
/// `SF_COMPRESSION` disables it. /// `SF_COMPRESSION` disables it.
@@ -460,9 +460,8 @@ impl LxMessage {
.unwrap_or(true); .unwrap_or(true);
} }
/// Register a callback fired when this message transitions to `Delivered`. /// Set the callback used by [`Self::notify_delivered`] and
/// /// [`Self::mark_delivered`], replacing any previous delivery callback.
/// Python reference: `LXMessage.register_delivery_callback` — LXMessage.py:264-265.
pub fn register_delivery_callback<F>(&mut self, callback: F) pub fn register_delivery_callback<F>(&mut self, callback: F)
where where
F: Fn(&LxMessage) + Send + Sync + 'static, F: Fn(&LxMessage) + Send + Sync + 'static,
@@ -470,9 +469,8 @@ impl LxMessage {
self.callbacks.on_delivered = Some(Arc::new(callback)); self.callbacks.on_delivered = Some(Arc::new(callback));
} }
/// Register a callback fired when this message transitions to `Failed`. /// Set the callback used by [`Self::notify_failed`] and
/// /// [`Self::mark_failed`], replacing any previous failure callback.
/// Python reference: `LXMessage.register_failed_callback` — LXMessage.py:267-268.
pub fn register_failed_callback<F>(&mut self, callback: F) pub fn register_failed_callback<F>(&mut self, callback: F)
where where
F: Fn(&LxMessage) + Send + Sync + 'static, F: Fn(&LxMessage) + Send + Sync + 'static,
@@ -480,14 +478,16 @@ impl LxMessage {
self.callbacks.on_failed = Some(Arc::new(callback)); self.callbacks.on_failed = Some(Arc::new(callback));
} }
/// Fire the registered delivery callback, if any. Idempotent on repeated calls. /// Invoke the delivery callback, if registered. Every call invokes it again;
/// the caller must prevent duplicate notifications when required.
pub fn notify_delivered(&self) { pub fn notify_delivered(&self) {
if let Some(ref cb) = self.callbacks.on_delivered { if let Some(ref cb) = self.callbacks.on_delivered {
cb(self); cb(self);
} }
} }
/// Fire the registered failure callback, if any. Idempotent on repeated calls. /// Invoke the failure callback, if registered. Every call invokes it again;
/// the caller must prevent duplicate notifications when required.
pub fn notify_failed(&self) { pub fn notify_failed(&self) {
if let Some(ref cb) = self.callbacks.on_failed { if let Some(ref cb) = self.callbacks.on_failed {
cb(self); cb(self);
@@ -495,7 +495,8 @@ impl LxMessage {
} }
/// Decode the first native LXMF file attachment while borrowing its bytes /// Decode the first native LXMF file attachment while borrowing its bytes
/// from this message. Only the small filename is allocated. /// from this message. The filename is copied into a string; it has no
/// separate length limit beyond the enclosing message's decode limits.
pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> { pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
let Some(field) = self.fields().get(FIELD_FILE_ATTACHMENTS) else { let Some(field) = self.fields().get(FIELD_FILE_ATTACHMENTS) else {
return Ok(None); return Ok(None);
@@ -515,7 +516,8 @@ impl LxMessage {
} }
/// Decode the native LXMF image field while borrowing its image bytes /// Decode the native LXMF image field while borrowing its image bytes
/// from this message. Only the short format string is allocated. /// from this message. The format string is copied; it has no separate
/// length limit beyond the enclosing message's decode limits.
pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> { pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
let Some(field) = self.fields().get(FIELD_IMAGE) else { let Some(field) = self.fields().get(FIELD_IMAGE) else {
return Ok(None); return Ok(None);
@@ -576,8 +578,10 @@ impl LxMessage {
} }
/// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is /// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is
/// `dest_hash(16) + encrypted_data + ?propagation_stamp`. The caller must decrypt and then /// `dest_hash(16) + encrypted_data + ?propagation_stamp`. The caller removes any
/// call [`Self::unpack`] on the decrypted bytes. /// propagation stamp, decrypts the ciphertext after the destination hash,
/// then prepends that destination hash before calling [`Self::unpack`].
/// Use a bounded wrapper parser for network ingress.
/// ///
/// Python reference: `LXMRouter.lxmf_propagation` / `propagation_resource_concluded`. /// Python reference: `LXMRouter.lxmf_propagation` / `propagation_resource_concluded`.
pub fn unpack_propagation_wrapper(data: &[u8]) -> Result<(f64, Vec<Vec<u8>>), MessageError> { pub fn unpack_propagation_wrapper(data: &[u8]) -> Result<(f64, Vec<Vec<u8>>), MessageError> {
@@ -586,9 +590,9 @@ impl LxMessage {
Ok(wrapper) Ok(wrapper)
} }
/// Smallest possible valid propagation entry: anything at or below /// Minimum entry length accepted by the bounded propagation-wrapper parser.
/// `LXMF_OVERHEAD + STAMP_SIZE` cannot carry a message (Python /// Matches Python `LXStamper.validate_pn_stamp`'s rejection of entries at or
/// `LXStamper.validate_pn_stamp` rejects it before building a workblock). /// below `LXMF_OVERHEAD + STAMP_SIZE` before workblock construction.
pub const MIN_PROPAGATION_ENTRY_SIZE: usize = pub const MIN_PROPAGATION_ENTRY_SIZE: usize =
crate::constants::LXMF_OVERHEAD + crate::constants::STAMP_SIZE + 1; crate::constants::LXMF_OVERHEAD + crate::constants::STAMP_SIZE + 1;
@@ -662,8 +666,7 @@ impl LxMessage {
/// Mark transmission as in progress. /// Mark transmission as in progress.
/// ///
/// Python reference: LXMessage.py:479, 499 — DIRECT and PROPAGATED messages enter SENDING /// Sets the local state to [`MessageState::Sending`]; performs no network I/O.
/// when transmission begins.
pub fn mark_sending(&mut self) { pub fn mark_sending(&mut self) {
self.state = MessageState::Sending; self.state = MessageState::Sending;
} }
@@ -678,7 +681,8 @@ impl LxMessage {
/// before emitting paper/QR content. The caller supplies that identity encryption closure, /// before emitting paper/QR content. The caller supplies that identity encryption closure,
/// keeping this crate independent from any concrete identity store. /// keeping this crate independent from any concrete identity store.
/// ///
/// Python reference: LXMessage.py:443-455 and LXMessage.py:687-705. /// Requires [`DeliveryMethod::Paper`] and a destination-plus-ciphertext
/// payload no larger than [`PAPER_MDU`].
pub fn to_paper_uri<F>(&self, encrypt_fn: F) -> Result<String, MessageError> pub fn to_paper_uri<F>(&self, encrypt_fn: F) -> Result<String, MessageError>
where where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>, F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -727,10 +731,11 @@ impl LxMessage {
Ok((destination_hash, bytes[DESTINATION_LENGTH..].to_vec())) Ok((destination_hash, bytes[DESTINATION_LENGTH..].to_vec()))
} }
/// Decode an upstream-compatible encrypted `lxm://` paper URI. /// Decode an encrypted `lxm://` paper URI.
/// ///
/// The caller supplies the local destination identity decryption closure. On success the /// The caller supplies destination-identity decryption. This method restores
/// decrypted wire message is unpacked exactly like Python's `ingest_lxm_uri` path. /// the destination prefix, parses the message, and marks its representation
/// as Paper. Authenticate the sender separately with [`Self::verify`].
pub fn from_paper_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError> pub fn from_paper_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError>
where where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>, F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -746,7 +751,7 @@ impl LxMessage {
Ok(message) Ok(message)
} }
/// Alias for [`Self::to_paper_uri`]; returns `None` if packing or encryption fails. /// Alias for [`Self::to_paper_uri`]; returns `None` on any error.
pub fn as_uri<F>(&self, encrypt_fn: F) -> Option<String> pub fn as_uri<F>(&self, encrypt_fn: F) -> Option<String>
where where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>, F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -754,7 +759,7 @@ impl LxMessage {
self.to_paper_uri(encrypt_fn).ok() self.to_paper_uri(encrypt_fn).ok()
} }
/// Alias for [`Self::from_paper_uri`]. Python reference: LXMessage.py:685-731. /// Alias for [`Self::from_paper_uri`].
pub fn from_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError> pub fn from_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError>
where where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>, F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -764,8 +769,11 @@ impl LxMessage {
/// Pack the message into a container for file storage. /// Pack the message into a container for file storage.
/// ///
/// Layout is a msgpack map `{state: u8, lxmf_bytes: bin, transport_encrypted: bool, /// Writes a five-element MessagePack array in this order:
/// transport_encryption: str?, method: u8}`. /// `[state, lxmf_bytes, transport_encrypted, transport_encryption, method]`.
/// `lxmf_bytes` is binary and `transport_encryption` is a string or nil.
/// Python's `packed_container` writes a named-field map; its file reader
/// does not accept this Rust array layout.
pub fn pack_container(&self) -> Result<Vec<u8>, MessageError> { pub fn pack_container(&self) -> Result<Vec<u8>, MessageError> {
let container = MessageContainerRef { let container = MessageContainerRef {
state: self.state as u8, state: self.state as u8,
@@ -777,7 +785,8 @@ impl LxMessage {
rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string())) rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
} }
/// Unpack a message from a container (Python parity: `unpack_from_file` in LXMessage.py). /// Decode a container array or a map with matching field names, then parse
/// its LXMF wire image. This does not verify the sender's signature.
pub fn unpack_container(data: &[u8]) -> Result<Self, MessageError> { pub fn unpack_container(data: &[u8]) -> Result<Self, MessageError> {
if data.len() > MessageDecodeLimits::default().max_wire_bytes + 65_536 { if data.len() > MessageDecodeLimits::default().max_wire_bytes + 65_536 {
return Err(MessageError::UnpackFailed( return Err(MessageError::UnpackFailed(
@@ -818,12 +827,10 @@ impl LxMessage {
/// Write the message to `directory_path`, named by the message hash. /// Write the message to `directory_path`, named by the message hash.
/// ///
/// Writes are atomic (unique tmp file + fsync + rename) so concurrent /// Writes [`Self::pack_container`] through the platform durability boundary
/// readers never observe a partial file — Python `write_to_directory`, /// in [`crate::persist::write_file_atomic`]. Publication errors, including
/// LXMessage.py:674-696 (1.0.1). Python additionally serializes the write /// uncertain commits, propagate to the caller. The message type does not
/// under a per-message persist lock; in Rust concurrent persists of one /// serialize concurrent calls; callers needing write ordering must provide it.
/// message are already exclusive-borrow serialized or hit unique tmp
/// files, with the rename as the atomic last-writer-wins step.
pub fn write_to_directory(&self, directory_path: &str) -> Result<String, MessageError> { pub fn write_to_directory(&self, directory_path: &str) -> Result<String, MessageError> {
let hash = self.message_id(); let hash = self.message_id();
let file_name = rns_crypto::hex_encode(&hash); let file_name = rns_crypto::hex_encode(&hash);
@@ -836,7 +843,8 @@ impl LxMessage {
Ok(file_path) Ok(file_path)
} }
/// Read a message from a container file (Python parity: `unpack_from_file`). /// Read a bounded container file. A 64-character hexadecimal filename must
/// match the parsed message ID. Sender authentication remains a separate step.
pub fn read_from_file(file_path: &str) -> Result<Self, MessageError> { pub fn read_from_file(file_path: &str) -> Result<Self, MessageError> {
use std::io::Read; use std::io::Read;
let file = std::fs::File::open(file_path) let file = std::fs::File::open(file_path)
+5 -2
View File
@@ -326,8 +326,9 @@ impl SignedLxMessage {
stamp_cost, stamp_cost,
} }
} }
/// Store this message so its delivery can resume after a restart, under /// Create a representation the caller can persist to resume delivery after
/// the same id. The stored form keeps the signing stamp cost as a floor. /// a restart under the same ID. It retains the signing stamp cost as a floor;
/// this method performs no file or database write.
pub fn to_resumable(&self) -> ResumableLxMessage { pub fn to_resumable(&self) -> ResumableLxMessage {
ResumableLxMessage::new(&self.message.wire, self.stamp_cost) ResumableLxMessage::new(&self.message.wire, self.stamp_cost)
} }
@@ -373,6 +374,8 @@ impl SignedLxMessage {
self.outbound_ticket self.outbound_ticket
} }
/// Compute the optional recipient stamp without changing the signed body. /// Compute the optional recipient stamp without changing the signed body.
/// Runs synchronously; proof of work uses [`crate::stamper::generate_stamp`]
/// and its attempt budget.
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> { pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
if let Some(ticket) = self.outbound_ticket { if let Some(ticket) = self.outbound_ticket {
let mut material = [0u8; 48]; let mut material = [0u8; 48];
+35 -21
View File
@@ -164,11 +164,12 @@ pub struct LxmPeer {
pub stamp_cost_flexibility: Option<u8>, pub stamp_cost_flexibility: Option<u8>,
/// Peering cost used for outbound peering-key generation. /// Peering cost used for outbound peering-key generation.
pub peering_cost: u8, pub peering_cost: u8,
/// Generated peering key `(stamp, value)`. `None` until [`LxmPeer::generate_peering_key`] succeeds. /// Cached peering stamp and work value, generated or restored from storage.
/// Use [`Self::peering_key_ready`] to check it against the current cost.
pub peering_key: Option<([u8; 32], u32)>, pub peering_key: Option<([u8; 32], u32)>,
/// Per-transfer propagation limit in KB. /// Per-transfer propagation limit in decimal kilobytes (1 kB = 1000 bytes).
pub propagation_transfer_limit: Option<f64>, pub propagation_transfer_limit: Option<f64>,
/// Per-sync propagation limit in KB. /// Per-sync propagation limit in decimal kilobytes (1 kB = 1000 bytes).
pub propagation_sync_limit: Option<f64>, pub propagation_sync_limit: Option<f64>,
pub currently_transferring_messages: Option<Vec<PropagationTransientId>>, pub currently_transferring_messages: Option<Vec<PropagationTransientId>>,
pub link_alive: bool, pub link_alive: bool,
@@ -290,10 +291,13 @@ impl LxmPeer {
peer peer
} }
/// Refresh announce-derived policy only when `timebase` is newer. /// Refresh policy when the supplied `timebase` is newer. The caller must
/// keep both supplied and stored timebases finite; this method does not
/// validate them, and NaN bypasses the ordering guard.
/// ///
/// Returns `true` when the peer was updated. Runtime counters, handled /// Returns `true` when updated. Handled messages and static-peer status are
/// messages and static-peer status remain owned by the existing peer. /// retained. Calling `heard()` updates liveness/last-heard and resets the
/// unreachable count and sync backoff; the next sync attempt is reset to zero.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce( pub fn refresh_from_announce(
&mut self, &mut self,
@@ -316,7 +320,9 @@ impl LxmPeer {
) )
} }
/// Refresh announce-derived policy and bounded metadata only when newer. /// Refresh policy and bounded metadata with the ordering and liveness
/// behavior of [`Self::refresh_from_announce`]. Both supplied and stored
/// timebases must be finite; this method does not reject NaN.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce_with_metadata( pub fn refresh_from_announce_with_metadata(
&mut self, &mut self,
@@ -548,13 +554,15 @@ impl LxmPeer {
self.sync_backoff self.sync_backoff
} }
/// Peers unseen for [`PEER_STALE_TIME`] are stale and should be rotated to the back of the queue. /// Whether more than [`PEER_STALE_TIME`] seconds have elapsed since last heard.
/// This check does not rotate or remove the peer.
pub fn is_stale(&self) -> bool { pub fn is_stale(&self) -> bool {
let now = now_f64(); let now = now_f64();
now - self.last_heard > PEER_STALE_TIME as f64 now - self.last_heard > PEER_STALE_TIME as f64
} }
/// Whether the peering key has been generated and meets [`Self::peering_cost`]. /// Whether a cached key's recorded work value meets [`Self::peering_cost`].
/// This trusts the stored/public value; it does not revalidate the key.
pub fn peering_key_ready(&self) -> bool { pub fn peering_key_ready(&self) -> bool {
if let Some((_, value)) = self.peering_key { if let Some((_, value)) = self.peering_key {
value >= self.peering_cost as u32 value >= self.peering_cost as u32
@@ -563,7 +571,8 @@ impl LxmPeer {
} }
} }
/// Peering-key value (leading zero bits), if generated. /// Cached peering-key work value (leading zero bits), if present.
/// Restored or caller-supplied values are returned without recomputation.
pub fn peering_key_value(&self) -> Option<u32> { pub fn peering_key_value(&self) -> Option<u32> {
self.peering_key.map(|(_, value)| value) self.peering_key.map(|(_, value)| value)
} }
@@ -573,7 +582,12 @@ impl LxmPeer {
/// Key material is `peer_identity_hash || our_identity_hash` (16 + 16 bytes), run through the /// Key material is `peer_identity_hash || our_identity_hash` (16 + 16 bytes), run through the
/// stamp PoW system with [`STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING`] expand rounds. /// stamp PoW system with [`STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING`] expand rounds.
/// ///
/// Python reference: `LXMPeer.generate_peering_key` — LXMPeer.py:242-265. /// Returns immediately when a key is already cached; it does not revalidate
/// that key against a changed cost. Use [`Self::peering_key_ready`] for that
/// check. Otherwise runs synchronous proof of work with
/// [`crate::stamper::generate_stamp`]'s attempt budget.
///
/// Python reference: `LXMPeer.generate_peering_key`.
pub fn generate_peering_key( pub fn generate_peering_key(
&mut self, &mut self,
peer_identity_hash: &[u8; 16], peer_identity_hash: &[u8; 16],
@@ -625,7 +639,7 @@ impl LxmPeer {
/// `next_sync_attempt` so sync can proceed immediately, updates `last_heard`, and marks the /// `next_sync_attempt` so sync can proceed immediately, updates `last_heard`, and marks the
/// peer alive. /// peer alive.
/// ///
/// Python reference: LXMPeer.py:530-538. /// This updates local peer state; it does not identify the link or start a sync.
pub fn link_established(&mut self, _link_id: [u8; 16], establishment_rate: Option<f64>) { pub fn link_established(&mut self, _link_id: [u8; 16], establishment_rate: Option<f64>) {
if let Some(rate) = establishment_rate { if let Some(rate) = establishment_rate {
self.link_establishment_rate = rate; self.link_establishment_rate = rate;
@@ -637,12 +651,10 @@ impl LxmPeer {
self.link_alive = true; self.link_alive = true;
} }
/// Link-closed callback: clears the link and transitions to [`PeerState::Idle`]. /// Clear the link-alive flag and transition to [`PeerState::Idle`].
/// ///
/// If the peer was mid-sync, the in-flight transfer list is cleared so backoff logic /// If the previous state was active, clear the in-flight transfer list.
/// treats it as a sync failure. /// This callback does not itself increment backoff or mark the peer unreachable.
///
/// Python reference: LXMPeer.py:540-542.
pub fn link_closed(&mut self) { pub fn link_closed(&mut self) {
let was_active = self.state != PeerState::Idle; let was_active = self.state != PeerState::Idle;
self.link_alive = false; self.link_alive = false;
@@ -694,11 +706,13 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
} }
} }
/// Select the best peer to sync with from a set of candidates. /// Return the input index of an idle peer with unhandled messages.
/// ///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers, /// Alive peers take priority: sort them by descending transfer rate and choose
/// mix in unknown-speed peers, and fall back to unresponsive peers that have passed their sync /// the first. This selection is deterministic; adding unknown-speed peers to
/// backoff. /// the candidate pool does not randomize the choice as Python `sync_peers()` does.
/// If no alive peer qualifies, choose the first unresponsive peer whose backoff
/// has elapsed. Backoff is not checked in the alive-peer branch.
pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> { pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> {
if peers.is_empty() { if peers.is_empty() {
return None; return None;
+11 -7
View File
@@ -1,14 +1,18 @@
//! Persistent router state — matches Python `<storagepath>/lxmf/` layout. //! Router state files in a caller-supplied directory.
//! //!
//! Files: //! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>` //! * `outbound_stamp_costs` — destination stamp costs and observation times
//! * `available_tickets` — versioned directional ticket state //! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>` //! * `local_deliveries` — delivered transient IDs and timestamps
//! * `locally_processed` — `HashMap<transient_id, timestamp>` //! * `locally_processed` — processed transient IDs and timestamps
//! * `node_stats` — propagation-node counters
//! * `propagation_suppression_v1` — bounded download suppression records
//! * `propagation_node_policies_v1` — recorded propagation-node policies
//! //!
//! All four files are MessagePack-encoded via `rmp-serde`. Missing files are //! These files use the Rust types' MessagePack representations; matching Python
//! treated as "no prior state" and do not raise errors — a fresh daemon is a //! filenames does not establish interchangeable contents. Missing files yield
//! valid state. //! empty/default state. Other I/O, malformed-data and capacity errors propagate
//! to the caller.
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
+5 -3
View File
@@ -7,9 +7,11 @@ pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name. /// Normalize and bound an untrusted display name.
/// ///
/// The result is NFKC-normalized, contains no control or presentation-control /// Applies NFKC normalization and filters control characters, bidi controls,
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is /// private-use characters, selected zero-width characters, variation selectors,
/// truncated by Unicode scalar values rather than UTF-8 bytes. /// and broad emoji/symbol ranges. Tabs and newlines are removed. Remaining
/// whitespace collapses to one ASCII space, with no leading or trailing space.
/// The length limit counts Unicode scalar values, not UTF-8 bytes.
pub fn sanitize_name(input: &str, max_chars: usize) -> String { pub fn sanitize_name(input: &str, max_chars: usize) -> String {
let mut output = sanitize_name_pass(input, max_chars); let mut output = sanitize_name_pass(input, max_chars);
let rounds = output.nfkd().count().saturating_add(2); let rounds = output.nfkd().count().saturating_add(2);
+23 -11
View File
@@ -1,6 +1,7 @@
//! Store-and-forward message storage for LXMF propagation nodes. //! In-memory propagation-entry accounting, deduplication caches and distribution queue.
//! //!
//! Mirrors propagation entry management in Python LXMRouter.py. //! The owning router or node handles durable files and admission. Weight-based
//! culling uses the formula from Python `LXMRouter.get_weight`.
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -17,7 +18,7 @@ pub struct PropagationEntry {
pub stamp_value: u8, pub stamp_value: u8,
pub size: usize, pub size: usize,
pub collected: bool, pub collected: bool,
/// Stored file contains `lxmf_data || propagation_stamp`. /// When true, the stored file contains `lxmf_data || propagation_stamp`.
/// ///
/// Client download strips the stamp; peer sync keeps it. /// Client download strips the stamp; peer sync keeps it.
pub stamped: bool, pub stamped: bool,
@@ -73,7 +74,11 @@ impl PropagationEntry {
/// Accepts canonical 64-hex transient IDs in both the 3-component format /// Accepts canonical 64-hex transient IDs in both the 3-component format
/// and the older 2-component `{transient_id}_{timestamp}` form (stamp_value /// and the older 2-component `{transient_id}_{timestamp}` form (stamp_value
/// defaults to 0). Pre-fix 32-hex transient IDs are rejected. /// defaults to 0). Shortened 32-hex transient IDs are rejected.
///
/// # Panics
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
/// Validate that untrusted filenames are ASCII before calling.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> { pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
let parts: Vec<&str> = filename.split('_').collect(); let parts: Vec<&str> = filename.split('_').collect();
match parts.len() { match parts.len() {
@@ -93,7 +98,8 @@ impl PropagationEntry {
} }
} }
/// Owned by the router actor; no shared access. /// In-memory index and accounting state. Mutations require exclusive access;
/// the owner handles synchronization, durable storage and admission policy.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct PropagationStore { pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>, entries: HashMap<PropagationTransientId, PropagationEntry>,
@@ -106,7 +112,8 @@ pub struct PropagationStore {
/// Prioritised destinations receive a 0.1x weight multiplier during culling. /// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[u8; 16]>, prioritised_destinations: HashSet<[u8; 16]>,
peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>, peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>,
/// `None` disables the byte-size cap. /// Optional byte-limit setting. This type does not enforce it automatically;
/// the owner must call culling with its chosen limit.
pub storage_limit: Option<usize>, pub storage_limit: Option<usize>,
} }
@@ -116,6 +123,10 @@ impl PropagationStore {
} }
/// Returns `false` if the destination is in the ignored list. /// Returns `false` if the destination is in the ignored list.
///
/// The caller must exclude an existing transient ID before inserting.
/// Replacing one adds the new size without subtracting the previous size.
/// This method performs no persistence, stamp validation or size-limit check.
pub fn insert(&mut self, entry: PropagationEntry) -> bool { pub fn insert(&mut self, entry: PropagationEntry) -> bool {
if self.ignored_destinations.contains(&entry.destination_hash) { if self.ignored_destinations.contains(&entry.destination_hash) {
return false; return false;
@@ -178,11 +189,12 @@ impl PropagationStore {
} }
} }
/// Cull messages by weighted score until total size is within `limit_bytes`. /// Remove indexed entries by weighted score until accounted size is within
/// `limit_bytes`, assuming each transient ID was inserted only once.
/// ///
/// Score = priority_weight * age_weight * size. Evicts highest-weight first /// Score = priority_weight * age_weight * size. Highest scores go first,
/// (oldest + largest + non-prioritised). Matches Python /// using Python `LXMRouter.get_weight`'s formula. This updates the in-memory
/// `clean_message_store()` in LXMRouter.py. /// index and byte count; it does not delete message files.
pub fn cull_by_weight(&mut self, limit_bytes: usize) { pub fn cull_by_weight(&mut self, limit_bytes: usize) {
if self.total_size <= limit_bytes { if self.total_size <= limit_bytes {
return; return;
@@ -299,7 +311,7 @@ impl PropagationStore {
} }
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python /// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
/// `LXMRouter.clean_transient_id_caches`, LXMRouter.py:956). Retention is /// `LXMRouter.clean_transient_id_caches`). Retention is
/// purely age-based: entries must outlive their store membership so a /// purely age-based: entries must outlive their store membership so a
/// culled-and-reoffered message is still recognised as already handled. /// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) { pub fn clean_transient_caches(&mut self, now: f64) {
@@ -23,9 +23,9 @@ use crate::constants::PN_STAMP_THROTTLE;
const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation"; const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation";
/// Default maximum number of concurrently transferring or validating syncs. /// Default active-sync threshold used when admitting new offers.
pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3; pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3;
/// Smallest accepted configured inbound-sync limit. /// Lower bound applied to the configured inbound-sync threshold.
pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1; pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1;
/// Duration applied after a known peer submits an invalid-stamp batch. /// Duration applied after a known peer submits an invalid-stamp batch.
pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE); pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE);
@@ -40,7 +40,9 @@ pub struct PnInboundAdmissionConfig {
/// The LXMF default is `false`, so a configured static peer bypasses both /// The LXMF default is `false`, so a configured static peer bypasses both
/// admission gates. /// admission gates.
pub static_sequential: bool, pub static_sequential: bool,
/// Maximum concurrent Resources in `Transferring` or `Validating` state. /// Reject new non-bypassing offers when this many records are Transferring
/// or Validating. Values below one are clamped to one. Accepted offers do
/// not reserve slots, and starting them does not recheck this threshold.
pub max_inbound_syncs: usize, pub max_inbound_syncs: usize,
/// Accept propagation offers only from configured static peers. /// Accept propagation offers only from configured static peers.
pub from_static_only: bool, pub from_static_only: bool,
@@ -286,7 +288,8 @@ impl PnInboundAdmission {
/// ///
/// A successful preflight creates no admission record. The returned /// A successful preflight creates no admission record. The returned
/// candidate binds the link and peer values that the caller must use for /// candidate binds the link and peer values that the caller must use for
/// external key validation. /// external key validation. The caller must supply the remote identity
/// verified on that Link; this coordinator receives hashes, not identity proofs.
pub fn preflight_offer( pub fn preflight_offer(
&mut self, &mut self,
link_id: [u8; 16], link_id: [u8; 16],
@@ -461,6 +464,7 @@ impl PnInboundAdmission {
} }
/// Transition an accepted offer when its inbound Resource starts. /// Transition an accepted offer when its inbound Resource starts.
/// This checks the previous state but does not rerun offer admission gates.
pub fn resource_started(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> { pub fn resource_started(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> {
self.transition( self.transition(
link_id, link_id,
@@ -480,7 +484,7 @@ impl PnInboundAdmission {
) )
} }
/// Conclude stamp validation and release all active accounting. /// Conclude stamp validation and release this link's active accounting.
/// ///
/// Only [`PnValidationResult::InvalidStamp`] installs a throttle, and a /// Only [`PnValidationResult::InvalidStamp`] installs a throttle, and a
/// throttle is possible only for a known peer retained in a valid record. /// throttle is possible only for a known peer retained in a valid record.
+51 -20
View File
@@ -1,16 +1,24 @@
//! Client-side propagation node download protocol. //! Client-side propagation node downloads, driven by the caller through
//! [`PropagationClient::drain_events`] and [`PropagationClient::tick`].
//! //!
//! Python reference: LXMRouter.py:484-587. //! The `/get` wire exchange corresponds to Python
//! `LXMRouter.request_messages_from_propagation_node()`.
//! //!
//! Protocol flow: //! 1. Establish a Link and identify with the configured public/signing key pair.
//! 1. Establish link to the propagation node destination. //! Without that pair, no identification is sent; an authenticating node rejects the request.
//! 2. Identify on the link (LinkIdentify). //! 2. Request `/get` with `[None, None]` to list available transient IDs.
//! 3. Request `/get` with `[None, None]` -- server returns available transient IDs. //! 3. Separate caller-installed durable haves from eligible wants. Purge those
//! 4. Client sorts into wants/haves. //! haves unless retention is enabled, then request bounded wants chunks.
//! 5. Purge known haves, then request bounded wants chunks with a per-transfer limit. //! 4. Validate the returned ciphertext IDs, membership, count and byte budget.
//! 6. Server returns `[lxmf_data_1, lxmf_data_2, ...]`. //! Pass downloaded payloads and admission tokens to the application's durable adapter.
//! 7. Client processes received messages. //! 5. Await local admission decisions. Only accepted durable receipts authorize
//! 8. `/get` with `[None, received_ids]` purges each downloaded batch before the next chunk. //! purging newly downloaded IDs; rejected items remain available for retry.
//! 6. Purge accepted IDs before requesting the next chunk. The retention option
//! applies to previously known haves, not these newly accepted downloads.
//!
//! Suppression records delay new wants but never authorize remote deletion.
//! Persist suppression changes and acknowledge their current revision before
//! further wants can proceed.
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{ use std::sync::{
@@ -57,9 +65,9 @@ pub enum PropagationClientState {
Receiving, Receiving,
/// `/get` with `[None, received_ids]` sent. /// `/get` with `[None, received_ids]` sent.
PurgeRequested, PurgeRequested,
/// Download bytes await a durable local application decision. /// Waiting for local admission decisions or a durable suppression checkpoint.
AwaitingAdmission, AwaitingAdmission,
/// At least one item was retained remotely for retry/revalidation. /// At least one downloaded item lacked durable local acceptance in this cycle.
Partial, Partial,
Complete, Complete,
Failed, Failed,
@@ -333,21 +341,31 @@ impl PropagationClient {
self.outbound_propagation_node = Some(dest_hash); self.outbound_propagation_node = Some(dest_hash);
} }
/// KB per transfer. /// Set the requested server response budget in decimal kB (1000 bytes).
/// The value is sent unchanged in `/get`; supply a finite positive number.
/// Local Resource and admission byte limits still apply independently.
pub fn set_delivery_limit(&mut self, limit_kb: f64) { pub fn set_delivery_limit(&mut self, limit_kb: f64) {
self.delivery_limit = Some(limit_kb); self.delivery_limit = Some(limit_kb);
} }
/// Trust this ID as a durable local have, with no expiry. It may authorize
/// remote purge on the next download cycle unless retention is enabled.
/// The caller must establish the durable local effect; this method does not verify it.
pub fn add_local_message(&mut self, transient_id: PropagationTransientId) { pub fn add_local_message(&mut self, transient_id: PropagationTransientId) {
self.local_message_expiry.remove(transient_id.as_slice()); self.local_message_expiry.remove(transient_id.as_slice());
self.local_messages.insert(transient_id.to_vec()); self.local_messages.insert(transient_id.to_vec());
} }
/// Trust a caller-supplied transient ID as a durable local have with no expiry.
/// This has the same purge authority as [`Self::add_local_message`]; it does
/// not check the ID length or verify a durable local effect.
pub fn add_local_message_id(&mut self, transient_id: Vec<u8>) { pub fn add_local_message_id(&mut self, transient_id: Vec<u8>) {
self.local_message_expiry.remove(&transient_id); self.local_message_expiry.remove(&transient_id);
self.local_messages.insert(transient_id); self.local_messages.insert(transient_id);
} }
/// Replace all local haves and clear their expiry times. Every supplied ID
/// is trusted as durable purge authority; lengths and local effects are not checked.
pub fn replace_local_message_ids<I>(&mut self, transient_ids: I) pub fn replace_local_message_ids<I>(&mut self, transient_ids: I)
where where
I: IntoIterator<Item = Vec<u8>>, I: IntoIterator<Item = Vec<u8>>,
@@ -356,6 +374,9 @@ impl PropagationClient {
self.local_message_expiry.clear(); self.local_message_expiry.clear();
} }
/// Replace local purge authority from the durable adapter, preserving expiry
/// times and pruning expired haves. This trusts the supplied records; it does
/// not revalidate stored files or commit new local effects.
pub fn replace_durable_haves( pub fn replace_durable_haves(
&mut self, &mut self,
haves: impl IntoIterator<Item = crate::admission::DurableHave>, haves: impl IntoIterator<Item = crate::admission::DurableHave>,
@@ -398,6 +419,9 @@ impl PropagationClient {
} }
} }
/// Keep previously known local haves on the node during subsequent selection.
/// Newly downloaded messages accepted through admission are still purged;
/// this flag does not provide retention for those messages.
pub fn set_retain_synced_on_node(&mut self, retain: bool) { pub fn set_retain_synced_on_node(&mut self, retain: bool) {
self.retain_synced_on_node = retain; self.retain_synced_on_node = retain;
} }
@@ -477,7 +501,9 @@ impl PropagationClient {
pub fn suppression_revision(&self) -> u64 { pub fn suppression_revision(&self) -> u64 {
self.suppression_revision self.suppression_revision
} }
/// A slow checkpoint must never reinstall an older ledger over new state. /// Acknowledge a completed durable checkpoint only if its revision is still
/// current. Returns `false` after intervening changes; otherwise clears the
/// dirty/failure flags without replacing the ledger. The caller performs the write.
pub fn acknowledge_suppression_persistence(&mut self, revision: u64) -> bool { pub fn acknowledge_suppression_persistence(&mut self, revision: u64) -> bool {
if revision != self.suppression_revision { if revision != self.suppression_revision {
return false; return false;
@@ -493,8 +519,9 @@ impl PropagationClient {
pub fn take_suppression_updates(&mut self) -> Vec<SuppressionRecord> { pub fn take_suppression_updates(&mut self) -> Vec<SuppressionRecord> {
std::mem::take(&mut self.suppression_updates) std::mem::take(&mut self.suppression_updates)
} }
/// The adapter must report a failed durable suppression update. Automatic /// Report a failed durable suppression update and pause new wants. Resume
/// new wants pause until persisted state is installed after recovery. /// after durably checkpointing and acknowledging the current revision, or
/// installing persisted state after recovery.
pub fn suppression_persistence_failed(&mut self) { pub fn suppression_persistence_failed(&mut self) {
self.suppression_persist_failed = true; self.suppression_persist_failed = true;
} }
@@ -534,8 +561,10 @@ impl PropagationClient {
self.start_download_with_limit(None) self.start_download_with_limit(None)
} }
/// Start a propagation download, limiting newly requested messages. /// Start a propagation download, limiting newly requested messages across
/// `None` and zero mirror Python's `PR_ALL_MESSAGES`. /// the whole cycle. `None` and zero select all eligible messages, as with
/// Python's `PR_ALL_MESSAGES`. Returns `false` while active, without a node,
/// with queued downloads, or while suppression persistence blocks a restart.
/// Move live downloads into the durable adapter before restarting. Failure /// Move live downloads into the durable adapter before restarting. Failure
/// or cancellation drops the client-owned queue and revokes its tokens; /// or cancellation drops the client-owned queue and revokes its tokens;
/// already moved payload/worker owners retain their memory leases. /// already moved payload/worker owners retain their memory leases.
@@ -649,7 +678,9 @@ impl PropagationClient {
true true
} }
/// Cancel an active request and return to the idle state. /// Revoke current admissions, drop client-owned downloads and return to idle.
/// External payload/worker owners retain their memory leases. Link cleanup
/// is queued; this call does not wait for network teardown to complete.
pub fn cancel_download(&mut self) { pub fn cancel_download(&mut self) {
self.cleanup(); self.cleanup();
self.status = PropagationTransferStatus::default(); self.status = PropagationTransferStatus::default();
+102 -70
View File
@@ -1,9 +1,10 @@
//! Store-and-forward propagation node with optional disk persistence. //! Propagation-node storage admission, peer offer selection and client GET plans.
//! //!
//! Mirrors propagation node management in Python LXMRouter.py. Provides //! Durable network deposits require a disk-backed v2 store. The node reserves
//! message acceptance with size/duplicate checks, sync offer generation with //! admission under its owner lock, publishes opaque bytes and provenance on a
//! per-peer filtering, peer persistence (save/load with handled message sets), //! blocking worker, then commits in-memory accounting. Expiry and quota culling
//! and expired message culling with orphaned file cleanup. //! retire indexed entries; unindexed legacy or orphan files are not promoted or
//! removed by ordinary maintenance.
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::PathBuf; use std::path::PathBuf;
@@ -18,15 +19,20 @@ use crate::types::PropagationTransientId;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PropagationNodeConfig { pub struct PropagationNodeConfig {
/// Stored-byte admission threshold. One new message may cross it: admission
/// checks current stored plus reserved bytes. Run maintenance to cull excess.
/// This is not a hard maximum for the resulting stored byte count.
pub max_storage: usize, pub max_storage: usize,
pub max_message_age: u64, pub max_message_age: u64,
/// Messages below this effective stamp value are rejected. Python derives /// Messages below this effective stamp value are rejected. Python derives
/// this from `propagation_stamp_cost - propagation_stamp_cost_flexibility`. /// this from `propagation_stamp_cost - propagation_stamp_cost_flexibility`.
pub min_stamp_cost: u8, pub min_stamp_cost: u8,
pub peering_cost: u8, pub peering_cost: u8,
/// Maximum newly admitted image size in bytes, including the 32-byte PN stamp.
pub max_message_size: usize, pub max_message_size: usize,
/// Maximum encoded inbound `/offer` request size. This follows the /// Maximum encoded inbound `/offer` request size in bytes. The default
/// node's advertised propagation sync budget. /// uses [`SYNC_LIMIT`] in decimal kilobytes; the caller must keep this
/// setting aligned with its advertised sync budget.
pub max_offer_size: usize, pub max_offer_size: usize,
} }
@@ -126,10 +132,10 @@ fn get_ids(input: Option<&[u8]>) -> impl Iterator<Item = PropagationTransientId>
}) })
} }
/// Outcome of [`PropagationNode::handle_get_request`]. Phases 1/3 (and /// Immediate GET response or deferred file-work plan. Listing and malformed
/// malformed input) are answered from the store alone; phase 2 returns a /// requests can return bytes directly. Requests with wants or haves produce
/// read plan so the embedder performs blocking file I/O after releasing /// a plan for durable retirements and reads, including purge-only requests.
/// the node lock. /// Resolve that plan after releasing the node lock.
#[derive(Debug)] #[derive(Debug)]
pub enum GetRequestAction { pub enum GetRequestAction {
Respond(Vec<u8>), Respond(Vec<u8>),
@@ -137,21 +143,22 @@ pub enum GetRequestAction {
} }
impl GetRequestAction { impl GetRequestAction {
/// Resolve to response bytes, performing any planned file reads inline. /// Resolve to response bytes, performing planned retirements and reads inline.
/// Blocking; do not call while holding a shared node lock. /// Blocking; do not call while holding a shared node lock.
pub fn into_response(self) -> Vec<u8> { pub fn into_response(self) -> Vec<u8> {
self.into_response_with_served_count().0 self.into_response_with_served_count().0
} }
/// Resolve the response and report how many messages were actually read /// Perform deferred retirements/reads and return the response with its
/// and admitted by the client's transfer limit. This lets the daemon keep /// served-message count. Only successfully read messages that fit the
/// Python-compatible served-message accounting without repeating I/O. /// client/local limits count. This method blocks when file work is planned.
pub fn into_response_with_served_count(self) -> (Vec<u8>, u64) { pub fn into_response_with_served_count(self) -> (Vec<u8>, u64) {
self.into_response_with_served_count_bounded(rns_protocol::resource::MAX_RESOURCE_SIZE) self.into_response_with_served_count_bounded(rns_protocol::resource::MAX_RESOURCE_SIZE)
} }
/// Resolve on a blocking worker with its previously reserved local response /// Perform deferred retirements/reads using a previously reserved local
/// allowance. Complete messages are skipped when they cannot fit. /// response allowance. The caller runs this on a blocking worker; this
/// method does not spawn one. Complete messages are skipped if they cannot fit.
pub fn into_response_with_served_count_bounded(self, maximum: usize) -> (Vec<u8>, u64) { pub fn into_response_with_served_count_bounded(self, maximum: usize) -> (Vec<u8>, u64) {
match self { match self {
GetRequestAction::Respond(bytes) if bytes.len() <= maximum => (bytes, 0), GetRequestAction::Respond(bytes) if bytes.len() <= maximum => (bytes, 0),
@@ -161,8 +168,9 @@ impl GetRequestAction {
} }
} }
/// Phase-2 read plan: wants resolved and ownership-gated under the node /// GET plan containing ownership-filtered wants and haves.
/// lock; [`GetServePlan::serve`] does the file reads outside it. /// [`Self::serve`] performs durable haves retirement before reading wants,
/// outside the node lock. A purge-only request has no reads.
#[derive(Debug)] #[derive(Debug)]
pub struct GetServePlan { pub struct GetServePlan {
reads: Vec<PlannedRead>, reads: Vec<PlannedRead>,
@@ -179,11 +187,12 @@ struct PlannedRead {
} }
impl GetServePlan { impl GetServePlan {
/// Read planned files and encode the phase-2 response. Mirrors Python /// Retire planned haves, then read wants and encode the response. A retirement
/// LXMRouter.message_get_request limit accounting (LXMRouter.py:1477-1494): /// error returns MessagePack nil. Client-limit accounting follows Python
/// 24-byte base + 16 bytes per message, full stored size counted, /// `LXMRouter.message_get_request`: a 24-byte base plus each full stored size
/// over-limit entries skipped (not a transfer abort), stamps stripped /// and 16 bytes per message. Over-limit or unreadable entries are skipped;
/// for client download. Unreadable files are skipped. /// stored propagation stamps are stripped for client download. Local encoded
/// response capacity is checked separately. This method blocks.
pub fn serve(&self) -> Vec<u8> { pub fn serve(&self) -> Vec<u8> {
self.serve_with_count().0 self.serve_with_count().0
} }
@@ -362,6 +371,7 @@ pub struct PlannedMessageRead {
/// Blocking reads for a plan from [`PropagationNode::plan_message_reads`]; /// Blocking reads for a plan from [`PropagationNode::plan_message_reads`];
/// call without holding the node lock. Missing/unreadable files are skipped. /// call without holding the node lock. Missing/unreadable files are skipped.
/// Returned images retain their stored propagation stamps.
pub fn read_planned_messages( pub fn read_planned_messages(
plan: &[PlannedMessageRead], plan: &[PlannedMessageRead],
) -> Vec<(PropagationTransientId, Vec<u8>)> { ) -> Vec<(PropagationTransientId, Vec<u8>)> {
@@ -664,7 +674,8 @@ pub struct PropagationNode {
} }
impl PropagationNode { impl PropagationNode {
/// In-memory node (no disk persistence). /// In-memory bookkeeping node. It cannot acknowledge durable network deposits;
/// use [`Self::with_storage`] for hosted propagation storage.
pub fn new(config: PropagationNodeConfig, dest_hash: [u8; 16]) -> Self { pub fn new(config: PropagationNodeConfig, dest_hash: [u8; 16]) -> Self {
Self { Self {
config, config,
@@ -732,7 +743,10 @@ impl PropagationNode {
self.offer_generation = self.offer_generation.saturating_add(1); self.offer_generation = self.offer_generation.saturating_add(1);
} }
/// Disk-backed node. Loads existing messages from `storage_path` on startup. /// Open a disk-backed v2 store, retain its hosting lock, and load indexed entries.
/// `storage_path` identifies the legacy/base path; its parent must exist.
/// Historical stores or incomplete migrations require explicit offline
/// migration rather than automatic promotion of existing files.
pub fn with_storage( pub fn with_storage(
config: PropagationNodeConfig, config: PropagationNodeConfig,
dest_hash: [u8; 16], dest_hash: [u8; 16],
@@ -807,7 +821,9 @@ impl PropagationNode {
}) })
} }
/// Release a reservation after a failed blocking write. /// Release failed-write accounting after its owning plan has been dropped.
/// Supply the plan's original transient ID and size. A still-live reservation
/// owner prevents release.
pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) { pub fn abort_store_write(&mut self, transient_id: &PropagationTransientId, size: usize) {
if self if self
.pending_admissions .pending_admissions
@@ -876,12 +892,13 @@ impl PropagationNode {
} }
} }
/// Store a validated propagated LXMF blob with its propagation-node stamp. /// Validate and reserve a new opaque propagation image plus its 32-byte stamp.
/// Checks the measured stamp value against `stamp_value` and node policy;
/// this method does not persist the returned plan.
/// ///
/// Canonical propagation-node storage mirrors upstream Python: keep /// Stored images retain `lxmf_data || stamp` for peer sync. Client `/get`
/// `lxmf_data || stamp` on disk so peer sync can forward proof-carrying /// strips that stamp. Duplicates return `None`; use [`Self::plan_opaque_admission`]
/// data. Client `/get` strips the final 32-byte stamp before returning /// when the caller needs pending/committed duplicate outcomes.
/// messages to recipients.
pub fn plan_accept_stamped_propagated_blob( pub fn plan_accept_stamped_propagated_blob(
&mut self, &mut self,
lxmf_data: &[u8], lxmf_data: &[u8],
@@ -904,8 +921,11 @@ impl PropagationNode {
_ => None, _ => None,
} }
} }
/// Preferred network admission API. Same-TID exact-image duplicates share /// Plan a durable network admission or observe an existing one. Pending
/// the original completion and never perform a second disk write. /// same-TID duplicates must have identical complete bytes and share the
/// original completion. A committed TID retains its first stored image and
/// returns a separate durability/provenance check; it is not overwritten.
/// Volatile nodes reject this operation.
pub fn plan_opaque_admission( pub fn plan_opaque_admission(
&mut self, &mut self,
blob: ValidatedOpaquePropagationBlob, blob: ValidatedOpaquePropagationBlob,
@@ -1109,7 +1129,9 @@ impl PropagationNode {
} }
} }
/// Returns only messages the peer has not already received. /// Return indexed IDs absent from the caller's handled set. This compatibility
/// helper does not apply stamp/transfer policy or pending-retirement filtering;
/// use [`Self::prepare_sync_offer_with_policy`] for a peer-policy offer.
pub fn create_offer_filtered( pub fn create_offer_filtered(
&self, &self,
handled: &HashSet<PropagationTransientId>, handled: &HashSet<PropagationTransientId>,
@@ -1198,9 +1220,9 @@ impl PropagationNode {
} }
} }
/// Inverse-offer pattern: the peer lists what it has; we return the IDs /// Local inverse-set helper: return indexed IDs absent from `offered_ids`.
/// we hold that the peer does not. Python reference: /// This is not the network `/offer` handler and performs no peer admission
/// LXMRouter.offer_request_received(). /// or pending-retirement filtering.
pub fn offer_request( pub fn offer_request(
&mut self, &mut self,
_peer_hash: [u8; 16], _peer_hash: [u8; 16],
@@ -1238,8 +1260,8 @@ impl PropagationNode {
crate::encode_value(&value) crate::encode_value(&value)
} }
/// Handle a Link REQUEST at the `/offer` path. Python reference: /// Handle a Link REQUEST at the `/offer` path. Related Python handler:
/// LXMRouter.offer_request() (LXMRouter.py:2139-2189). /// `LXMRouter.offer_request`.
/// ///
/// `request_data` is msgpack `[peering_key, [transient_id_1, ...]]`. /// `request_data` is msgpack `[peering_key, [transient_id_1, ...]]`.
/// Transitional compatibility wrapper for callers that still compute the /// Transitional compatibility wrapper for callers that still compute the
@@ -1314,16 +1336,17 @@ impl PropagationNode {
) )
} }
/// Handle a Link REQUEST at the `/get` path for client download. Python /// Plan a Link REQUEST at `/get` for an already authenticated client. The
/// reference: LXMRouter.message_get_request() (LXMRouter.py:1425-1499). /// caller binds `client_dest_hash` to that identity and enforces access policy.
/// Related Python handler: `LXMRouter.message_get_request`.
/// ///
/// Wire format is msgpack `[wants, haves]` or `[wants, haves, delivery_limit]`: /// Wire format is msgpack `[wants, haves]` or `[wants, haves, delivery_limit]`:
/// - Phase 1 (list): `[None, None]` -> available transient IDs for the client, /// - Phase 1 (list): `[None, None]` -> available transient IDs for the client,
/// smallest message first (Python sorts by file size ascending). /// smallest message first (Python sorts by file size ascending).
/// - Phase 2 (get): `[[wants...], [haves...]]` -> haves are purged first /// - Phase 2 (get): `[[wants...], [haves...]]` -> a [`GetServePlan`] retires
/// (Python order), then wants resolve to a [`GetServePlan`] whose file /// haves before reading wants when resolved on the blocking worker.
/// reads the embedder performs without holding the node lock. /// - Phase 3 (purge): `[None, [received_ids...]]` -> the same deferred plan
/// - Phase 3 (purge): `[None, [received_ids...]]` -> delete from store. /// with retirements and no reads. Planning itself performs no file I/O.
pub fn handle_get_request( pub fn handle_get_request(
&mut self, &mut self,
request_data: &[u8], request_data: &[u8],
@@ -1442,7 +1465,9 @@ impl PropagationNode {
/// Resolve requested transient IDs into store-file read plans (no I/O). /// Resolve requested transient IDs into store-file read plans (no I/O).
/// Perform the reads via [`read_planned_messages`] after releasing the /// Perform the reads via [`read_planned_messages`] after releasing the
/// node lock. Returns an empty vec when there is no disk storage. /// node lock. Returns an empty vec when there is no disk storage. The caller
/// must enforce any destination or offered-ID restrictions before using this
/// helper; it selects existing eligible IDs without those authorization checks.
pub fn plan_message_reads( pub fn plan_message_reads(
&self, &self,
requested_ids: &[PropagationTransientId], requested_ids: &[PropagationTransientId],
@@ -1466,9 +1491,9 @@ impl PropagationNode {
.collect() .collect()
} }
/// Fetch raw packed message data for each requested transient ID. Python /// Fetch full stored opaque images, including propagation stamps, for the
/// reference: LXMRouter.message_get_request_received(). Blocking /// supplied IDs. Blocking convenience over [`Self::plan_message_reads`],
/// convenience over [`Self::plan_message_reads`] — prefer the staged pair /// with the same caller authorization responsibility. Prefer the staged pair
/// when the node sits behind a shared lock. /// when the node sits behind a shared lock.
pub fn message_get_request( pub fn message_get_request(
&self, &self,
@@ -1477,9 +1502,10 @@ impl PropagationNode {
read_planned_messages(&self.plan_message_reads(requested_ids)) read_planned_messages(&self.plan_message_reads(requested_ids))
} }
/// Produce a `SyncOffer` listing message IDs the peer has not yet handled. /// Blocking compatibility wrapper: load the peer policy from disk, falling
/// The caller sends it over an established link. Python reference: /// back to [`OutboundOfferPolicy::unrestricted`] if unavailable, then prepare
/// LXMRouter.sync_request_received(). /// an offer. Prefer an authoritative live policy snapshot. The returned
/// [`SyncOffer`] is local data; the network task encodes the binary `/offer` wire form.
pub fn prepare_sync_offer(&mut self, peer_hash: [u8; 16]) -> SyncOffer { pub fn prepare_sync_offer(&mut self, peer_hash: [u8; 16]) -> SyncOffer {
let policy = self let policy = self
.load_peer(&peer_hash) .load_peer(&peer_hash)
@@ -1552,11 +1578,15 @@ impl PropagationNode {
/// Prepare one offer from an authoritative peer-policy snapshot. /// Prepare one offer from an authoritative peer-policy snapshot.
/// ///
/// Selection mirrors `LXMPeer.sync`: only existing, unhandled messages /// Select eligible unhandled messages by ascending weight, filtering stamp
/// meeting the peer's stamp and transfer limits are eligible. Candidates /// and per-message limits before the cumulative sync cap, as in Python
/// are ordered by ascending store weight before the cumulative sync cap is /// `LXMPeer.sync`. The session retains the chosen IDs; the network task uses
/// applied. The chosen IDs are retained in the session so a subsequent /// them to validate responses. [`Self::process_sync_get`] does not perform
/// response cannot request data outside this offer. /// that membership check.
///
/// This compatibility wrapper performs blocking peer-file reads and may
/// persist terminal handled-ID updates. The network task stages this work
/// outside the node lock.
pub fn prepare_sync_offer_with_policy(&mut self, policy: &OutboundOfferPolicy) -> SyncOffer { pub fn prepare_sync_offer_with_policy(&mut self, policy: &OutboundOfferPolicy) -> SyncOffer {
loop { loop {
let snapshot = self.snapshot_sync_offer_preparation(policy); let snapshot = self.snapshot_sync_offer_preparation(policy);
@@ -1582,8 +1612,9 @@ impl PropagationNode {
} }
} }
/// Compare a peer's `SyncOffer` against our store and return a `SyncGet` /// Local compatibility helper: select offered 32-byte IDs absent from the
/// listing IDs we want. Python reference: LXMRouter.offer_request_received(). /// index and replace this peer's session. It does not validate a peering key
/// or apply the network offer-admission policy.
pub fn process_sync_offer(&mut self, peer_hash: [u8; 16], offer: &SyncOffer) -> SyncGet { pub fn process_sync_offer(&mut self, peer_hash: [u8; 16], offer: &SyncOffer) -> SyncGet {
// process_offer needs &self.store; compute the get before mutating sync_sessions. // process_offer needs &self.store; compute the get before mutating sync_sessions.
let mut tmp_session = SyncSession::new(peer_hash); let mut tmp_session = SyncSession::new(peer_hash);
@@ -1592,9 +1623,10 @@ impl PropagationNode {
result result
} }
/// Return the packed message data for each ID in `get`. The caller /// Blocking compatibility helper returning full stored images for the valid
/// transfers each blob as a Resource over the link. Python reference: /// 32-byte IDs in `get`. This does not restrict requests to a previous offer;
/// LXMRouter.message_get_request_received(). /// the caller must validate that membership. The network task in
/// [`crate::propagation_sync`] filters responses and constructs the batch wire format.
pub fn process_sync_get(&mut self, peer_hash: [u8; 16], get: &SyncGet) -> Vec<Vec<u8>> { pub fn process_sync_get(&mut self, peer_hash: [u8; 16], get: &SyncGet) -> Vec<Vec<u8>> {
if let Some(session) = self.sync_sessions.get_mut(&peer_hash) { if let Some(session) = self.sync_sessions.get_mut(&peer_hash) {
session.process_get(get); session.process_get(get);
@@ -1623,11 +1655,10 @@ impl PropagationNode {
.collect() .collect()
} }
/// Record a successful transfer for a peer. Loads the peer, adds the /// Best-effort blocking bookkeeping for a successful peer transfer. If the
/// transient ID to its handled set, saves it, and records the transfer in /// peer loads, add the ID and attempt to save; save errors are ignored.
/// the sync session. Python reference: /// An existing session's transfer counter increments independently. Use
/// LXMRouter.propagation_resource_concluded() (LXMRouter.py:2271) -- /// [`Self::persist_peer_handled`] when the caller needs persistence errors.
/// `peer.queue_handled_message(transient_id)`.
pub fn mark_peer_handled( pub fn mark_peer_handled(
&mut self, &mut self,
peer_hash: &[u8; 16], peer_hash: &[u8; 16],
@@ -1643,8 +1674,9 @@ impl PropagationNode {
} }
} }
/// Merge peer-handled observations into persisted state using the same /// Merge peer-handled observations using the authoritative offer policy and
/// authoritative policy that produced the offer. /// persist the result, returning write errors. This blocks on peer-file I/O.
/// A volatile node returns success without writing a peer file.
pub fn persist_peer_handled( pub fn persist_peer_handled(
&self, &self,
policy: &OutboundOfferPolicy, policy: &OutboundOfferPolicy,
+4 -1
View File
@@ -13,7 +13,10 @@ use crate::types::PropagationTransientId;
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes. /// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34; const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
/// A peering-key-validated offer and the subset not present in local storage. /// Offer outcome and the subset absent from local storage. The variants are
/// publicly constructible, so this value alone is not proof of authentication
/// or admission. Obtain it through [`crate::propagation_node::PropagationNode::evaluate_offer_request`]
/// after preflight, then commit it to that same admission candidate.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum PnOfferEvaluation { pub enum PnOfferEvaluation {
HaveAll, HaveAll,
+10 -5
View File
@@ -27,8 +27,10 @@ pub struct PreparedNode {
pub policy: AdvertisedNodePolicy, pub policy: AdvertisedNodePolicy,
} }
/// Identity and policy freshness are required; the recipient itself may be /// Check the node identity, node path, advertised policy and recipient key.
/// offline. Only a missing recipient key warrants recipient path discovery. /// Policy must be younger than [`NODE_METADATA_MAX_AGE`] and have a finite,
/// nonnegative transfer limit. The recipient may be offline: only its key is
/// needed. This function reports missing inputs; it performs no path discovery.
pub fn propagation_readiness( pub fn propagation_readiness(
node: [u8; 16], node: [u8; 16],
node_identity_known: bool, node_identity_known: bool,
@@ -58,8 +60,9 @@ pub fn propagation_readiness(
Ok(PreparedNode { node, policy }) Ok(PreparedNode { node, policy })
} }
/// One send-owned encryption result. Retrying changes only the outer timestamp /// One send-owned encryption result. Retrying changes the outer timestamp and,
/// and (when required cost rises) the PN stamp, never ciphertext or transient ID. /// if the saved stamp no longer meets the node's cost, regenerates the PN stamp.
/// Ciphertext and transient ID stay fixed.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PropagationEnvelope { pub struct PropagationEnvelope {
message: LxMessage, message: LxMessage,
@@ -155,7 +158,9 @@ impl PropagationEnvelope {
self.message.wire_bytes() == message.wire_bytes() self.message.wire_bytes() == message.wire_bytes()
&& &self.encryption_binding == encryption_binding && &self.encryption_binding == encryption_binding
} }
/// Call immediately before dispatch with refreshed advertised policy. /// Pack immediately before dispatch using policy checked by
/// [`propagation_readiness`]. This does not refresh the policy or send data.
/// It may synchronously regenerate the PN stamp if more work is required.
pub fn pack_for( pub fn pack_for(
&mut self, &mut self,
node: PreparedNode, node: PreparedNode,
@@ -177,8 +177,10 @@ fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> {
} }
Ok(()) Ok(())
} }
/// Startup only initializes a truly absent store. An incomplete journal or /// Initialize a truly absent store or validate a completed v2 store. An
/// historical directory requires the explicit offline recovery path. /// incomplete journal or historical directory requires explicit offline migration.
/// The temporary store lock is released before this returns the path; this
/// function does not grant a hosting lease.
pub fn open_store(legacy: &Path) -> io::Result<PathBuf> { pub fn open_store(legacy: &Path) -> io::Result<PathBuf> {
Ok(open_locked_store(legacy)?.0) Ok(open_locked_store(legacy)?.0)
} }
@@ -230,8 +232,10 @@ fn verify_published(j: &MigrationJournal) -> io::Result<()> {
durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?; durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
Ok(()) Ok(())
} }
/// The guard binds both path and verified writer exclusion. Neither a retry nor /// Migrate the canonical path protected by the guard. Keep the constructor's
/// operator approval promotes any legacy object without independent provenance. /// writer-exclusion conditions in force throughout this call. Legacy objects
/// remain quarantined; a retry or operator approval does not establish ingress
/// provenance for them.
pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result<MigrationReport> { pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result<MigrationReport> {
migrate(&guard.legacy, None) migrate(&guard.legacy, None)
} }
@@ -1,8 +1,10 @@
use super::*; use super::*;
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
/// Holds the same OS lock as every v2 host. Legacy binaries ignore this lock; /// Hold the OS lock shared with current v2 hosts during offline migration.
/// the mandatory supervisor assertion and known-process probe address that gap. /// Legacy binaries ignore it. The desktop constructor also requires the caller
/// to stop supervisors and checks known processes; the iOS/Android constructors
/// use restricted app-container checks and require the caller to join its writers.
pub struct OfflineMigrationGuard { pub struct OfflineMigrationGuard {
pub(super) legacy: PathBuf, pub(super) legacy: PathBuf,
pub(super) _lock: File, pub(super) _lock: File,
@@ -91,8 +91,10 @@ fn validate(
} }
/// Import exact positively attested archive entries under the same offline /// Import exact positively attested archive entries under the same offline
/// guard. Every entry is checked before the first write, then rechecked at its /// guard. Existing deletion journals are reconciled first. All selected entries
/// publication boundary. Partial IO completion is restart-safe and idempotent. /// are checked before any imported object is published, then rechecked at each
/// publication boundary. Retrying after partial completion retains already
/// committed entries and imports only those still absent.
pub fn import_trusted_recovery_manifest( pub fn import_trusted_recovery_manifest(
guard: &OfflineMigrationGuard, guard: &OfflineMigrationGuard,
path: &Path, path: &Path,
+35 -25
View File
@@ -1,13 +1,17 @@
//! Propagation sync background task. //! Outbound propagation-peer sync, driven by the caller through
//! [`PropagationSyncTask::drain_events`] and [`PropagationSyncTask::tick`].
//! //!
//! Outbound sync to a configured propagation node using the Link //! The `/offer` exchange follows Python `LXMPeer.sync()` and `offer_response()`:
//! REQUEST/RESPONSE pattern. Python reference: LXMPeer.py:381-386. //! 1. Establish a Link and send identification when local identity material is configured.
//! 2. Send `/offer` with `[peering_key, transient_ids]`.
//! 3. Read the response and intersect requested IDs with this attempt's offer.
//! 4. Transfer available requested messages as a Resource, splitting large payloads.
//! 5. Expose handled-ID updates and a terminal result for the caller to persist.
//! //!
//! Flow: //! Use an authoritative peer-policy snapshot for production sync. Policy-based
//! 1. Establish a link to the node. //! offer preparation and message reads use blocking workers when a Tokio runtime
//! 2. Send link.request("/offer", [peering_key, transient_ids]). //! is available; without one, they run synchronously. Compatibility offer
//! 3. Receive a Response packet (context 0x0A) with OfferResponse. //! preparation is always synchronous. This type does not spawn its own polling loop.
//! 4. Transfer requested messages as a Resource.
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@@ -62,11 +66,12 @@ pub struct PeerSyncTerminalResult {
/// Store generation used by successful offer preparation. Failures leave /// Store generation used by successful offer preparation. Failures leave
/// this unset so unchanged-store work remains retryable after backoff. /// this unset so unchanged-store work remains retryable after backoff.
pub offer_generation: Option<u64>, pub offer_generation: Option<u64>,
/// True only when no cumulative-limit or vanished-file work remains for /// With an authoritative policy, a completed attempt sets this only when
/// this generation. /// no cumulative-limit or vanished-file work remains for the generation.
/// The compatibility path without a policy assumes the offer exhausted it;
/// it does not track work excluded by its offer limit.
pub generation_exhausted: bool, pub generation_exhausted: bool,
/// Peer accounting deltas matching Python `LXMPeer.offer_response()` and /// Number of IDs offered in a completed attempt; zero on failure.
/// `resource_concluded()` semantics.
pub offered: u64, pub offered: u64,
pub outgoing: u64, pub outgoing: u64,
pub tx_bytes: u64, pub tx_bytes: u64,
@@ -232,7 +237,9 @@ impl PropagationSyncTask {
} }
} }
/// Create a sync task with disk-backed propagation storage. /// Create a sync task with v2 propagation storage and its retained hosting lock.
/// Path resolution, startup errors and migration prerequisites are those of
/// [`PropagationNode::with_storage`].
pub fn with_storage( pub fn with_storage(
transport_tx: mpsc::Sender<TransportMessage>, transport_tx: mpsc::Sender<TransportMessage>,
dest_hash: [u8; 16], dest_hash: [u8; 16],
@@ -358,11 +365,10 @@ impl PropagationSyncTask {
self.node_dest_hash = Some(dest_hash); self.node_dest_hash = Some(dest_hash);
} }
/// Force an immediate sync attempt with `dest_hash`. /// Start an attempt without waiting for the periodic interval. Returns
/// /// `false` when busy, while a terminal result awaits collection, or if Link
/// Python `LXMPeer.sync()` is called directly by lxmd control requests; /// setup cannot be staged. This compatibility entry point clears the
/// this public shim preserves that behavior without waiting for the /// authoritative policy; use [`Self::request_sync_now_with_policy`] when available.
/// periodic sync interval.
pub fn request_sync_now(&mut self, dest_hash: [u8; 16]) -> bool { pub fn request_sync_now(&mut self, dest_hash: [u8; 16]) -> bool {
if self.state != SyncTaskState::Idle || self.terminal_result.is_some() { if self.state != SyncTaskState::Idle || self.terminal_result.is_some() {
return false; return false;
@@ -376,7 +382,9 @@ impl PropagationSyncTask {
true true
} }
/// Force an immediate sync using an authoritative peer-policy snapshot. /// Start an attempt with an authoritative peer-policy snapshot, bypassing
/// the periodic interval. Returns `false` when busy, while a terminal result
/// awaits collection, or if Link setup cannot be staged.
pub fn request_sync_now_with_policy(&mut self, policy: OutboundOfferPolicy) -> bool { pub fn request_sync_now_with_policy(&mut self, policy: OutboundOfferPolicy) -> bool {
if self.state != SyncTaskState::Idle || self.terminal_result.is_some() { if self.state != SyncTaskState::Idle || self.terminal_result.is_some() {
return false; return false;
@@ -399,9 +407,9 @@ impl PropagationSyncTask {
self.identity_key = Some(identity_key); self.identity_key = Some(identity_key);
} }
/// Drain peer-handled updates discovered during offer negotiation or /// Drain handled IDs from policy filtering, offer negotiation and proven
/// proven Resource transfer. The daemon merges these into its authoritative /// Resource transfer. The caller must merge these into its authoritative
/// `LxmPeer` and persists that peer. /// `LxmPeer` and persist it; draining alone performs no write.
pub fn take_handled_updates(&mut self) -> Vec<PropagationTransientId> { pub fn take_handled_updates(&mut self) -> Vec<PropagationTransientId> {
std::mem::take(&mut self.handled_updates) std::mem::take(&mut self.handled_updates)
} }
@@ -410,9 +418,11 @@ impl PropagationSyncTask {
self.terminal_result.take() self.terminal_result.take()
} }
/// Cancel all active and pending work for one peer. Dropping the bounded /// Discard this task's active and pending work for a matching peer, remove
/// worker receivers makes late preparation results inert, and clearing /// its session and return to idle. Already running blocking workers may
/// handled deltas prevents an explicit unpeer from recreating persistence. /// finish their I/O, but dropped result receivers prevent installing their
/// results. Handled deltas are cleared so this task cannot restore them
/// after an explicit unpeer. Returns `false` if neither node nor policy matches.
pub fn cancel_peer_sync(&mut self, peer_hash: &[u8; 16]) -> bool { pub fn cancel_peer_sync(&mut self, peer_hash: &[u8; 16]) -> bool {
let matches_active = self.node_dest_hash.as_ref() == Some(peer_hash); let matches_active = self.node_dest_hash.as_ref() == Some(peer_hash);
let matches_policy = self let matches_policy = self
+176 -150
View File
@@ -1,7 +1,9 @@
//! LXMF Router: message delivery engine and propagation node. //! LXMF routing policy, delivery queues and propagation bookkeeping.
//! //!
//! Python reference: LXMF/LXMRouter.py. Actor pattern — a single tokio task owns //! The embedding application owns and drives [`LxmRouter`]. It must connect
//! all mutable state. //! transport delivery, durable admission and peer-sync workers; the router does
//! not spawn an actor loop or host a propagation node by itself. Python's
//! `LXMRouter` is the corresponding protocol reference.
use crate::now_f64; use crate::now_f64;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
@@ -26,15 +28,17 @@ use crate::stamper;
use crate::ticket::{Ticket, TicketStore}; use crate::ticket::{Ticket, TicketStore};
use crate::types::PropagationTransientId; use crate::types::PropagationTransientId;
/// Outstanding actor-owned admission. Only this router can match its nonce. /// Outstanding inbound admission reservation. Return it to the same router
/// instance that issued it; its counter is not unique across router instances.
#[derive(Debug)] #[derive(Debug)]
pub struct InboundReservation { pub struct InboundReservation {
message_id: [u8; 32], message_id: [u8; 32],
nonce: u64, nonce: u64,
} }
/// Durable barrier for router-minted reply tickets. Signing the marked draft /// Persistence barrier for a router-minted reply ticket. Signing the marked
/// fails until this exact intent has committed its immutable ticket snapshot. /// draft remains blocked until this intent establishes that the required ticket
/// is durable, either in its snapshot or a newer committed ticket snapshot.
pub struct OutboundTicketIntent { pub struct OutboundTicketIntent {
barrier: Option<std::sync::Arc<()>>, barrier: Option<std::sync::Arc<()>>,
snapshot: Option<crate::persist::TicketPersistenceSnapshot>, snapshot: Option<crate::persist::TicketPersistenceSnapshot>,
@@ -63,8 +67,8 @@ impl OutboundTicketIntent {
/// Router configuration. /// Router configuration.
/// ///
/// Core fields are stable for downstream compatibility; additional Python /// Additional settings live in [`RouterConfigExt`] behind the `ext` field.
/// `LXMRouter.__init__` knobs live in [`RouterConfigExt`] behind the `ext` field. /// Embedders must pass relevant policy to their transport and propagation owners.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RouterConfig { pub struct RouterConfig {
pub propagation_enabled: bool, pub propagation_enabled: bool,
@@ -81,7 +85,7 @@ pub struct RouterConfig {
/// Extended router configuration. /// Extended router configuration.
/// ///
/// Additional `LXMRouter.__init__` fields; all have sensible defaults. /// Additional routing, admission and propagation settings with a [`Default`] implementation.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RouterConfigExt { pub struct RouterConfigExt {
pub autopeer_maxdepth: usize, pub autopeer_maxdepth: usize,
@@ -89,13 +93,14 @@ pub struct RouterConfigExt {
pub peering_cost: u8, pub peering_cost: u8,
pub max_peering_cost: u8, pub max_peering_cost: u8,
pub processing_outbound: bool, pub processing_outbound: bool,
/// Maximum outbound messages to process per tick (`None` = unlimited). /// Maximum messages advanced per outbound-processing call (`None` = no count limit).
pub processing_limit: Option<usize>, pub processing_limit: Option<usize>,
pub retain_synced_on_node: bool, pub retain_synced_on_node: bool,
pub auth_required: bool, pub auth_required: bool,
/// Generate outbound message PoW stamps through the router deferred-stamp queue. /// Generate outbound message PoW stamps through the router deferred-stamp queue.
pub defer_stamp_generation: bool, pub defer_stamp_generation: bool,
/// Propagation storage cap in bytes (`None` = unlimited). /// Size-culling target for the router's in-memory propagation index, in bytes.
/// `None` disables size-based culling; this is not an insertion or disk quota.
pub message_storage_limit: Option<usize>, pub message_storage_limit: Option<usize>,
/// Name advertised in propagation announce metadata. /// Name advertised in propagation announce metadata.
pub name: Option<String>, pub name: Option<String>,
@@ -235,12 +240,9 @@ pub enum DirectDeliveryPlan {
Fail, Fail,
} }
/// Apply upstream LXMF Direct delivery attempt/path/link policy to one message. /// Plan a Direct delivery from the caller's identity, route and Link snapshot.
/// /// Mutates attempt, timing, progress and message state; the caller performs
/// This is a policy primitive for embedders that still own transport adapters. /// path requests and Link operations and reports their outcomes.
/// It mutates the same attempt/progress fields Python mutates in
/// `LXMRouter.process_outbound`, but leaves actual path requests and Link
/// creation to the caller.
pub fn plan_direct_delivery( pub fn plan_direct_delivery(
message: &mut LxMessage, message: &mut LxMessage,
input: DirectDeliveryPlanInput, input: DirectDeliveryPlanInput,
@@ -314,7 +316,7 @@ pub fn plan_direct_delivery(
} }
} }
/// LXMF router — owns all mutable state under the actor pattern. /// Router-owned policy and queues. The embedding application serializes access and drives it.
pub struct LxmRouter { pub struct LxmRouter {
pub config: RouterConfig, pub config: RouterConfig,
pub pending_outbound: Vec<LxMessage>, pub pending_outbound: Vec<LxMessage>,
@@ -323,13 +325,13 @@ pub struct LxmRouter {
/// Order in which `defer_stamp` queued the deferred messages, so stamps /// Order in which `defer_stamp` queued the deferred messages, so stamps
/// are generated first in, first out. /// are generated first in, first out.
deferred_stamp_order: VecDeque<[u8; 32]>, deferred_stamp_order: VecDeque<[u8; 32]>,
/// Captured at construction so deferred-stamp PoW can spawn onto the /// Fallback runtime for deferred stamp workers, captured at construction.
/// blocking pool even when the caller is itself on a `spawn_blocking` /// The current runtime is preferred. If neither is available, stamp search
/// thread, where `Handle::try_current()` fails. Without it the tick grinds /// runs synchronously in the calling thread.
/// stamps inline while holding the manager lock (observed 53 s stall).
pub runtime_handle: Option<tokio::runtime::Handle>, pub runtime_handle: Option<tokio::runtime::Handle>,
pub active_deferred_stamp: Option<DeferredStampJob>, pub active_deferred_stamp: Option<DeferredStampJob>,
/// Identities allowed for delivery. An empty list means "all allowed". /// Allow-list consulted by [`Self::is_allowed`]. Empty admits identities not blocked;
/// authentication policy must be enforced separately by the embedding adapter.
pub allowed: Vec<[u8; 16]>, pub allowed: Vec<[u8; 16]>,
pub blocked: Vec<[u8; 16]>, pub blocked: Vec<[u8; 16]>,
pub allowed_control: Vec<[u8; 16]>, pub allowed_control: Vec<[u8; 16]>,
@@ -342,7 +344,8 @@ pub struct LxmRouter {
pub outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>, pub outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>,
pub ticket_store: TicketStore, pub ticket_store: TicketStore,
ticket_intent_in_flight: std::sync::Weak<()>, ticket_intent_in_flight: std::sync::Weak<()>,
/// Identity hash → priority level. /// Destination hash → recorded priority level. The propagation index uses
/// membership to apply its fixed priority weight; it does not use the level.
pub prioritized: HashMap<[u8; 16], u8>, pub prioritized: HashMap<[u8; 16], u8>,
pub delivery_callback: Option<DeliveryCallback>, pub delivery_callback: Option<DeliveryCallback>,
pub transport_tx: Option<mpsc::Sender<rns_transport::messages::TransportMessage>>, pub transport_tx: Option<mpsc::Sender<rns_transport::messages::TransportMessage>>,
@@ -405,8 +408,8 @@ pub struct StampCostEntry {
/// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`]. /// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`].
/// ///
/// Creating the snapshot only clones in-memory state. The caller can therefore /// Capturing this snapshot clones in-memory state and assigns a ticket revision.
/// release any lock that protects the router before calling [`Self::save_state`], /// The caller can release any router lock before calling [`Self::save_state`],
/// keeping filesystem I/O out of the router's critical section. /// keeping filesystem I/O out of the router's critical section.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RouterStateSnapshot { pub struct RouterStateSnapshot {
@@ -421,7 +424,8 @@ impl RouterStateSnapshot {
/// Persist this owned snapshot using the router's MessagePack layout. /// Persist this owned snapshot using the router's MessagePack layout.
/// ///
/// Each file is written atomically via rename, matching /// Each file is written atomically via rename, matching
/// [`LxmRouter::save_state`]. /// [`LxmRouter::save_state`]. The group is not one transaction: an error can
/// follow successful writes to earlier files. Serialize snapshot writes.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> { pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist; use crate::persist;
@@ -503,14 +507,14 @@ impl LxmRouter {
/// Number of active ordinary inbound delivery Resources. /// Number of active ordinary inbound delivery Resources.
/// ///
/// Python reference: `LXMRouter.inbound_count` — LXMRouter.py:466. /// Python reference: `LXMRouter.inbound_count`.
pub fn inbound_count(&self) -> usize { pub fn inbound_count(&self) -> usize {
self.inbound_resource_tracker.inbound_count() self.inbound_resource_tracker.inbound_count()
} }
/// Owned handles for all active ordinary inbound delivery Resources. /// Owned handles for all active ordinary inbound delivery Resources.
/// ///
/// Python reference: `LXMRouter.inbound_resources` — LXMRouter.py:474. /// Python reference: `LXMRouter.inbound_resources`.
pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> { pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> {
self.inbound_resource_tracker.inbound_resources() self.inbound_resource_tracker.inbound_resources()
} }
@@ -527,7 +531,7 @@ impl LxmRouter {
/// Queue cancellation for one unique active logical Resource. /// Queue cancellation for one unique active logical Resource.
/// ///
/// Python reference: `LXMRouter.cancel_inbound` — LXMRouter.py:484. /// Python reference: `LXMRouter.cancel_inbound`.
pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool { pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool {
self.inbound_resource_tracker.cancel_inbound(resource_id) self.inbound_resource_tracker.cancel_inbound(resource_id)
} }
@@ -538,8 +542,8 @@ impl LxmRouter {
} }
/// Queue cancellation for a stable snapshot of all active Resources. /// Queue cancellation for a stable snapshot of all active Resources.
/// /// Returns the number of requests accepted by the adapter queue, not the
/// Python reference: `LXMRouter.cancel_all_inbound` — LXMRouter.py:505. /// number of completed cancellations.
pub fn cancel_all_inbound(&self) -> usize { pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resource_tracker.cancel_all_inbound() self.inbound_resource_tracker.cancel_all_inbound()
} }
@@ -565,10 +569,10 @@ impl LxmRouter {
/// Queue a message for outbound delivery and report immediate routing errors. /// Queue a message for outbound delivery and report immediate routing errors.
/// ///
/// Mirrors Python LXMF 0.9.8's explicit `IOError` when a caller attempts /// Propagated delivery requires an outbound propagation node; otherwise the
/// `PROPAGATED` delivery without configuring an outbound propagation node. /// returned error owns the message after its failure callback has fired.
/// The legacy [`send`](Self::send) wrapper preserves older Rust call-sites /// This low-level method does not verify signatures or reject duplicate IDs.
/// while still marking the message failed and firing its callback. /// Use [`Self::submit_signed`] for signed-message preparation and duplicate checks.
pub fn try_send(&mut self, mut message: LxMessage) -> Result<(), SendError> { pub fn try_send(&mut self, mut message: LxMessage) -> Result<(), SendError> {
if message.method == DeliveryMethod::Propagated && self.outbound_propagation_node.is_none() if message.method == DeliveryMethod::Propagated && self.outbound_propagation_node.is_none()
{ {
@@ -602,8 +606,9 @@ impl LxmRouter {
/// Learned outbound tickets do not change signed fields and can be /// Learned outbound tickets do not change signed fields and can be
/// attached at any time. A requested reply ticket is a signed LXMF field, /// attached at any time. A requested reply ticket is a signed LXMF field,
/// so it must be inserted before signing. The method is deliberately /// so it must be inserted before signing. The method is deliberately
/// signer-agnostic: callers may subsequently use either `sign` or /// signer-agnostic. When the returned intent requires persistence, call
/// `sign_with` without exposing private key material to the router. /// [`OutboundTicketIntent::persist`] with this draft before `sign` or
/// `sign_with`; signing remains blocked until that barrier is released.
pub fn prepare_outbound( pub fn prepare_outbound(
&mut self, &mut self,
message: &mut LxMessageDraft, message: &mut LxMessageDraft,
@@ -684,11 +689,10 @@ impl LxmRouter {
/// Restore a stored message for another delivery under the same id. /// Restore a stored message for another delivery under the same id.
/// ///
/// `source_public_key` is the active identity's: the message must verify /// The caller supplies the active identity's public key; the message must
/// as sent by it. The outbound ticket is the current one, and the stamp /// verify against it. Uses the current outbound ticket and the larger of
/// cost is the larger of the cost the message was signed under and the /// the stored stamp-cost floor and the destination's current cost. Pass the
/// destination's current cost. Finish the message as for a fresh send, /// returned signed message to [`Self::submit_signed`] for recipient work and queuing.
/// then pass it to [`Self::submit_signed`].
pub fn restore_signed( pub fn restore_signed(
&self, &self,
stored: &ResumableLxMessage, stored: &ResumableLxMessage,
@@ -860,7 +864,8 @@ impl LxmRouter {
self.blocked.retain(|h| h != identity_hash); self.blocked.retain(|h| h != identity_hash);
} }
/// An empty allow-list means "everyone not blocked is allowed". /// An empty allow-list admits every identity not blocked. This helper does
/// not consult [`Self::requires_authentication`] or verify an identity proof.
pub fn is_allowed(&self, identity_hash: &[u8; 16]) -> bool { pub fn is_allowed(&self, identity_hash: &[u8; 16]) -> bool {
if !self.blocked.contains(identity_hash) { if !self.blocked.contains(identity_hash) {
self.allowed.is_empty() || self.allowed.contains(identity_hash) self.allowed.is_empty() || self.allowed.contains(identity_hash)
@@ -873,47 +878,47 @@ impl LxmRouter {
self.allowed_control.contains(identity_hash) self.allowed_control.contains(identity_hash)
} }
/// Whether delivery requires an entry in the allow-list. /// Configured authentication requirement for the embedding delivery adapter.
/// /// This getter does not enforce access; [`Self::is_allowed`] is a separate check.
/// Python reference: `LXMRouter.requires_authentication` — LXMRouter.py:415-417.
pub fn requires_authentication(&self) -> bool { pub fn requires_authentication(&self) -> bool {
self.config.ext.auth_required self.config.ext.auth_required
} }
/// Toggle whether delivery requires an entry in the allow-list. /// Set the authentication requirement consumed by the embedding adapter.
/// /// This does not change [`Self::is_allowed`] or validate incoming messages itself.
/// Python reference: `LXMRouter.set_authentication` — LXMRouter.py:409-413.
pub fn set_authentication(&mut self, required: bool) { pub fn set_authentication(&mut self, required: bool) {
self.config.ext.auth_required = required; self.config.ext.auth_required = required;
} }
/// Whether the node keeps synchronized messages in its propagation store. /// Retention preference passed to [`crate::propagation_client::PropagationClient`].
/// The current client retains previously known haves when enabled; newly
/// downloaded messages accepted through admission are still purged.
pub fn retain_node_lxms(&self) -> bool { pub fn retain_node_lxms(&self) -> bool {
self.config.ext.retain_synced_on_node self.config.ext.retain_synced_on_node
} }
/// Toggle whether the node keeps synchronized messages in its propagation store. /// Set the retention preference for the embedding propagation client.
/// /// The adapter must copy it to the client. See [`Self::retain_node_lxms`]
/// Python reference: `LXMRouter.set_retain_node_lxms` — LXMRouter.py:419-420. /// for the current known-haves-only scope.
pub fn set_retain_node_lxms(&mut self, retain: bool) { pub fn set_retain_node_lxms(&mut self, retain: bool) {
self.config.ext.retain_synced_on_node = retain; self.config.ext.retain_synced_on_node = retain;
} }
/// Propagation storage cap in bytes (`None` = unlimited). /// Size-culling target for the router's propagation index, in bytes.
/// `None` disables size-based culling.
pub fn message_storage_limit(&self) -> Option<usize> { pub fn message_storage_limit(&self) -> Option<usize> {
self.config.ext.message_storage_limit self.config.ext.message_storage_limit
} }
/// Set the propagation storage cap in bytes (`None` = unlimited). /// Set the propagation index's size-culling target in bytes. `None` disables
/// /// size-based culling; the setter does not cull immediately or impose a disk quota.
/// Python reference: `LXMRouter.set_message_storage_limit` — LXMRouter.py:423-424. /// Culling runs through [`Self::cull_propagation`] or enabled periodic jobs.
pub fn set_message_storage_limit(&mut self, limit: Option<usize>) { pub fn set_message_storage_limit(&mut self, limit: Option<usize>) {
self.config.ext.message_storage_limit = limit; self.config.ext.message_storage_limit = limit;
} }
/// Current on-disk-equivalent size of the propagation store, in bytes. /// Byte count recorded by the router's in-memory propagation index.
/// /// This does not inspect files or a separately hosted [`crate::propagation_node::PropagationNode`].
/// Python reference: `LXMRouter.message_storage_size` — LXMRouter.py:437-441.
pub fn message_storage_size(&self) -> usize { pub fn message_storage_size(&self) -> usize {
self.propagation_store.total_size() self.propagation_store.total_size()
} }
@@ -923,7 +928,9 @@ impl LxmRouter {
/// The returned token can be shared with a peer that should bypass stamp PoW when sending /// The returned token can be shared with a peer that should bypass stamp PoW when sending
/// to this router. Default expiry is [`TICKET_EXPIRY`] seconds. /// to this router. Default expiry is [`TICKET_EXPIRY`] seconds.
/// ///
/// Python reference: `LXMRouter.generate_ticket` — LXMRouter.py:1094-1108. /// This low-level helper always generates a token, without renewal/interval
/// reuse or persistence. Persist ticket state before advertising the token;
/// [`Self::prepare_outbound`] supplies the normal reply-ticket barrier.
pub fn generate_ticket( pub fn generate_ticket(
&mut self, &mut self,
destination_hash: [u8; 16], destination_hash: [u8; 16],
@@ -940,15 +947,15 @@ impl LxmRouter {
/// Record an externally-provided outbound ticket so the router can use it when sending. /// Record an externally-provided outbound ticket so the router can use it when sending.
/// ///
/// Python reference: `LXMRouter.remember_ticket` — LXMRouter.py:1110-1113. /// Python reference: `LXMRouter.remember_ticket`.
pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) { pub fn remember_ticket(&mut self, destination_hash: [u8; 16], token: [u8; 16], expires: f64) {
self.ticket_store self.ticket_store
.remember_outbound(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`. /// Return the currently stored valid outbound ticket for `destination_hash`.
/// ///
/// Python reference: `LXMRouter.get_outbound_ticket` — LXMRouter.py:1058-1064. /// Python reference: `LXMRouter.get_outbound_ticket`.
pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> { pub fn get_outbound_ticket(&self, destination_hash: &[u8; 16]) -> Option<[u8; 16]> {
let now = now_f64(); let now = now_f64();
self.ticket_store self.ticket_store
@@ -958,7 +965,7 @@ impl LxmRouter {
/// Returns the expiry (Unix epoch seconds) of the valid ticket for `destination_hash`. /// Returns the expiry (Unix epoch seconds) of the valid ticket for `destination_hash`.
/// ///
/// Python reference: `LXMRouter.get_outbound_ticket_expiry` — LXMRouter.py:1125-1131. /// Python reference: `LXMRouter.get_outbound_ticket_expiry`.
pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option<f64> { pub fn get_outbound_ticket_expiry(&self, destination_hash: &[u8; 16]) -> Option<f64> {
let now = now_f64(); let now = now_f64();
self.ticket_store self.ticket_store
@@ -966,19 +973,16 @@ impl LxmRouter {
.map(|t| t.expires) .map(|t| t.expires)
} }
/// Snapshot of all stored tickets (including expired / used entries). /// Borrow all locally issued inbound tickets, across destinations. Expired
/// /// entries remain visible until culled. This does not include learned outbound tickets.
/// Python reference: `LXMRouter.get_inbound_tickets` — LXMRouter.py:1133-1136.
pub fn get_inbound_tickets(&self) -> &[Ticket] { pub fn get_inbound_tickets(&self) -> &[Ticket] {
self.ticket_store.inbound() self.ticket_store.inbound()
} }
/// Cancel an outbound message before it is sent. /// Remove a matching message from the router's outbound or deferred-stamp queue.
/// /// Returns `true` when found, regardless of its prior state. A matching active
/// Removes the message from `pending_outbound` (or `pending_deferred_stamps`) if it is still /// stamp worker receives a cooperative cancellation request. The embedding
/// in a cancellable state. Returns `true` if the message was found and cancelled. /// runtime must separately cancel any Link/Resource work it already owns.
///
/// Python reference: `LXMRouter.cancel_outbound` — LXMRouter.py:474-487.
pub fn cancel_outbound(&mut self, message_hash: &[u8; 32]) -> bool { pub fn cancel_outbound(&mut self, message_hash: &[u8; 32]) -> bool {
if let Some(pos) = self if let Some(pos) = self
.pending_outbound .pending_outbound
@@ -1051,8 +1055,8 @@ impl LxmRouter {
/// Python's router retains each one's announce data in Reticulum so its /// Python's router retains each one's announce data in Reticulum so its
/// identity outlives its path (LXMRouter.py:2761). Send each as /// identity outlives its path (LXMRouter.py:2761). Send each as
/// `TransportQuery::RetainDestination` through the control plane, which /// `TransportQuery::RetainDestination` through the control plane, which
/// forwards to a shared instance. At most the newest 256 are kept between /// forwards to a shared instance. Up to 256 distinct destinations are kept
/// calls. /// in insertion order; a repeat delivery does not refresh an existing entry's position.
pub fn take_destination_retains(&mut self) -> Vec<[u8; 16]> { pub fn take_destination_retains(&mut self) -> Vec<[u8; 16]> {
self.destination_retains.drain(..).collect() self.destination_retains.drain(..).collect()
} }
@@ -1107,9 +1111,10 @@ impl LxmRouter {
true true
} }
/// Get the outbound-delivery progress (0.0..=1.0) for a pending message. /// Get the recorded progress for a queued or deferred message. The value is
/// returned unchanged; caller-written metadata is not clamped here.
/// ///
/// Python reference: `LXMRouter.get_outbound_progress` — LXMRouter.py:489-495. /// Python reference: `LXMRouter.get_outbound_progress`.
pub fn get_outbound_progress(&self, message_hash: &[u8; 32]) -> Option<f64> { pub fn get_outbound_progress(&self, message_hash: &[u8; 32]) -> Option<f64> {
self.pending_outbound self.pending_outbound
.iter() .iter()
@@ -1124,42 +1129,37 @@ impl LxmRouter {
/// Get the cached required stamp cost for a destination (delivery). /// Get the cached required stamp cost for a destination (delivery).
/// ///
/// Returns `None` if no announce has advertised a cost for this destination. /// Returns the cached entry unchanged, without an expiry check. Use
/// /// [`Self::get_stamp_cost`] to exclude expired entries. Unlike Python's
/// Python reference: `LXMRouter.get_outbound_lxm_stamp_cost` — LXMRouter.py:1138-1147. /// same-named message-ID lookup, this API takes a destination hash.
pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<u8> { pub fn get_outbound_lxm_stamp_cost(&self, destination_hash: &[u8; 16]) -> Option<u8> {
self.outbound_stamp_costs self.outbound_stamp_costs
.get(destination_hash) .get(destination_hash)
.map(|e| e.cost) .map(|e| e.cost)
} }
/// Get the propagation stamp cost for a message queued for propagation-node delivery. /// Return the recipient stamp cost recorded on a deferred message.
/// /// Despite this method's name, it reads only `pending_deferred_stamps` and
/// Returns the per-message `stamp_cost` recorded on the pending message when it was enqueued. /// does not return the separate propagation-node admission stamp target.
///
/// Python reference: `LXMRouter.get_outbound_lxm_propagation_stamp_cost` — LXMRouter.py:1149-1156.
pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option<u8> { pub fn get_outbound_lxm_propagation_stamp_cost(&self, message_hash: &[u8; 32]) -> Option<u8> {
self.pending_deferred_stamps self.pending_deferred_stamps
.get(message_hash) .get(message_hash)
.and_then(|m| m.stamp_cost()) .and_then(|m| m.stamp_cost())
} }
/// Return whether a message or propagation transient ID has already been /// Check the local-delivery dedupe cache for a message or transient ID.
/// delivered locally. /// Durable discard/deletion decisions can also populate it; presence does
/// /// not prove a message file exists. This lookup does not check expiry.
/// Python reference: `LXMRouter.has_message` — LXMRouter.py:1667-1669.
pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool { pub fn has_message(&self, transient_id: &PropagationTransientId) -> bool {
self.propagation_store.is_locally_delivered(transient_id) self.propagation_store.is_locally_delivered(transient_id)
} }
/// Atomically admit one already-decoded inbound message and invoke the /// Mark a message ID delivered in memory and invoke the registered callback.
/// router callback at most once. /// With `allow_duplicate = false`, an ID already in the local-delivery cache
/// /// returns `false`; with `true`, repeated calls may invoke the callback again.
/// Both ordinary packet/Resource delivery and propagation download must /// This compatibility helper does not verify the message, persist local
/// use this actor-owned gate before any application-visible side effect. /// effects or record a distinct ciphertext transient ID. Use the reservation
/// A propagation message may carry a ciphertext-derived `transient_id` /// and durable-receipt commit path for application admission.
/// 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 { pub fn deliver_inbound(&mut self, message: &LxMessage, allow_duplicate: bool) -> bool {
let message_id = message.message_id(); let message_id = message.message_id();
if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) { if !allow_duplicate && self.propagation_store.is_locally_delivered(&message_id) {
@@ -1172,8 +1172,10 @@ impl LxmRouter {
true true
} }
/// Reserve before local disk/DB work; no ticket learning, dedupe publication /// Reserve a message ID before local disk/DB work. An existing reservation
/// or callback occurs until commit. An aborted write leaves retries possible. /// for that ID returns `None`; this does not check the delivered cache or
/// authenticate the message. No ticket learning, dedupe publication or callback
/// occurs here. Return the reservation to this instance to abort or commit it.
pub fn reserve_inbound(&mut self, message: &LxMessage) -> Option<InboundReservation> { pub fn reserve_inbound(&mut self, message: &LxMessage) -> Option<InboundReservation> {
let message_id = message.message_id(); let message_id = message.message_id();
if self.inbound_reservations.contains_key(&message_id) { if self.inbound_reservations.contains_key(&message_id) {
@@ -1191,6 +1193,12 @@ impl LxmRouter {
} }
} }
/// Complete a matching reservation after the adapter has obtained a durable
/// receipt. Records both message and transient IDs; learns a ticket only from
/// a matching verified message with a committed/duplicate disposition.
/// Returns whether the new-commit delivery path ran; `false` also covers
/// duplicates, discards and mismatched reservations. The caller establishes
/// identity/node scope and durable effects before invoking this method.
pub fn commit_inbound( pub fn commit_inbound(
&mut self, &mut self,
reservation: InboundReservation, reservation: InboundReservation,
@@ -1249,6 +1257,10 @@ impl LxmRouter {
true true
} }
/// Decode/decrypt a paper URI and pass it to [`Self::deliver_inbound`] without
/// signature verification or durable persistence. The returned message is
/// unverified, and a registered callback may already have run. For verified
/// durable admission, decode separately and use the reservation/commit path.
pub fn ingest_lxm_uri<F>( pub fn ingest_lxm_uri<F>(
&mut self, &mut self,
uri: &str, uri: &str,
@@ -1262,9 +1274,11 @@ impl LxmRouter {
Ok(message) Ok(message)
} }
/// Register a router-wide callback fired on every inbound message delivery. /// Replace the router-wide callback used by inbound delivery/commit helpers.
/// It runs synchronously in the calling thread; duplicate/discard behavior
/// depends on the helper used.
/// ///
/// Python reference: `LXMRouter.register_delivery_callback` — LXMRouter.py:358-359. /// Python reference: `LXMRouter.register_delivery_callback`.
pub fn register_delivery_callback<F>(&mut self, callback: F) pub fn register_delivery_callback<F>(&mut self, callback: F)
where where
F: Fn(&LxMessage) + Send + 'static, F: Fn(&LxMessage) + Send + 'static,
@@ -1273,9 +1287,9 @@ impl LxmRouter {
} }
/// Load persisted runtime state (stamp costs, tickets, dedup sets) from /// Load persisted runtime state (stamp costs, tickets, dedup sets) from
/// `state_dir`. Missing files are treated as empty state. Dedup-cache /// `state_dir`. Missing files are treated as empty state; other load errors
/// timestamps are restored as persisted so age-based expiry survives /// propagate after any earlier fields have already been replaced. Dedup-cache
/// restarts. /// timestamps are restored so age-based expiry survives restarts.
pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> { pub fn load_state(&mut self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist; use crate::persist;
self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?; self.outbound_stamp_costs = persist::load_stamp_costs(state_dir)?;
@@ -1323,8 +1337,9 @@ impl LxmRouter {
} }
} }
/// Persist runtime state to `state_dir` using MessagePack. Safe to call /// Persist runtime state to `state_dir` using MessagePack. Each file is
/// periodically; each file is written atomically via rename. /// replaced atomically; the set is not a single transaction. Serialize writes
/// so an older snapshot cannot overwrite newer state.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> { pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
self.state_snapshot().save_state(state_dir) self.state_snapshot().save_state(state_dir)
} }
@@ -1351,9 +1366,10 @@ impl LxmRouter {
} }
/// Return authoritative policies for peers that have not processed the /// Return authoritative policies for peers that have not processed the
/// current propagation-store generation. This is an O(peers) scheduler /// current propagation-store generation. Prefers eligible alive peers; if
/// query; exact message eligibility is intentionally deferred to the /// none are alive, returns eligible unresponsive peers. Snapshots clone peer
/// sync task's off-loop offer preparation. /// policy/handled-ID state and are sorted by peer hash. Exact message
/// eligibility is checked during offer preparation.
/// ///
/// The method does not mutate peer state, allowing a single shared sync /// The method does not mutate peer state, allowing a single shared sync
/// task to accept one policy before the daemon marks that peer started. /// task to accept one policy before the daemon marks that peer started.
@@ -1385,10 +1401,11 @@ impl LxmRouter {
true true
} }
/// Add a peer from announce data. /// Add or refresh a peer from announce data. New peers count toward
/// /// `max_peers`; static peers bypass autopeer and hop-depth gates.
/// The peer is added only when autopeer is enabled, the router is below /// Other peers require autopeer enabled and, when hops are known, an allowed
/// `max_peers`, and the announce hop count is within `autopeer_maxdepth`. /// depth. Excess peering cost is refused and can remove an existing peer on
/// a non-stale policy announce. The caller supplies authenticated, finite data.
pub fn autopeer(&mut self, candidate: AutopeerCandidate) -> bool { pub fn autopeer(&mut self, candidate: AutopeerCandidate) -> bool {
let AutopeerCandidate { let AutopeerCandidate {
destination_hash, destination_hash,
@@ -1540,9 +1557,9 @@ impl LxmRouter {
/// Mark pending propagated messages due after the configured propagation node announces. /// Mark pending propagated messages due after the configured propagation node announces.
/// ///
/// Mirrors LXMF 0.9.8's propagation announce handler. The announce app_data /// Requires the configured destination and app data accepted by
/// must be a valid propagation-node announce before any retry backoff is /// [`crate::handlers::parse_pn_announce_data`] before clearing retry backoff.
/// cleared. /// The caller verifies the announce's identity and authenticity.
pub fn trigger_outbound_for_propagation_node_announce( pub fn trigger_outbound_for_propagation_node_announce(
&mut self, &mut self,
destination_hash: [u8; 16], destination_hash: [u8; 16],
@@ -1576,7 +1593,8 @@ impl LxmRouter {
self.config.max_peers = max; self.config.max_peers = max;
} }
/// Propagation storage limit in kilobytes. /// Set the advertised per-transfer propagation limit in decimal kB.
/// This does not set total storage capacity or update a separate node owner.
pub fn set_propagation_limit(&mut self, limit_kb: usize) { pub fn set_propagation_limit(&mut self, limit_kb: usize) {
self.config.propagation_limit_kb = limit_kb; self.config.propagation_limit_kb = limit_kb;
} }
@@ -1588,7 +1606,7 @@ impl LxmRouter {
/// Build propagation-node announce app_data (msgpack). /// Build propagation-node announce app_data (msgpack).
/// ///
/// Python reference: LXMRouter.get_propagation_node_app_data — LXMRouter.py:306-318. /// Python reference: LXMRouter.get_propagation_node_app_data.
pub fn get_propagation_node_app_data(&self) -> Vec<u8> { pub fn get_propagation_node_app_data(&self) -> Vec<u8> {
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -1634,9 +1652,9 @@ impl LxmRouter {
/// Validate a stamp, accepting a matching ticket hash as a bypass. /// Validate a stamp, accepting a matching ticket hash as a bypass.
/// ///
/// A ticket is matched by comparing the first 16 bytes of /// A ticket matches only when the complete stamp equals the 16-byte
/// `SHA-256(ticket.token || message_id)` against the stamp prefix; /// truncated hash of `ticket.token || message_id`. A nonmatching stamp must
/// otherwise falls back to PoW validation. /// be exactly 32 bytes for PoW validation; a matching prefix alone is no ticket bypass.
pub fn validate_stamp_with_tickets( pub fn validate_stamp_with_tickets(
&self, &self,
message_id: &[u8; 32], message_id: &[u8; 32],
@@ -1677,7 +1695,9 @@ impl LxmRouter {
} }
} }
/// Summarise propagation-node state for a control status request. /// Summarise router-held propagation configuration, index and peer counters.
/// Returns `None` when propagation is disabled. This does not query a separate
/// live node or filesystem; the embedding runtime supplies those totals.
/// ///
/// Python reference: LXMRouter.compile_stats. /// Python reference: LXMRouter.compile_stats.
pub fn control_status(&self) -> Option<NodeStats> { pub fn control_status(&self) -> Option<NodeStats> {
@@ -1794,11 +1814,10 @@ impl LxmRouter {
} }
} }
/// Drain pending outbound messages into [`OutboundAction`]s. /// Move eligible outbound messages into [`OutboundAction`]s, subject to
/// /// retry times and the per-call processing limit. Other messages remain queued.
/// A delivery that later fails externally (e.g. unknown destination key) /// The caller owns emitted deliveries, including proof tracking and retries;
/// should be re-queued via [`send`][Self::send] with `delivery_attempts` /// requeue retryable failures through [`Self::try_send`] after updating attempts.
/// incremented.
#[tracing::instrument( #[tracing::instrument(
level = "debug", level = "debug",
name = "router.process_outbound", name = "router.process_outbound",
@@ -1930,12 +1949,9 @@ impl LxmRouter {
actions actions
} }
/// Process outbound messages while keeping Direct deliveries in the router /// Plan Direct deliveries while retaining their originals in the router queue.
/// queue until LinkDeliveryManager reports a terminal result. /// The caller executes plans, reports terminal Link results to the router and
/// /// handles non-Direct actions. This method does not poll a Link manager itself.
/// This mirrors Python's `LXMRouter.process_outbound` ownership model for
/// Direct messages while preserving [`Self::process_outbound`] for older
/// embedders that still take ownership of Direct messages themselves.
pub fn process_outbound_with_direct<F>(&mut self, mut direct_input: F) -> Vec<OutboundAction> pub fn process_outbound_with_direct<F>(&mut self, mut direct_input: F) -> Vec<OutboundAction>
where where
F: FnMut(&LxMessage, f64) -> DirectDeliveryPlanInput, F: FnMut(&LxMessage, f64) -> DirectDeliveryPlanInput,
@@ -2096,10 +2112,11 @@ impl LxmRouter {
} }
} }
/// Send single-packet opportunistic actions via the configured transport. /// Compatibility executor without a destination encryptor. With transport
/// /// configured, Opportunistic actions fail encryption and are requeued.
/// Direct and Propagated actions require a Reticulum link and are handled by /// Direct/Propagated actions are consumed without delivery; without transport,
/// `LinkDeliveryManager` / propagation helpers in the embedding runtime. /// all supplied actions are discarded. Handle delivery actions in the embedder
/// or use [`Self::execute_actions_with_encryptor`] for Opportunistic work.
pub fn execute_actions(&mut self, actions: Vec<OutboundAction>) { pub fn execute_actions(&mut self, actions: Vec<OutboundAction>) {
self.execute_actions_with_encryptor(actions, |dest_hash, _plaintext| { self.execute_actions_with_encryptor(actions, |dest_hash, _plaintext| {
Err(MessageError::PackFailed(format!( Err(MessageError::PackFailed(format!(
@@ -2115,6 +2132,12 @@ impl LxmRouter {
/// Python encrypts Opportunistic LXMF packet payloads with the recipient /// Python encrypts Opportunistic LXMF packet payloads with the recipient
/// destination identity before handing bytes to Reticulum. Core cannot /// destination identity before handing bytes to Reticulum. Core cannot
/// infer destination keys, so embeddings must provide the encryptor. /// infer destination keys, so embeddings must provide the encryptor.
///
/// This consumes the action list. Direct/Propagated actions are discarded,
/// and without a configured transport all actions are discarded. Dispatch
/// those methods separately before calling. Successful packet enqueueing does
/// not retain a message for delivery-proof tracking; the embedding runtime
/// must own that lifecycle when delivery confirmation is required.
pub fn execute_actions_with_encryptor<F>( pub fn execute_actions_with_encryptor<F>(
&mut self, &mut self,
actions: Vec<OutboundAction>, actions: Vec<OutboundAction>,
@@ -2204,7 +2227,10 @@ impl LxmRouter {
} }
} }
/// Advance one scheduler tick: drain outbound, then run periodic jobs. /// Advance deferred stamps and periodic jobs using the compatibility executor.
/// Direct messages stay queued; Propagated actions are consumed without delivery,
/// and Opportunistic work lacks destination encryption. This is not a complete
/// delivery driver; use explicit action processing in an embedding runtime.
pub fn tick(&mut self) { pub fn tick(&mut self) {
self.processing_count += 1; self.processing_count += 1;
@@ -2217,8 +2243,9 @@ impl LxmRouter {
self.run_periodic_jobs(); self.run_periodic_jobs();
} }
/// Advance one scheduler tick using caller-supplied destination encryption /// Advance stamps, Opportunistic actions and periodic jobs with destination
/// for Opportunistic packet actions. /// encryption. Direct messages stay queued; Propagated actions are consumed
/// without delivery. For other methods or proof tracking, drive actions explicitly.
pub fn tick_with_encryptor<F>(&mut self, encrypt_fn: F) pub fn tick_with_encryptor<F>(&mut self, encrypt_fn: F)
where where
F: FnMut([u8; 16], &[u8]) -> Result<Vec<u8>, MessageError>, F: FnMut([u8; 16], &[u8]) -> Result<Vec<u8>, MessageError>,
@@ -2234,13 +2261,11 @@ impl LxmRouter {
self.run_periodic_jobs(); self.run_periodic_jobs();
} }
/// Drive the periodic job machinery for embedders that process outbound /// Drive periodic jobs when the embedder processes outbound actions itself.
/// themselves via `process_outbound_with_direct` instead of calling /// Advances the job counter at most once per `0.9 * PROCESSING_INTERVAL`
/// [`Self::tick`]. Without this the jobloop counters never advance and /// wall-clock seconds; missed intervals are not replayed. Jobs clean transient
/// transient-cache cleaning, store culls, and peer rotation never run. /// caches/throttles and, when propagation is enabled, cull the router index
/// Time-gated to Python's `PROCESSING_INTERVAL` so callers may invoke it /// and rotate peers. This does not drive outbound work or a separate node store.
/// every loop pass regardless of their tick rate (lxmd: 4 s, Ratspeak:
/// 500 ms) without skewing the jobloop cadences.
pub fn run_jobs_tick(&mut self) { pub fn run_jobs_tick(&mut self) {
let now = now_f64(); let now = now_f64();
if now - self.last_jobs_tick < PROCESSING_INTERVAL as f64 * 0.9 { if now - self.last_jobs_tick < PROCESSING_INTERVAL as f64 * 0.9 {
@@ -2306,7 +2331,8 @@ pub enum OutboundAction {
message: LxMessage, message: LxMessage,
prop_hash: [u8; 16], prop_hash: [u8; 16],
}, },
/// Small enough for single-packet delivery. /// Opportunistic packet action. Final encryption and packet-size admission
/// remain the executor's responsibility.
DeliverOpportunistic { DeliverOpportunistic {
message: LxMessage, message: LxMessage,
dest_hash: [u8; 16], dest_hash: [u8; 16],
+30 -15
View File
@@ -8,8 +8,10 @@
//! workblock. Only the expand-round count differs per kind (see //! workblock. Only the expand-round count differs per kind (see
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs). //! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
//! //!
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading //! Rust validation requires at least `cost` leading zero bits in
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`. //! `SHA-256(workblock || stamp)`. Python uses an inclusive numeric threshold,
//! `result <= 1 << (256 - cost)`; the exact equality boundary differs for
//! nonzero cost.
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
@@ -80,11 +82,10 @@ pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
stamp_value(workblock, stamp) >= cost as u32 stamp_value(workblock, stamp) >= cost as u32
} }
/// Give-up bound for stamp searches: 64× the expected `2^cost` work, so the /// Attempt budget for [`generate_stamp`] and [`generate_stamp_cancellable`]:
/// failure probability for an honest cost is ~e^-64 while a hostile cost can /// `64 * 2^cost`. Returns `None` for costs at least 58 because the budget would
/// no longer pin a thread forever. Costs ≥ 58 (cap would overflow u64) are /// overflow `u64`. This limits attempts, not elapsed time. Deferred stamp
/// unsatisfiable on real hardware and fail immediately. Python has no cap and /// workers use explicit cancellation and do not use this budget.
/// blocks until success — deliberate divergence, see fix-registry.
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> { pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
if cost >= 58 { if cost >= 58 {
return None; return None;
@@ -94,13 +95,15 @@ pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
/// Single-threaded brute-force stamp search. Bounded by /// Single-threaded brute-force stamp search. Bounded by
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the /// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
/// cost is unsatisfiable. /// requested cost has no supported iteration budget.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> { pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false)) generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
} }
/// Synchronous bounded worker entry. Cancellation revokes work without claiming /// Synchronous search with the [`stamp_iteration_cap`] attempt budget.
/// that an async task abort stopped this closure or released its byte owners. /// Checks cancellation before workblock construction and every 1,000 attempts;
/// workblock construction itself is not interrupted. Run on a blocking worker
/// when called from async code.
pub fn generate_stamp_cancellable( pub fn generate_stamp_cancellable(
material: &[u8], material: &[u8],
cost: u8, cost: u8,
@@ -179,7 +182,7 @@ pub fn validate_stamp(
stamp_valid(stamp, cost, &workblock) stamp_valid(stamp, cost, &workblock)
} }
/// Python reference: LXStamper.py:48-51 (`validate_peering_key`). /// Python reference: `LXStamper.validate_peering_key`.
/// ///
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical). /// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation. /// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
@@ -191,7 +194,7 @@ pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_co
stamp_valid(peering_key, target_cost, &workblock) stamp_valid(peering_key, target_cost, &workblock)
} }
/// Python reference: LXStamper.py:53-65 (`validate_pn_stamp`). /// Python reference: `LXStamper.validate_pn_stamp`.
/// ///
/// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes. /// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes.
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation. /// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
@@ -222,7 +225,9 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
Some((transient_id, lxm_data.to_vec(), value, stamp)) Some((transient_id, lxm_data.to_vec(), value, stamp))
} }
/// Cancellation handle for a deferred PoW task. /// Cooperative cancellation handle for a deferred PoW task.
/// Call `cancel()` to request cancellation; dropping this handle or the result
/// receiver does not stop the worker.
#[derive(Clone)] #[derive(Clone)]
pub struct DeferredStampHandle { pub struct DeferredStampHandle {
cancel: Arc<AtomicBool>, cancel: Arc<AtomicBool>,
@@ -247,6 +252,11 @@ pub enum DeferredStampResult {
/// Spawn a deferred stamp-generation task on a blocking worker. /// Spawn a deferred stamp-generation task on a blocking worker.
/// ///
/// Returns a cancellation handle and a oneshot receiver for the result. /// Returns a cancellation handle and a oneshot receiver for the result.
/// The search has no iteration cap; see [`spawn_deferred_stamp_on`] for its
/// cancellation contract.
///
/// # Panics
/// Panics when called outside a Tokio runtime.
#[tracing::instrument( #[tracing::instrument(
level = "debug", level = "debug",
name = "stamper.compute", name = "stamper.compute",
@@ -269,8 +279,13 @@ pub fn spawn_deferred_stamp(
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds) spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
} }
/// Handle-explicit variant: callable from `spawn_blocking` threads (no /// Spawn on an explicit runtime handle, without requiring a current runtime
/// implicit runtime context) — the manager tick runs there. /// context on the calling thread.
///
/// After workblock construction, a nonzero-cost search checks cancellation
/// between batches of 1,000 attempts and runs until success or cancellation.
/// It does not apply [`stamp_iteration_cap`]. Keep the cancellation handle and
/// call `cancel()` when abandoning the result.
pub fn spawn_deferred_stamp_on( pub fn spawn_deferred_stamp_on(
runtime: &tokio::runtime::Handle, runtime: &tokio::runtime::Handle,
message_id: [u8; 32], message_id: [u8; 32],
+20 -9
View File
@@ -1,7 +1,9 @@
//! LXMF Propagation Sync Protocol -- Offer/Get between peers. //! Propagation offer/response values and local sync-session bookkeeping.
//!
//! The network task in [`crate::propagation_sync`] follows this exchange:
//! //!
//! 1. Peer A opens a Link to Peer B. //! 1. Peer A opens a Link to Peer B.
//! 2. A sends Offer { transient_ids }. //! 2. A sends `/offer` with `[peering_key, transient_ids]`.
//! 3. B responds with one of: //! 3. B responds with one of:
//! - `true`: peer wants ALL offered messages. //! - `true`: peer wants ALL offered messages.
//! - `false`: peer already has everything. //! - `false`: peer already has everything.
@@ -9,7 +11,11 @@
//! - integer error code: 0xF0 NoIdentity, 0xF1 NoAccess, 0xF3 InvalidKey, //! - integer error code: 0xF0 NoIdentity, 0xF1 NoAccess, 0xF3 InvalidKey,
//! 0xF4 InvalidData, 0xF5 InvalidStamp, 0xF6 Throttled. //! 0xF4 InvalidData, 0xF5 InvalidStamp, 0xF6 Throttled.
//! 4. A sends requested messages via Resource transfer. //! 4. A sends requested messages via Resource transfer.
//! 5. B stores and sends proof. //! 5. Resource proof reports transport completion; application admission is a
//! separate responsibility.
//!
//! [`SyncGet`] and [`SyncSession`] are local helpers. They do not implement the
//! authenticated `/offer` admission policy in [`crate::propagation_admission`].
//! //!
//! Python reference: LXMPeer.py (offer_response). //! Python reference: LXMPeer.py (offer_response).
@@ -23,10 +29,13 @@ use crate::types::PropagationTransientId;
pub const SYNC_MSG_OFFER: u16 = 0x0001; pub const SYNC_MSG_OFFER: u16 = 0x0001;
pub const SYNC_MSG_GET: u16 = 0x0002; pub const SYNC_MSG_GET: u16 = 0x0002;
/// Offer message: "I have these messages". /// Local offer data: a peering stamp and the transient IDs available for sync.
/// ///
/// Python wire: `[peering_key, unhandled_ids]`. `peering_key` is the raw stamp /// The `/offer` request uses `[peering_key, unhandled_ids]` with a MessagePack
/// bytes (Python `self.peering_key[0]`), required by the receiver for access control. /// binary key and binary IDs. This type's `MessageBase::pack` uses the default
/// Serde representation, which encodes its byte vectors as integer arrays.
/// [`crate::propagation_sync`] constructs the required binary wire values
/// explicitly when sending the request.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncOffer { pub struct SyncOffer {
pub peering_key: Vec<u8>, pub peering_key: Vec<u8>,
@@ -66,7 +75,8 @@ impl MessageBase for SyncOffer {
} }
} }
/// Get message: "Send me these messages". /// Local wanted-ID list used by [`SyncSession`]. This wrapper is not the
/// `/offer` wire response; use [`OfferResponse`] for that response.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncGet { pub struct SyncGet {
pub wanted_ids: Vec<Vec<u8>>, pub wanted_ids: Vec<Vec<u8>>,
@@ -103,7 +113,7 @@ impl MessageBase for SyncGet {
} }
} }
/// Parsed offer response from a propagation node. Python: LXMPeer.py:396-439. /// Parsed offer response from a propagation node. See Python `LXMPeer.offer_response`.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum OfferResponse { pub enum OfferResponse {
WantAll, WantAll,
@@ -231,7 +241,8 @@ impl SyncSession {
} }
} }
/// Process a received offer; returns a SyncGet for IDs we don't have. /// Select 32-byte IDs absent from the local store and enter Receiving state.
/// This helper does not validate the peering key or enforce admission policy.
pub fn process_offer(&mut self, offer: &SyncOffer, our_store: &PropagationStore) -> SyncGet { pub fn process_offer(&mut self, offer: &SyncOffer, our_store: &PropagationStore) -> SyncGet {
let wanted: Vec<Vec<u8>> = offer let wanted: Vec<Vec<u8>> = offer
.transient_ids .transient_ids
+3 -1
View File
@@ -47,7 +47,9 @@ impl Ticket {
Ok(encoded) Ok(encoded)
} }
/// Decode a signed inbound Python-compatible ticket field. /// Decode a Python-compatible ticket field with a finite future expiry and
/// a 16-byte token. The caller must authenticate the containing message and
/// bind `destination_hash` to its sender before storing the learned ticket.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> { pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded); let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?; let value = rmpv::decode::read_value(&mut cursor).ok()?;
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::constants::DESTINATION_LENGTH;
/// Reticulum destination hash, as carried in LXMF wire messages. /// Reticulum destination hash, as carried in LXMF wire messages.
pub type DestinationHash = [u8; DESTINATION_LENGTH]; pub type DestinationHash = [u8; DESTINATION_LENGTH];
/// Reticulum identity hash, used for peer and ticket identity binding. /// Reticulum identity hash. Ticket stores use delivery destination hashes instead.
pub type IdentityHash = [u8; DESTINATION_LENGTH]; pub type IdentityHash = [u8; DESTINATION_LENGTH];
/// Canonical LXMF message id / SHA-256 digest. /// Canonical LXMF message id / SHA-256 digest.
+10 -10
View File
@@ -1,4 +1,4 @@
//! LXMF daemon configuration and runner. //! LXMF daemon configuration and inbound-hook helpers.
//! //!
//! Python reference: LXMF/Utilities/lxmd.py. //! Python reference: LXMF/Utilities/lxmd.py.
@@ -11,9 +11,8 @@ use rns_runtime::config::{Config, ConfigSection};
/// Normalized view of Python `lxmd.apply_config()` behavior. /// Normalized view of Python `lxmd.apply_config()` behavior.
/// ///
/// This intentionally mirrors Python's active_configuration keys and units. /// Values retain Python's configuration units before conversion into
/// It is kept separate from [`DaemonConfig`] while the daemon still has legacy /// [`DaemonConfig`], including decimal KB/MB and announce intervals in seconds.
/// Rust fields and storage layout.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct PythonLxmdConfig { pub struct PythonLxmdConfig {
pub display_name: String, pub display_name: String,
@@ -190,7 +189,7 @@ pub struct DaemonConfig {
pub enforce_stamps: bool, pub enforce_stamps: bool,
pub message_storage_limit: Option<usize>, pub message_storage_limit: Option<usize>,
pub from_static_only: bool, pub from_static_only: bool,
/// Max accepted inbound delivery transfer size in KB. Python reference: /// Max accepted inbound delivery transfer size in decimal KB. Python reference:
/// `delivery_transfer_max_accepted_size` in `lxmd.py`. /// `delivery_transfer_max_accepted_size` in `lxmd.py`.
pub delivery_transfer_max_accepted_size: f64, pub delivery_transfer_max_accepted_size: f64,
} }
@@ -407,8 +406,9 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
execute_on_inbound_with_event(command, message_path, "") execute_on_inbound_with_event(command, message_path, "")
} }
/// Durable propagation outbox events may replay after a crash. Hooks can use /// Execute an inbound hook with `event_id` in the `LXMF_EVENT_ID` environment
/// this stable identifier for their own idempotency boundary. /// variable when the identifier is nonempty. Durable propagation outbox events
/// may replay after a crash; the hook can use the identifier to deduplicate them.
pub fn execute_on_inbound_with_event( pub fn execute_on_inbound_with_event(
command: &str, command: &str,
message_path: &str, message_path: &str,
@@ -523,9 +523,9 @@ fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
Ok(parts) Ok(parts)
} }
/// Persist a received message before invoking the configured hook. Keeping /// Persist a received message, then invoke the configured hook after the write
/// both operations in one blocking job prevents the hook from racing the /// succeeds. This function blocks; async callers must run it on a blocking
/// atomic file write and keeps process execution off the async daemon loop. /// worker. A hook error is returned after the message has already been saved.
pub fn persist_inbound_and_execute( pub fn persist_inbound_and_execute(
message_path: &std::path::Path, message_path: &std::path::Path,
packed: &[u8], packed: &[u8],
+18 -14
View File
@@ -79,11 +79,12 @@ pub struct Args {
#[arg(long)] #[arg(long)]
pub exampleconfig: bool, pub exampleconfig: bool,
/// Run as a system service (no interactive output). /// Default to warning-level logging for service use; -v/-q override this.
/// The process remains in the foreground.
#[arg(short = 's', long)] #[arg(short = 's', long)]
pub service: bool, pub service: bool,
/// Display local node status and exit. /// Query node status over Reticulum and exit (use `--remote` for another node).
#[arg(long)] #[arg(long)]
pub status: bool, pub status: bool,
@@ -107,7 +108,7 @@ pub struct Args {
#[arg(short = 'r', long, value_name = "DEST_HASH")] #[arg(short = 'r', long, value_name = "DEST_HASH")]
pub remote: Option<String>, pub remote: Option<String>,
/// Identity path used for remote query operations. /// Identity path used for local or remote control queries.
#[arg(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub identity: Option<PathBuf>, pub identity: Option<PathBuf>,
@@ -115,22 +116,24 @@ pub struct Args {
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])] #[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
pub send: Option<Vec<String>>, pub send: Option<Vec<String>>,
/// Read outgoing --send content from a UTF-8 file instead of argv. /// Read outgoing `--send` content from a UTF-8 file instead of argv.
#[arg(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub send_file: Option<PathBuf>, pub send_file: Option<PathBuf>,
/// Delivery method for --send. /// Delivery method for `--send`.
#[arg(long, value_enum, default_value_t = SendMethod::Opportunistic)] #[arg(long, value_enum, default_value_t = SendMethod::Opportunistic)]
pub send_method: SendMethod, pub send_method: SendMethod,
/// Link/resource completion timeout for --send. /// Nominal wait in seconds for each `--send` completion phase. Each poll
/// includes a one-second sleep; discovery and work between polls add time.
#[arg(long, default_value_t = 90)] #[arg(long, default_value_t = 90)]
pub send_timeout_secs: u64, pub send_timeout_secs: u64,
/// Attach custom LXMF fields to the outgoing --send message. Accepts a /// Attach binary LXMF fields to `--send`. Accepts a JSON object mapping
/// JSON object mapping field-id -> base64(value). Example: /// decimal field IDs (0–255) to base64-encoded bytes. Example:
/// --send-fields-json '{"1":"aGVsbG8=","42":"AAECA/8="}' /// `--send-fields-json '{"200":"aGVsbG8=","201":"AAECA/8="}'`.
/// Only meaningful alongside --send. /// Choose IDs agreed with the receiving application. This option does not
/// construct native structured MessagePack fields. Only used with `--send`.
#[arg(long, value_name = "JSON")] #[arg(long, value_name = "JSON")]
pub send_fields_json: Option<String>, pub send_fields_json: Option<String>,
} }
@@ -203,7 +206,8 @@ autopeer_maxdepth = 6
# Let configured static peers bypass sequential validation and inbound limits. # Let configured static peers bypass sequential validation and inbound limits.
# static_peers_bypass_sequential = yes # static_peers_bypass_sequential = yes
# Maximum concurrent inbound propagation sync transfers. # Threshold for new inbound propagation sync offers. Already accepted offers
# and static-peer bypass can exceed this value.
# max_inbound_syncs = 3 # max_inbound_syncs = 3
# message_storage_limit = 500 # message_storage_limit = 500
@@ -253,9 +257,9 @@ loglevel = 4
} }
/// Parse a plaintext destination-hash list: one 16-byte hex value per line. /// Parse a plaintext destination-hash list: one 16-byte hex value per line.
/// Missing files return empty. Like Python `lxmd.py`, this accepts only raw /// Read errors return an empty list. Each line must contain exactly 32 ASCII
/// 32-byte hex lines; comments and inline comments are ignored only because /// hexadecimal characters; a trailing CR is allowed for CRLF files. Whitespace
/// their raw line length is not exactly 32 bytes. /// and comments are not stripped, so lines containing them are skipped.
/// ///
/// Python reference: `lxmd.py` reads `ignored` / `allowed` from the config dir. /// Python reference: `lxmd.py` reads `ignored` / `allowed` from the config dir.
pub fn load_hash_list(path: &Path) -> Vec<[u8; 16]> { pub fn load_hash_list(path: &Path) -> Vec<[u8; 16]> {
+3 -3
View File
@@ -1,7 +1,7 @@
//! Pure `lxmd` runtime helpers extracted from the binary. //! `lxmd` path selection, control-command preflight, and status formatting.
//! //!
//! This module keeps daemon path handling and other pure helpers out of the //! Path selection reads environment variables and checks the filesystem;
//! binary so CLI behavior can be tested directly. //! these helpers do not start the daemon runtime.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
+8 -3
View File
@@ -70,9 +70,14 @@ def verify(directory: Path, tag: str) -> None:
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(
parser.add_argument("--tag", required=True) description="Check the three release archives, then write SHA256SUMS."
parser.add_argument("--directory", type=Path, required=True) )
parser.add_argument("--tag", required=True, help="release version in vX.Y.Z form, as used in archive names")
parser.add_argument(
"--directory", type=Path, required=True,
help="directory containing only the three platform archives; SHA256SUMS is written here after validation",
)
args = parser.parse_args() args = parser.parse_args()
verify(args.directory, args.tag) verify(args.directory, args.tag)
+3 -3
View File
@@ -211,10 +211,10 @@ def check_candidate_tag(tag: str, version: str) -> None:
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(description=__doc__)
tags = parser.add_mutually_exclusive_group() tags = parser.add_mutually_exclusive_group()
tags.add_argument("--release-tag") tags.add_argument("--release-tag", help="also verify the existing annotated vX.Y.Z tag matches the workspace version and HEAD")
tags.add_argument("--candidate-tag") tags.add_argument("--candidate-tag", help="also verify vX.Y.Z matches the workspace version and has no local tag yet")
args = parser.parse_args() args = parser.parse_args()
version, reticulum_version = check_packages(metadata()) version, reticulum_version = check_packages(metadata())
+8 -3
View File
@@ -274,10 +274,15 @@ def render_snapshot(
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(
parser.add_argument("--metadata-only", action="store_true") description="Compare current public APIs with the stored snapshots, or refresh them after review."
)
parser.add_argument(
"--metadata-only", action="store_true",
help="validate metadata, package inventory and stored snapshot hashes without generating API output; incompatible with --update",
)
parser.add_argument("--update", action="store_true", parser.add_argument("--update", action="store_true",
help="refresh snapshots from the working tree to commit alongside source changes") help="regenerate snapshots and update their counts/hashes in api/stability.json; review the diff before committing")
parser.add_argument("--snapshot-source-commit", parser.add_argument("--snapshot-source-commit",
help="optional HEAD guard for --update; includes uncommitted source changes") help="optional HEAD guard for --update; includes uncommitted source changes")
args = parser.parse_args() args = parser.parse_args()
+4 -2
View File
@@ -122,12 +122,14 @@ def render_contract() -> str:
def main() -> None: def main() -> None:
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(
description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json."
)
parser.add_argument( parser.add_argument(
"--print", "--print",
action="store_true", action="store_true",
dest="print_contract", dest="print_contract",
help="print the current canonical contract for reviewed application", help="print current Cargo contract JSON instead of comparing it with the saved snapshot",
) )
args = parser.parse_args() args = parser.parse_args()
rendered = render_contract() rendered = render_contract()