Compare commits

..
92 Commits
Author SHA1 Message Date
DeFiDude 5c18a5f8e6 ci: pin rsReticulum f6d0d69 2026-11-20 12:57:54 -07:00
DeFiDude 483bf7f970 propagation: the delivery limit bounds only a message download, not the ID list 2026-11-20 11:47:18 -07:00
DeFiDude 094c49bd83 ci: pin rsReticulum 54c8525 2026-11-19 20:51:38 -07:00
DeFiDude 3d606ca703 message: a signed message lends out its attachment bytes 2026-11-19 20:47:47 -07:00
DeFiDude 419711b0ee propagation: the Offline Inbox client refuses a response larger than its delivery limit allows 2026-11-19 20:28:05 -07:00
DeFiDude 9436d052c5 message: media fields encode once at their size, and signing builds the wire in place 2026-11-19 20:28:05 -07:00
DeFiDude 70fa224211 ci: pin rsReticulum 5e35c9f 2026-11-19 09:33:10 -07:00
DeFiDude 2d04201bff ci: pin rsReticulum 0ce5a12 2026-11-19 08:55:25 -07:00
DeFiDude 7cbb87cd47 test: lxmd's ratchet test re-announces a second later, past Reticulum's same-second prefilter 2026-11-19 08:52:27 -07:00
DeFiDude b92923e2ec ci: pin rsReticulum 3d53958 2026-11-19 07:54:34 -07:00
DeFiDude bc04e75c4b lxmd: deregister destination types once at exit, through runtime shutdown 2026-11-18 20:11:17 -07:00
DeFiDude 2e057f6172 readme: 1.5.1 follows LXMF 1.3.1 and Reticulum 1.6.1 2026-11-18 17:14:39 -07:00
DeFiDude e2719fbe07 release: version 1.5.1 2026-11-18 17:08:58 -07:00
DeFiDude f65ffa6295 stamps: fractional PN stamp test uses a stamp only the expanded form accepts 2026-11-18 16:54:38 -07:00
DeFiDude 932d59ab74 lxmf: report LXMF 1.3.1 2026-11-18 16:54:38 -07:00
DeFiDude eae4fd50a4 stamps: accept both LXMF workblock forms 2026-11-18 12:59:15 -07:00
DeFiDude bc07d04396 discovery: delegate both-form stamp validation 2026-11-18 12:54:32 -07:00
DeFiDude eee86a37c2 build: lock rsReticulum 1.5.1 2026-11-18 11:36:52 -07:00
DeFiDude b21732352b lxmd: startup logs the full identity, delivery, and propagation hashes as lxmd does 2026-11-15 19:46:27 -07:00
DeFiDude 2520ee1594 ci: pin rsReticulum 184bbfe 2026-11-15 10:08:18 -07:00
DeFiDude 65d43b19a8 ci: pin rsReticulum 81e6188 2026-11-15 08:51:42 -07:00
DeFiDude cf56eb3f1f ci: pin rsReticulum 0680941 2026-11-15 07:20:50 -07:00
DeFiDude 8380416ad5 lxmd: the ctrl-c test kills and reaps its daemon on every path 2026-11-15 04:38:40 -07:00
DeFiDude fa02487ef8 ci: pin rsReticulum cce85ec 2026-11-15 00:26:45 -07:00
DeFiDude 8f0bda8653 ci: pin rsReticulum 1.5.0 2026-11-14 19:38:57 -07:00
DeFiDude d946da1b2a lxmd: drop the hand-over of earlier releases' received ratchets 2026-11-14 01:18:58 -07:00
DeFiDude 9209d9f888 docs: README and changelog for 1.5.0 2026-11-14 00:02:11 -07:00
DeFiDude 91da3bf6df api: version 1.5.0 with refreshed baselines and the 1.5 migration guide 2026-11-13 23:06:43 -07:00
DeFiDude 1b6002e162 build: take rns-tools without the rnodeconf firmware feature 2026-11-13 21:56:43 -07:00
DeFiDude caeb3ffd1b propagation: a node announces the LXMF version it follows 2026-11-13 18:28:52 -07:00
DeFiDude 49728b0f4a build: lxmf-core builds without SQLite when default features are off 2026-11-13 18:08:48 -07:00
DeFiDude 3be3248b58 propagation: turn a node's announce into its policy in one place 2026-11-13 17:53:58 -07:00
DeFiDude 3110cf1a0e lxmd: use Reticulum's ratchet store; unknown announce facts stay unknown
Ratchet files from earlier releases are handed to Reticulum's import
once.
2026-11-13 16:54:34 -07:00
DeFiDude 146ade134c router: keep delivered ids, stamp costs, and tickets in LXMF's state.db
Cache files from earlier versions are imported once. A file that cannot
be used never stops the router.
2026-11-13 14:43:36 -07:00
DeFiDude c90b371c3d lxmd: accept the released -c and -V spellings with a warning 2026-11-13 13:59:58 -07:00
DeFiDude c6fd9e488b lxmd: print the LXMF and Reticulum versions it follows; drop -c and -V 2026-11-13 13:03:30 -07:00
DeFiDude ec3924a812 build: lock file gains the SQLite dependencies 2026-11-13 11:25:03 -07:00
DeFiDude 747aa966f6 api: make config structs non-exhaustive and the outbound module private 2026-11-13 11:25:03 -07:00
DeFiDude d508f19b77 api: type router limits as PnLimit and hide the delivery-claim helpers 2026-11-13 10:12:42 -07:00
DeFiDude 68fe75d34e delivery: a link that fails or closes leaves settled messages alone 2026-11-12 07:42:34 -07:00
DeFiDude cdc8df4b01 lxmf: cite upstream files without line numbers in comments 2026-11-12 06:58:08 -07:00
DeFiDude db559f282d api: update the baselines and draft the next release's migration guide 2026-11-12 05:26:29 -07:00
DeFiDude aa728fde06 lxmf: drop an older upstream version name from comments 2026-11-11 22:29:29 -07:00
DeFiDude ba4202a18a lxmd: keep one processed store and bound the announce backlog 2026-11-11 09:25:42 -07:00
DeFiDude a5ad58e999 lxmf: receive Resources without a segment cap and carry the window over 2026-11-11 09:21:10 -07:00
DeFiDude 01da92ecd4 lxmf: signal the next-hop MTU on delivery, download, and peer sync links 2026-11-11 04:05:31 -07:00
DeFiDude 455e0b1476 propagation: match upstream in the client's requests, purges, and errors 2026-11-11 00:52:26 -07:00
DeFiDude 1f5a51b8b2 lxmf: links can open with prepared request keys 2026-11-10 22:48:47 -07:00
DeFiDude 5939c7b124 propagation: follow upstream store limits, unpeering, and identify retry 2026-11-10 22:22:09 -07:00
DeFiDude 2ae0610272 tests: pass the link SDU through the propagation client test 2026-11-10 21:51:16 -07:00
DeFiDude 1a7d5aaa90 lxmf: send and honour Resource cancels in delivery and propagation 2026-11-10 20:57:10 -07:00
DeFiDude 747c7e98ab lxmd: control commands wait for a path to the control destination 2026-11-10 19:45:15 -07:00
DeFiDude ff3bf1031c propagation: add a configurable stamp throttle and drop ignored sources 2026-11-10 19:19:20 -07:00
DeFiDude ed3ec7070c router: journal delivery claims and keep upstream's delivery metadata 2026-11-10 19:12:40 -07:00
DeFiDude 186ffb48e3 lxmf: check the proof cache after a Resource proof times out 2026-11-10 15:36:52 -07:00
DeFiDude 1a9830008c lxmf: stamp link requests, wait for paths, and pick peers like upstream 2026-11-10 13:37:20 -07:00
DeFiDude 052128bf4e delivery: count inbound link data toward link liveness 2026-11-10 12:45:02 -07:00
DeFiDude 5d9320d7da propagation: follow the Resource reassembly limit API 2026-11-10 12:35:45 -07:00
DeFiDude ea5c61aa6f router: rework outbound delivery to follow upstream's process_outbound 2026-11-10 12:23:55 -07:00
DeFiDude f855bcfbe5 router: follow upstream on paper messages, PLAIN sends, and compression 2026-11-10 10:17:56 -07:00
DeFiDude d486ae85d7 lxmd: follow upstream config, exit codes, and logging; close idle links 2026-11-10 09:56:26 -07:00
DeFiDude 3e9341ad66 lxmd: announce through the stamped announce builder 2026-11-10 08:41:04 -07:00
DeFiDude b6db122563 lxmd: send no stats reply when it is not a propagation node 2026-11-10 08:14:57 -07:00
DeFiDude d3ad54a457 delivery: send link packet proofs with upstream's context 2026-11-10 07:16:18 -07:00
DeFiDude 4f04bcac4e lxmd: keep node announces out of the delivery stamp cost cache 2026-11-10 06:35:05 -07:00
DeFiDude 7edeff229e lxmd: take the log level from its own config and flags, as upstream does 2026-11-10 05:18:02 -07:00
DeFiDude 05ab881975 lxmd: match upstream control requests, announces, and peering config 2026-11-10 05:08:58 -07:00
DeFiDude 01764f3238 lxmd: register its destination types with the shared instance 2026-11-10 04:14:12 -07:00
DeFiDude c65f9ef960 lxmf: support fractional stamp costs and announce them as upstream does 2026-11-10 03:28:42 -07:00
DeFiDude c8a793b0d5 lxmd: answer control requests with a packed value reply 2026-11-10 02:16:22 -07:00
DeFiDude 718419b9d0 lxmf: build the discovery stamper on Reticulum's stamp code 2026-11-10 01:43:29 -07:00
DeFiDude 408d088e56 lxmf: hash messages canonically and match upstream names and paper URIs 2026-11-10 00:00:36 -07:00
DeFiDude 00f439df7e Release 1.4.0 2026-11-08 11:54:07 -07:00
DeFiDude 5a6a0cbbdb Replace invalid AGPL license with Reticulum License
This repository is a port of LXMF, which is licensed under the Reticulum
License. The AGPL-3.0-or-later grant previously in LICENSE was never
effective, because there was no right to place the derived code under AGPL
terms. The Reticulum License now in LICENSE governs every revision in this
repository's history, not only revisions from this commit forward. Additions
and modifications by Ratspeak LLC remain its copyright and are licensed under
the same terms.
2026-11-07 20:49:18 -07:00
DeFiDude 18b99b8932 docs: refresh guides and reference help 2026-11-02 11:13:50 -07:00
DeFiDude b5c3365b57 build: pin rsReticulum to the commit the lockfiles match 2026-10-26 09:04:26 -06:00
DeFiDude 7922c5d7b0 router: retain delivered destinations in Reticulum, as Python LXMF does 2026-10-25 21:26:31 -06:00
DeFiDude bc25696fda router: generate deferred stamps in submission order 2026-10-25 21:13:04 -06:00
DeFiDude e674b3f24b router: resume a stored signed message under its own id 2026-10-25 21:06:21 -06:00
DeFiDude 9bb80d754b build: lock the AES zeroize dependencies 2026-10-25 10:14:00 -06:00
DeFiDude f45abdc335 build: lock rns-link's clock dependencies in the API fixture 2026-10-25 09:34:28 -06:00
DeFiDude 0da6a73b5d build: lock rns-link's new clock dependencies 2026-10-25 06:35:40 -06:00
DeFiDude cfd9a9e82d lxmd: learn the identities Reticulum validated before it subscribed, and recall missing ones 2026-10-25 06:04:18 -06:00
DeFiDude ea09b0e105 router: fall back to direct delivery above Python's 287-byte opportunistic limit 2026-10-25 02:51:46 -06:00
DeFiDude 769d0eb0a3 lxmd: space propagation node announces like Python lxmd 2026-10-21 14:45:25 -06:00
DeFiDude bf348ae810 tests: skip long backdated timeouts on freshly booted Windows clocks 2026-10-20 23:30:56 -06:00
DeFiDude 32084c24a1 docs: accept network and RAM-backed relay storage with a warning 2026-10-20 20:27:13 -06:00
DeFiDude f6a402363f ci: pin Rust 1.96.0 instead of floating stable 2026-10-20 20:08:40 -06:00
DeFiDude ecfb115027 propagation: start without rereading and re-flushing every stored message 2026-10-20 19:53:20 -06:00
DeFiDude 580fe1deab lxmf: harden relay replies and crypto storage initialization 2026-10-13 17:47:25 -06:00
DeFiDude 652dc3cd46 daemon: restore direct receipts and authenticated ticket learning 2026-10-13 00:56:16 -06:00
DeFiDude 66e22cb41f lxmf: require durable propagation acceptance and immutable messages 2026-10-13 00:32:49 -06:00
78 changed files with 30423 additions and 12067 deletions

No files matched your search

+3 -3
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
api-compat:
@@ -69,7 +69,7 @@ jobs:
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
@@ -98,7 +98,7 @@ jobs:
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
toolchain: 1.96.0
components: clippy, rustfmt
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
+2 -2
View File
@@ -24,8 +24,8 @@ env:
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_VERSION: 1.3.0
RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8
RSLXMF_RSRETICULUM_VERSION: 1.5.1
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
verify:
+45
View File
@@ -2,6 +2,51 @@
## Unreleased
## 1.5.1 - 2026-11-18
- **Follows Python LXMF 1.3.1** with Reticulum 1.6.1 (rsReticulum 1.5.1), and reports LXMF 1.3.1, propagation-node announces included.
- Message, propagation-node, and peering stamps are accepted in both workblock forms: the non-expanded one LXMF senders are moving to, tried first, then the expanded one. A stamp's value comes from the form that passed. Generation stays expanded until senders switch.
- Discovery stamps are validated in both forms through rsReticulum's discovery stamper.
## 1.5.0 - 2026-11-13
### Added
- **Fractional stamp costs**: stamp costs can be fractional, as in LXMF 1.3.0, and announces carry them where LXMF 1.3.0 reads them.
- **Stamped links**: delivery, propagation downloads, and peer sync stamp their link requests when the destination asks for it, following Reticulum's `[stamps]` settings. With stamping on, `lxmd-rs` also stamps its own announces.
### Fixed and improved
- `lxmd-rs` reads its config as Python's `lxmd` does: a malformed value, or a stamp cost of 100 or more, now stops it instead of being replaced by a default. It writes a default config on first run and, as a service, logs to `logfile` in its config directory.
- `lxmd-rs --version` prints `lxmd-rs 1.5.0 (LXMF 1.3.0, Reticulum 1.6.0)`, and it logs at Notice by default.
- Control commands (`--status`, `--peers`, `--sync`, `--break`) wait for a path to the node within `--timeout`.
- Propagation nodes follow LXMF 1.3.0 in storage limits, peering, and sync, throttle peers that send invalid stamps, and announce LXMF 1.3.0 as their version.
- The propagation client waits for a path, reuses an open link, and reports a missing path, refused access, and a missing identity as separate failures.
- Outgoing messages reuse an open link to the same destination, and a link that closes no longer fails messages it already delivered.
- Paper messages are checked for duplicates, and messages are compressed only when the recipient says it supports it.
- Message ids and signatures match Python LXMF for messages packed by any encoder. Display names in announces are passed through unchanged; use `presentation::sanitize_name` before showing one.
### Build and compatibility
- Delivered message ids, stamp costs, and tickets are stored in `lxmf/state.db`, the same SQLite store LXMF 1.3.0 uses, and ratchets and identities are left to Reticulum. The old cache files are imported on first start, and `lxmd-rs`'s old ratchet and identity files are removed: each contact's ratchet returns with its next announce. Going back to an older release starts without them.
- Breaking API changes are listed in the [1.5 migration guide](api/migrations/1.5.md); use the `~1.5.0` line with rsReticulum `~1.5.0`. The default `sqlite-store` feature builds a bundled SQLite, so builds need a C compiler.
## 1.4.0 - 2026-11-08
- Start a propagation node without rereading and flushing every stored message, so restarts with large stores no longer delay announces and hosting. Each message is still verified when it is served.
- Space `lxmd` announces like Python lxmd: the propagation and control announces follow their trigger by 20 seconds instead of going out together with the delivery announce, so Python transport nodes no longer hold the control announce after a restart. A node set not to announce at start now waits a full interval before its first periodic announce.
- Fall back from opportunistic to direct delivery whenever a message's content does not fit one encrypted packet, over 287 bytes, as in Python LXMF 1.2.0.
- `lxmd` learns the identities Reticulum validated before it subscribed to announces, and asks Reticulum for a missing identity before a propagation download, a delivery or a peer sync, as Python LXMF recalls them.
- Store a signed message so its delivery can resume after a restart under the same id. A message that is already queued is no longer queued twice.
- Generate deferred stamps in the order messages were sent, as Python LXMF does, so a reply no longer overtakes the message it answers.
- Keep a destination's identity in Reticulum once a message to it is delivered, as Python LXMF does. `lxmd` asks the shared instance when attached to one.
- 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.
- 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.
- 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`. Use the `~1.4.0` compatibility line for these source-breaking APIs.
## 1.3.0 - 2026-10-12
### Added
Generated
+260 -36
View File
@@ -11,6 +11,19 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
@@ -132,15 +145,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block2"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2",
]
[[package]]
name = "bytes"
version = "1.11.1"
@@ -165,6 +169,16 @@ dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
@@ -191,6 +205,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -324,6 +339,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"pem-rfc7468",
"zeroize",
]
@@ -334,6 +350,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
@@ -379,6 +396,18 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.4.1"
@@ -391,6 +420,12 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "fnv"
version = "1.0.7"
@@ -449,6 +484,15 @@ dependencies = [
"wasip3",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -464,6 +508,15 @@ version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [
"hashbrown 0.14.5",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -601,6 +654,9 @@ name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
dependencies = [
"spin",
]
[[package]]
name = "leb128fmt"
@@ -620,6 +676,23 @@ version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -643,11 +716,13 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2",
"proptest",
"rand 0.8.5",
"rmp",
@@ -659,18 +734,20 @@ dependencies = [
"rns-protocol",
"rns-transport",
"rns-wire",
"rusqlite",
"serde",
"sha2",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tracing",
"unicode-general-category",
"unicode-normalization",
]
[[package]]
name = "lxmf-tools"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
@@ -681,13 +758,15 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-runtime",
"rns-tools",
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tracing",
"tracing-subscriber",
"zeroize",
]
[[package]]
@@ -758,6 +837,41 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-bigint-dig"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
dependencies = [
"lazy_static",
"libm",
"num-integer",
"num-iter",
"num-traits",
"rand 0.8.5",
"smallvec",
"zeroize",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -765,31 +879,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
name = "objc-sys"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.5.2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc-sys",
"objc2-encode",
]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2-foundation",
]
@@ -802,13 +909,11 @@ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
]
@@ -847,12 +952,32 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
dependencies = [
"base64ct",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkcs1"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
dependencies = [
"der",
"pkcs8",
"spki",
]
[[package]]
name = "pkcs8"
version = "0.10.2"
@@ -863,6 +988,12 @@ dependencies = [
"spki",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -1052,7 +1183,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"aes",
"cbc",
@@ -1070,9 +1201,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmp-serde",
"rmpv",
@@ -1080,6 +1212,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
@@ -1088,7 +1221,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1117,9 +1250,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmpv",
"rns-crypto",
@@ -1127,12 +1261,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bzip2",
"hex",
@@ -1141,6 +1276,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -1148,7 +1284,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1167,15 +1303,43 @@ dependencies = [
"serde",
"sha2",
"subtle",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "rns-tools"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
"clap",
"hex",
"nix 0.29.0",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-interface",
"rns-runtime",
"rns-transport",
"rns-wire",
"rsa",
"serde",
"serde_json",
"serialport",
"sha2",
"tokio",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1185,6 +1349,7 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"rusqlite",
"serde",
"subtle",
"thiserror 2.0.18",
@@ -1194,13 +1359,47 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"rns-crypto",
"sha2",
"thiserror 2.0.18",
]
[[package]]
name = "rsa"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
dependencies = [
"const-oid",
"digest",
"num-bigint-dig",
"num-integer",
"num-traits",
"pkcs1",
"pkcs8",
"rand_core 0.6.4",
"signature",
"spki",
"subtle",
"zeroize",
]
[[package]]
name = "rusqlite"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
dependencies = [
"bitflags 2.11.0",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -1347,6 +1546,12 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -1363,6 +1568,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core 0.6.4",
]
@@ -1392,6 +1598,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
[[package]]
name = "spki"
version = "0.7.3"
@@ -1608,6 +1820,12 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "unicode-general-category"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2281c8c1d221438e373249e065ca4989c4c36952c211ff21a0ee91c44a3869e7"
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -1641,6 +1859,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
+17 -12
View File
@@ -6,25 +6,26 @@ members = [
]
[workspace.package]
version = "1.3.0"
version = "1.5.1"
edition = "2024"
license = "AGPL-3.0-or-later"
license-file = "LICENSE"
rust-version = "1.89"
[workspace.dependencies]
# Reticulum crates from a sibling rsReticulum checkout during development.
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.5.1" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.5.1" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.5.1" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.5.1" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.5.1" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.5.1", default-features = false }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.5.1" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.5.1" }
rns-tools = { path = "../rsReticulum/crates/rns-tools", version = "~1.5.1", default-features = false }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.3.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.3.0" }
lxmf-core = { path = "crates/lxmf-core", version = "~1.5.1" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.5.1" }
# Encoding
base64 = "0.22"
@@ -54,10 +55,14 @@ tracing-subscriber = "0.3"
# Error handling
thiserror = "2"
# SQLite (router state, LXMF 1.3.0 state.db)
rusqlite = { version = "0.32", features = ["bundled"] }
# Misc
hex = "0.4"
tempfile = "3"
unicode-normalization = "0.1"
unicode-general-category = "0.6"
# Testing
proptest = "1"
+26 -653
View File
@@ -1,661 +1,34 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Reticulum License
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Derived from the reference implementation at
https://github.com/markqvist/LXMF
Preamble
Copyright (c) 2020-2026 Mark Qvist, unless otherwise noted
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Additions and modifications Copyright (c) 2026 Ratspeak LLC
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- The Software shall not be used in any kind of system which includes amongst
its functions the ability to purposefully do harm to human beings.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
- The Software shall not be used, directly or indirectly, in the creation of
an artificial intelligence, machine learning or language model training
dataset, including but not limited to any use that contributes to the
training or development of such a model or algorithm.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+76 -62
View File
@@ -4,10 +4,10 @@
**Rust LXMF messaging and propagation for Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![License: Reticulum License](https://img.shields.io/badge/license-Reticulum%20License-blue.svg)](LICENSE)
[![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)
[![Current reference: LXMF 1.1.0](https://img.shields.io/badge/current%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![Baseline: LXMF 1.3.1](https://img.shields.io/badge/baseline-LXMF%201.3.1-success.svg)](https://github.com/markqvist/LXMF)
[![Reticulum 1.6.1](https://img.shields.io/badge/reticulum-1.6.1-blue.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[LXMF Reference](https://github.com/markqvist/LXMF) |
@@ -19,10 +19,10 @@
---
rsLXMF is a Rust implementation of LXMF, the Reticulum messaging layer. This is not a fork of LXMF, this is LXMF written in a different language focused on staying interoperable. This is not a source of truth implementation, do not use it as such.
Commands are intentionally namespaced for Rust with the Rust-specific `lxmd-rs` command, so rsLXMF can live beside other
LXMF daemons on `PATH` without worry.
rsLXMF is a Rust port of [LXMF](https://github.com/markqvist/LXMF), the
Reticulum messaging layer, from the reference implementation by Mark Qvist. It
was written from the reference source, not from a specification, and tracks the
reference's wire behavior release by release.
## Contents
@@ -33,11 +33,12 @@ LXMF daemons on `PATH` without worry.
- [Delivery Model](#delivery-model)
- [Feature Status](#feature-status)
- [Compatibility Notes](#compatibility-notes)
- [Contributing](#contributing)
- [License](#license)
## Build It
This guide describes the 1.5.1 release, [v1.5.1](https://github.com/ratspeak/rsLXMF/releases/tag/v1.5.1), built with rsReticulum [v1.5.1](https://github.com/ratspeak/rsReticulum/releases/tag/v1.5.1), the source line Ratspeak builds from.
The current development layout for rsLXMF requires
rsReticulum as a sibling directory/repo next to it, such as:
@@ -52,9 +53,13 @@ mkdir ratspeak-src
cd ratspeak-src
git clone https://github.com/ratspeak/rsReticulum
git clone https://github.com/ratspeak/rsLXMF
git -C rsReticulum checkout --detach v1.5.1
git -C rsLXMF checkout --detach v1.5.1
cd rsLXMF
```
Run the build commands below from that `rsLXMF` directory. The host crates require Rust 1.89 or newer. The default build compiles a bundled SQLite, so it also needs a C compiler; the build tools below provide one.
### macOS
Install Rust with `rustup`, then install Apple's build tools:
@@ -66,7 +71,6 @@ xcode-select --install
Build from the sibling checkout:
```bash
cd rsLXMF
cargo build --release --locked
```
@@ -78,25 +82,24 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
sudo apt install -y build-essential pkg-config
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
sudo dnf install gcc make pkgconf-pkg-config
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
sudo pacman -S --needed base-devel pkgconf
```
#### Build the daemon:
```bash
cd rsLXMF
cargo build --release --locked
```
@@ -108,7 +111,6 @@ Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell:
```powershell
cd rsLXMF
cargo build --release --locked
```
@@ -125,7 +127,7 @@ macOS/Linux or `.\target\release\lxmd-rs.exe` on Windows.
Generate the example config:
Print the example configuration to standard output:
```bash
lxmd-rs --exampleconfig
@@ -143,11 +145,11 @@ Run a 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
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
@@ -157,7 +159,7 @@ Send UTF-8 file content or select a delivery method:
```bash
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
@@ -167,20 +169,23 @@ Attach custom LXMF fields from scripts:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> "with fields" \
--send-fields-json '{"1":"aGVsbG8=","42":"AAECAw=="}'
--send "DELIVERY_DESTINATION_HASH" "with fields" \
--send-fields-json '{"200":"aGVsbG8=","201":"AAECAw=="}'
```
The JSON object maps field IDs to base64-encoded bytes. It is only a shell
convenience; LXMF fields remain MessagePack field maps on the wire.
The CLI JSON object maps IDs from 0 to 255 to base64-encoded binary values.
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:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --status
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --peers
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync <peer_hash>
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break <peer_hash>
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync "PEER_PROPAGATION_HASH"
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break "PEER_PROPAGATION_HASH"
```
These commands query an `lxmf.propagation.control` endpoint over Reticulum.
@@ -192,7 +197,7 @@ For a remote propagation node, pass the node's propagation destination hash:
```bash
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`
@@ -218,6 +223,8 @@ If no LXMF config directory is supplied, the default is:
| Linux/macOS | `/etc/rsLXMF/config`, then `~/.config/rsLXMF/config`, then `~/.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
rsReticulum-specific defaults.
@@ -232,7 +239,7 @@ Recommended standalone locations:
Use existing LXMF or Reticulum directories, such as `~/.lxmd`, `~/.lxmf`, or
`~/.reticulum`, only by passing them explicitly. That keeps the default install
isolated while still allowing deliberate drop-in and migration tests.
isolated.
Minimal config:
@@ -251,8 +258,8 @@ autopeer = yes
autopeer_maxdepth = 6
auth_required = no
# node_name = Rat Nest
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d
# outbound_node = e17f833c4ddf8890dd3a79a6fea8161d
# static_peers = 0123456789abcdef0123456789abcdef
# outbound_node = 0123456789abcdef0123456789abcdef
# max_peers = 20
# propagation_stamp_cost_target = 16
# propagation_stamp_cost_flexibility = 3
@@ -261,17 +268,16 @@ auth_required = no
loglevel = 4
```
The standalone daemon follows current Python LXMF 1.1.0 and defaults this
setting to 1 decimal KB when it is omitted. This is intentionally distinct
from the reusable router library's 1000 KB default. Applications that accept
`delivery_transfer_max_accepted_size` limits incoming Direct Resource data
in decimal KB and defaults to 1 when omitted. The reusable router library has a separate 1000 KB default. Applications that accept
larger incoming messages should set their own explicit policy.
Supported sections:
Common sections and supported keys (see `--exampleconfig` for annotated defaults):
| Section | Keys |
| --- | --- |
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_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`, `propagation_stamp_throttle`, `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` |
| `[logging]` | `loglevel` |
@@ -279,10 +285,17 @@ Optional hash-list files live next to `<config-dir>/config`:
| File | Meaning |
| --- | --- |
| `ignored` | Hashes loaded into the router ignored list. |
| `allowed` | Hashes loaded into the router delivery allow-list. Empty means no allow-list restriction. |
| `ignored` | LXMF destination hashes to ignore. |
| `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.
Router state (delivered and processed transient IDs, stamp costs, and tickets)
is kept in `<config-dir>/storage/lxmf/state.db`, the SQLite file LXMF 1.3.1 uses.
Received ratchets are kept
by Reticulum in its own storage. These stores come from the default
`sqlite-store` feature of `lxmf-core`; without it, router state lasts only for
the session.
## Delivery Model
@@ -291,7 +304,7 @@ and, where network-backed, through `lxmd-rs --send-method`.
| 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. |
| 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. |
@@ -312,13 +325,16 @@ signature 64 bytes
payload MessagePack([timestamp, title, content, fields, optional_stamp])
```
`title` and `content` are bytes on the wire. `fields` is a `map<u8, bytes>` for
application-defined data such as tickets, attachments, location data, or
application envelopes.
`title` and `content` are bytes on the wire. `fields` maps integer IDs to
MessagePack values, which can be binary, text, arrays, maps or other supported
values. Standard fields have defined schemas. The 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
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a
requested ticket that would require changing an already-signed message.
Construct `LxMessageDraft` and set `include_ticket` before calling
`LxmRouter::prepare_outbound`; any reply ticket it adds is already in the
router's state store when the call returns. Signing consumes the draft, and
finalization produces an immutable message.
## Feature Status
@@ -326,35 +342,33 @@ requested ticket that would require changing an already-signed message.
| 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. |
| 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. |
| 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, fractional and cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
| Access lists | `ignored` and `allowed` hash-list files in the LXMF config directory. |
## Compatibility Notes
Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
`--propagation-node`, `--on-inbound`, `--status`, `--peers`, `--sync`,
`--break`, `--remote`, `--identity`, `--timeout`, `--exampleconfig`, and
`--version`.
All upstream `lxmd` flags are implemented: `--config`, `--rnsconfig`,
`--propagation-node`, `--on-inbound`, `--verbose`, `--quiet`, `--service`,
`--status`, `--peers`, `--sync`, `--break`, `--remote`, `--identity`,
`--timeout`, `--exampleconfig`, and `--version`.
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
`--send-timeout-secs`, and `--send-fields-json`.
The complete release-baseline corpus and live matrix use Python LXMF 1.0.1
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
same Reticulum 1.4.2 source. Historical vectors retain their original
provenance, and RNS 1.5.0 is intentionally deferred.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
and Reticulum remain the reference implementations.
PRs are closed for now until I have time to catch up on everything. I'm tired.
rsLXMF 1.5.1 follows Python LXMF 1.3.1 with Reticulum 1.6.1, and
`lxmd-rs --version` names both.
## License
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
rsLXMF is licensed under the [Reticulum License](LICENSE), the license of the
reference implementation it is ported from. Copyright (c) 2020-2026 Mark Qvist,
unless otherwise noted; additions and modifications Copyright (c) 2026 Ratspeak
LLC.
The license is permissive with two conditions: no use in systems built to
purposefully harm people, and no use in or contribution to AI or language-model
training. The copyright and permission notice must stay in every copy.
[LICENSE](LICENSE) is the binding text.
+13 -7
View File
@@ -1,15 +1,20 @@
# Rust API
Application code that constructs or inspects LXMF messages should use
`lxmf_core::message_api`. It re-exports the existing message, status, and
identifier types without wrapping or replacing them. The original
module-qualified paths remain supported.
This guide describes the 1.5.0 API, published as v1.5.0. Application code should use `lxmf_core::message_api`, which
re-exports the message types without wrappers. The equivalent module-qualified
paths remain available. The [1.5 migration guide](migrations/1.5.md) covers
the changes since 1.4.0.
The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path.
## Stability
The 1.5 line follows LXMF 1.3.0. It makes stamp costs and values `f64`, keeps
the router's delivered ids, stamp costs, and tickets in LXMF's SQLite state
store, and marks the router and daemon configuration structs
`#[non_exhaustive]`. See the [1.5 migration guide](migrations/1.5.md).
`lxmf-core` is candidate stable, but that classification does not make every
public implementation detail a permanent API. The message facade is the
recommended application path. Router ownership, delivery orchestration,
@@ -20,8 +25,9 @@ provisional module-qualified APIs.
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library
integration target.
The message facade changes no wire fields, signatures, serialization,
delivery methods, proofs, persistence, or runtime behavior. Later reductions
Choosing the facade instead of the equivalent module-qualified path does not
change behavior. Upgrading from 1.3 to 1.4, and from 1.4 to 1.5, does change
message and persistence APIs; follow the migration guides. Further reductions
to the broader module tree require a reviewed API diff, downstream migration,
and an explicit version decision.
@@ -34,7 +40,7 @@ Keep periodic ticks for protocol deadlines, but schedule application maintenance
separately. Drains are bounded and may leave another ready turn. Cancelling the
wait does not discard a packet or publish an unread endpoint binding; existing
periodic consumers remain supported. The API is provisional delivery-owner
integration (LXMF-02/03, RET-05/07), not a new wire protocol or success signal.
integration, not a new wire protocol or success signal.
`LinkDeliveryManager::set_link_endpoint_dispatch_handle` opts Direct packet
sends into the Reticulum owner's exact local-admission receipts. Supply the
+269 -15
View File
@@ -11,6 +11,19 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
@@ -79,6 +92,22 @@ dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -93,6 +122,17 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
name = "combine"
version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
dependencies = [
"bytes",
"memchr",
]
[[package]]
@@ -203,12 +243,30 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fiat-crypto"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -230,6 +288,24 @@ dependencies = [
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [
"hashbrown",
]
[[package]]
name = "hex"
version = "0.4.3"
@@ -264,6 +340,48 @@ dependencies = [
"generic-array",
]
[[package]]
name = "jni"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec"
dependencies = [
"cesu8",
"combine",
"jni-sys 0.3.1",
"log",
"thiserror 1.0.69",
"walkdir",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
dependencies = [
"jni-sys 0.4.1",
]
[[package]]
name = "jni-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
dependencies = [
"jni-sys-macros",
]
[[package]]
name = "jni-sys-macros"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn 2.0.119",
]
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
@@ -276,6 +394,17 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -285,13 +414,21 @@ dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lxmf-core"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2",
"rand",
"rmp",
"rmp-serde",
@@ -302,11 +439,13 @@ dependencies = [
"rns-protocol",
"rns-transport",
"rns-wire",
"rusqlite",
"serde",
"sha2",
"thiserror",
"thiserror 2.0.20",
"tokio",
"tracing",
"unicode-general-category",
"unicode-normalization",
]
@@ -317,6 +456,12 @@ dependencies = [
"lxmf-core",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mio"
version = "1.2.3"
@@ -337,6 +482,21 @@ dependencies = [
"autocfg",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -382,6 +542,12 @@ dependencies = [
"spki",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -474,11 +640,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
dependencies = [
"rmp",
"serde",
"serde_bytes",
]
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"aes",
"cbc",
@@ -489,16 +657,17 @@ dependencies = [
"rand_core",
"sha2",
"subtle",
"thiserror",
"thiserror 2.0.20",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand",
"rmp-serde",
"rmpv",
@@ -506,7 +675,8 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"thiserror",
"sha2",
"thiserror 2.0.20",
"tracing",
"windows-sys",
"zeroize",
@@ -514,22 +684,24 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-wire",
"thiserror",
"thiserror 2.0.20",
"tracing",
"windows-sys",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bzip2",
"hex",
@@ -538,14 +710,15 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"thiserror",
"serde",
"thiserror 2.0.20",
"tokio",
"tracing",
]
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -555,20 +728,35 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"rusqlite",
"serde",
"subtle",
"thiserror",
"thiserror 2.0.20",
"tokio",
"tracing",
]
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.5.1"
dependencies = [
"rns-crypto",
"sha2",
"thiserror",
"thiserror 2.0.20",
]
[[package]]
name = "rusqlite"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
@@ -580,6 +768,15 @@ dependencies = [
"semver",
]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
@@ -643,6 +840,12 @@ dependencies = [
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -716,13 +919,33 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]]
name = "thiserror"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl",
"thiserror-impl 2.0.20",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
@@ -816,6 +1039,12 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-general-category"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2281c8c1d221438e373249e065ca4989c4c36952c211ff21a0ee91c44a3869e7"
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -831,18 +1060,43 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
+29
View File
@@ -57,3 +57,32 @@ pub mod delivery_ownership {
});
}
}
/// Reviewed immutable construction, full-width keys and source-bound verification.
pub mod immutable_messages {
use lxmf_core::message_api::{
DeliveryMethod, FieldId, LxMessage, LxMessageDraft, MessageError, RecipientStamp,
VerifiedLxMessage,
};
pub fn with_external_signer<F, E>(signer: F) -> Result<LxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct)?;
draft.set_field(FieldId::from(u64::MAX), vec![1, 2])?;
draft.set_msgpack_field(FieldId::from(i64::MIN), vec![0x91, 0x01])?;
let signed = draft.sign_with(signer)?;
let _id = signed.message_id();
signed.finalize(Some(RecipientStamp::Ticket([0; 16])))
}
pub fn inspect<'a>(
message: &'a LxMessage,
public_key: &[u8; 64],
) -> Result<VerifiedLxMessage<'a>, MessageError> {
let _same_owner = message.wire_owned();
let _custom = message.fields().get(u64::MAX);
message.verify(public_key)
}
}
+196
View File
@@ -0,0 +1,196 @@
# Migrating to the 1.4 source API
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
from. These APIs and migration commands require a 1.4 build.
Messages now retain the exact signed bytes received or finalized for sending.
Verification, storage, and delivery metadata cannot change those bytes. The
`message_api` and `message` module paths export the same types.
## Construct, sign, then finalize
This fragment uses `?` to propagate `MessageError` from the enclosing function.
```rust
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
use rns_crypto::ed25519::Ed25519PrivateKey;
let mut draft = LxMessageDraft::new(
[0x11; 16], [0x22; 16], "Hello", "A message", DeliveryMethod::Direct,
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
// When using a router, prepare and durably commit its reply-ticket intent here.
let signed = draft.sign(&Ed25519PrivateKey::generate())?;
let stamp = signed.generate_recipient_stamp()?;
let message = signed.finalize(stamp)?;
let bytes = message.wire_bytes();
```
Use `sign_with` for an external or hardware signer. Both signing methods consume
the draft. Signing refuses a router-prepared ticket whose persistence intent is
still pending. `SignedLxMessage` exposes the stable message ID for recipient
stamp work, but cannot be sent. `finalize(None)` explicitly chooses no recipient
stamp. A finalized message has no content setters, signing method, or assignable
hash/signature/stamp. To change content, construct a new draft and explicitly
copy the desired fields; reply tickets and authentication state are not copied
implicitly. Propagation encryption/stamps belong to their separate send owner.
## Read the immutable message
| Previous access | Replacement |
| --- | --- |
| `message.destination_hash`, `source_hash` | `destination_hash()`, `source_hash()` |
| `message.hash` or `message.message_id` | `message_id()`; always present |
| `message.signature` | `signature()`; always present |
| `message.title`, `content` | `title_text()`, `content_text()` return `Cow<str>`; `*_bytes()` preserve exact bytes |
| `message.timestamp` | `timestamp()` |
| `message.fields`, `msgpack_field_ids` | `fields()` and coherent `FieldValueRef` |
| `message.stamp` | `recipient_stamp()` |
| `message.signature_validated` | successful source-bound `verify` capability |
| `message.wire_payload` | `wire_bytes()` for the complete image |
Mutable delivery metadata remains available through `MessageMetadata` and
field access (`message.method`, `message.progress`, etc.). It cannot alter
content or create authentication authority.
`wire_bytes()` borrows the complete image; `wire_owned()` cheaply shares its
ownership for asynchronous writes. `pack()` explicitly copies it into a Vec.
`pack_payload()` copies the original payload. `unpack_owned(Bytes, limits)`
takes ownership without copying; `unpack(&[u8])` makes a convenience copy.
Container and paper exports preserve these bytes. Repeated verification is pure.
`verify(&full_reticulum_public_key)` checks that the complete 64-byte public key
binds the claimed `lxmf.delivery` source, then verifies the signature. It returns
a private-construction `VerifiedLxMessage` for sender-authorized operations such
as ticket learning. `verify_signature(&ed25519_key)` remains available for
detached diagnostics, but does not establish source identity. Parsing and an
unknown sender are not authenticated-sender status.
## Fields and profiles
`FieldId` preserves integers from `i64::MIN` through `u64::MAX`. Nonnegative IDs
serialize as MessagePack unsigned64; negative IDs as signed64. Equivalent
positive signed and unsigned integer encodings compare equal. Outer duplicate
IDs are rejected, including alternative encodings of the same number. IDs above
255 and negative IDs remain custom keys and never alias a standard field.
`set_field` emits a binary value. `set_msgpack_field` accepts exactly one validated
encoded MessagePack value. `set_field_value` accepts their coherent `FieldValue`
representation. `FieldValueRef::encoded()` exposes exact encoded bytes;
`as_binary()` unwraps only binary. Binary bytes that happen to look like a map
or array do not become structured values. Recognized schema readers can use
`unique_map()` to reject duplicate integer/text keys before acting; unknown
nested values remain opaque. `MessagePayload` is a semantic DTO, not an archive
or signature source.
The host default profile permits 4,096 outer fields and 134,217,727 complete
wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit
`MessageDecodeLimits` when selecting another local policy. Construction checks
count and exact size before signing and finalization, including stamp framing.
These are parser/construction ceilings, not transport promises: Resource segment
limits, metadata, encryption and propagation wrapping impose separate admission
checks. The embedded profile retains 64 fields and depth 8; host-valid custom
messages are not automatically compatible with every device.
Old corrupted files are never silently repaired or re-signed. A hash-shaped
filename that disagrees with its decoded message ID returns a distinct error;
the file is retained. Restore original bytes from a trusted backup when available.
Unknown sender keys cannot establish whether an old signature is valid.
Use the reviewed compatible minor line (for example `~1.4.0`) or an exact source
revision when migrating dependents together. A default caret requirement permits
subsequent minor lines. Do not mix dependent code still using mutable messages
with this API.
## Router, propagation, and asynchronous ownership
`prepare_outbound(&mut draft)` returns an `OutboundTicketIntent`; persist it
through the intended durable state store before signing. A pending intent blocks
the exact draft's signer. `submit_signed` takes a `SignedLxMessage` and handles
recipient-stamp work before finalization; `defer_stamp` and the deferred map also
own signed messages. The former mutable `get_stamp` work belongs to
`SignedLxMessage::generate_recipient_stamp`, while frozen-message stamp checks
are read-only and return a result for the current policy.
`learn_ticket_from_inbound` takes a successful `VerifiedLxMessage`. When a worker
must retain authentication across an asynchronous handoff, use `to_owned()` and
later `OwnedVerifiedLxMessage::as_verified()`. The owned capability shares the
original bytes and does not expose mutable authenticated state.
Replace `pack_propagated_encrypted*` with `PropagationEnvelope` in the
`propagation_send` module. It owns the frozen message, encrypted blob, exact TID
and PN stamp. Reuse that envelope for retries; regenerate only the work whose
policy changed. The old message `transient_id` and `propagation_stamp` fields no
longer exist. `PendingDelivery.message` is a retained delivery owner that can
release payload bytes when an idle Link only needs metadata/receipt state.
Replace `take_received_messages` with `take_downloaded_messages`. Keep each
leased image and admission token until validation and durable local commit;
resolve the token with the explicit disposition and durable receipt. A fetched
message or Resource proof is not permission to purge remote data.
Hosted propagation accepts a validated opaque encrypted/stamped blob through
`ValidatedOpaquePropagationBlob` and `plan_opaque_admission`, followed by the
plan's durable persistence and exact commit. Plain `accept_message`,
`accept_propagated_blob`, their old planning variants and sync plaintext
admission are removed: plaintext signatures are not relay storage authority.
Use a durable node store and follow the [relay store migration](relay-store-v2.md).
A nondurable `PropagationNode::new` cannot acknowledge relay storage.
Hosted `/get` handlers must use the bounded deferred request API in
`rns_runtime::LinkManager`, after installing its exact endpoint dispatch handle.
Check the handler registration result. Retain `DeferredRequestResponder` inside
the actual blocking worker through store planning, durable purge and verified
file reads; cancellation of an async caller must not detach uncharged I/O.
Pass `response_byte_limit()` to both `handle_get_request_bounded` and
`into_response_with_served_count_bounded`, using the configured propagation
transfer ceiling when registering the handler. These methods reject malformed
requests before purge, deduplicate wants, preserve complete-message accounting
and build one bounded response. An absent client limit still obeys the local
ceiling. The runtime fences responses to the original Link generation and keeps
Resource credits until the transfer releases its data. `Sent` acknowledges
queue acceptance or Resource initiation, not remote delivery.
`unpack_propagation_wrapper_owned(Bytes, limit)` returns shared `Bytes` payloads
and checks framing/counts before allocation. The Vec-returning compatibility
helper still copies explicitly. `FieldValueRef::from_encoded` validates exactly
one borrowed value, and `as_text` accepts UTF8 MessagePack text only; binary data
is not silently interpreted. Use `unique_map` before acting on recognized map
keys. Text/media projections borrow where possible; repaired UTF8 allocates only
the exact replacement length.
`constants::ENCRYPTED_PACKET_MAX_CONTENT` is LXMF 1.2.0's single-packet
content limit, 287 bytes, which `LxmRouter::try_send` applies to opportunistic
messages. Applications that choose a delivery method themselves should compare
against it rather than a hard-coded limit.
## Resuming a signed message
`SignedLxMessage::to_resumable()` returns a `ResumableLxMessage` to store before
`submit_signed`; `as_bytes()` and `ResumableLxMessage::from_bytes` move it
through storage. It keeps the signed, unstamped message and the stamp cost it
was signed under. It is not a wire message, and `LxMessage::unpack` rejects it.
After a restart, `LxmRouter::restore_signed(&stored, &active_public_key,
method)` verifies the message as sent by the active identity, so no signing key
is needed. It attaches the current outbound ticket and uses the larger of the
stored and current stamp costs. Set delivery metadata such as `auto_compress`,
then call `submit_signed`. The message keeps its id, so recipients deduplicate a
copy that was already delivered.
`submit_signed` now refuses a message whose id is already queued, awaiting its
stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as
already queued; it is not evidence of transmission or recipient delivery.
## Retaining delivered destinations
`LxmRouter::take_destination_retains()` returns the destinations whose messages
were delivered since the last call; the router keeps the newest 256. Send each
as `TransportQuery::RetainDestination` through Reticulum's control plane
(`ReticulumHandle::query_control`), which forwards to a shared instance, so the
destination's identity outlives its path, as in Python LXMF.
The API ledger retains its original compatibility floor and lists exact removed
rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary
field access through Deref; duplicate `message_api` snapshot paths describe the
same type migration. No unrelated API removal is waived.
+254
View File
@@ -0,0 +1,254 @@
# Migrating to rsLXMF 1.5
This guide covers source and behaviour changes from the published 1.4.0
release (commit `00f439d`) to 1.5.0. The crates now follow LXMF 1.3.0 on
Reticulum 1.6.0. Upstream references are to LXMF 1.3.0 (`LXMF/...:line`) and
Reticulum 1.6.0 (`RNS/...:line`). `api/stability.json` lists every removed
snapshot line under `approvedBreakingChanges`.
Migrate together with rsReticulum 1.5, whose guide covers `StampControl`, link
request stamps, the transport's SQLite stores, and the runtime changes.
## Stamp costs are fractional
LXMF 1.3.0 takes stamp values from `RNS.Stamps.stamp_value`, which returns a
float (`LXMF/LXStamper.py:12`, `RNS/Stamps.py:104`). Its router costs are
floats too (`PEERING_COST = 18.0`, `PROPAGATION_COST = 16.0`,
`LXMF/LXMRouter.py:63-67`). Every stamp cost, flexibility, peering cost, and
stamp value in the API is now `f64`:
- the `constants::{PROPAGATION_COST, PROPAGATION_COST_MIN, PROPAGATION_COST_FLEX,
PEERING_COST, MAX_PEERING_COST, COST_TICKET}` constants;
- `RouterConfig::{stamp_cost, propagation_stamp_cost, propagation_stamp_flex}`
and `RouterConfigExt::{peering_cost, max_peering_cost, propagation_cost_min}`;
- `LxmRouter::{set_stamp_cost, get_stamp_cost, set_stamp_requirements,
get_outbound_lxm_stamp_cost, get_outbound_lxm_propagation_stamp_cost,
validate_stamp, validate_stamp_with_tickets}`;
- `LxMessageDraft::stamp_cost`, `SignedLxMessage::stamp_cost()`,
`LxMessage::{validate_stamp_with_tickets, validated_stamp_value}`;
- the `LxmPeer`, `OutboundOfferPolicy`, `AutopeerCandidate`, `PeerStats`,
`NodeStats`, `PropagationEntry`, `PropagationNodeConfig`,
`AdvertisedNodePolicy`, and `RecoveryPolicy` cost fields;
- `LxmPeer::{from_announce, from_announce_with_metadata, refresh_from_announce,
refresh_from_announce_with_metadata, minimum_accepted_stamp_cost}`,
`PropagationEntry::{new_stamped, parse_filename}`, and
`PropagationStore::get_stamp_value`;
- `PropagationNode::{min_stamp_cost, set_min_stamp_cost, create_offer,
accept_stamped_propagated_blob, plan_accept_stamped_propagated_blob}`,
`ValidatedOpaquePropagationBlob::{validate, stamp_value}`;
- `handlers::{get_announce_app_data, parse_announce_app_data,
stamp_cost_from_app_data, pn_stamp_cost_from_app_data}`. The announce cost
slot may be an int or a float (`LXMF/LXMF.py:183-195`).
A destination that announces no cost is recorded with no cost, as
`outbound_stamp_costs[dest] = [time, stamp_cost]` stores `None`
(`LXMF/LXMRouter.py:1160`). The costs live in the router's state store (see
"Router state"); read them with `get_outbound_lxm_stamp_cost`.
```rust
// old
router.set_stamp_cost(dest, 8);
// new
router.set_stamp_cost(dest, 8.0);
```
### Stamper
| Old | New |
| --- | --- |
| `stamper::generate_stamp(&[u8], u8, usize) -> Option<([u8; 32], u32)>` | `generate_stamp(&[u8], f64, usize, &StampControl) -> Result<Option<([u8; 32], f64)>, StampError>` |
| `generate_stamp_cancellable(.., &AtomicBool)`, `generate_stamp_limited`, `stamp_iteration_cap` | `generate_stamp` with `StampControl { cancel, deadline, threads }` |
| `stamper::stamp_value(&[u8], &[u8; 32]) -> u32`, `stamper::stamp_workblock` | re-exports of `rns_identity::stamps::{stamp_value, stamp_workblock}`; `stamp_value(&[u8], &[u8]) -> f64` |
| `stamp_valid(&[u8; 32], u8, &[u8])` | `stamp_valid(&[u8], f64, &[u8])` |
| `validate_stamp(&[u8; 32], &[u8; 32], u8, usize)` | `validate_stamp(&[u8; 32], &[u8], f64, usize)` |
| `validate_peering_key(&[u8], &[u8; 32], u8)` | `validate_peering_key(&[u8], &[u8], f64)` (`LXMF/LXStamper.py:26-29`) |
| `validate_pn_stamp(&[u8], u8)`, `PropagationStampParts` with a `u32` value | `f64` value |
| `spawn_deferred_stamp(_on)(.., u8, ..)`, `DeferredStampResult::Success { value: u32 }` | `f64`; new `DeferredStampResult::Failed(StampError)` |
| `PropagationEnvelope::new_cancellable(.., &AtomicBool)`, `pack_for_cancellable(.., &AtomicBool)` | `&StampControl` |
| `PropagationEnvelope::{new, new_cancellable, matches}(.., [u8; 32], ..)` | `EncryptionBinding`, from `EncryptionBinding::for_recipient(&public_key, ratchet)` |
| `LxmPeer::generate_peering_key(&mut self, &[u8; 16], &[u8; 16])` | adds `&StampControl` |
| `LxmfDiscoveryStamper::{generate, valid, value}` | `f64` costs; `generate` takes `&StampControl` |
```rust
let control = rns_identity::stamps::StampControl::default();
let stamp = lxmf_core::stamper::generate_stamp(&material, 8.0, 3000, &control)?;
```
## LXMF delivery (outbound queue)
The router's outbound pass follows `LXMRouter.process_outbound`
(`LXMF/LXMRouter.py:3050`). It returns embedder work instead of per-method
deliveries:
| Old `OutboundAction` | New |
| --- | --- |
| `DeliverOpportunistic { dest_hash, message }` | `SendOpportunistic { message }` |
| `DeliverDirect { dest_hash, message }`, `PlanDirect { dest_hash, message, plan }`, `DeliverPropagated { prop_hash, message }` | `DeliverOverLink { target, message, plan: LinkDeliveryPlan }` (`UseLink` or `StartLink { hops }`), for Direct and Propagated |
| path requests issued inside planning | `RequestPath { destination, drop_existing }` |
| `Expired(message)` | `Failed(message)`: the failure callback has run |
These helpers are removed:
- `DirectDeliveryPlan`, `DirectDeliveryPlanInput`, `DirectRouteSnapshot`,
`plan_direct_delivery`;
- `LxmRouter::process_outbound_with_direct`, `defer_outbound_for_path_request`.
Call `process_outbound_with_inputs(&OutboundInputs, now)` with a snapshot of
known identities, links, and routes (`OutboundInputs::medium: MediumSnapshot`).
Use `await_outbound_path` / `outbound_link_closed` for the path and link
callbacks. `process_outbound()` keeps working with empty inputs.
`MessageMetadata::ratchet_id` is `Option<Vec<u8>>`. It holds the 10-byte
ratchet id or the 16-byte link id the message arrived under, as
`lxmf_delivery(.., ratchet_id=packet.ratchet_id ..)` passes either
(`LXMF/LXMRouter.py:2165-2173`, `RNS/Identity.py:521-522`).
`MessageMetadata` gains upstream's delivery fields (`stamp_checked`,
`stamp_valid`, `sent_on_path`, `awaiting_path`, ...).
**Paper messages.** `LxmRouter::ingest_lxm_uri(&mut self, uri, decrypt)`
becomes `ingest_lxm_uri(uri, allow_duplicate, decrypt) ->
Result<PaperIngest, _>`. `PaperIngest::Delivered(Box<LxMessage>)` or
`Duplicate` replaces upstream's `signal_local_delivery`/`signal_duplicate`
callbacks (`LXMF/LXMRouter.py:2905`).
`DeliveryRatchetState::create_announce` takes a trailing
`Option<&AnnounceStampExt>` for the stamped announce.
## Router state
`RouterConfig` and `RouterConfigExt` are `#[non_exhaustive]`. Start from
`RouterConfig::default()` and set fields:
```rust
let mut config = RouterConfig::default();
config.stamp_cost = Some(8.0);
let router = LxmRouter::new(config);
```
`LxmRouter::load_state(dir)` keeps delivered and processed message ids,
outbound stamp costs, and tickets in `dir/state.db` (`state_store::FILE_NAME`),
the store LXMF 1.3.0 keeps (`LXMFStore`, `LXMF/Storage.py`). The
`state_store` module holds `SqliteStateStore`, the sealed `StateStore` trait,
and `StateStoreError`. Before `load_state`, or when the file cannot be opened,
the state is kept in memory for the session.
| Old | New |
| --- | --- |
| `persist::{load,save}_{local_deliveries, locally_processed, stamp_costs, tickets}`, `LOCAL_DELIVERIES_FILE`, `LOCALLY_PROCESSED_FILE`, `STAMP_COSTS_FILE`, `TICKETS_FILE` | removed; `load_state` imports those files once |
| `LxmRouter::outbound_stamp_costs`, `StampCostEntry`, `RouterStats::stamp_costs_cached` | `get_outbound_lxm_stamp_cost`, `update_stamp_cost`, `cull_stamp_costs` |
| `LxmRouter::ticket_store` | `generate_ticket`, `get_inbound_tickets`, `get_outbound_ticket`, `remember_ticket` |
| `generate_ticket(..) -> [u8; 16]` | `-> Option<Ticket>`; `None` within `TICKET_INTERVAL` of the last ticket delivered there, or when the store could not commit the new one (`LXMRouter.generate_ticket`) |
| `get_inbound_tickets(&self) -> &[Ticket]` | `get_inbound_tickets(&self, &[u8; 16]) -> Option<Vec<[u8; 16]>>`, the unexpired tickets issued to one destination (`LXMRouter.get_inbound_tickets`) |
| `prepare_outbound(..) -> Result<OutboundTicketIntent, _>`, `OutboundTicketIntent::{persist, requires_persistence}`, `TicketPreparationError::PendingPersistence` | `prepare_outbound(..) -> Result<(), _>`; a reply ticket is in the store when it returns |
`lxmf-core` has a default `sqlite-store` feature. It builds SQLite from source
through `rusqlite`'s `bundled` feature, so the build needs a C compiler, and
turns on `rns-transport/sqlite-store`. With `default-features = false` the
router keeps this state in memory only.
## Propagation
- `LxmRouter::sync_peers(&mut self) -> Vec<[u8; 16]>` becomes
`sync_peers(&mut self, now, store_bytes) -> PeerSyncPass { culled, selected }`.
This follows the cull-then-select pass in `LXMF/LXMRouter.py:2468-2516`.
`select_sync_peer` takes the current time.
- `LxmRouter::sync_peer_policies_for_store` is removed.
- `LxmPeer::unhandled_messages` is now a public
`HashSet<PropagationTransientId>` instead of a count method. Use
`unhandled_message_count()`.
- `add_unhandled_message(&mut self)` takes the transient id, as
`add_unhandled_message(transient_id)` does (`LXMF/LXMPeer.py:588-626`).
`set_unhandled_count` is removed.
- `LxmPeer::peering_key` stores `([u8; 32], f64)`, and `peering_key_value()`
returns `Option<f64>`.
- Transfer and sync limits keep Python's number kind: lxmd's defaults are ints
and configured values are floats, and the announce packs whichever it holds
(`LXMF/LXMRouter.py:394-395`). The following fields are now
`handlers::PnLimit` (`Int(u64)` or `Float(f64)`, `From<u64>`/`From<f64>`):
- `PropagationNodeAnnounceData::{transfer_limit, sync_limit}`;
- `DaemonConfig::{propagation_limit_kb, sync_limit_kb}`;
- `PythonLxmdConfig::propagation_{transfer,sync}_max_accepted_size`;
- `RouterConfig::{propagation_limit_kb, sync_limit_kb}`;
- `NodeStats::{propagation_limit, sync_limit}`.
`PropagationNodeAnnounceData::new` and `LxmRouter::set_propagation_limit`
take `impl Into<PnLimit>`.
- `PropagationClientState`, `SyncTaskState`, and `PeerSyncTerminalState` gain
`NoPath`, `PathRequested`, `NoAccess`, `Throttled`, `LinkFailed`,
`TransferFailed`, and `NoIdentityReceived`, where they apply.
`PropagationAdmission` gains `AlreadyProcessed`. Exhaustive matches need the
new arms.
## Tools (lxmd library)
- `DaemonConfig` is `#[non_exhaustive]`; build it with `from_config` or
`DaemonConfig::default()` and set fields.
- `LxmdPaths::received_ratchets_dir` and `known_identities_path` become
`legacy_received_ratchets_dir` and `legacy_known_identities_path`. Reticulum
now keeps received ratchets and known destinations. `LocalStatusView::
stamp_costs_cached` is removed.
- `DaemonConfig::from_config` and `PythonLxmdConfig::from_config` return
`Result<Self, DaemonConfigError>`. lxmd exits when `as_float`/`as_int`/
`as_bool` raise on a malformed key (`LXMF/Utilities/lxmd.py:187-240`):
```rust
let config = lxmf_tools::daemon::DaemonConfig::from_config(&cfg)?;
```
- The `PythonLxmdConfig` cost fields are `f64` instead of `i64`, read with
`as_float` (`LXMF/Utilities/lxmd.py:187-215`). `DaemonConfig` cost fields are
`f64`.
- `lxmd_control::encode_router_control_stats` takes a trailing per-peer lookup
closure. `encode_nil_response` is removed.
- `lxmd_runtime::delivery_announce_app_data` takes `Option<f64>`.
## New fields and variants
`RouterConfig`, `RouterConfigExt` (which gains `pn_stamp_throttle`), and
`DaemonConfig` (likewise) are now `#[non_exhaustive]`; set fields on their
defaults.
Exhaustive literals and matches over these types need updating:
- `MessageMetadata`, `PropagationNodeAnnounceData`, `LxmPeer`,
`OutboundOfferPolicy`;
- `PnInboundAdmissionConfig` (`invalid_stamp_throttle`), `DirectLinkSnapshot`,
and `DeliveryResult::Failed` (`link_activated`);
- `PythonLxmdConfig` (`propagation_stamp_throttle`), `lxmd_cli::Args`
(`version`), `LxmdPaths`;
- `LinkDeliveryStartError::StampFailure`, `SendError::ContentTooLarge`.
## Behaviour and configuration an operator sees
- **Strict lxmd config.** A malformed number or boolean in lxmd's config now
stops lxmd with a `DaemonConfigError`. 1.4.0 fell back to the default.
Costs below their floor are raised to it, as `lxmd.py` does
(`LXMF/Utilities/lxmd.py:187-215`); a cost of 100 or more, which upstream
accepts but no stamp can meet, is rejected at load.
- **Announced node version.** A propagation node announces the LXMF release
it follows (`lxmf_core::constants::LXMF_COMPAT_VERSION`, "1.3.0") as its
version, where it announced the Rust crate version
(`LXMF/LXMRouter.py`, `get_propagation_node_announce_metadata`).
`PropagationNodeAnnounceData::new` sets it. `lxmd-rs --version` still names
both versions.
- **Stored files.**
- Delivered and processed message ids, outbound stamp costs, and tickets
move to `lxmf/state.db`. On first start the caches it replaces
(`local_deliveries`, `locally_processed`, `outbound_stamp_costs`,
`available_tickets`) are imported once and renamed with an `.imported`
suffix (`LXMRouter.__import_legacy_storage`). A file that cannot be opened
never stops the router; the state is kept in memory for the session.
- lxmd moves the received-ratchet files of earlier releases from its
`ratchets/received` directory to Reticulum's `storage/ratchets`, where
Reticulum imports them once, and removes `ratchets/known_identities`.
- Admission bodies move from the messages directory to
`download-admission-bodies` under the router state directory. Bodies still
in the old place are moved on first start.
- lxmd keeps one processed-message store.
- **Log levels.** lxmd starts at Notice (3) without a `loglevel` key and always
applies `-v`/`-q`, as `lxmd.py` does. Control commands log at Notice on
stdout.
- **Link MTU and stamps.** Delivery, the propagation client, and peer sync open
links that signal the next hop's MTU and carry link request stamps at the
cost the destination announced. These follow the Reticulum
`link_mtu_discovery` and `[stamps]` settings.
+137
View File
@@ -0,0 +1,137 @@
# Relay store migration
This guide applies to the 1.4 API and daemon, published as v1.4.0. The 1.3.0
binary does not provide this migration.
Relay nodes now admit only validated opaque propagation data to a durable store.
A packet proof follows complete validation and acknowledged durable admission.
Resource completion still means transport completion; it does not certify the
receiver's application storage. Ordinary message archives are separate from
relay storage and must never be copied into it.
## Startup and recovery
A new store can initialize automatically. An existing legacy directory requires
explicit offline migration. An incomplete migration, invalid committed record,
or unavailable storage prevents hosting. Network shares and RAM disks are
accepted with a logged warning because they cannot guarantee crash safety. Daemons fail
startup when required relay storage is unavailable. Applications retain the
user's hosting preference but show hosting as unavailable until recovery succeeds.
There is no automatic in-memory fallback for a durable host. Startup checks each
committed record's index, provenance, size and destination without rereading
whole message bodies; every read verifies the full body, and a body that fails
is not served.
Stop every process that can write the store, including service supervisors and
scheduled restarts. Then run the 1.4 source-built daemon against the correct config:
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped
```
Check `lxmd-rs --help` for the config-path option supported by your build. The
writer-stopped flag is an explicit assertion that supervisors have been stopped.
The tool also holds the store's OS lock and refuses when it finds another known
Ratspeak/LXMF daemon process, or cannot enumerate processes. Older binaries do not
honor the new lock; manually restarting one while migration runs is unsupported.
The process-name check cannot discover every renamed or custom relay program.
On iOS and Android, use the application's inbox recovery action for its private
store. The app first stops and joins its hosting and sync workers. Recovery
checks native application ownership and takes the same exclusive store lock;
it does not run the desktop process-list command or accept arbitrary external
directories. iOS recovery is restricted to the main app's private data container,
excluding extensions and shared app groups. Android recovery additionally
requires an exclusive app UID, the default app process, and no declared secondary
processes. Shared storage, shared UIDs and unverified ownership remain unavailable
for automatic recovery. Keep the original files and resolve the ownership or
storage error before retrying; do not remove the guard or copy archives into the
live store.
The migrator inventories relative paths, lengths and SHA-256 hashes before
moving anything. Symbolic links, special files, changed inventory and conflicting
unowned destinations stop migration without overwriting originals. It preserves
the legacy directory as `<store>.legacy-quarantine`, writes a regular-file guard
at the old path, and creates `<store>.v2`. The sibling `<store>.migration` journal
records every transition. Interrupted runs resume through the same command;
do not remove journals or guards to force startup. Windows directory publication
uses recorded sibling moves rather than inferring durability from existence.
The completion report gives the number and size of preserved files. Legacy
files are not offered, served, or counted as live relay messages. Their apparent
encryption shape, filename, previous app version, or old directory location does
not establish opaque-ingress provenance. Migration never automatically deletes
or expires the archive.
## Explicitly trusted recovery
Recovery requires independent, per-entry evidence of the original opaque
propagation ingress. A directory-wide assertion is insufficient. An operator
can supply a MessagePack named-map `TrustedRecoveryManifest` with these fields:
| Field | Value |
| --- | --- |
| `version` | `2` |
| `provenance` | Nonempty explanation of the independently checked evidence |
| `entries` | Array of the exact authorized records |
| Entry `archive_relative_path` | Relative path from the committed inventory |
| Entry `content_hash` | SHA-256 of the complete stored bytes, as 32 integer bytes |
| Entry `transient_id` | SHA-256 of destination+ciphertext, excluding a trailing PN stamp |
| Entry `stamped` | Whether the file includes the 32-byte PN stamp |
| Entry `stored_at` | Finite, nonnegative receipt timestamp |
Use the exported Rust structs and `rmp_serde::to_vec_named` to encode the record.
Review the manifest and independently record its SHA-256. Supply that approved
digest separately; merely hashing an unreviewed manifest does not establish trust.
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped \
--recover-propagation-manifest /path/to/recovery.msgpack \
--recovery-manifest-sha256 APPROVED_SHA256_HEX
```
The importer checks the complete archive against its committed inventory, every
selected path/hash/TID, ciphertext framing, positive plaintext rejection, actual
stamp strength, and current size/quota policy before publication. Unstamped
recovery requires both explicit provenance and a zero minimum stamp policy.
Entries without evidence remain quarantined. Repeating the exact approved import
is idempotent; it cannot replace a different first accepted image. A failed IO
can leave a valid subset committed, so retain the manifest and retry.
## Library integration
Use `PropagationNode::with_storage` for a durable host. Keep readiness bound to
the active identity generation and drain the old generation's workers before
opening or migrating its store. `begin_offline_migration` returns the retained
writer-exclusion guard used by both migration and trusted recovery.
Mobile embeddings use `begin_ios_container_migration` or
`begin_android_container_migration` on the corresponding target. The Android
function takes the attached worker's JNI environment and real platform Context;
it obtains package, UID, component and data-directory metadata from the framework.
Neither API accepts a caller-provided container root or a flag to bypass ownership
checks. Hold the identity/session lifecycle guard through the actual blocking
operation and restart, including after the invoking UI task is canceled. An app
that launches additional native relay writers must stop and join those writers
too; the container boundary does not replace ownership of current-process work.
For ingress, validate a complete packet batch before writing anything, then use
`plan_opaque_admission`. Run `Reserved(plan).persist()` on a blocking worker and
commit its returned capability to that same node. Await `Pending` outside the
bounded storage-worker slots. `CommittedDuplicate(check)` is only a plan: call
`check.verify()` on a blocking worker before treating it as durable. Keep the
original typed Link receipt alive through all these operations. A dropped worker
result yields no proof; retry reuses the first complete indexed image.
The private format publishes an immutable object and provenance record, then a
per-TID active index. Unindexed remnants are never served. A durable deletion
intent revokes eligibility before cleanup; restart resumes cleanup. Purge and
maintenance operate on a particular admission path, so a stale plan cannot
delete a later admission of the same TID. Resolve `GetServePlan` and maintenance
plans off the actor; a failed purge intent cannot return an empty success array.
The old-path guard prevents ordinary reopening of that exact legacy directory.
It cannot revoke objects already held in an old process or prevent an old daemon
from using another path or its in-memory fallback. If rolling back software,
keep **both relay hosting and propagation sync disabled**. Preserve the archive,
journal, guard and v2 store; never copy them back to the legacy layout.
+1075 -264
View File
File diff suppressed because it is too large. Load diff
+52 -23
View File
@@ -1,6 +1,26 @@
pub mod lxmf_tools
pub mod lxmf_tools::daemon
pub struct lxmf_tools::daemon::DaemonConfig
pub use lxmf_tools::daemon::PnLimit
pub enum lxmf_tools::daemon::DaemonConfigError
pub lxmf_tools::daemon::DaemonConfigError::CostOutOfRange
pub lxmf_tools::daemon::DaemonConfigError::CostOutOfRange::key: &'static str
pub lxmf_tools::daemon::DaemonConfigError::CostOutOfRange::section: &'static str
pub lxmf_tools::daemon::DaemonConfigError::CostOutOfRange::value: f64
pub lxmf_tools::daemon::DaemonConfigError::InvalidStaticPeer(alloc::string::String)
pub lxmf_tools::daemon::DaemonConfigError::NegativeMaxPeers(i64)
pub lxmf_tools::daemon::DaemonConfigError::NotABoolean
pub lxmf_tools::daemon::DaemonConfigError::NotABoolean::key: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotABoolean::section: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotABoolean::value: alloc::string::String
pub lxmf_tools::daemon::DaemonConfigError::NotANumber
pub lxmf_tools::daemon::DaemonConfigError::NotANumber::key: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotANumber::section: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotANumber::value: alloc::string::String
pub lxmf_tools::daemon::DaemonConfigError::NotAnInteger
pub lxmf_tools::daemon::DaemonConfigError::NotAnInteger::key: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotAnInteger::section: &'static str
pub lxmf_tools::daemon::DaemonConfigError::NotAnInteger::value: alloc::string::String
#[non_exhaustive] pub struct lxmf_tools::daemon::DaemonConfig
pub lxmf_tools::daemon::DaemonConfig::announce_at_start: bool
pub lxmf_tools::daemon::DaemonConfig::announce_interval: core::option::Option<u64>
pub lxmf_tools::daemon::DaemonConfig::auth_required: bool
@@ -12,7 +32,7 @@ pub lxmf_tools::daemon::DaemonConfig::display_name: core::option::Option<alloc::
pub lxmf_tools::daemon::DaemonConfig::enforce_stamps: bool
pub lxmf_tools::daemon::DaemonConfig::from_static_only: bool
pub lxmf_tools::daemon::DaemonConfig::max_inbound_syncs: usize
pub lxmf_tools::daemon::DaemonConfig::max_peering_cost: u8
pub lxmf_tools::daemon::DaemonConfig::max_peering_cost: f64
pub lxmf_tools::daemon::DaemonConfig::max_peers: usize
pub lxmf_tools::daemon::DaemonConfig::message_storage_limit: core::option::Option<usize>
pub lxmf_tools::daemon::DaemonConfig::node_announce_at_start: bool
@@ -20,19 +40,21 @@ pub lxmf_tools::daemon::DaemonConfig::node_announce_interval: core::option::Opti
pub lxmf_tools::daemon::DaemonConfig::node_name: core::option::Option<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::on_inbound_command: core::option::Option<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::outbound_propagation_node: core::option::Option<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::peering_cost: u8
pub lxmf_tools::daemon::DaemonConfig::peering_cost: f64
pub lxmf_tools::daemon::DaemonConfig::pn_stamp_throttle: f64
pub lxmf_tools::daemon::DaemonConfig::prioritise_destinations: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::propagation_enabled: bool
pub lxmf_tools::daemon::DaemonConfig::propagation_limit_kb: usize
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_cost: u8
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_flex: u8
pub lxmf_tools::daemon::DaemonConfig::propagation_limit_kb: lxmf_core::handlers::PnLimit
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_cost: f64
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_flex: f64
pub lxmf_tools::daemon::DaemonConfig::sequential_pn_stamp_validation: bool
pub lxmf_tools::daemon::DaemonConfig::stamp_cost: core::option::Option<u8>
pub lxmf_tools::daemon::DaemonConfig::stamp_cost: core::option::Option<f64>
pub lxmf_tools::daemon::DaemonConfig::static_peers: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::static_peers_bypass_sequential: bool
pub lxmf_tools::daemon::DaemonConfig::sync_limit_kb: usize
pub lxmf_tools::daemon::DaemonConfig::sync_limit_kb: lxmf_core::handlers::PnLimit
impl lxmf_tools::daemon::DaemonConfig
pub fn lxmf_tools::daemon::DaemonConfig::from_config(&rns_runtime::config::Config) -> Self
pub fn lxmf_tools::daemon::DaemonConfig::from_config(&rns_runtime::config::Config) -> core::result::Result<Self, lxmf_tools::daemon::DaemonConfigError>
pub fn lxmf_tools::daemon::DaemonConfig::min_accepted_stamp_cost(&self) -> f64
pub fn lxmf_tools::daemon::DaemonConfig::to_inbound_admission_config(&self) -> lxmf_core::propagation_admission::PnInboundAdmissionConfig
pub fn lxmf_tools::daemon::DaemonConfig::to_router_config(&self) -> lxmf_core::router::RouterConfig
impl core::default::Default for lxmf_tools::daemon::DaemonConfig
@@ -55,23 +77,25 @@ pub lxmf_tools::daemon::PythonLxmdConfig::node_name: core::option::Option<alloc:
pub lxmf_tools::daemon::PythonLxmdConfig::on_inbound: core::option::Option<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::peer_announce_at_start: bool
pub lxmf_tools::daemon::PythonLxmdConfig::peer_announce_interval: core::option::Option<i64>
pub lxmf_tools::daemon::PythonLxmdConfig::peer_stamp_cost: i64
pub lxmf_tools::daemon::PythonLxmdConfig::peering_cost: i64
pub lxmf_tools::daemon::PythonLxmdConfig::peer_stamp_cost: f64
pub lxmf_tools::daemon::PythonLxmdConfig::peering_cost: f64
pub lxmf_tools::daemon::PythonLxmdConfig::prioritised_lxmf_destinations: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_flexibility: i64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_target: i64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_sync_max_accepted_size: f64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_transfer_max_accepted_size: f64
pub lxmf_tools::daemon::PythonLxmdConfig::remote_peering_cost_max: i64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_flexibility: f64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_target: f64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_throttle: f64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_sync_max_accepted_size: lxmf_core::handlers::PnLimit
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_transfer_max_accepted_size: lxmf_core::handlers::PnLimit
pub lxmf_tools::daemon::PythonLxmdConfig::remote_peering_cost_max: f64
pub lxmf_tools::daemon::PythonLxmdConfig::sequential_pn_stamp_validation: bool
pub lxmf_tools::daemon::PythonLxmdConfig::static_peers: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::static_peers_bypass_sequential: bool
pub lxmf_tools::daemon::PythonLxmdConfig::target_loglevel: core::option::Option<i64>
impl lxmf_tools::daemon::PythonLxmdConfig
pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::Config) -> Self
pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::Config) -> core::result::Result<Self, lxmf_tools::daemon::DaemonConfigError>
pub fn lxmf_tools::daemon::create_router(&lxmf_tools::daemon::DaemonConfig) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::create_router_with_transport(&lxmf_tools::daemon::DaemonConfig, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::execute_on_inbound(&str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::execute_on_inbound_with_event(&str, &str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::persist_inbound_and_execute(&std::path::Path, &[u8], core::option::Option<&str>) -> core::io::error::Result<()>
pub mod lxmf_tools::lxmd_cli
pub enum lxmf_tools::lxmd_cli::SendMethod
@@ -84,10 +108,14 @@ pub struct lxmf_tools::lxmd_cli::Args
pub lxmf_tools::lxmd_cli::Args::config: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::exampleconfig: bool
pub lxmf_tools::lxmd_cli::Args::identity: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::migrate_propagation_store: bool
pub lxmf_tools::lxmd_cli::Args::on_inbound: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::peers: bool
pub lxmf_tools::lxmd_cli::Args::propagation_node: bool
pub lxmf_tools::lxmd_cli::Args::quiet: u8
pub lxmf_tools::lxmd_cli::Args::recover_propagation_manifest: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::recovery_manifest_sha256: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::relay_writers_stopped: bool
pub lxmf_tools::lxmd_cli::Args::remote: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::rnsconfig: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::send: core::option::Option<alloc::vec::Vec<alloc::string::String>>
@@ -101,6 +129,9 @@ pub lxmf_tools::lxmd_cli::Args::sync: core::option::Option<alloc::string::String
pub lxmf_tools::lxmd_cli::Args::timeout: core::option::Option<f64>
pub lxmf_tools::lxmd_cli::Args::unpeer: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::verbose: u8
pub lxmf_tools::lxmd_cli::Args::version: bool
pub const lxmf_tools::lxmd_cli::LXMF_COMPAT_VERSION: &str
pub fn lxmf_tools::lxmd_cli::default_config_file_text() -> alloc::string::String
pub fn lxmf_tools::lxmd_cli::example_config() -> &'static str
pub fn lxmf_tools::lxmd_cli::load_hash_list(&std::path::Path) -> alloc::vec::Vec<[u8; 16]>
pub fn lxmf_tools::lxmd_cli::normalize_hash_hex(&str) -> alloc::string::String
@@ -122,9 +153,8 @@ pub const lxmf_tools::lxmd_control::CONTROL_APP_NAME: &str
pub const lxmf_tools::lxmd_control::PROPAGATION_APP_NAME: &str
pub fn lxmf_tools::lxmd_control::decode_control_response(&[u8]) -> lxmf_tools::lxmd_control::ControlResponse
pub fn lxmf_tools::lxmd_control::encode_control_success() -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_nil_response() -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_peer_error(lxmf_core::constants::PeerError) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_router_control_stats(&lxmf_core::router::LxmRouter, [u8; 16], [u8; 16], core::option::Option<&lxmf_core::propagation_node::PropagationNode>, f64) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_router_control_stats(&lxmf_core::router::LxmRouter, [u8; 16], [u8; 16], core::option::Option<&lxmf_core::propagation_node::PropagationNode>, f64, impl core::ops::function::Fn(&[u8; 16]) -> u8) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::exit_for_control_response(lxmf_tools::lxmd_control::ControlCommandKind, &lxmf_tools::lxmd_control::ControlResponse) -> bool
pub fn lxmf_tools::lxmd_control::format_remote_status(&rmpv::Value, bool, bool, f64) -> alloc::string::String
pub fn lxmf_tools::lxmd_control::peer_error_from_code(u8) -> core::option::Option<lxmf_core::constants::PeerError>
@@ -153,31 +183,30 @@ pub lxmf_tools::lxmd_runtime::LocalStatusView::pending_outbound: usize
pub lxmf_tools::lxmd_runtime::LocalStatusView::propagation_enabled: bool
pub lxmf_tools::lxmd_runtime::LocalStatusView::propagation_entries: usize
pub lxmf_tools::lxmd_runtime::LocalStatusView::propagation_size: usize
pub lxmf_tools::lxmd_runtime::LocalStatusView::stamp_costs_cached: usize
impl lxmf_tools::lxmd_runtime::LocalStatusView
pub fn lxmf_tools::lxmd_runtime::LocalStatusView::from_router_stats([u8; 16], bool, &lxmf_core::router::RouterStats) -> Self
pub struct lxmf_tools::lxmd_runtime::LxmdPaths
pub lxmf_tools::lxmd_runtime::LxmdPaths::config_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::identity_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::known_identities_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_identity_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_known_identities_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_lxmf_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_messages_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_propagation_store_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_received_ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::lxmf_storage_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::messages_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::propagation_store_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchet_control_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchet_ring_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::received_ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::router_state_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::storage_dir: std::path::PathBuf
impl lxmf_tools::lxmd_runtime::LxmdPaths
pub fn lxmf_tools::lxmd_runtime::LxmdPaths::new(impl core::convert::Into<std::path::PathBuf>) -> Self
pub fn lxmf_tools::lxmd_runtime::LxmdPaths::preferred_identity_path(&self) -> &std::path::Path
pub fn lxmf_tools::lxmd_runtime::delivery_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_runtime::delivery_announce_app_data(core::option::Option<&str>, core::option::Option<f64>) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_runtime::format_local_peers(&[lxmf_tools::lxmd_runtime::LocalPeerView]) -> alloc::string::String
pub fn lxmf_tools::lxmd_runtime::format_local_status(&lxmf_tools::lxmd_runtime::LocalStatusView) -> alloc::string::String
pub fn lxmf_tools::lxmd_runtime::preflight_control_command(&std::path::Path, core::option::Option<&std::path::Path>, core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<lxmf_tools::lxmd_runtime::ControlPreflight, lxmf_tools::lxmd_runtime::ControlPreflightError>
+98 -20
View File
@@ -4,10 +4,18 @@
"packages": [
{
"name": "lxmf-core",
"version": "1.3.0",
"version": "1.5.1",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
"features": {
"default": [
"sqlite-store"
],
"sqlite-store": [
"dep:rusqlite",
"rns-transport/sqlite-store"
]
},
"targets": [
{
"name": "lxmf_core",
@@ -95,7 +103,9 @@
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"with-serde"
],
"sourceKind": "registry"
},
{
@@ -103,7 +113,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -114,7 +124,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -125,7 +135,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -136,7 +146,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -147,9 +157,9 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
@@ -158,12 +168,25 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rusqlite",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.32",
"optional": true,
"defaultFeatures": true,
"features": [
"bundled"
],
"sourceKind": "registry"
},
{
"name": "serde",
"rename": null,
@@ -223,6 +246,17 @@
"features": [],
"sourceKind": "registry"
},
{
"name": "unicode-general-category",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.6",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "unicode-normalization",
"rename": null,
@@ -233,12 +267,34 @@
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "jni",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"android\")",
"requirement": "^0.19",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "objc2",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"ios\")",
"requirement": "^0.6",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
},
{
"name": "lxmf-tools",
"version": "1.3.0",
"version": "1.5.1",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -306,7 +362,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -328,7 +384,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -339,7 +395,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -350,7 +406,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -358,14 +414,25 @@
],
"sourceKind": "path"
},
{
"name": "rns-tools",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
@@ -374,7 +441,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -391,6 +458,17 @@
"features": [],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
"kind": null,
"target": null,
"requirement": "^2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "tokio",
"rename": null,
@@ -416,11 +494,11 @@
"sourceKind": "registry"
},
{
"name": "tracing-subscriber",
"name": "zeroize",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.3",
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
+216 -7
View File
@@ -14,8 +14,8 @@
"commit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"compatibilityFloor": {
"evidenceCommit": "80bb96f799330e28a0125367d4c29826f5147cc3",
"sourceCommit": "b8d7afce73f7f098706029361568e63f22888ea3"
"evidenceCommit": "00f439df7e6d14d29e5ca75efc7c694ab4990b3d",
"sourceCommit": "00f439df7e6d14d29e5ca75efc7c694ab4990b3d"
},
"packages": [
{
@@ -24,8 +24,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 1647,
"sha256": "b7b1d52406e2c97a204a5fb567abc6a216733594a7abd63797ff55a70d8d3b73"
"itemCount": 2458,
"sha256": "93bd001beb46ae13e2ece84d355e9fd4ffc8198029233de3a397b1a645b77651"
},
{
"name": "lxmf-tools",
@@ -33,8 +33,217 @@
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
"itemCount": 214,
"sha256": "61656c05c28423f95c71f716998a834e0e9bc8855d0ddd29617aed1a0ee3045b"
}
]
],
"approvedBreakingChanges": {
"releaseLine": "1.5",
"migrationGuide": "api/migrations/1.5.md",
"removed": {
"lxmf-core": [
"impl lxmf_core::router::DirectRouteSnapshot",
"impl lxmf_core::router::OutboundTicketIntent",
"pub const lxmf_core::constants::COST_TICKET: u16",
"pub const lxmf_core::constants::MAX_PEERING_COST: u8",
"pub const lxmf_core::constants::PEERING_COST: u8",
"pub const lxmf_core::constants::PROPAGATION_COST: u8",
"pub const lxmf_core::constants::PROPAGATION_COST_FLEX: u8",
"pub const lxmf_core::constants::PROPAGATION_COST_MIN: u8",
"pub const lxmf_core::persist::LOCALLY_PROCESSED_FILE: &str",
"pub const lxmf_core::persist::LOCAL_DELIVERIES_FILE: &str",
"pub const lxmf_core::persist::STAMP_COSTS_FILE: &str",
"pub const lxmf_core::persist::TICKETS_FILE: &str",
"pub enum lxmf_core::router::DirectDeliveryPlan",
"pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::create_announce(&mut self, &rns_identity::identity::Identity, &[u8], u64, f64, lxmf_core::delivery_ratchet::DeliveryAnnounceKind<'_>) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::delivery_ratchet::DeliveryRatchetError>",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::generate(&self, &[u8; 32], u8) -> core::option::Option<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> u8",
"pub fn lxmf_core::handlers::PropagationNodeAnnounceData::new(bool, u64, u64, u8, u8, u8) -> Self",
"pub fn lxmf_core::handlers::get_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>",
"pub fn lxmf_core::handlers::parse_announce_app_data(&[u8]) -> core::option::Option<(core::option::Option<alloc::string::String>, core::option::Option<u8>)>",
"pub fn lxmf_core::handlers::pn_stamp_cost_from_app_data(&[u8]) -> core::option::Option<u8>",
"pub fn lxmf_core::handlers::stamp_cost_from_app_data(&[u8]) -> core::option::Option<u8>",
"pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> bool",
"pub fn lxmf_core::message::LxMessage::validated_stamp_value(&self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> core::option::Option<u16>",
"pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::Option<u8>",
"pub fn lxmf_core::peer::LxmPeer::add_unhandled_message(&mut self)",
"pub fn lxmf_core::peer::LxmPeer::from_announce([u8; 16], f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>) -> Self",
"pub fn lxmf_core::peer::LxmPeer::from_announce_with_metadata([u8; 16], f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<std::collections::hash::map::HashMap<u8, alloc::vec::Vec<u8>>>) -> Self",
"pub fn lxmf_core::peer::LxmPeer::generate_peering_key(&mut self, &[u8; 16], &[u8; 16]) -> bool",
"pub fn lxmf_core::peer::LxmPeer::minimum_accepted_stamp_cost(&self) -> u8",
"pub fn lxmf_core::peer::LxmPeer::peering_key_value(&self) -> core::option::Option<u32>",
"pub fn lxmf_core::peer::LxmPeer::refresh_from_announce(&mut self, f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>) -> bool",
"pub fn lxmf_core::peer::LxmPeer::refresh_from_announce_with_metadata(&mut self, f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<std::collections::hash::map::HashMap<u8, alloc::vec::Vec<u8>>>) -> bool",
"pub fn lxmf_core::peer::LxmPeer::set_unhandled_count(&mut self, u32)",
"pub fn lxmf_core::peer::LxmPeer::unhandled_messages(&self) -> u32",
"pub fn lxmf_core::peer::select_sync_peer(&[&lxmf_core::peer::LxmPeer]) -> core::option::Option<usize>",
"pub fn lxmf_core::persist::load_local_deliveries(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>>",
"pub fn lxmf_core::persist::load_locally_processed(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>>",
"pub fn lxmf_core::persist::load_stamp_costs(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>>",
"pub fn lxmf_core::persist::load_tickets(&std::path::Path) -> core::io::error::Result<(lxmf_core::ticket::TicketStoreSnapshot, core::option::Option<alloc::vec::Vec<lxmf_core::ticket::Ticket>>)>",
"pub fn lxmf_core::persist::save_local_deliveries(&std::path::Path, &std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_locally_processed(&std::path::Path, &std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_stamp_costs(&std::path::Path, &std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_tickets(&std::path::Path, &lxmf_core::ticket::TicketStoreSnapshot) -> core::io::error::Result<()>",
"pub fn lxmf_core::propagation::PropagationEntry::new(lxmf_core::types::PropagationTransientId, [u8; 32], [u8; 16], usize, u8) -> Self",
"pub fn lxmf_core::propagation::PropagationEntry::new_stamped(lxmf_core::types::PropagationTransientId, [u8; 32], [u8; 16], usize, u8) -> Self",
"pub fn lxmf_core::propagation::PropagationEntry::parse_filename(&str) -> core::option::Option<(lxmf_core::types::PropagationTransientId, f64, u8)>",
"pub fn lxmf_core::propagation::PropagationStore::get_stamp_value(&self, &lxmf_core::types::PropagationTransientId) -> core::option::Option<u8>",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::create_offer(&self, [u8; 16], core::option::Option<u8>) -> alloc::vec::Vec<lxmf_core::types::PropagationTransientId>",
"pub fn lxmf_core::propagation_node::PropagationNode::min_stamp_cost(&self) -> u8",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_node::PropagationNode::set_min_stamp_cost(&mut self, u8)",
"pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::stamp_value(&self) -> u8",
"pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::validate(bytes::bytes::Bytes, u8) -> core::option::Option<Self>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::matches(&self, &lxmf_core::message::LxMessage, &[u8; 32]) -> bool",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::new<F>(lxmf_core::message::LxMessage, [u8; 32], u8, F) -> core::result::Result<Self, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::new_cancellable<F>(lxmf_core::message::LxMessage, [u8; 32], u8, F, &core::sync::atomic::AtomicBool) -> core::result::Result<Self, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::pack_for_cancellable(&mut self, lxmf_core::propagation_send::PreparedNode, f64, &core::sync::atomic::AtomicBool) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::stamp_value(&self) -> u32",
"pub fn lxmf_core::router::DirectRouteSnapshot::new([u8; 16], u8) -> Self",
"pub fn lxmf_core::router::LxmRouter::defer_outbound_for_path_request(&mut self, &[u8; 32], f64) -> bool",
"pub fn lxmf_core::router::LxmRouter::generate_ticket(&mut self, [u8; 16], core::option::Option<u64>) -> [u8; 16]",
"pub fn lxmf_core::router::LxmRouter::get_inbound_tickets(&self) -> &[lxmf_core::ticket::Ticket]",
"pub fn lxmf_core::router::LxmRouter::get_outbound_lxm_propagation_stamp_cost(&self, &[u8; 32]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::get_outbound_lxm_stamp_cost(&self, &[u8; 16]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::get_stamp_cost(&self, &[u8; 16]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::ingest_lxm_uri<F>(&mut self, &str, F) -> core::result::Result<lxmf_core::message::LxMessage, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessageDraft) -> core::result::Result<lxmf_core::router::OutboundTicketIntent, lxmf_core::router::TicketPreparationError>",
"pub fn lxmf_core::router::LxmRouter::process_outbound_with_direct<F>(&mut self, F) -> alloc::vec::Vec<lxmf_core::router::OutboundAction> where F: core::ops::function::FnMut(&lxmf_core::message::LxMessage, f64) -> lxmf_core::router::DirectDeliveryPlanInput",
"pub fn lxmf_core::router::LxmRouter::set_propagation_limit(&mut self, usize)",
"pub fn lxmf_core::router::LxmRouter::set_stamp_cost(&mut self, [u8; 16], u8)",
"pub fn lxmf_core::router::LxmRouter::set_stamp_requirements(&mut self, u8, u8)",
"pub fn lxmf_core::router::LxmRouter::sync_peer_policies_for_store(&self, u64) -> alloc::vec::Vec<lxmf_core::peer::OutboundOfferPolicy>",
"pub fn lxmf_core::router::LxmRouter::sync_peers(&mut self) -> alloc::vec::Vec<[u8; 16]>",
"pub fn lxmf_core::router::LxmRouter::validate_stamp(&self, &[u8; 32], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::router::LxmRouter::validate_stamp_with_tickets(&self, &[u8; 32], &[u8], u8, &[u8; 16]) -> bool",
"pub fn lxmf_core::router::OutboundTicketIntent::persist(self, &std::path::Path, &mut lxmf_core::message::LxMessageDraft) -> core::io::error::Result<()>",
"pub fn lxmf_core::router::OutboundTicketIntent::requires_persistence(&self) -> bool",
"pub fn lxmf_core::router::plan_direct_delivery(&mut lxmf_core::message::LxMessage, lxmf_core::router::DirectDeliveryPlanInput, f64) -> lxmf_core::router::DirectDeliveryPlan",
"pub fn lxmf_core::stamper::generate_stamp(&[u8], u8, usize) -> core::option::Option<([u8; 32], u32)>",
"pub fn lxmf_core::stamper::generate_stamp_cancellable(&[u8], u8, usize, &core::sync::atomic::AtomicBool) -> core::option::Option<([u8; 32], u32)>",
"pub fn lxmf_core::stamper::generate_stamp_limited(&[u8], u8, usize, u64) -> core::option::Option<[u8; 32]>",
"pub fn lxmf_core::stamper::spawn_deferred_stamp([u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver<lxmf_core::stamper::DeferredStampResult>)",
"pub fn lxmf_core::stamper::spawn_deferred_stamp_on(&tokio::runtime::handle::Handle, [u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver<lxmf_core::stamper::DeferredStampResult>)",
"pub fn lxmf_core::stamper::stamp_iteration_cap(u8) -> core::option::Option<u64>",
"pub fn lxmf_core::stamper::stamp_valid(&[u8; 32], u8, &[u8]) -> bool",
"pub fn lxmf_core::stamper::stamp_value(&[u8], &[u8; 32]) -> u32",
"pub fn lxmf_core::stamper::stamp_workblock(&[u8], usize) -> alloc::vec::Vec<u8>",
"pub fn lxmf_core::stamper::validate_peering_key(&[u8], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::stamper::validate_pn_stamp(&[u8], u8) -> core::option::Option<lxmf_core::stamper::PropagationStampParts>",
"pub fn lxmf_core::stamper::validate_stamp(&[u8; 32], &[u8; 32], u8, usize) -> bool",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::peering_cost: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::stamp_cost: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::stamp_flex: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::sync_limit: u64",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::transfer_limit: u64",
"pub lxmf_core::message::LxMessageDraft::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message_api::LxMessageDraft::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message_api::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::peer::LxmPeer::peering_cost: u8",
"pub lxmf_core::peer::LxmPeer::peering_key: core::option::Option<([u8; 32], u32)>",
"pub lxmf_core::peer::LxmPeer::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::peer::LxmPeer::stamp_cost_flexibility: core::option::Option<u8>",
"pub lxmf_core::peer::OutboundOfferPolicy::minimum_stamp_cost: u8",
"pub lxmf_core::peer::OutboundOfferPolicy::peering_cost: u8",
"pub lxmf_core::peer::OutboundOfferPolicy::peering_key_value: core::option::Option<u32>",
"pub lxmf_core::peer::OutboundOfferPolicy::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::peer::OutboundOfferPolicy::stamp_cost_flexibility: core::option::Option<u8>",
"pub lxmf_core::propagation::PropagationEntry::stamp_value: u8",
"pub lxmf_core::propagation_node::PropagationNodeConfig::min_stamp_cost: u8",
"pub lxmf_core::propagation_node::PropagationNodeConfig::peering_cost: u8",
"pub lxmf_core::propagation_send::AdvertisedNodePolicy::stamp_cost: u8",
"pub lxmf_core::propagation_store_v2::RecoveryPolicy::minimum_stamp_cost: u8",
"pub lxmf_core::router::AutopeerCandidate::peering_cost: core::option::Option<u8>",
"pub lxmf_core::router::AutopeerCandidate::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::AutopeerCandidate::stamp_flexibility: core::option::Option<u8>",
"pub lxmf_core::router::DirectDeliveryPlan::DeferTerminalFailure",
"pub lxmf_core::router::DirectDeliveryPlan::Fail",
"pub lxmf_core::router::DirectDeliveryPlan::RequestPath",
"pub lxmf_core::router::DirectDeliveryPlan::RequestPath::drop_existing: bool",
"pub lxmf_core::router::DirectDeliveryPlan::StartNewLink",
"pub lxmf_core::router::DirectDeliveryPlan::StartNewLink::hops: u8",
"pub lxmf_core::router::DirectDeliveryPlan::UseReusableLink",
"pub lxmf_core::router::DirectDeliveryPlan::WaitForReusableLink",
"pub lxmf_core::router::DirectDeliveryPlanInput::identity_known: bool",
"pub lxmf_core::router::DirectDeliveryPlanInput::reusable_link: lxmf_core::router::DirectReusableLinkState",
"pub lxmf_core::router::DirectDeliveryPlanInput::route: core::option::Option<lxmf_core::router::DirectRouteSnapshot>",
"pub lxmf_core::router::DirectRouteSnapshot::destination_hash: [u8; 16]",
"pub lxmf_core::router::DirectRouteSnapshot::expires_at: core::option::Option<f64>",
"pub lxmf_core::router::DirectRouteSnapshot::hops: u8",
"pub lxmf_core::router::DirectRouteSnapshot::interface_name: core::option::Option<alloc::string::String>",
"pub lxmf_core::router::DirectRouteSnapshot::learned_at: core::option::Option<f64>",
"pub lxmf_core::router::LxmRouter::outbound_stamp_costs: std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>",
"pub lxmf_core::router::LxmRouter::ticket_store: lxmf_core::ticket::TicketStore",
"pub lxmf_core::router::NodeStats::peering_cost: u8",
"pub lxmf_core::router::NodeStats::propagation_limit: usize",
"pub lxmf_core::router::NodeStats::stamp_cost: u8",
"pub lxmf_core::router::NodeStats::stamp_flex: u8",
"pub lxmf_core::router::NodeStats::sync_limit: usize",
"pub lxmf_core::router::OutboundAction::DeliverDirect",
"pub lxmf_core::router::OutboundAction::DeliverDirect::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::DeliverDirect::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverPropagated",
"pub lxmf_core::router::OutboundAction::DeliverPropagated::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverPropagated::prop_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::Expired(lxmf_core::message::LxMessage)",
"pub lxmf_core::router::OutboundAction::PlanDirect",
"pub lxmf_core::router::OutboundAction::PlanDirect::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::PlanDirect::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::PlanDirect::plan: lxmf_core::router::DirectDeliveryPlan",
"pub lxmf_core::router::PeerStats::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::RouterConfig::propagation_limit_kb: usize",
"pub lxmf_core::router::RouterConfig::propagation_stamp_cost: u8",
"pub lxmf_core::router::RouterConfig::propagation_stamp_flex: u8",
"pub lxmf_core::router::RouterConfig::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::RouterConfig::sync_limit_kb: usize",
"pub lxmf_core::router::RouterConfigExt::max_peering_cost: u8",
"pub lxmf_core::router::RouterConfigExt::peering_cost: u8",
"pub lxmf_core::router::RouterConfigExt::propagation_cost_min: u8",
"pub lxmf_core::router::RouterStats::stamp_costs_cached: usize",
"pub lxmf_core::router::StampCostEntry::cost: u8",
"pub lxmf_core::router::StampCostEntry::recorded_at: f64",
"pub lxmf_core::router::TicketPreparationError::PendingPersistence",
"pub lxmf_core::stamper::DeferredStampResult::Success::value: u32",
"pub struct lxmf_core::router::DirectDeliveryPlanInput",
"pub struct lxmf_core::router::DirectRouteSnapshot",
"pub struct lxmf_core::router::OutboundTicketIntent",
"pub struct lxmf_core::router::RouterConfig",
"pub struct lxmf_core::router::RouterConfigExt",
"pub struct lxmf_core::router::StampCostEntry",
"pub type lxmf_core::stamper::PropagationStampParts = ([u8; 32], alloc::vec::Vec<u8>, u32, [u8; 32])"
],
"lxmf-tools": [
"pub fn lxmf_tools::daemon::DaemonConfig::from_config(&rns_runtime::config::Config) -> Self",
"pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::Config) -> Self",
"pub fn lxmf_tools::lxmd_control::encode_nil_response() -> alloc::vec::Vec<u8>",
"pub fn lxmf_tools::lxmd_control::encode_router_control_stats(&lxmf_core::router::LxmRouter, [u8; 16], [u8; 16], core::option::Option<&lxmf_core::propagation_node::PropagationNode>, f64) -> alloc::vec::Vec<u8>",
"pub fn lxmf_tools::lxmd_runtime::delivery_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>",
"pub lxmf_tools::daemon::DaemonConfig::max_peering_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::peering_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::propagation_limit_kb: usize",
"pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_flex: u8",
"pub lxmf_tools::daemon::DaemonConfig::stamp_cost: core::option::Option<u8>",
"pub lxmf_tools::daemon::DaemonConfig::sync_limit_kb: usize",
"pub lxmf_tools::daemon::PythonLxmdConfig::peer_stamp_cost: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::peering_cost: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_flexibility: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_target: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_sync_max_accepted_size: f64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_transfer_max_accepted_size: f64",
"pub lxmf_tools::daemon::PythonLxmdConfig::remote_peering_cost_max: i64",
"pub lxmf_tools::lxmd_runtime::LocalStatusView::stamp_costs_cached: usize",
"pub lxmf_tools::lxmd_runtime::LxmdPaths::known_identities_path: std::path::PathBuf",
"pub lxmf_tools::lxmd_runtime::LxmdPaths::received_ratchets_dir: std::path::PathBuf",
"pub struct lxmf_tools::daemon::DaemonConfig"
]
}
}
}
+16 -2
View File
@@ -5,7 +5,13 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
[features]
default = ["sqlite-store"]
# SQLite router state at lxmf/state.db, as LXMF 1.3.0 keeps it. Without it the
# router keeps that state in memory only.
sqlite-store = ["dep:rusqlite", "rns-transport/sqlite-store"]
[dependencies]
base64 = { workspace = true }
@@ -21,12 +27,20 @@ bytes = { workspace = true }
tracing = { workspace = true }
rmp = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
serde = { workspace = true }
sha2 = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
unicode-normalization = { workspace = true }
unicode-general-category = { workspace = true }
rusqlite = { workspace = true, optional = true }
[target.'cfg(target_os = "ios")'.dependencies]
objc2 = "0.6"
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
[dev-dependencies]
tempfile = { workspace = true }
+12 -10
View File
@@ -1,21 +1,23 @@
//! Construct, sign, pack, and inspect an LXMF message through the canonical API.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, MessageState};
//! 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 rns_crypto::ed25519::Ed25519PrivateKey;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut message = LxMessage::new(
let mut draft = LxMessageDraft::new(
[0x11; 16],
[0x22; 16],
"Hello",
"LXMF from Rust",
DeliveryMethod::Direct,
);
message.sign(&Ed25519PrivateKey::generate())?;
let packed = message.pack()?;
let unpacked = LxMessage::unpack(&packed)?;
assert_eq!(unpacked.title, "Hello");
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
let message = draft.sign(&Ed25519PrivateKey::generate())?.finalize(None)?;
let unpacked = LxMessage::unpack(message.wire_bytes())?;
assert_eq!(unpacked.title_text(), "Hello");
assert_eq!(unpacked.state, MessageState::Generating);
assert_eq!(unpacked.wire_bytes(), message.wire_bytes());
Ok(())
}
+630
View File
@@ -0,0 +1,630 @@
//! Durable propagation-download admission and non-purging retry policy.
//!
//! A transport Resource proof is not an application receipt. The trusted local
//! adapter implements [`DurableAdmissionBackend`] and commits its body/effects
//! and receipt together before a download token can authorize remote deletion.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
pub const MAX_DOWNLOAD_ITEMS: usize = 4096;
pub const MAX_RETAINED_DOWNLOAD_BYTES: usize = 134_217_727;
pub const MAX_PROCESSING_BYTES: usize = 256 * 1024 * 1024;
pub const MAX_PROCESSORS: usize = 4;
pub const POLICY_RECEIPT_LIFETIME: u64 = 90 * 86400;
/// Exact remote and local ownership of a ciphertext transient ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AdmissionScope {
pub identity: [u8; 16],
pub node: [u8; 16],
pub transient_id: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DurableDisposition {
Committed,
Duplicate,
PolicyDiscard,
UserDeleted,
}
/// Persisted effect identity. A duplicate need not have the same complete wire
/// hash: the optional recipient stamp is excluded from the signed message ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionRecord {
pub scope: AdmissionScope,
pub message_id: [u8; 32],
pub received_wire_hash: [u8; 32],
pub stored_message_wire_hash: Option<[u8; 32]>,
pub disposition: DurableDisposition,
pub committed_at: u64,
}
/// Local purge authority with an optional expiry. Policy-discard and user-deleted
/// 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)]
pub struct DurableHave {
pub transient_id: [u8; 32],
pub expires_at: Option<u64>,
}
impl DurableHave {
pub fn from_record(record: &AdmissionRecord) -> Self {
Self {
transient_id: record.scope.transient_id,
expires_at: matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
)
.then(|| record.committed_at.saturating_add(POLICY_RECEIPT_LIFETIME)),
}
}
pub fn active(self, now: u64) -> bool {
self.expires_at.is_none_or(|expiry| now < expiry)
}
}
#[derive(Debug, thiserror::Error)]
pub enum AdmissionError {
#[error("admission was not committed: {0}")]
NotCommitted(String),
#[error("admission publication is uncertain; reconcile all durability barriers: {0}")]
CommitUncertain(String),
#[error("durable disposition ledger is full")]
DispositionLedgerFull,
#[error("admission scope does not match the downloaded ciphertext")]
WrongScope,
}
/// Trusted persistence adapter boundary. Implementations must atomically commit
/// the receipt with the message/effect, or reference a previously durable effect.
/// In particular, returning a record after a failed/uncertain filesystem or SQL
/// commit violates this contract. SQL adapters must establish their transaction
/// and durability guarantees. [`crate::admission_store::FileAdmissionStore`]
/// uses an intent/body/commit journal.
pub trait DurableAdmissionBackend {
fn commit(self) -> Result<AdmissionRecord, AdmissionError>;
}
#[derive(Debug)]
pub struct DurableAdmissionReceipt {
record: AdmissionRecord,
}
impl DurableAdmissionReceipt {
pub fn commit(backend: impl DurableAdmissionBackend) -> Result<Self, AdmissionError> {
Ok(Self {
record: backend.commit()?,
})
}
pub fn record(&self) -> &AdmissionRecord {
&self.record
}
}
/// Persisted, deterministic epochs; never reset these to a process generation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionEpochs {
pub policy: [u8; 32],
pub keys: [u8; 32],
pub budget: [u8; 32],
pub storage_health: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SuppressionReason {
Malformed,
WrongDestination,
InvalidSignature,
InvalidStamp,
DecryptionFailed,
TooLarge,
MissingKey,
StorageUnavailable,
StorageBusy,
Quota,
WorkerUnavailable,
DispositionLedgerFull,
Cancelled,
}
impl SuppressionReason {
pub fn is_transient(self) -> bool {
matches!(
self,
Self::MissingKey
| Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::WorkerUnavailable
| Self::DispositionLedgerFull
| Self::Cancelled
)
}
fn epoch_matches(self, before: AdmissionEpochs, now: AdmissionEpochs) -> bool {
match self {
Self::DecryptionFailed | Self::MissingKey => before.keys == now.keys,
Self::InvalidSignature => before.keys == now.keys && before.policy == now.policy,
Self::TooLarge => before.budget == now.budget,
Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::DispositionLedgerFull => before.storage_health == now.storage_health,
_ => before.policy == now.policy,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionRecord {
pub scope: AdmissionScope,
pub reason: SuppressionReason,
pub epochs: AdmissionEpochs,
pub attempts: u16,
pub last_failure: u64,
pub next_retry: u64,
pub expires_at: u64,
}
impl SuppressionRecord {
pub fn active(&self, now: u64, epochs: AdmissionEpochs) -> bool {
now < self.expires_at
&& now < self.next_retry
&& self.reason.epoch_matches(self.epochs, epochs)
}
}
/// Quotas bound metadata independently of message bytes. Full ledgers preserve
/// existing entries and pause new wants, rather than evicting into a retry loop.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppressionLedger {
records: HashMap<AdmissionScope, SuppressionRecord>,
}
impl SuppressionLedger {
pub const PER_NODE: usize = 4096;
pub const PER_IDENTITY: usize = 16384;
pub const GLOBAL: usize = 65536;
/// Restore typed rows only after duplicate and quota validation. Never
/// silently overwrite persisted scope decisions during hydration.
pub fn from_records(
records: impl IntoIterator<Item = SuppressionRecord>,
) -> Result<Self, AdmissionError> {
let mut ledger = Self::default();
let mut identities = HashMap::<[u8; 16], usize>::new();
let mut nodes = HashMap::<([u8; 16], [u8; 16]), usize>::new();
for record in records {
if ledger.records.contains_key(&record.scope) {
return Err(AdmissionError::NotCommitted(
"duplicate suppression scope".into(),
));
}
if record.attempts == 0
|| record.next_retry < record.last_failure
|| record.expires_at <= record.last_failure
|| record.expires_at > record.last_failure.saturating_add(30 * 86400)
{
return Err(AdmissionError::NotCommitted(
"invalid suppression interval".into(),
));
}
let identity = identities.entry(record.scope.identity).or_default();
let node = nodes
.entry((record.scope.identity, record.scope.node))
.or_default();
if ledger.records.len() >= Self::GLOBAL
|| *identity >= Self::PER_IDENTITY
|| *node >= Self::PER_NODE
{
return Err(AdmissionError::DispositionLedgerFull);
}
*identity += 1;
*node += 1;
ledger.records.insert(record.scope, record);
}
Ok(ledger)
}
pub fn records(&self) -> impl Iterator<Item = &SuppressionRecord> {
self.records.values()
}
pub fn get(&self, scope: &AdmissionScope) -> Option<&SuppressionRecord> {
self.records.get(scope)
}
pub fn remove(&mut self, scope: &AdmissionScope) {
self.records.remove(scope);
}
pub fn prune(&mut self, now: u64, epochs: AdmissionEpochs) {
self.records.retain(|_, record| {
now < record.expires_at && record.reason.epoch_matches(record.epochs, epochs)
});
}
pub fn saturated(&self, identity: [u8; 16], node: [u8; 16]) -> bool {
self.records.len() >= Self::GLOBAL
|| self
.records
.keys()
.filter(|k| k.identity == identity)
.count()
>= Self::PER_IDENTITY
|| self
.records
.keys()
.filter(|k| k.identity == identity && k.node == node)
.count()
>= Self::PER_NODE
}
pub fn record_failure(
&mut self,
scope: AdmissionScope,
reason: SuppressionReason,
epochs: AdmissionEpochs,
now: u64,
) -> Result<&SuppressionRecord, AdmissionError> {
self.prune(now, epochs);
if !self.records.contains_key(&scope) && self.saturated(scope.identity, scope.node) {
return Err(AdmissionError::DispositionLedgerFull);
}
let attempts = self
.records
.get(&scope)
.filter(|r| r.reason == reason)
.map_or(1, |r| r.attempts.saturating_add(1));
let (next_retry, expires_at) = if reason.is_transient() {
let base = (60u64 << attempts.saturating_sub(1).min(6)).min(3600);
// Stable +/-10% jitter avoids synchronized retries after restart.
let jitter =
u16::from_be_bytes([scope.transient_id[0], scope.transient_id[1]]) as u64 % 21;
(
now.saturating_add(base * (90 + jitter) / 100),
now.saturating_add(86400),
)
} else {
(
now.saturating_add(30 * 86400),
now.saturating_add(30 * 86400),
)
};
self.records.insert(
scope,
SuppressionRecord {
scope,
reason,
epochs,
attempts,
last_failure: now,
next_retry,
expires_at,
},
);
Ok(&self.records[&scope])
}
}
#[derive(Debug)]
pub enum DownloadAdmissionOutcome {
Accepted(DurableAdmissionReceipt),
Rejected(SuppressionReason),
}
pub(crate) struct AdmissionResolution {
pub generation: u64,
pub scope: AdmissionScope,
pub outcome: DownloadAdmissionOutcome,
}
/// Single-use, generation-bound authority. Dropping an unresolved token attempts
/// to send a Cancelled rejection to its consumer. Cancelling the client generation
/// cannot cancel a blocking commit.
pub struct DownloadAdmissionToken {
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: Option<mpsc::UnboundedSender<AdmissionResolution>>,
}
impl std::fmt::Debug for DownloadAdmissionToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DownloadAdmissionToken")
.field("scope", &self.scope)
.field("generation", &self.generation)
.finish_non_exhaustive()
}
}
impl DownloadAdmissionToken {
pub(crate) fn new(
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: mpsc::UnboundedSender<AdmissionResolution>,
) -> Self {
Self {
scope,
generation,
current_generation,
tx: Some(tx),
}
}
pub fn scope(&self) -> AdmissionScope {
self.scope
}
/// Read whether this token still belongs to the current client generation.
///
/// 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 {
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> {
if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome
&& receipt.record.scope != self.scope
{
return Err(AdmissionError::WrongScope);
}
if !self.is_current() {
self.tx.take();
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
let tx = self.tx.take().ok_or_else(|| {
AdmissionError::NotCommitted("download authority already consumed".into())
})?;
tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome,
})
.map_err(|_| AdmissionError::NotCommitted("download consumer is closed".into()))?;
// The client rechecks the exact generation while consuming. This result
// reports enqueue only; adapters need their lifecycle gate around any
// current-generation UI effects, not an atomic-cancellation promise.
if !self.is_current() {
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
Ok(())
}
}
impl Drop for DownloadAdmissionToken {
fn drop(&mut self) {
if let Some(tx) = self.tx.take() {
let _ = tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome: DownloadAdmissionOutcome::Rejected(SuppressionReason::Cancelled),
});
}
}
}
#[derive(Debug)]
pub struct DownloadedPropagationMessage {
data: Bytes,
token: DownloadAdmissionToken,
}
impl DownloadedPropagationMessage {
pub(crate) fn new(data: Bytes, token: DownloadAdmissionToken) -> Self {
Self { data, token }
}
pub fn data(&self) -> &Bytes {
&self.data
}
pub fn scope(&self) -> AdmissionScope {
self.token.scope
}
pub fn into_parts(self) -> (Bytes, DownloadAdmissionToken) {
(self.data, self.token)
}
}
fn raw_budget() -> &'static Arc<Semaphore> {
static BUDGET: OnceLock<Arc<Semaphore>> = OnceLock::new();
BUDGET.get_or_init(|| Arc::new(Semaphore::new(MAX_RETAINED_DOWNLOAD_BYTES)))
}
struct RetainedResponse {
bytes: Bytes,
_credit: OwnedSemaphorePermit,
}
impl AsRef<[u8]> for RetainedResponse {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
/// Credit follows every Bytes clone/slice, including payloads in cancelled
/// blocking workers. Moving a response out of the client never releases it.
pub(crate) fn retain_response(
bytes: Bytes,
local_limit: usize,
) -> Result<Bytes, SuppressionReason> {
if bytes.len() > local_limit.min(MAX_RETAINED_DOWNLOAD_BYTES) {
return Err(SuppressionReason::TooLarge);
}
let credit = raw_budget()
.clone()
.try_acquire_many_owned(bytes.len() as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Bytes::from_owner(RetainedResponse {
bytes,
_credit: credit,
}))
}
/// Full peak reservation is obtained before decrypting while raw ciphertext is
/// retained separately. Never wait for a partial reservation while holding the
/// parent response. This bounds Rust-owned buffers, not SQLite's native heap.
fn processing_budget() -> &'static Arc<Semaphore> {
static BYTES: OnceLock<Arc<Semaphore>> = OnceLock::new();
BYTES.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSING_BYTES)))
}
/// Additional explicitly bounded adapter state, sharing the processing byte
/// budget without taking a second worker slot. Admission is always nonblocking.
pub struct ProcessingMemoryLease {
_bytes: OwnedSemaphorePermit,
}
impl ProcessingMemoryLease {
pub fn try_acquire(amount: usize) -> Result<Self, SuppressionReason> {
if amount > MAX_PROCESSING_BYTES {
return Err(SuppressionReason::TooLarge);
}
Ok(Self {
_bytes: processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?,
})
}
}
pub struct ProcessingLease {
_bytes: OwnedSemaphorePermit,
_worker: OwnedSemaphorePermit,
}
impl ProcessingLease {
pub fn try_acquire(cipher_len: usize) -> Result<Self, SuppressionReason> {
static WORKERS: OnceLock<Arc<Semaphore>> = OnceLock::new();
let amount = cipher_len
.checked_mul(4)
.and_then(|v| v.checked_add(128 * 1024 + 256))
.filter(|v| *v <= MAX_PROCESSING_BYTES)
.ok_or(SuppressionReason::TooLarge)?;
let bytes = processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
let worker = WORKERS
.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSORS)))
.clone()
.try_acquire_owned()
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Self {
_bytes: bytes,
_worker: worker,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [n; 32],
}
}
#[test]
fn resolution_rejects_revoked_generation_and_closed_consumer() {
let generation = Arc::new(AtomicU64::new(1));
let (tx, mut rx) = mpsc::unbounded_channel();
let token = DownloadAdmissionToken::new(scope(1), 1, generation.clone(), tx.clone());
generation.store(2, Ordering::Release);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
assert!(rx.try_recv().is_err());
let token = DownloadAdmissionToken::new(scope(2), 2, generation, tx);
drop(rx);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
}
#[test]
fn permanent_failures_revalidate_on_epoch_change_or_expiry() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
let r = ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(r.active(101, epoch));
let mut changed = epoch;
changed.keys[0] = 1;
assert!(!r.active(101, changed));
assert!(!r.active(100 + 30 * 86400, epoch));
assert!(rmp_serde::to_vec(r).unwrap().len() <= 512);
}
#[test]
fn temporary_storage_failure_is_retryable_and_bounded() {
let mut ledger = SuppressionLedger::default();
for _ in 0..20 {
ledger
.record_failure(
scope(1),
SuppressionReason::StorageBusy,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
let r = ledger.get(&scope(1)).unwrap();
assert!((3340..=4060).contains(&r.next_retry));
assert_eq!(r.expires_at, 86500);
}
#[test]
fn full_node_ledger_does_not_evict_existing_suppression() {
let mut ledger = SuppressionLedger::default();
for n in 0..SuppressionLedger::PER_NODE {
let mut s = scope(0);
s.transient_id[..8].copy_from_slice(&(n as u64).to_be_bytes());
ledger
.record_failure(
s,
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
assert!(
ledger
.record_failure(
scope(255),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100
)
.is_err()
);
assert_eq!(ledger.records().count(), SuppressionLedger::PER_NODE);
}
#[test]
fn impossible_processing_size_rejects_without_partial_wait() {
assert!(matches!(
ProcessingLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::TooLarge)
));
}
}
+714
View File
@@ -0,0 +1,714 @@
//! File adapter for lxmd's durable download receipts and hook outbox.
//! 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 bytes::Bytes;
use rns_identity::persistence::{
DurableCommitPhase, DurableWriteError, durable_create_dir_all, durable_reconcile,
durable_remove, durable_write,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionIntent {
version: u8,
admission_id: [u8; 32],
record: AdmissionRecord,
body_path: Option<PathBuf>,
hook_event: Option<[u8; 32]>,
}
/// One atomic logical commit publishes both the receipt and pending hook event.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionCommit {
intent: AdmissionIntent,
hook_completed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserDeletedMessage {
version: u8,
identity: [u8; 16],
message_id: [u8; 32],
deleted_at: u64,
}
struct Inner {
journal: PathBuf,
bodies: PathBuf,
/// The only directory journaled bodies may be moved in from.
legacy_bodies: Option<PathBuf>,
committed: HashMap<AdmissionScope, AdmissionCommit>,
deleted: HashMap<([u8; 16], [u8; 32]), UserDeletedMessage>,
}
#[derive(Clone)]
pub struct FileAdmissionStore {
inner: Arc<Mutex<Inner>>,
}
fn error(e: DurableWriteError) -> AdmissionError {
match e.phase {
DurableCommitPhase::NotCommitted => AdmissionError::NotCommitted(e.to_string()),
_ => AdmissionError::CommitUncertain(e.to_string()),
}
}
fn other(e: impl std::fmt::Display) -> AdmissionError {
AdmissionError::NotCommitted(e.to_string())
}
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, AdmissionError> {
rmp_serde::to_vec_named(value).map_err(other)
}
fn read_bounded(path: &Path, limit: usize) -> Result<Vec<u8>, AdmissionError> {
use std::io::Read;
let mut bytes = Vec::new();
std::fs::File::open(path)
.map_err(other)?
.take(limit as u64 + 1)
.read_to_end(&mut bytes)
.map_err(other)?;
if bytes.len() > limit {
return Err(other("admission artifact exceeds limit"));
}
Ok(bytes)
}
fn admission_id(scope: &AdmissionScope) -> Result<[u8; 32], AdmissionError> {
Ok(rns_crypto::sha::full_hash(&encode(scope)?))
}
impl FileAdmissionStore {
/// Parent is the daemon's already configured state directory. A strict
/// outside bootstrap receipt witnesses creation of journal/body directories.
pub fn open(state_dir: &Path, bodies: &Path) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, None)
}
/// [`Self::open`] for a store whose bodies used to live in `legacy_bodies`:
/// a journaled body still there is moved into `bodies`.
pub fn open_moving_bodies_from(
state_dir: &Path,
bodies: &Path,
legacy_bodies: &Path,
) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, Some(legacy_bodies))
}
fn open_inner(
state_dir: &Path,
bodies: &Path,
legacy_bodies: Option<&Path>,
) -> Result<Self, AdmissionError> {
let journal = state_dir.join("download-admission-v1");
let parent = state_dir
.ancestors()
.find(|parent| {
bodies.starts_with(parent) && *parent != bodies && parent.parent().is_some()
})
.ok_or_else(|| other("admission state and bodies need a private common ancestor"))?;
let scope = encode(&(1u8, state_dir, bodies))?;
let bootstrap_path = parent.join(format!(
"download-admission-{}.bootstrap",
hex::encode(rns_crypto::sha::full_hash(&scope))
));
let bootstrap = durable_write(&bootstrap_path, &scope).map_err(error)?;
durable_create_dir_all(&journal, &bootstrap).map_err(error)?;
durable_create_dir_all(bodies, &bootstrap).map_err(error)?;
let mut inner = Inner {
journal,
bodies: bodies.to_owned(),
legacy_bodies: legacy_bodies.map(Path::to_owned),
committed: HashMap::new(),
deleted: HashMap::new(),
};
inner.recover()?;
Ok(Self {
inner: Arc::new(Mutex::new(inner)),
})
}
/// 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(
&self,
mut record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
) -> FileAdmissionCommit {
// The caller cannot mislabel the incoming image even for a duplicate.
record.received_wire_hash = rns_crypto::sha::full_hash(&wire);
FileAdmissionCommit {
store: self.clone(),
record,
wire,
run_hook,
}
}
/// Return live receipts from committed or recovered state for this identity/node.
/// 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>> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| c.intent.record.scope.transient_id.to_vec())
.collect()
}
pub fn durable_haves(
&self,
identity: [u8; 16],
node: [u8; 16],
now: u64,
) -> Vec<super::admission::DurableHave> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| super::admission::DurableHave::from_record(&c.intent.record))
.collect()
}
/// Explicit user deletion is a permanent message-ID decision, separate
/// from expiring per-node TID accelerators. No filesystem absence is treated
/// as user authorization. Removing this tombstone requires explicit reset.
pub fn mark_user_deleted(
&self,
identity: [u8; 16],
message_id: [u8; 32],
now: u64,
) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let tombstone = UserDeletedMessage {
version: 1,
identity,
message_id,
deleted_at: now,
};
let path = inner.journal.join(format!(
"{}-{}.deleted",
hex::encode(identity),
hex::encode(message_id)
));
let witness = durable_write(&path, &encode(&tombstone)?).map_err(error)?;
inner.deleted.insert((identity, message_id), tombstone);
let targets = inner
.committed
.iter()
.filter(|(_, c)| {
c.intent.record.scope.identity == identity
&& c.intent.record.message_id == message_id
})
.map(|(scope, c)| (*scope, c.clone()))
.collect::<Vec<_>>();
for (scope, mut commit) in targets {
commit.intent.body_path = None;
commit.intent.hook_event = None;
commit.hook_completed = true;
commit.intent.record.disposition = DurableDisposition::UserDeleted;
commit.intent.record.stored_message_wire_hash = None;
commit.intent.record.committed_at = now;
durable_write(
&inner.intent_path(&commit.intent.admission_id),
&encode(&commit.intent)?,
)
.map_err(error)?;
durable_write(
&inner.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
inner.committed.insert(scope, commit);
}
durable_remove(
&inner
.bodies
.join(format!("{}.lxm", hex::encode(message_id))),
&witness,
)
.map_err(error)?;
Ok(())
}
/// Prune only expired invisible TID receipts. Visible archive authority and
/// permanent UserDeleted message decisions are retained independently.
pub fn maintain(&self, now: u64) -> Result<usize, AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let expired = inner
.committed
.iter()
.filter(|(_, c)| !live(&c.intent.record, now))
.map(|(scope, c)| (*scope, c.intent.admission_id))
.collect::<Vec<_>>();
if expired.is_empty() {
return Ok(0);
}
let witness = durable_write(
&inner.journal.join("receipt-pruning-v1"),
&encode(&(1u8, &expired))?,
)
.map_err(error)?;
let mut removed = 0;
for (scope, id) in expired {
durable_remove(&inner.intent_path(&id), &witness).map_err(error)?;
durable_remove(&inner.commit_path(&id), &witness).map_err(error)?;
inner.committed.remove(&scope);
removed += 1;
}
Ok(removed)
}
pub fn pending_hooks(&self) -> Vec<([u8; 32], PathBuf)> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| !c.hook_completed)
.filter_map(|c| {
c.intent.body_path.as_ref()?;
Some((
c.intent.hook_event?,
inner.body_path(&c.intent.record.message_id),
))
})
.collect()
}
pub fn complete_hook(&self, event: [u8; 32]) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let Some(scope) = inner
.committed
.iter()
.find_map(|(s, c)| (c.intent.hook_event == Some(event)).then_some(*s))
else {
return Ok(());
};
let mut updated = inner.committed[&scope].clone();
updated.hook_completed = true;
durable_write(
&inner.commit_path(&updated.intent.admission_id),
&encode(&updated)?,
)
.map_err(error)?;
inner.committed.insert(scope, updated);
Ok(())
}
}
fn live(record: &AdmissionRecord, now: u64) -> bool {
!matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) || now.saturating_sub(record.committed_at) < POLICY_RECEIPT_LIFETIME
}
pub struct FileAdmissionCommit {
store: FileAdmissionStore,
record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
}
impl DurableAdmissionBackend for FileAdmissionCommit {
fn commit(self) -> Result<AdmissionRecord, AdmissionError> {
let mut inner = self.store.inner.lock().unwrap_or_else(|p| p.into_inner());
let parsed = crate::message::LxMessage::unpack_owned(self.wire.clone(), Default::default())
.map_err(other)?;
if parsed.message_id() != self.record.message_id {
return Err(other("admission message identity mismatch"));
}
if let Some(existing) = inner.committed.get(&self.record.scope) {
if existing.intent.record.received_wire_hash != self.record.received_wire_hash {
return Err(other("ciphertext TID receipt wire mismatch"));
}
if !inner
.deleted
.contains_key(&(self.record.scope.identity, self.record.message_id))
&& live(&existing.intent.record, self.record.committed_at)
&& matches!(
existing.intent.record.disposition,
DurableDisposition::Committed | DurableDisposition::Duplicate
)
&& self.record.disposition == DurableDisposition::Committed
{
inner.validate_body(&existing.intent)?;
let mut duplicate = existing.intent.record.clone();
duplicate.disposition = DurableDisposition::Duplicate;
return Ok(duplicate);
}
}
let mut record = self.record;
if inner
.deleted
.contains_key(&(record.scope.identity, record.message_id))
{
record.disposition = DurableDisposition::UserDeleted;
}
let invisible = matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
);
if invisible {
let existing = inner.committed.values().filter(|c| {
matches!(
c.intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) && live(&c.intent.record, record.committed_at)
});
let global = existing.clone().count();
let identity = existing
.filter(|c| c.intent.record.scope.identity == record.scope.identity)
.count();
if global >= 65536 || identity >= 16384 {
return Err(AdmissionError::DispositionLedgerFull);
}
}
let body_path = (!invisible).then(|| {
inner
.bodies
.join(format!("{}.lxm", hex::encode(record.message_id)))
});
let mut body = None;
let mut newly_visible = false;
if let Some(path) = &body_path {
match std::fs::metadata(path) {
Ok(_) => {
let existing = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
// Keep the first immutable archive. Same message ID can have
// a different fifth-stamp image; record both hashes.
let parsed = crate::message::LxMessage::unpack(&existing).map_err(other)?;
if parsed.message_id() != record.message_id {
return Err(other("existing archive has a different message ID"));
}
record.stored_message_wire_hash = Some(rns_crypto::sha::full_hash(&existing));
record.disposition = DurableDisposition::Duplicate;
body = Some(Bytes::from(existing));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
record.stored_message_wire_hash = Some(record.received_wire_hash);
newly_visible = true;
body = Some(self.wire.clone());
}
Err(e) => return Err(other(e)),
}
}
let admission_id = admission_id(&record.scope)?;
let intent = AdmissionIntent {
version: 1,
admission_id,
record: record.clone(),
body_path,
hook_event: (self.run_hook && newly_visible).then_some(admission_id),
};
durable_write(&inner.intent_path(&admission_id), &encode(&intent)?).map_err(error)?;
if let (Some(path), Some(body)) = (&intent.body_path, body) {
if newly_visible {
durable_write(path, &body).map_err(error)?;
} else {
durable_reconcile(path, &body).map_err(error)?;
}
}
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(&inner.commit_path(&admission_id), &encode(&commit)?).map_err(error)?;
inner.committed.insert(record.scope, commit);
Ok(record)
}
}
impl Inner {
fn body_path(&self, message_id: &[u8; 32]) -> PathBuf {
self.bodies.join(format!("{}.lxm", hex::encode(message_id)))
}
fn intent_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.intent", hex::encode(id)))
}
fn commit_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.commit", hex::encode(id)))
}
fn validate_body(&self, intent: &AdmissionIntent) -> Result<(), AdmissionError> {
if intent.version != 1 || admission_id(&intent.record.scope)? != intent.admission_id {
return Err(other("unknown admission journal version or identity"));
}
if self
.deleted
.contains_key(&(intent.record.scope.identity, intent.record.message_id))
&& intent.record.disposition != DurableDisposition::UserDeleted
{
return Err(other("message was explicitly deleted"));
}
if let Some(path) = &intent.body_path {
if path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
{
return Err(other("admission archive path escapes configured inbox"));
}
// A journal written before the bodies moved names the old directory.
let journaled = path;
let path = &self.body_path(&intent.record.message_id);
if !path.exists()
&& self.legacy_bodies.is_some()
&& journaled.parent() == self.legacy_bodies.as_deref()
&& journaled.exists()
{
std::fs::rename(journaled, path).map_err(other)?;
}
let body = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
if Some(rns_crypto::sha::full_hash(&body)) != intent.record.stored_message_wire_hash {
return Err(other("admission archive content mismatch"));
}
// A previous CommitUncertain becomes authoritative only after all
// native barriers succeed again, never merely after readback.
durable_reconcile(path, &body).map_err(error)?;
} else if !matches!(
intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) {
return Err(other("visible admission is missing its archive"));
}
Ok(())
}
fn recover(&mut self) -> Result<(), AdmissionError> {
// Stream directory passes: directory size must not itself allocate an
// unbounded vector. Malformed artifacts remain private and unavailable.
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("deleted") {
continue;
}
let data = read_bounded(&path, 2048)?;
let tombstone: UserDeletedMessage = rmp_serde::from_slice(&data).map_err(other)?;
if tombstone.version != 1
|| path.file_name().and_then(|s| s.to_str())
!= Some(
format!(
"{}-{}.deleted",
hex::encode(tombstone.identity),
hex::encode(tombstone.message_id)
)
.as_str(),
)
{
return Err(other("invalid user deletion tombstone"));
}
let witness = durable_reconcile(&path, &data).map_err(error)?;
durable_remove(
&self
.bodies
.join(format!("{}.lxm", hex::encode(tombstone.message_id))),
&witness,
)
.map_err(error)?;
self.deleted
.insert((tombstone.identity, tombstone.message_id), tombstone);
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("commit") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let commit: AdmissionCommit = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.commit_path(&commit.intent.admission_id) {
return Err(other("commit filename mismatch"));
}
self.validate_body(&commit.intent)?;
durable_reconcile(&path, &data).map_err(error)?;
Ok(commit)
})();
match result {
Ok(commit) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"unavailable admission preserved without purge authority")
}
}
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("intent") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let intent: AdmissionIntent = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.intent_path(&intent.admission_id) {
return Err(other("intent filename mismatch"));
}
if self
.committed
.get(&intent.record.scope)
.is_some_and(|c| c.intent.record == intent.record)
{
return Ok(None);
}
self.validate_body(&intent)?;
durable_reconcile(&path, &data).map_err(error)?;
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(
&self.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
Ok(Some(commit))
})();
match result {
Ok(Some(commit)) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Ok(None) => {}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"uncommitted admission preserved without purge authority")
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn committed_receipt_survives_reopen_and_hook_is_in_same_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
let receipt = DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
assert_eq!(
receipt.record().received_wire_hash,
rns_crypto::sha::full_hash(message.wire_bytes())
);
drop(store);
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
recovered
.complete_hook(recovered.pending_hooks()[0].0)
.unwrap();
assert!(recovered.pending_hooks().is_empty());
}
/// A store whose one committed body sits in `<temp>/messages`.
fn store_with_body_in_inbox() -> (tempfile::TempDir, PathBuf, String, AdmissionScope, Vec<u8>) {
let temp = tempfile::tempdir().unwrap();
let inbox = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &inbox).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
drop(store);
let name = format!("{}.lxm", hex::encode(message.message_id()));
assert!(inbox.join(&name).exists());
(temp, inbox, name, scope, message.wire_bytes().to_vec())
}
#[test]
fn bodies_journaled_in_the_inbox_move_to_a_new_bodies_directory_on_open() {
let (temp, inbox, name, scope, wire) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let reopened =
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &inbox).unwrap();
assert!(!inbox.join(&name).exists());
assert_eq!(std::fs::read(bodies.join(&name)).unwrap(), wire);
assert_eq!(
reopened.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(reopened.pending_hooks()[0].1, bodies.join(&name));
}
#[test]
fn bodies_are_moved_in_only_from_the_named_legacy_directory() {
let (temp, inbox, name, _, _) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let elsewhere = temp.path().join("elsewhere");
for _ in [
FileAdmissionStore::open(temp.path(), &bodies),
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &elsewhere),
] {
assert!(inbox.join(&name).exists());
assert!(!bodies.join(&name).exists());
}
}
}
+58 -30
View File
@@ -18,21 +18,21 @@ pub const FIELD_TICKET: u8 = 0x0C;
pub const FIELD_EVENT: u8 = 0x0D;
pub const FIELD_RNR_REFS: u8 = 0x0E;
pub const FIELD_RENDERER: u8 = 0x0F;
/// Bytes, full `LXMessage` hash. Python reference: LXMF.py:23.
/// Bytes, full `LXMessage` hash. Python reference: LXMF.py.
pub const FIELD_REPLY_TO: u8 = 0x30;
/// Bytes, quoted content in UTF-8 encoding. Python reference: LXMF.py:24.
/// Bytes, quoted content in UTF-8 encoding. Python reference: LXMF.py.
pub const FIELD_REPLY_QUOTE: u8 = 0x31;
/// Dict keyed by [`REACTION_TO`] / [`REACTION_CONTENT`]. Python reference: LXMF.py:25.
/// Dict keyed by [`REACTION_TO`] / [`REACTION_CONTENT`]. Python reference: LXMF.py.
pub const FIELD_REACTION: u8 = 0x40;
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py:26.
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py.
pub const FIELD_COMMENT: u8 = 0x41;
/// Dict keyed by [`CONTINUATION_OF`]. Python reference: LXMF.py:27.
/// Dict keyed by [`CONTINUATION_OF`]. Python reference: LXMF.py.
pub const FIELD_CONTINUATION: u8 = 0x42;
// Unallocated fields between 0x00 and 0x80, both included, should be
// considered reserved for future extensibility. For experimental and
// unstable features, it is recommended to use fields above 0xFF.
// Python reference: LXMF.py:29-32.
// Python reference: LXMF.py.
pub const FIELD_CUSTOM_TYPE: u8 = 0xFB;
pub const FIELD_CUSTOM_DATA: u8 = 0xFC;
@@ -69,7 +69,7 @@ pub const RENDERER_BBCODE: u8 = 0x03;
// Clients choose how to handle reaction content, if at all. While reactions
// are typically a single unicode emoji or similar, the exact implementation
// and sanitization is left up to the client. FIELD_REACTION dict keys —
// Python reference: LXMF.py:104-110.
// Python reference: LXMF.py.
/// Bytes, full `LXMessage` hash.
pub const REACTION_TO: u8 = 0x00;
/// Bytes, the reaction content in UTF-8 encoding.
@@ -77,22 +77,29 @@ pub const REACTION_CONTENT: u8 = 0x01;
// Comment content is carried as the normal LXM content, so clients that do
// not support comments display them as normal messages. FIELD_COMMENT dict
// key — Python reference: LXMF.py:112-118.
// key — Python reference: LXMF.py.
/// Bytes, full `LXMessage` hash.
pub const COMMENT_FOR: u8 = 0x00;
// Continuation content is carried as the normal LXM content, so clients that
// do not support continuations display them as normal messages.
// FIELD_CONTINUATION dict key — Python reference: LXMF.py:120-126.
// FIELD_CONTINUATION dict key — Python reference: LXMF.py.
/// Bytes, full `LXMessage` hash.
pub const CONTINUATION_OF: u8 = 0x00;
pub const PN_META_VERSION: u8 = 0x00;
/// The LXMF release this port follows. A propagation node announces it as
/// its [`PN_META_VERSION`], where upstream announces `LXMF.__version__`
/// (LXMRouter.py, `get_propagation_node_announce_metadata`).
pub const LXMF_COMPAT_VERSION: &str = "1.3.1";
pub const PN_META_NAME: u8 = 0x01;
pub const PN_META_SYNC_STRATUM: u8 = 0x02;
pub const PN_META_SYNC_THROTTLE: u8 = 0x03;
pub const PN_META_AUTH_BAND: u8 = 0x04;
pub const PN_META_UTIL_PRESSURE: u8 = 0x05;
pub const PN_META_IMPL_NAME: u8 = 0xFE;
/// Implementation name upstream advertises under [`PN_META_IMPL_NAME`].
pub const PN_IMPL_NAME: &str = "lxmd";
pub const PN_META_CUSTOM: u8 = 0xFF;
pub const SF_COMPRESSION: u8 = 0x00;
@@ -152,6 +159,14 @@ pub const STRUCT_OVERHEAD: usize = 8;
/// 2 * dest(16) + sig(64) + timestamp(8) + struct(8) = 112.
pub const LXMF_OVERHEAD: usize =
2 * DESTINATION_LENGTH + SIGNATURE_LENGTH + TIMESTAMP_SIZE + STRUCT_OVERHEAD;
/// Largest content an opportunistic message carries in one encrypted packet;
/// the packet's destination supplies the destination hash. 383 - 112 + 16 = 287.
pub const ENCRYPTED_PACKET_MAX_CONTENT: usize =
rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH;
/// Largest content of an unencrypted single packet to a PLAIN destination.
/// 464 - 112 + 16 = 368.
pub const PLAIN_PACKET_MAX_CONTENT: usize =
rns_wire::constants::PLAIN_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH;
pub const PAPER_MDU: usize = 2210;
pub const TICKET_EXPIRY: u64 = 21 * 24 * 60 * 60;
@@ -159,7 +174,7 @@ pub const TICKET_GRACE: u64 = 5 * 24 * 60 * 60;
pub const TICKET_RENEW: u64 = 14 * 24 * 60 * 60;
pub const TICKET_INTERVAL: u64 = 24 * 60 * 60;
/// Sentinel cost value that always exceeds the maximum PoW cost.
pub const COST_TICKET: u16 = 0x100;
pub const COST_TICKET: f64 = 256.0;
pub const MAX_DELIVERY_ATTEMPTS: u32 = 5;
/// Interval between router job ticks (seconds).
@@ -169,7 +184,7 @@ pub const PATH_REQUEST_WAIT: u64 = 7;
pub const MAX_PATHLESS_TRIES: u32 = 1;
/// Maximum link inactivity before teardown (seconds).
pub const LINK_MAX_INACTIVITY: u64 = 10 * 60;
/// Maximum propagation link inactivity (seconds).
/// Inbound propagation links with no data for this long are torn down (seconds).
pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60;
pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
@@ -182,17 +197,21 @@ pub const PROPAGATION_LIMIT: usize = 256;
pub const DELIVERY_LIMIT: usize = 1000;
/// PROPAGATION_LIMIT * 40, in KB.
pub const SYNC_LIMIT: usize = 10240;
pub const PROPAGATION_COST_MIN: u8 = 13;
pub const PROPAGATION_COST: u8 = 16;
pub const PROPAGATION_COST_FLEX: u8 = 3;
pub const PEERING_COST: u8 = 18;
pub const MAX_PEERING_COST: u8 = 26;
/// Link-request stamp cost announced by delivery destinations (LXMRouter.py).
pub const DELIVERY_LINK_COST: f64 = 3.25;
/// Link-request stamp cost announced by propagation destinations (LXMRouter.py).
pub const PROPAGATION_LINK_COST: f64 = 3.25;
pub const PROPAGATION_COST_MIN: f64 = 13.0;
pub const PROPAGATION_COST: f64 = 16.0;
pub const PROPAGATION_COST_FLEX: f64 = 3.0;
pub const PEERING_COST: f64 = 18.0;
pub const MAX_PEERING_COST: f64 = 26.0;
pub const MAX_PEERS: usize = 20;
pub const PN_STAMP_THROTTLE: u64 = 180;
pub const PN_STAMP_THROTTLE: u64 = 300;
pub const AUTOPEER: bool = true;
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;
/// Percentage of max_peers kept as headroom for rotation.
pub const ROTATION_HEADROOM_PCT: usize = 10;
@@ -209,12 +228,12 @@ pub const DUPLICATE_SIGNAL: &str = "lxmf_duplicate";
pub const OFFER_REQUEST_PATH: &str = "/offer";
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;
/// Sync backoff step per consecutive failure (12 minutes).
pub const SYNC_BACKOFF_STEP: u64 = 12 * 60;
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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -259,22 +278,25 @@ pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PN: usize = 1000;
pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING: usize = 25;
/// SHA-256 output length.
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;
/// 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;
/// 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;
/// 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;
/// Interval (in ticks) for cleaning transient ID caches.
pub const JOB_TRANSIENT_INTERVAL: u64 = 60;
/// Interval (in ticks) for cleaning the message store.
pub const JOB_STORE_INTERVAL: u64 = 120;
/// Interval (in ticks) for syncing peers.
/// Interval (in ticks) for culling stamp costs and expired tickets.
pub const JOB_STAMPCOST_INTERVAL: u64 = 120;
/// 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;
/// 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;
/// 56 * JOB_PEERINGEST_INTERVAL.
pub const JOB_ROTATE_INTERVAL: u64 = 56 * 6;
@@ -292,6 +314,12 @@ mod tests {
assert_eq!(LXMF_OVERHEAD, 112);
}
/// LXMF 1.2.0 `ENCRYPTED_PACKET_MAX_CONTENT` (LXMessage.pyfc60af).
#[test]
fn encrypted_packet_max_content_is_lxmf_1_2_0s() {
assert_eq!(ENCRYPTED_PACKET_MAX_CONTENT, 287);
}
#[test]
fn test_message_states_distinct() {
assert_ne!(MessageState::Generating as u8, MessageState::Outbound as u8);
@@ -324,7 +352,7 @@ mod tests {
assert_eq!(TICKET_GRACE, 432_000);
assert_eq!(TICKET_RENEW, 1_209_600);
assert_eq!(TICKET_INTERVAL, 86_400);
assert_eq!(COST_TICKET, 256);
assert_eq!(COST_TICKET, 256.0);
}
#[test]
@@ -363,8 +391,8 @@ mod tests {
assert_eq!(P_LINK_MAX_INACTIVITY, 180);
assert_eq!(NODE_ANNOUNCE_DELAY, 20);
assert_eq!(SYNC_LIMIT, 10240);
assert_eq!(PROPAGATION_COST_MIN, 13);
assert_eq!(MAX_PEERING_COST, 26);
assert_eq!(PROPAGATION_COST_MIN, 13.0);
assert_eq!(MAX_PEERING_COST, 26.0);
assert_eq!(AUTOPEER_MAXDEPTH, 4);
assert_eq!(FASTEST_N_RANDOM_POOL, 2);
}
@@ -385,7 +413,7 @@ mod tests {
#[test]
fn test_field_standards_match_python_101() {
// LXMF.py:23-27 field allocations plus dict-key constants (LXMF.py:104-126).
// LXMF.py field allocations plus dict-key constants (LXMF.py).
assert_eq!(FIELD_REPLY_TO, 0x30);
assert_eq!(FIELD_REPLY_QUOTE, 0x31);
assert_eq!(FIELD_REACTION, 0x40);
+59 -11
View File
@@ -6,6 +6,7 @@
use std::path::{Path, PathBuf};
use rns_identity::announce::AnnounceStampExt;
use rns_identity::announce_state::RatchetControlState;
use rns_identity::destination::{AnnounceTime, DestType, Destination, Direction};
use rns_identity::identity::Identity;
@@ -57,7 +58,11 @@ pub struct 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
/// ring that cannot be stored leaves delivery available but unratcheted.
@@ -70,7 +75,7 @@ impl DeliveryRatchetState {
control_path: PathBuf,
wall_now: u64,
) -> Result<Self, DeliveryRatchetError> {
let destination = Destination::new(
let mut destination = Destination::new(
Some(identity),
Direction::In,
DestType::Single,
@@ -79,6 +84,7 @@ impl DeliveryRatchetState {
if destination.hash != destination_hash {
return Err(DeliveryRatchetError::DestinationMismatch);
}
destination.set_link_cost(crate::constants::DELIVERY_LINK_COST);
let ring_existed = ring_path.exists();
let (mut ring, ring_file_trusted) = if ring_existed {
@@ -87,7 +93,7 @@ impl DeliveryRatchetState {
let format = loaded.format();
let ring = loaded.into_ring();
if format == RatchetRingFormat::LegacyRust {
match ring.save_verified(&ring_path, identity) {
match ring.save_verified_durable(&ring_path, identity) {
Ok(()) => tracing::info!(
path = %ring_path.display(),
"migrated legacy Rust ratchet ring to canonical format"
@@ -145,7 +151,7 @@ impl DeliveryRatchetState {
if ring.is_empty() && ring_file_trusted && control_file_trusted {
let prepared = ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&ring_path, identity) {
match prepared.ring().save_verified_durable(&ring_path, identity) {
Ok(()) => {
ring.commit_prepared_rotation(prepared);
control = control.with_rotation_at(wall_now);
@@ -161,7 +167,7 @@ impl DeliveryRatchetState {
if control_file_trusted
&& (!control_existed || control_changed)
&& let Err(error) = control.save_verified(&control_path, identity)
&& let Err(error) = control.save_verified_durable(&control_path, identity)
{
tracing::warn!(
path = %control_path.display(),
@@ -185,6 +191,15 @@ impl DeliveryRatchetState {
self.destination.hash
}
/// The delivery destination, holding its destination stamp and link cost.
pub fn destination(&self) -> &Destination {
&self.destination
}
pub fn destination_mut(&mut self) -> &mut Destination {
&mut self.destination
}
pub fn ring(&self) -> &RatchetRing {
&self.ring
}
@@ -197,7 +212,8 @@ impl DeliveryRatchetState {
///
/// `wall_now` supplies both rotation age and the 40-bit wire ordering
/// value. `cache_now` is a separate local elapsed-time domain used only for
/// tagged path-response expiry.
/// tagged path-response expiry. `stamp_ext` is appended to the app data
/// when the stamp policy stamps destinations.
pub fn create_announce(
&mut self,
identity: &Identity,
@@ -205,6 +221,7 @@ impl DeliveryRatchetState {
wall_now: u64,
cache_now: f64,
kind: DeliveryAnnounceKind<'_>,
stamp_ext: Option<&AnnounceStampExt>,
) -> Result<Vec<u8>, DeliveryRatchetError> {
if identity.hash != self.control.identity_hash() {
return Err(DeliveryRatchetError::DestinationMismatch);
@@ -241,7 +258,10 @@ impl DeliveryRatchetState {
let mut ratchet_public = self.ring.current_public_key();
if rotation_due && self.ring_file_trusted {
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&self.ring_path, identity) {
match prepared
.ring()
.save_verified_durable(&self.ring_path, identity)
{
Ok(()) => {
ratchet_public = Some(prepared.public_key());
candidate_control = candidate_control.with_rotation_at(wall_now);
@@ -256,7 +276,7 @@ impl DeliveryRatchetState {
}
candidate_control
.save_verified(&self.control_path, identity)
.save_verified_durable(&self.control_path, identity)
.map_err(|source| DeliveryRatchetError::PersistControl {
path: self.control_path.clone(),
source,
@@ -278,13 +298,14 @@ impl DeliveryRatchetState {
DeliveryAnnounceKind::PathResponse { tag } => (true, tag),
};
self.destination
.announce_packet_at(
.announce_packet_with_ext_at(
identity,
Some(app_data),
ratchet_public.as_ref(),
path_response,
tag,
AnnounceTime::new(wire_now, announce_time.cache)?,
stamp_ext,
)
.map_err(DeliveryRatchetError::from)
}
@@ -293,17 +314,33 @@ impl DeliveryRatchetState {
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted
&& let Err(error) = self.ring.save_verified(&self.ring_path, identity)
&& let Err(error) = self.ring.save_verified_durable(&self.ring_path, identity)
{
tracing::warn!(%error, "failed to save ratchet ring");
}
if self.control_file_trusted
&& let Err(error) = self.control.save_verified(&self.control_path, identity)
&& let Err(error) = self
.control
.save_verified_durable(&self.control_path, identity)
{
tracing::warn!(%error, "failed to save ratchet control state");
}
}
/// Checked strict checkpoint. Invalid files discovered during load remain
/// untouched and prevent a successful checkpoint claim.
pub fn save_durable(&self, identity: &Identity) -> std::io::Result<()> {
if !self.ring_file_trusted || !self.control_file_trusted {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"ratchet checkpoint contains untrusted state",
));
}
self.ring.save_verified_durable(&self.ring_path, identity)?;
self.control
.save_verified_durable(&self.control_path, identity)
}
pub fn ring_path(&self) -> &Path {
&self.ring_path
}
@@ -360,6 +397,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
@@ -373,6 +411,7 @@ mod tests {
101,
101.5,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Coalesced)
));
@@ -387,6 +426,7 @@ mod tests {
102,
102.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert_eq!(unpack_announce(&raw).1.ratchet, Some(initial_public));
@@ -399,6 +439,7 @@ mod tests {
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let rotated_public = unpack_announce(&raw).1.ratchet.unwrap();
@@ -436,6 +477,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
@@ -460,6 +502,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert!(!unpack_announce(&raw).0.flags.context_flag);
@@ -478,6 +521,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let live_public = state.ring.current_public_key();
@@ -492,6 +536,7 @@ mod tests {
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::PersistControl { .. })
));
@@ -512,6 +557,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
let committed_wire = state.control.last_announce_wire();
@@ -523,6 +569,7 @@ mod tests {
101,
102.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
assert_eq!(
@@ -551,6 +598,7 @@ mod tests {
101,
f64::NAN,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Destination(_))
));
+88 -142
View File
@@ -1,23 +1,19 @@
//! LXMF-backed stamper for Reticulum interface discovery.
//!
//! # Layering
//!
//! Python `RNS/Discovery.py:41` imports `LXMF.LXStamper` directly; the
//! discovery subsystem cannot work without LXMF installed. Rust keeps
//! Reticulum below LXMF, so `rns-transport` depends on a trait object and
//! the concrete implementation lives here.
//!
//! # Workblock: Python parity
//!
//! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)`
//! (RNS/Discovery.py:220), where `stamp_workblock` is the
//! HKDF-expanded construction: one HKDF expand per round, each round
//! producing 256 bytes, total `expand_rounds * 256` bytes.
//! [`crate::stamper::stamp_workblock`] is the same construction.
//! Stamper for Reticulum interface discovery.
//!
//! Upstream's discovery stamper is `RNS.Stamps` (Discovery.py);
//! [`LxmfDiscoveryStamper`] delegates to
//! `rns_transport::discovery::RnsDiscoveryStamper` for callers that install it.
use rns_transport::discovery::DiscoveryStamper;
use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
use rand::RngCore;
use crate::stamper::{stamp_valid, stamp_workblock};
fn random_stamp() -> [u8; 32] {
let mut stamp = [0u8; 32];
rand::thread_rng().fill_bytes(&mut stamp);
stamp
}
/// Python `RNS.Discovery.InterfaceAnnouncer.WORKBLOCK_EXPAND_ROUNDS`,
/// the expand-round count discovery uses when building its workblock.
@@ -26,103 +22,64 @@ use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
/// interface, so this path has to stay cheap enough for periodic announces.
pub const DISCOVERY_WORKBLOCK_EXPAND_ROUNDS: usize = 20;
/// Upper bound on the random-stamp search before we give up on a given
/// tick. If the cap is hit, the announcer skips this cycle and tries again
/// rather than pinning a blocking worker indefinitely.
///
/// 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.
/// Attempt budget for [`generate_discovery_stamp`] callers. The
/// [`LxmfDiscoveryStamper`] trait implementation has no cap.
pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000;
/// PoW stamper for on-network discovery announces. Thin wrapper around
/// [`lxmf_core::stamper`](crate::stamper) that binds the exact Python
/// discovery construction (HKDF workblock with 20 expand rounds).
///
/// Clonable and `Send + Sync`; the default instance is fine for most
/// users.
/// Discovery stamper; delegates to
/// [`rns_transport::discovery::RnsDiscoveryStamper`], which has no attempt cap.
#[derive(Debug, Clone, Default)]
pub struct LxmfDiscoveryStamper {
/// Override the iteration cap; defaults to [`DISCOVERY_MAX_ITERATIONS`].
/// Zero means "use the default".
max_iterations: u64,
_private: (),
}
impl LxmfDiscoveryStamper {
/// Build a stamper with a custom iteration cap. Most callers want
/// [`LxmfDiscoveryStamper::default`].
pub fn with_max_iterations(max_iterations: u64) -> Self {
Self { max_iterations }
}
fn effective_max_iterations(&self) -> u64 {
if self.max_iterations == 0 {
DISCOVERY_MAX_ITERATIONS
} else {
self.max_iterations
}
/// Discovery generation has no attempt cap upstream; the argument is ignored.
#[deprecated(note = "discovery stamp generation has no attempt cap; use `default()`")]
pub fn with_max_iterations(_max_iterations: u64) -> Self {
Self::default()
}
}
impl DiscoveryStamper for LxmfDiscoveryStamper {
fn generate(&self, infohash: &[u8; 32], target_value: u8) -> Option<Vec<u8>> {
if target_value == 0 {
return Some(vec![0u8; 32]);
}
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..self.effective_max_iterations() {
let candidate = crate::stamper::rand_bytes();
if stamp_valid(&candidate, target_value, &workblock) {
return Some(candidate.to_vec());
}
}
None
fn generate(
&self,
infohash: &[u8; 32],
target_value: f64,
ctl: &rns_identity::stamps::StampControl,
) -> Option<Vec<u8>> {
rns_transport::discovery::RnsDiscoveryStamper.generate(infohash, target_value, ctl)
}
fn value(&self, infohash: &[u8; 32], stamp: &[u8]) -> u8 {
if stamp.len() != 32 {
return 0;
}
let mut stamp_arr = [0u8; 32];
stamp_arr.copy_from_slice(stamp);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let v = stamp_value(&workblock, &stamp_arr);
v.min(u8::MAX as u32) as u8
fn value(&self, infohash: &[u8; 32], stamp: &[u8]) -> f64 {
rns_transport::discovery::RnsDiscoveryStamper.value(infohash, stamp)
}
fn valid(&self, infohash: &[u8; 32], stamp: &[u8], required_value: u8) -> bool {
if required_value == 0 {
return true;
}
if stamp.len() != 32 {
return false;
}
let mut stamp_arr = [0u8; 32];
stamp_arr.copy_from_slice(stamp);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
stamp_valid(&stamp_arr, required_value, &workblock)
fn valid(&self, infohash: &[u8; 32], stamp: &[u8], required_value: f64) -> bool {
rns_transport::discovery::RnsDiscoveryStamper.valid(infohash, stamp, required_value)
}
fn validate(&self, infohash: &[u8; 32], stamp: &[u8], required_value: f64) -> Option<f64> {
rns_transport::discovery::RnsDiscoveryStamper.validate(infohash, stamp, required_value)
}
}
/// Validation helper: synchronous wrapper mirroring
/// [`crate::stamper::generate_stamp_limited`] but using the HKDF
/// workblock construction. Public so interop tests and downstream validation
/// can exercise discovery stamping without a transport runtime.
/// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
/// explicit attempt limit. Uses the same construction as
/// [`crate::stamper::generate_stamp`], without a transport runtime.
/// For nonzero cost, a zero iteration limit returns `None`.
pub fn generate_discovery_stamp(
infohash: &[u8; 32],
target_value: u8,
max_iterations: u64,
) -> Option<[u8; 32]> {
if target_value == 0 {
return Some([0u8; 32]);
return Some(random_stamp());
}
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..max_iterations {
let candidate = crate::stamper::rand_bytes();
if stamp_valid(&candidate, target_value, &workblock) {
let candidate = random_stamp();
if stamp_valid(&candidate, f64::from(target_value), &workblock) {
return Some(candidate);
}
}
@@ -133,80 +90,70 @@ pub fn generate_discovery_stamp(
mod tests {
use super::*;
use rns_crypto::sha::sha256;
use rns_identity::stamps::StampControl;
use std::sync::atomic::Ordering;
fn mk_infohash(seed: &[u8]) -> [u8; 32] {
sha256(seed)
}
#[test]
fn cost_zero_generates_immediately_and_is_always_valid() {
let stamper = LxmfDiscoveryStamper::default();
fn cost_zero_returns_a_random_stamp_valid_at_zero() {
let infohash = mk_infohash(b"cost-zero");
let stamp = stamper.generate(&infohash, 0).unwrap();
assert_eq!(stamp.len(), 32);
assert!(stamper.valid(&infohash, &stamp, 0));
let ctl = StampControl::default();
let a = LxmfDiscoveryStamper::default()
.generate(&infohash, 0.0, &ctl)
.unwrap();
let b = LxmfDiscoveryStamper::default()
.generate(&infohash, 0.0, &ctl)
.unwrap();
assert_eq!(a.len(), 32);
assert_ne!(a, b);
assert!(LxmfDiscoveryStamper::default().valid(&infohash, &a, 0.0));
}
#[test]
fn generate_stamp_passes_valid() {
let stamper = LxmfDiscoveryStamper::with_max_iterations(200_000);
let infohash = mk_infohash(b"generate-round-trip");
let cost = 6;
let stamp = stamper.generate(&infohash, cost);
assert!(stamp.is_some(), "cost={cost} should be findable within cap");
assert!(stamper.valid(&infohash, &stamp.unwrap(), cost));
}
#[test]
fn value_reports_leading_zero_bits() {
let stamper = LxmfDiscoveryStamper::with_max_iterations(200_000);
fn generated_stamp_value_meets_fractional_target() {
let infohash = mk_infohash(b"value-check");
let cost = 4;
let stamp = stamper.generate(&infohash, cost).unwrap();
let value = stamper.value(&infohash, &stamp);
assert!(value >= cost, "value {value} must be >= cost {cost}");
let stamp = LxmfDiscoveryStamper::default()
.generate(&infohash, 6.5, &StampControl::default())
.unwrap();
let value = LxmfDiscoveryStamper::default().value(&infohash, &stamp);
assert!(value >= 6.5, "value {value}");
assert!(LxmfDiscoveryStamper::default().valid(&infohash, &stamp, 6.5));
}
#[test]
fn invalid_stamp_is_rejected() {
let stamper = LxmfDiscoveryStamper::default();
fn invalid_and_short_stamps_are_rejected() {
let infohash = mk_infohash(b"invalid");
let bogus = [0xFFu8; 32];
assert!(!stamper.valid(&infohash, &bogus, 32));
assert!(!LxmfDiscoveryStamper::default().valid(&infohash, &[0xFF; 32], 32.0));
assert!(LxmfDiscoveryStamper::default().value(&infohash, &[0u8; 16]) < 8.0);
assert!(!LxmfDiscoveryStamper::default().valid(&infohash, &[0xFF; 16], 8.0));
}
#[test]
fn non_32_byte_stamp_is_rejected() {
let stamper = LxmfDiscoveryStamper::default();
let infohash = mk_infohash(b"wrong-size");
// Non-standard length; must not panic, must not validate.
assert_eq!(stamper.value(&infohash, &[0u8; 16]), 0);
assert!(!stamper.valid(&infohash, &[0u8; 16], 8));
}
#[test]
fn generate_gives_up_when_cap_exhausted() {
// Cost 64 is astronomically unreachable in a handful of iters.
fn cancelled_generation_returns_none() {
let ctl = StampControl::default();
ctl.cancel.store(true, Ordering::Relaxed);
#[allow(deprecated)]
let stamper = LxmfDiscoveryStamper::with_max_iterations(10);
let infohash = mk_infohash(b"unreachable");
assert!(stamper.generate(&infohash, 64).is_none());
assert!(
stamper
.generate(&mk_infohash(b"unreachable"), 64.0, &ctl)
.is_none()
);
}
#[test]
fn two_generated_stamps_both_validate_independently() {
let stamper = LxmfDiscoveryStamper::with_max_iterations(200_000);
let a = mk_infohash(b"a");
let b = mk_infohash(b"b");
let cost = 4;
let sa = stamper.generate(&a, cost).unwrap();
let sb = stamper.generate(&b, cost).unwrap();
assert!(stamper.valid(&a, &sa, cost));
assert!(stamper.valid(&b, &sb, cost));
// Cross-validation MUST fail (different workblocks).
assert!(
!stamper.valid(&a, &sb, 16) || stamper.value(&a, &sb) < 16,
"cross-infohash stamp must not clear a meaningful cost"
);
fn non_expanded_stamps_validate_with_their_own_value() {
let infohash = mk_infohash(b"non-expanded");
let (stamp, value) =
rns_identity::stamps::generate_stamp(&infohash, 6.0, 0, 32, &StampControl::default())
.unwrap()
.unwrap();
let stamper = LxmfDiscoveryStamper::default();
assert_eq!(stamper.validate(&infohash, &stamp, 6.0), Some(value));
assert!(stamper.valid(&infohash, &stamp, 6.0));
}
#[test]
@@ -219,14 +166,13 @@ mod tests {
let infohash = mk_infohash(b"helper");
let stamp = generate_discovery_stamp(&infohash, 4, 200_000);
assert!(stamp.is_some());
let stamper = LxmfDiscoveryStamper::default();
assert!(stamper.valid(&infohash, &stamp.unwrap(), 4));
assert!(LxmfDiscoveryStamper::default().valid(&infohash, &stamp.unwrap(), 4.0));
}
#[test]
fn generate_discovery_stamp_cost_zero_is_instant() {
let infohash = mk_infohash(b"helper-zero");
let stamp = generate_discovery_stamp(&infohash, 0, 1);
assert_eq!(stamp, Some([0u8; 32]));
assert!(stamp.is_some());
}
}
File diff suppressed because it is too large. Load diff
+71 -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)]
pub struct InboundResourceSnapshot {
pub key: InboundResourceKey,
@@ -133,10 +134,12 @@ impl InboundResourceHandle {
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
/// actor owner has dropped its sender.
/// Returns `None` once the sender is gone and its latest value has been seen.
/// 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> {
if self.snapshot_rx.changed().await.is_err() {
return None;
@@ -158,6 +161,21 @@ impl InboundResourceHandle {
.is_ok()
})
}
/// Like [`Self::cancel`], but waits for room in the command channel instead
/// of refusing when it is full.
pub async fn cancel_wait(&self) -> bool {
if self.snapshot().is_closed() {
return false;
}
match &self.cancel_tx {
Some(tx) => tx
.send(InboundResourceCancelRequest::new(self.key))
.await
.is_ok(),
None => false,
}
}
}
struct ActiveInboundResource {
@@ -166,9 +184,10 @@ struct ActiveInboundResource {
/// Single-owner active Resource registry.
///
/// Terminal records are removed immediately, so the registry is bounded by
/// concurrent transfers. Previously returned handles retain the final owned
/// snapshot without keeping actor state alive.
/// Concluded and LinkClosed events remove records immediately. The embedder
/// must forward those events to keep the registry limited to active transfers;
/// the tracker has no independent entry cap or timeout. Previously returned
/// handles retain their latest snapshot without keeping tracker state alive.
#[derive(Default)]
pub struct InboundResourceTracker {
active: HashMap<InboundResourceKey, ActiveInboundResource>,
@@ -203,8 +222,8 @@ impl InboundResourceTracker {
/// Return the active Resource matching `resource_id`.
///
/// A cryptographic ID collision across two Links fails closed instead of
/// choosing the wrong cancellation authority.
/// If the same Resource ID is active on more than one Link, returns `None`.
/// Use [`Self::inbound_resource_exact`] with the full key to disambiguate.
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
let mut matches = self
.active
@@ -237,7 +256,8 @@ impl InboundResourceTracker {
/// Queue cancellation for a stable snapshot of every active Resource.
///
/// The returned count is the number accepted by the bounded command
/// channel, matching Python's count-oriented `cancel_all_inbound` API.
/// channel, not the number of completed cancellations. Closure is reported
/// by subsequent lifecycle events.
pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resources()
.into_iter()
@@ -245,6 +265,22 @@ impl InboundResourceTracker {
.count()
}
/// Request cancellation of every active Resource, waiting for channel room,
/// so the count covers all of them as Python's `cancel_all_inbound` does.
/// The future owns its handles and does not borrow the tracker.
pub fn cancel_all_inbound_wait(
&self,
) -> impl std::future::Future<Output = usize> + Send + 'static {
let handles = self.inbound_resources();
async move {
let mut cancelled = 0;
for handle in handles {
cancelled += usize::from(handle.cancel_wait().await);
}
cancelled
}
}
/// Apply one lifecycle update from the embedding runtime.
pub fn handle_event(&mut self, event: InboundResourceEvent) {
match event {
@@ -281,6 +317,15 @@ impl InboundResourceTracker {
return;
}
tracing::debug!(
"Began {} transfer for LXMF delivery resource {}",
if data_size > 0 {
pretty_size(data_size)
} else {
"unknown size".to_string()
},
hex::encode(key.resource_id)
);
let snapshot = InboundResourceSnapshot {
key,
data_size,
@@ -328,6 +373,22 @@ impl InboundResourceTracker {
}
}
/// Python `RNS.prettysize` for byte counts.
fn pretty_size(size: usize) -> String {
let mut num = size as f64;
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"] {
if num.abs() < 1000.0 {
return if unit.is_empty() {
format!("{num:.0} B")
} else {
format!("{num:.2} {unit}B")
};
}
num /= 1000.0;
}
format!("{num:.2}YB")
}
#[cfg(test)]
mod tests {
use super::*;
+37 -8
View File
@@ -4,20 +4,20 @@
//!
//! This crate implements the LXMF wire model and is the core LXMF building
//! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications.
//! Its Reticulum dependency is `rns-transport` from rsReticulum; LXMF sits one
//! layer above the Reticulum stack.
//! It uses rsReticulum for transport, links, identities and Resources; LXMF
//! sits one layer above the Reticulum stack.
//!
//! # Module map
//!
//! | 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 |
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
//! | [`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 |
//! | [`propagation`] | On-disk store-and-forward message pool |
//! | [`propagation`] | In-memory propagation message index and selection |
//! | [`propagation_node`] | Propagation-node role logic |
//! | [`propagation_client`]| Client side of propagation sync |
//! | [`propagation_sync`] | Wire-level peer sync exchange |
@@ -25,9 +25,16 @@
//! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery |
//! | [`sync`] | Shared peer-to-peer sync primitives |
//! | [`link_delivery`] | Reticulum-link-based delivery path |
//! | [`handlers`] | Callback trait surface for delivery events |
//! | [`ticket`] | Small typed identifier for propagation workflows |
//! | [`handlers`] | Announce parsing and propagation control handlers |
//! | [`ticket`] | Directional tickets for bypassing recipient stamp work |
//! | [`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. |
//!
//! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum`
@@ -43,6 +50,20 @@ pub(crate) fn now_f64() -> f64 {
.as_secs_f64()
}
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
#[cfg(test)]
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
pub mod admission;
pub mod admission_store;
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
@@ -58,9 +79,12 @@ pub mod propagation_admission;
pub mod propagation_client;
pub mod propagation_node;
pub mod propagation_offer;
pub mod propagation_send;
pub mod propagation_store_v2;
pub mod propagation_sync;
pub mod router;
pub mod stamper;
pub mod state_store;
pub mod sync;
pub mod ticket;
pub mod types;
@@ -74,7 +98,12 @@ pub mod message_api {
pub use crate::constants::{
DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason,
};
pub use crate::message::{AudioField, LxMessage, MessageError};
pub use crate::message::{
AudioField, EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields,
LxMessage, LxMessageDraft, MessageDecodeLimits, MessageError, MessageMetadata,
OwnedVerifiedLxMessage, RecipientStamp, ResumableLxMessage, SignedLxMessage,
UniqueFieldMap, VerifiedLxMessage,
};
pub use crate::types::{DestinationHash, IdentityHash, MessageId};
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+509
View File
@@ -0,0 +1,509 @@
//! MessagePack decoding with the acceptance rules of the umsgpack decoder used
//! by Python LXMF, and its canonical re-encoding (`umsgpack.packb(unpackb(x))`).
use super::MessageError;
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
const MAX_DEPTH: usize = 64;
// datetime.min / datetime.max relative to the Unix epoch, in microseconds.
const MIN_TIMESTAMP_MICROS: i128 = -62_135_596_800 * 1_000_000;
const MAX_TIMESTAMP_MICROS: i128 = 253_402_300_799 * 1_000_000 + 999_999;
/// Python value identity of a decoded map key.
#[derive(Debug)]
enum Key {
Nil,
Number(i128),
Float(u64),
NaN,
Str(Vec<u8>),
Bin(Vec<u8>),
Ext(i8, Vec<u8>),
Time(i128),
Tuple(Vec<Key>),
Unhashable,
}
impl Key {
fn same(&self, other: &Key) -> bool {
match (self, other) {
(Key::Nil, Key::Nil) => true,
(Key::Number(a), Key::Number(b)) => a == b,
(Key::Float(a), Key::Float(b)) => a == b,
(Key::Str(a), Key::Str(b)) | (Key::Bin(a), Key::Bin(b)) => a == b,
(Key::Ext(t, a), Key::Ext(u, b)) => t == u && a == b,
(Key::Time(a), Key::Time(b)) => a == b,
(Key::Tuple(a), Key::Tuple(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.same(y))
}
_ => false,
}
}
fn hashable(&self) -> bool {
match self {
Key::Unhashable => false,
Key::Tuple(items) => items.iter().all(Key::hashable),
_ => true,
}
}
fn contains_nan(&self) -> bool {
match self {
Key::NaN => true,
Key::Tuple(items) => items.iter().any(Key::contains_nan),
_ => false,
}
}
fn from_float(value: f64) -> Key {
if value.is_nan() {
Key::NaN
} else if value.fract() == 0.0 && value.abs() < 1.0e38 {
Key::Number(value as i128)
} else {
Key::Float(value.to_bits())
}
}
}
// Equality is reflexive for every key that reaches the index (NaN keys never do).
impl PartialEq for Key {
fn eq(&self, other: &Key) -> bool {
self.same(other)
}
}
impl Eq for Key {}
impl Hash for Key {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Key::Nil => 0u8.hash(state),
Key::Number(n) => (1u8, n).hash(state),
Key::Float(bits) => (2u8, bits).hash(state),
Key::NaN => 3u8.hash(state),
Key::Str(v) => (4u8, v).hash(state),
Key::Bin(v) => (5u8, v).hash(state),
Key::Ext(t, v) => (6u8, t, v).hash(state),
Key::Time(t) => (7u8, t).hash(state),
Key::Tuple(items) => {
8u8.hash(state);
items.len().hash(state);
for item in items {
item.hash(state);
}
}
Key::Unhashable => 9u8.hash(state),
}
}
}
fn fail(reason: &str) -> MessageError {
MessageError::UnpackFailed(reason.to_string())
}
fn take<'a>(input: &mut &'a [u8], length: usize) -> Result<&'a [u8], MessageError> {
if input.len() < length {
return Err(fail("truncated MessagePack value"));
}
let (value, rest) = input.split_at(length);
*input = rest;
Ok(value)
}
fn be(input: &mut &[u8], width: usize) -> Result<u64, MessageError> {
Ok(take(input, width)?
.iter()
.fold(0u64, |acc, byte| (acc << 8) | u64::from(*byte)))
}
fn emit(out: &mut Option<&mut Vec<u8>>, bytes: &[u8]) {
if let Some(out) = out.as_deref_mut() {
out.extend_from_slice(bytes);
}
}
fn write_int(out: &mut Vec<u8>, value: i128) {
if value < 0 {
if value >= -32 {
out.push(value as i8 as u8);
} else if value >= i128::from(i8::MIN) {
out.push(0xd0);
out.push(value as i8 as u8);
} else if value >= i128::from(i16::MIN) {
out.push(0xd1);
out.extend_from_slice(&(value as i16).to_be_bytes());
} else if value >= i128::from(i32::MIN) {
out.push(0xd2);
out.extend_from_slice(&(value as i32).to_be_bytes());
} else {
out.push(0xd3);
out.extend_from_slice(&(value as i64).to_be_bytes());
}
} else if value < 128 {
out.push(value as u8);
} else if value <= i128::from(u8::MAX) {
out.push(0xcc);
out.push(value as u8);
} else if value <= i128::from(u16::MAX) {
out.push(0xcd);
out.extend_from_slice(&(value as u16).to_be_bytes());
} else if value <= i128::from(u32::MAX) {
out.push(0xce);
out.extend_from_slice(&(value as u32).to_be_bytes());
} else {
out.push(0xcf);
out.extend_from_slice(&(value as u64).to_be_bytes());
}
}
fn write_sized(out: &mut Vec<u8>, length: usize, fix: Option<(u8, usize)>, wide: [u8; 3]) {
match fix {
Some((base, limit)) if length < limit => out.push(base | length as u8),
_ if length <= usize::from(u8::MAX) && wide[0] != 0 => {
out.push(wide[0]);
out.push(length as u8);
}
_ if length <= usize::from(u16::MAX) => {
out.push(wide[1]);
out.extend_from_slice(&(length as u16).to_be_bytes());
}
_ => {
out.push(wide[2]);
out.extend_from_slice(&(length as u32).to_be_bytes());
}
}
}
fn write_ext(out: &mut Vec<u8>, ext_type: i8, data: &[u8]) {
match data.len() {
1 => out.push(0xd4),
2 => out.push(0xd5),
4 => out.push(0xd6),
8 => out.push(0xd7),
16 => out.push(0xd8),
length => write_sized(out, length, None, [0xc7, 0xc8, 0xc9]),
}
out.push(ext_type as u8);
out.extend_from_slice(data);
}
fn timestamp_micros(data: &[u8]) -> Result<i128, MessageError> {
let (seconds, micros) = match data.len() {
4 => (
i128::from(u32::from_be_bytes(data.try_into().expect("length"))),
0,
),
8 => {
let value = u64::from_be_bytes(data.try_into().expect("length"));
(
i128::from(value & 0x3_ffff_ffff),
i128::from(value >> 34) / 1000,
)
}
12 => (
i128::from(i64::from_be_bytes(data[4..12].try_into().expect("length"))),
i128::from(u32::from_be_bytes(data[0..4].try_into().expect("length"))) / 1000,
),
_ => return Err(fail("unsupported MessagePack timestamp")),
};
let total = seconds * 1_000_000 + micros;
if !(MIN_TIMESTAMP_MICROS..=MAX_TIMESTAMP_MICROS).contains(&total) {
return Err(fail("MessagePack timestamp out of range"));
}
Ok(total)
}
fn write_timestamp(out: &mut Vec<u8>, total: i128) {
let seconds = total.div_euclid(1_000_000);
let micros = total.rem_euclid(1_000_000);
if micros == 0 && (0..=i128::from(u32::MAX)).contains(&seconds) {
out.extend_from_slice(&[0xd6, 0xff]);
out.extend_from_slice(&(seconds as u32).to_be_bytes());
} else if (0..(1i128 << 34)).contains(&seconds) {
let value = ((micros as u64 * 1000) << 34) | seconds as u64;
out.extend_from_slice(&[0xd7, 0xff]);
out.extend_from_slice(&value.to_be_bytes());
} else {
out.extend_from_slice(&[0xc7, 0x0c, 0xff]);
out.extend_from_slice(&((micros * 1000) as u32).to_be_bytes());
out.extend_from_slice(&(seconds as i64).to_be_bytes());
}
}
/// Decode one value, writing its canonical encoding to `out` when present.
/// Returns the value's key identity when `want_key` is set.
fn walk(
input: &mut &[u8],
mut out: Option<&mut Vec<u8>>,
want_key: bool,
depth: usize,
) -> Result<Option<Key>, MessageError> {
if depth >= MAX_DEPTH {
return Err(fail("MessagePack nesting exceeds limit"));
}
let marker = take(input, 1)?[0];
let number = |value: i128, out: Option<&mut Vec<u8>>| {
if let Some(out) = out {
write_int(out, value);
}
Ok(want_key.then_some(Key::Number(value)))
};
match marker {
0x00..=0x7f => number(i128::from(marker), out),
0xe0..=0xff => number(i128::from(marker as i8), out),
0xcc => number(i128::from(be(input, 1)?), out),
0xcd => number(i128::from(be(input, 2)?), out),
0xce => number(i128::from(be(input, 4)?), out),
0xcf => number(i128::from(be(input, 8)?), out),
0xd0 => number(i128::from(be(input, 1)? as u8 as i8), out),
0xd1 => number(i128::from(be(input, 2)? as u16 as i16), out),
0xd2 => number(i128::from(be(input, 4)? as u32 as i32), out),
0xd3 => number(i128::from(be(input, 8)? as i64), out),
0xc0 => {
emit(&mut out, &[0xc0]);
Ok(want_key.then_some(Key::Nil))
}
0xc1 => Err(fail("reserved MessagePack marker")),
0xc2 | 0xc3 => {
emit(&mut out, &[marker]);
Ok(want_key.then_some(Key::Number(i128::from(marker == 0xc3))))
}
0xca | 0xcb => {
let value = if marker == 0xca {
f64::from(f32::from_bits(be(input, 4)? as u32))
} else {
f64::from_bits(be(input, 8)?)
};
if let Some(out) = out {
out.push(0xcb);
out.extend_from_slice(&value.to_bits().to_be_bytes());
}
Ok(want_key.then(|| Key::from_float(value)))
}
0xa0..=0xbf | 0xd9..=0xdb => {
let length = match marker {
0xd9 => be(input, 1)?,
0xda => be(input, 2)?,
0xdb => be(input, 4)?,
_ => u64::from(marker & 0x1f),
} as usize;
let data = take(input, length)?;
if std::str::from_utf8(data).is_err() {
return Err(fail("MessagePack string is invalid UTF-8"));
}
if let Some(out) = out {
write_sized(out, length, Some((0xa0, 32)), [0xd9, 0xda, 0xdb]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Str(data.to_vec())))
}
0xc4..=0xc6 => {
let length = be(input, 1 << (marker - 0xc4))? as usize;
let data = take(input, length)?;
if let Some(out) = out {
write_sized(out, length, None, [0xc4, 0xc5, 0xc6]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Bin(data.to_vec())))
}
0xc7..=0xc9 | 0xd4..=0xd8 => {
let length = match marker {
0xc7 => be(input, 1)? as usize,
0xc8 => be(input, 2)? as usize,
0xc9 => be(input, 4)? as usize,
_ => 1 << (marker - 0xd4),
};
let ext_type = take(input, 1)?[0] as i8;
let data = take(input, length)?;
if ext_type == -1 {
let total = timestamp_micros(data)?;
if let Some(out) = out {
write_timestamp(out, total);
}
return Ok(want_key.then_some(Key::Time(total)));
}
if let Some(out) = out {
write_ext(out, ext_type, data);
}
Ok(want_key.then(|| Key::Ext(ext_type, data.to_vec())))
}
0x90..=0x9f | 0xdc | 0xdd => {
let count = match marker {
0xdc => be(input, 2)?,
0xdd => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
if let Some(out) = out.as_deref_mut() {
write_sized(out, count as usize, Some((0x90, 16)), [0, 0xdc, 0xdd]);
}
let mut items = Vec::new();
for _ in 0..count {
let item = walk(input, out.as_deref_mut(), want_key, depth + 1)?;
if let Some(item) = item {
items.push(item);
}
}
Ok(want_key.then_some(Key::Tuple(items)))
}
0x80..=0x8f | 0xde | 0xdf => {
let count = match marker {
0xde => be(input, 2)?,
0xdf => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
walk_map(input, out, count, depth)?;
Ok(want_key.then_some(Key::Unhashable))
}
}
}
struct Entry {
encoded_key: Vec<u8>,
encoded_value: Vec<u8>,
}
fn walk_map(
input: &mut &[u8],
out: Option<&mut Vec<u8>>,
count: u64,
depth: usize,
) -> Result<(), MessageError> {
let writing = out.is_some();
let mut entries: Vec<Entry> = Vec::new();
let mut index: HashMap<Key, usize> = HashMap::new();
for _ in 0..count {
let is_list = matches!(input.first(), Some(0x90..=0x9f | 0xdc | 0xdd));
let mut encoded_key = Vec::new();
let key = walk(input, writing.then_some(&mut encoded_key), true, depth + 1)?
.expect("key requested");
// Lists become tuples and bypass the duplicate check; later ones overwrite.
if !is_list {
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
if index.contains_key(&key) {
return Err(fail("duplicate MessagePack map key"));
}
}
let mut encoded_value = Vec::new();
walk(
input,
writing.then_some(&mut encoded_value),
false,
depth + 1,
)?;
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
let existing = if key.contains_nan() {
None
} else {
index.get(&key).copied()
};
match existing {
Some(position) => entries[position].encoded_value = encoded_value,
None => {
if !key.contains_nan() {
index.insert(key, entries.len());
}
entries.push(Entry {
encoded_key,
encoded_value,
});
}
}
}
if let Some(out) = out {
write_sized(out, entries.len(), Some((0x80, 16)), [0, 0xde, 0xdf]);
for entry in entries {
out.extend_from_slice(&entry.encoded_key);
out.extend_from_slice(&entry.encoded_value);
}
}
Ok(())
}
/// Check that the leading value decodes under the umsgpack rules; trailing bytes are ignored.
pub(crate) fn validate_leading(bytes: &[u8]) -> Result<(), MessageError> {
let mut input = bytes;
walk(&mut input, None, false, 0).map(|_| ())
}
/// Canonical re-encoding of exactly one value.
pub(crate) fn canonicalize(bytes: &[u8]) -> Result<Vec<u8>, MessageError> {
let mut input = bytes;
let mut out = Vec::with_capacity(bytes.len());
walk(&mut input, Some(&mut out), false, 0)?;
if !input.is_empty() {
return Err(fail("trailing MessagePack bytes"));
}
Ok(out)
}
/// The payload bytes Python hashes: the received bytes, or the canonical
/// re-encoding of the first four elements when a stamp is present.
pub(crate) fn hashed_payload(payload: &[u8]) -> Result<Cow<'_, [u8]>, MessageError> {
let mut input = payload;
let count = match take(&mut input, 1)?[0] {
marker @ 0x90..=0x9f => u64::from(marker & 0x0f),
0xdc => be(&mut input, 2)?,
0xdd => be(&mut input, 4)?,
_ => return Err(fail("expected MessagePack array")),
};
if count <= 4 {
return Ok(Cow::Borrowed(payload));
}
let mut out = vec![0x94];
for _ in 0..4 {
walk(&mut input, Some(&mut out), false, 1)?;
}
Ok(Cow::Owned(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn canon(hex_in: &str) -> Result<String, MessageError> {
canonicalize(&hex::decode(hex_in).unwrap()).map(hex::encode)
}
#[test]
fn reencodes_minimally_and_widens_floats() {
assert_eq!(canon("91ca3fc00000").unwrap(), "91cb3ff8000000000000");
assert_eq!(canon("cd0005").unwrap(), "05");
assert_eq!(canon("d9026869").unwrap(), "a26869");
assert_eq!(canon("de00010102").unwrap(), "810102");
assert_eq!(canon("c50001aa").unwrap(), "c401aa");
assert_eq!(canon("c701050a").unwrap(), "d4050a");
assert_eq!(canon("d0ff").unwrap(), "ff");
}
#[test]
fn rejects_duplicates_by_python_equality() {
assert!(canon("820101 0102".replace(' ', "").as_str()).is_err());
assert!(canon("8201 01cb3ff0000000000000 02".replace(' ', "").as_str()).is_err());
assert!(canon("82c301 0102".replace(' ', "").as_str()).is_err());
assert!(canon("82a1610 1c4016102".replace(' ', "").as_str()).is_ok());
assert!(
canon(
"82cb7ff8000000000000 01cb7ff8000000000000 02"
.replace(' ', "")
.as_str()
)
.is_ok()
);
}
#[test]
fn list_keys_overwrite_instead_of_failing() {
assert_eq!(canon("82910101910102").unwrap(), "81910102");
assert!(canon("81918001 01".replace(' ', "").as_str()).is_err());
assert!(canon("818001 01".replace(' ', "").as_str()).is_err());
}
#[test]
fn rejects_invalid_text_and_reserved_marker() {
assert!(canon("a1ff").is_err());
assert!(canon("c1").is_err());
assert!(canon("c7").is_err());
}
}
+461
View File
@@ -0,0 +1,461 @@
//! Checked mutable construction followed by consuming signature/finalization.
use super::*;
use rns_crypto::ed25519::Ed25519PrivateKey;
/// Mutable outbound semantics. This type cannot be submitted as a wire message.
/// ```compile_fail
/// use lxmf_core::message::LxMessageDraft;
/// fn send_unsigned(draft: LxMessageDraft) { let _ = draft.wire_bytes(); }
/// ```
#[derive(Debug, Clone)]
pub struct LxMessageDraft {
destination: [u8; 16],
source: [u8; 16],
title: Bytes,
content: Bytes,
timestamp: f64,
fields: BTreeMap<FieldId, FieldValue>,
limits: MessageDecodeLimits,
pub metadata: MessageMetadata,
pub include_ticket: bool,
pub outbound_ticket: Option<[u8; 16]>,
pub stamp_cost: Option<f64>,
}
impl Deref for LxMessageDraft {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.metadata
}
}
impl DerefMut for LxMessageDraft {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.metadata
}
}
/// Frozen signed body awaiting its optional recipient stamp. Not a sendable type.
#[derive(Debug)]
pub struct SignedLxMessage {
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<f64>,
}
impl Deref for SignedLxMessage {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.message.metadata
}
}
impl DerefMut for SignedLxMessage {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.message.metadata
}
}
impl LxMessageDraft {
pub fn new(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
) -> Result<Self, MessageError> {
Self::new_with_limits(
destination,
source,
title,
content,
method,
MessageDecodeLimits::default(),
)
}
pub fn new_with_limits(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
limits: MessageDecodeLimits,
) -> Result<Self, MessageError> {
limits.check_wire(
title
.len()
.checked_add(content.len())
.and_then(|n| n.checked_add(110))
.ok_or_else(|| MessageError::PackFailed("length overflow".into()))?,
)?;
let draft = Self {
destination,
source,
title: Bytes::copy_from_slice(title.as_bytes()),
content: Bytes::copy_from_slice(content.as_bytes()),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64(),
fields: BTreeMap::new(),
limits,
metadata: MessageMetadata {
method,
..MessageMetadata::default()
},
include_ticket: false,
outbound_ticket: None,
stamp_cost: None,
};
draft.checked_wire_len()?;
Ok(draft)
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination
}
pub fn source_hash(&self) -> [u8; 16] {
self.source
}
pub fn timestamp(&self) -> f64 {
self.timestamp
}
pub fn title_bytes(&self) -> &[u8] {
&self.title
}
pub fn content_bytes(&self) -> &[u8] {
&self.content
}
pub fn fields(&self) -> &BTreeMap<FieldId, FieldValue> {
&self.fields
}
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
self.fields.get(&id.into())
}
pub fn set_timestamp(&mut self, value: f64) -> Result<(), MessageError> {
if !value.is_finite() {
return Err(MessageError::PackFailed(
"nonfinite outbound timestamp".into(),
));
}
self.timestamp = value;
Ok(())
}
pub fn set_title(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, true)
}
pub fn set_content(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, false)
}
fn set_text(&mut self, value: &str, title: bool) -> Result<(), MessageError> {
self.limits.check_wire(value.len())?;
let next = Bytes::copy_from_slice(value.as_bytes());
let old = if title {
std::mem::replace(&mut self.title, next)
} else {
std::mem::replace(&mut self.content, next)
};
if let Err(e) = self.checked_wire_len() {
if title {
self.title = old
} else {
self.content = old
};
return Err(e);
}
Ok(())
}
pub fn set_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(id, FieldValue::Binary(bytes.into()))
}
pub fn set_msgpack_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
let value = EncodedFieldValue::canonical(bytes.into())?;
self.insert_field(id.into(), FieldValue::MessagePack(value))
}
pub fn set_field_value(
&mut self,
id: impl Into<FieldId>,
value: FieldValue,
) -> Result<(), MessageError> {
let value = match value {
FieldValue::MessagePack(v) => {
FieldValue::MessagePack(EncodedFieldValue::canonical(v.into_bytes())?)
}
binary => binary,
};
self.insert_field(id.into(), value)
}
/// Encode one of this crate's media fields at its exact size, once.
fn set_media_field<T: serde::Serialize>(
&mut self,
id: FieldId,
value: &T,
bytes: usize,
name: usize,
) -> Result<(), MessageError> {
self.limits.check_wire(bytes)?;
// Two array headers, a str header and a bin header: at most 12 bytes.
let mut encoded = Vec::with_capacity(bytes + name + 12);
rmp_serde::encode::write(&mut encoded, value).map_err(packed)?;
let value = EncodedFieldValue::trusted(encoded.into());
self.insert_field(id, FieldValue::MessagePack(value))
}
fn insert_field(&mut self, id: FieldId, value: FieldValue) -> Result<(), MessageError> {
if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let old = self.fields.insert(id, value);
if let Err(e) = self.checked_wire_len() {
match old {
Some(v) => {
self.fields.insert(id, v);
}
None => {
self.fields.remove(&id);
}
};
return Err(e);
}
Ok(())
}
pub fn remove_field(&mut self, id: impl Into<FieldId>) -> Option<FieldValue> {
self.fields.remove(&id.into())
}
pub fn set_image_field(&mut self, format: &str, bytes: &[u8]) -> Result<(), MessageError> {
let value = ImageFieldRef { format, bytes };
self.set_media_field(FIELD_IMAGE.into(), &value, bytes.len(), format.len())
}
pub fn set_audio_field(&mut self, mode: u8, bytes: &[u8]) -> Result<(), MessageError> {
let value = AudioFieldRef { mode, bytes };
self.set_media_field(FIELD_AUDIO.into(), &value, bytes.len(), 0)
}
pub fn set_file_attachment_field(
&mut self,
file_name: &str,
bytes: &[u8],
) -> Result<(), MessageError> {
let value = FileAttachmentsFieldRef { file_name, bytes };
self.set_media_field(
FIELD_FILE_ATTACHMENTS.into(),
&value,
bytes.len(),
file_name.len(),
)
}
/// Exact unsigned payload, for diagnostics; it is not a transmittable message.
pub fn pack_payload(&self) -> Result<Vec<u8>, MessageError> {
let size = self.checked_wire_len()?;
let mut out = Vec::with_capacity(size - 96);
self.write_payload(&mut out)?;
Ok(out)
}
pub fn checked_wire_len(&self) -> Result<usize, MessageError> {
if self.fields.len() > self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let mut counter = CountingWriter::default();
self.write_payload(&mut counter)?;
let len = counter
.bytes
.checked_add(96)
.ok_or_else(|| packed("length overflow"))?;
self.limits.check_wire(len)?;
Ok(len)
}
fn write_payload<W: Write>(&self, out: &mut W) -> Result<(), MessageError> {
rmp::encode::write_array_len(out, 4).map_err(packed)?;
rmp::encode::write_f64(out, self.timestamp).map_err(packed)?;
write_bin(out, &self.title)?;
write_bin(out, &self.content)?;
rmp::encode::write_map_len(out, length(self.fields.len())?).map_err(packed)?;
for (id, value) in &self.fields {
if id.as_i128() >= 0 {
rmp::encode::write_uint(out, u64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
} else {
rmp::encode::write_sint(out, i64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
}
match value {
FieldValue::Binary(b) => write_bin(out, b)?,
FieldValue::MessagePack(v) => out.write_all(v.encoded()).map_err(packed)?,
}
}
Ok(())
}
pub fn sign(self, key: &Ed25519PrivateKey) -> Result<SignedLxMessage, MessageError> {
self.sign_with(|bytes| Ok::<_, std::convert::Infallible>(key.sign(bytes)))
}
pub fn sign_with<F, E>(mut self, sign: F) -> Result<SignedLxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
let size = self.checked_wire_len()?;
let mut signed = Vec::with_capacity(size);
signed.extend_from_slice(&self.destination);
signed.extend_from_slice(&self.source);
self.write_payload(&mut signed)?;
// The payload now lives in `signed` alone.
self.fields.clear();
let id = sha256(&signed);
signed.extend_from_slice(&id);
let signature = sign(&signed).map_err(packed)?;
// The wire in place: drop the id and open the signature after the
// two hashes. `size` is exactly the wire length, so nothing moves.
let payload_end = signed.len() - 32;
signed.truncate(payload_end);
signed.resize(size, 0);
signed.copy_within(32..payload_end, 96);
signed[32..96].copy_from_slice(&signature);
let mut message = LxMessage::unpack_owned(signed.into(), self.limits)?;
message.metadata = self.metadata;
message.incoming = false;
message.state = MessageState::Outbound;
Ok(SignedLxMessage {
message,
outbound_ticket: self.outbound_ticket,
stamp_cost: self.stamp_cost,
})
}
}
impl SignedLxMessage {
pub(crate) fn restored(
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<f64>,
) -> Self {
Self {
message,
outbound_ticket,
stamp_cost,
}
}
/// Create a representation the caller can persist to resume delivery after
/// 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 {
ResumableLxMessage::new(&self.message.wire, self.stamp_cost)
}
pub fn timestamp(&self) -> f64 {
self.message.timestamp()
}
/// Complete no-stamp wire length; finalization can add a recipient stamp.
pub fn packed_len(&self) -> Result<usize, MessageError> {
self.message.packed_len()
}
/// Signed payload length, without exposing sendable bytes before finalization.
pub fn payload_len(&self) -> usize {
self.message.wire_bytes().len() - 96
}
pub fn title_bytes(&self) -> &[u8] {
self.message.title_bytes()
}
pub fn content_bytes(&self) -> &[u8] {
self.message.content_bytes()
}
pub fn title_text(&self) -> std::borrow::Cow<'_, str> {
self.message.title_text()
}
pub fn content_text(&self) -> std::borrow::Cow<'_, str> {
self.message.content_text()
}
pub fn message_id(&self) -> [u8; 32] {
self.message.message_id()
}
pub fn destination_hash(&self) -> [u8; 16] {
self.message.destination_hash()
}
pub fn source_hash(&self) -> [u8; 16] {
self.message.source_hash()
}
pub fn fields(&self) -> Fields<'_> {
self.message.fields()
}
/// The first file attachment's name and bytes, borrowed from the wire.
pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.first_file_attachment()
}
/// The image field's format and bytes, borrowed from the wire.
pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.image_attachment()
}
/// The signed, unstamped message, for failing it without a stamp.
pub fn into_unstamped(self) -> LxMessage {
self.message
}
pub fn stamp_cost(&self) -> Option<f64> {
self.stamp_cost
}
pub fn outbound_ticket(&self) -> Option<[u8; 16]> {
self.outbound_ticket
}
/// Compute the optional recipient stamp without changing the signed body.
/// Runs synchronously until the proof of work is found; a cost Python
/// cannot generate is an error.
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
self.generate_recipient_stamp_with(&crate::stamper::StampControl::default())
}
/// [`Self::generate_recipient_stamp`], stopped by `ctl`'s cancel flag or deadline.
pub fn generate_recipient_stamp_with(
&self,
ctl: &crate::stamper::StampControl,
) -> Result<Option<RecipientStamp>, MessageError> {
if let Some(ticket) = self.outbound_ticket {
let mut material = [0u8; 48];
material[..16].copy_from_slice(&ticket);
material[16..].copy_from_slice(&self.message_id());
return Ok(Some(RecipientStamp::Ticket(truncated_hash(&material))));
}
let Some(cost) = self.stamp_cost else {
return Ok(None);
};
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS, ctl)
.map_err(packed)?
.map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp)))
.ok_or_else(|| packed("recipient stamp generation stopped"))
}
pub fn finalize(self, stamp: Option<RecipientStamp>) -> Result<LxMessage, MessageError> {
self.try_finalize(stamp).map_err(|failed| failed.0)
}
/// [`Self::finalize`], returning the unstamped message with the error so
/// the caller can still fail it.
pub fn try_finalize(
self,
stamp: Option<RecipientStamp>,
) -> Result<LxMessage, Box<(MessageError, LxMessage)>> {
let Some(stamp) = stamp else {
return Ok(self.message);
};
match Self::stamped(&self.message, &stamp) {
Ok(message) => Ok(message),
Err(error) => Err(Box::new((error, self.message))),
}
}
fn stamped(message: &LxMessage, stamp: &RecipientStamp) -> Result<LxMessage, MessageError> {
let size = message
.wire
.len()
.checked_add(2 + stamp.as_bytes().len())
.ok_or_else(|| packed("length overflow"))?;
message.limits.check_wire(size)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&message.wire);
wire[96] = 0x95;
write_bin(&mut wire, stamp.as_bytes())?;
let mut stamped = LxMessage::unpack_owned(wire.into(), message.limits)?;
debug_assert_eq!(stamped.message_id, message.message_id);
stamped.metadata = message.metadata.clone();
Ok(stamped)
}
}
fn packed(error: impl std::fmt::Display) -> MessageError {
MessageError::PackFailed(error.to_string())
}
fn length(value: usize) -> Result<u32, MessageError> {
u32::try_from(value).map_err(packed)
}
fn write_bin<W: Write>(out: &mut W, bytes: &[u8]) -> Result<(), MessageError> {
rmp::encode::write_bin_len(out, length(bytes.len())?).map_err(packed)?;
out.write_all(bytes).map_err(packed)
}
+356
View File
@@ -0,0 +1,356 @@
//! Full-width LXMF field keys and coherent binary/structured values.
use super::{MessageError, read_msgpack_binary, skip_msgpack_value};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::{fmt, ops::Range};
/// A MessagePack integer field key, preserving the complete signed/unsigned domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FieldId(i128);
impl FieldId {
pub const fn as_i128(self) -> i128 {
self.0
}
pub fn as_standard(self) -> Option<u8> {
u8::try_from(self.0).ok()
}
}
macro_rules! field_from { ($($t:ty),*) => { $(impl From<$t> for FieldId { fn from(v:$t)->Self { Self(i128::from(v)) } })* }; }
field_from!(u8, u16, u32, u64, i8, i16, i32, i64);
impl TryFrom<i128> for FieldId {
type Error = MessageError;
fn try_from(v: i128) -> Result<Self, Self::Error> {
if v < i128::from(i64::MIN) || v > i128::from(u64::MAX) {
return Err(MessageError::InvalidFieldId);
}
Ok(Self(v))
}
}
impl Serialize for FieldId {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if self.0 >= 0 {
s.serialize_u64(u64::try_from(self.0).map_err(serde::ser::Error::custom)?)
} else {
s.serialize_i64(i64::try_from(self.0).map_err(serde::ser::Error::custom)?)
}
}
}
impl<'de> Deserialize<'de> for FieldId {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = FieldId;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a signed or unsigned 64-bit integer")
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<FieldId, E> {
FieldId::try_from(v).map_err(E::custom)
}
fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<FieldId, E> {
u64::try_from(v).map(FieldId::from).map_err(E::custom)
}
}
d.deserialize_any(V)
}
}
/// One structurally valid encoded MessagePack value. Storage cannot be mutated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedFieldValue(Bytes);
impl EncodedFieldValue {
pub fn new(bytes: Bytes) -> Result<Self, MessageError> {
let mut remaining = bytes.as_ref();
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self(bytes))
}
/// The value as Python LXMF decodes and re-encodes it; fails where
/// Python's decoder fails (duplicate or unhashable map keys, invalid UTF-8).
pub fn canonical(bytes: Bytes) -> Result<Self, MessageError> {
let canonical = super::canonical::canonicalize(&bytes)?;
if canonical == bytes.as_ref() {
return Ok(Self(bytes));
}
Ok(Self(canonical.into()))
}
pub fn encoded(&self) -> &[u8] {
&self.0
}
/// For this crate's encoders, whose output is canonical by construction.
pub(crate) fn trusted(bytes: Bytes) -> Self {
Self(bytes)
}
pub(crate) fn into_bytes(self) -> Bytes {
self.0
}
}
/// A binary byte string or a native structured MessagePack value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldValue {
Binary(Bytes),
MessagePack(EncodedFieldValue),
}
impl Serialize for FieldValue {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Self::Binary(b) => s.serialize_bytes(b),
Self::MessagePack(v) => {
let value = rmpv::decode::read_value(&mut v.encoded())
.map_err(serde::ser::Error::custom)?;
value.serialize(s)
}
}
}
}
impl<'de> Deserialize<'de> for FieldValue {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let value = rmpv::Value::deserialize(d)?;
if let rmpv::Value::Binary(b) = value {
return Ok(Self::Binary(b.into()));
}
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?;
EncodedFieldValue::canonical(bytes.into())
.map(Self::MessagePack)
.map_err(serde::de::Error::custom)
}
}
/// Borrowed exact encoded field value. Binary is never inferred to be structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldValueRef<'a> {
pub(super) encoded: &'a [u8],
}
impl<'a> FieldValueRef<'a> {
/// Borrow exactly one structurally valid value without decoding or copying it.
/// Binary payloads are never interpreted implicitly.
pub fn from_encoded(encoded: &'a [u8]) -> Result<Self, MessageError> {
let mut remaining = encoded;
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self { encoded })
}
/// Exact UTF-8 MessagePack text, without accepting a binary value as text.
pub fn as_text(self) -> Option<&'a str> {
if !matches!(self.encoded.first(), Some(0xa0..=0xbf | 0xd9..=0xdb)) {
return None;
}
let mut input = self.encoded;
let bytes = super::read_msgpack_string_or_binary(&mut input).ok()?;
if !input.is_empty() {
return None;
}
std::str::from_utf8(bytes).ok()
}
pub fn encoded(self) -> &'a [u8] {
self.encoded
}
pub fn as_binary(self) -> Option<&'a [u8]> {
let mut value = self.encoded;
let bytes = read_msgpack_binary(&mut value).ok()?;
value.is_empty().then_some(bytes)
}
/// Owned explicit copy, for constructing a new message deliberately.
pub fn to_owned(self) -> FieldValue {
match self.as_binary() {
Some(b) => FieldValue::Binary(Bytes::copy_from_slice(b)),
None => {
FieldValue::MessagePack(EncodedFieldValue(Bytes::copy_from_slice(self.encoded)))
}
}
}
}
#[derive(Debug, Clone)]
pub(super) struct FieldIndex {
pub id: FieldId,
pub range: Range<usize>,
}
const _: () = assert!(std::mem::size_of::<FieldIndex>() <= 32);
/// Numeric-key ordered view; original field wire order stays in the message.
#[derive(Debug, Clone, Copy)]
pub struct Fields<'a> {
pub(super) wire: &'a [u8],
pub(super) indexes: &'a [FieldIndex],
}
impl<'a> Fields<'a> {
pub fn get(self, id: impl Into<FieldId>) -> Option<FieldValueRef<'a>> {
let id = id.into();
self.indexes
.binary_search_by_key(&id, |entry| entry.id)
.ok()
.map(|i| FieldValueRef {
encoded: &self.wire[self.indexes[i].range.clone()],
})
}
pub fn contains(self, id: impl Into<FieldId>) -> bool {
self.get(id).is_some()
}
pub fn len(self) -> usize {
self.indexes.len()
}
pub fn is_empty(self) -> bool {
self.indexes.is_empty()
}
pub fn iter(self) -> impl ExactSizeIterator<Item = (FieldId, FieldValueRef<'a>)> {
self.indexes.iter().map(move |entry| {
(
entry.id,
FieldValueRef {
encoded: &self.wire[entry.range.clone()],
},
)
})
}
}
pub(super) mod map_serde {
use super::*;
use std::collections::BTreeMap;
pub fn serialize<S: serde::Serializer>(
map: &BTreeMap<FieldId, FieldValue>,
s: S,
) -> Result<S::Ok, S::Error> {
map.serialize(s)
}
pub fn deserialize<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<BTreeMap<FieldId, FieldValue>, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = BTreeMap<FieldId, FieldValue>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("unique integer fields")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut access: A,
) -> Result<Self::Value, A::Error> {
let mut map = BTreeMap::new();
while let Some(key) = access.next_key::<FieldId>()? {
if map.len()
>= super::super::MessageDecodeLimits::default().max_top_level_fields
{
return Err(serde::de::Error::custom("too many fields"));
}
if map.contains_key(&key) {
return Err(serde::de::Error::custom("duplicate field ID"));
}
let value = access.next_value()?;
map.insert(key, value);
}
Ok(map)
}
}
d.deserialize_map(V)
}
}
/// Validated schema-map keys. Integer encodings normalize; text is exact UTF-8.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FieldMapKey<'a> {
Integer(FieldId),
Text(&'a str),
}
/// Borrowed map values with a compact sorted key-offset index.
///
/// Intended for recognized reaction/chat/game schemas. Unknown structured fields
/// remain opaque and need not request this semantic validation. The index uses
/// four bytes per entry (at most twice the encoded field size), with no value copies.
#[derive(Debug)]
pub struct UniqueFieldMap<'a> {
encoded: &'a [u8],
offsets: Vec<u32>,
}
impl<'a> FieldValueRef<'a> {
pub fn unique_map(self) -> Result<UniqueFieldMap<'a>, MessageError> {
let mut input = self.encoded;
let count = super::read_msgpack_map_len(&mut input)? as usize;
if count > input.len() / 2 {
return Err(MessageError::UnpackFailed(
"impossible nested map count".into(),
));
}
let mut offsets = Vec::new();
offsets
.try_reserve_exact(count)
.map_err(|_| MessageError::UnpackFailed("nested map index allocation".into()))?;
for _ in 0..count {
offsets.push(
u32::try_from(self.encoded.len() - input.len())
.map_err(|_| MessageError::InvalidFieldId)?,
);
read_map_key(&mut input)?;
skip_msgpack_value(&mut input, 0)?;
}
if !input.is_empty() {
return Err(MessageError::UnpackFailed(
"trailing nested map bytes".into(),
));
}
let key_at = |offset: &u32| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated immutable map key")
};
offsets.sort_unstable_by(|a, b| key_at(a).cmp(&key_at(b)));
if offsets
.windows(2)
.any(|pair| key_at(&pair[0]) == key_at(&pair[1]))
{
return Err(MessageError::DuplicateField);
}
Ok(UniqueFieldMap {
encoded: self.encoded,
offsets,
})
}
}
impl<'a> UniqueFieldMap<'a> {
pub fn len(&self) -> usize {
self.offsets.len()
}
pub fn is_empty(&self) -> bool {
self.offsets.is_empty()
}
pub fn get(&self, key: FieldMapKey<'_>) -> Option<FieldValueRef<'a>> {
let index = self
.offsets
.binary_search_by(|offset| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated map key")
.cmp(&key)
})
.ok()?;
let mut input = &self.encoded[self.offsets[index] as usize..];
read_map_key(&mut input).ok()?;
let value = input;
skip_msgpack_value(&mut input, 0).ok()?;
Some(FieldValueRef {
encoded: &value[..value.len() - input.len()],
})
}
}
fn read_map_key<'a>(input: &mut &'a [u8]) -> Result<FieldMapKey<'a>, MessageError> {
if input
.first()
.is_some_and(|marker| matches!(*marker,0xa0..=0xbf|0xd9..=0xdb))
{
let text = super::read_msgpack_string_or_binary(input)?;
Ok(FieldMapKey::Text(std::str::from_utf8(text).map_err(
|_| MessageError::UnpackFailed("map key is not UTF-8".into()),
)?))
} else {
Ok(FieldMapKey::Integer(FieldId::try_from(
super::read_msgpack_integer(input)?,
)?))
}
}
@@ -0,0 +1,16 @@
# Expected outputs of upstream's decode step in LXMRouter.ingest_lxm_uri@1.3.0:
# base64.urlsafe_b64decode(uri.replace("lxm://","").replace("/","")+"==")
import base64, json, random, sys
import RNS, LXMF
assert RNS.__version__ == "1.6.0" and LXMF.__version__ == "1.3.0"
random.seed(1517)
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+/= .:!\n"
cases = ["", "QUJD", "QUI", "QU", "Q", "QUJD=QUJD", "QU=JD", "=QUJD", "QUJD==", "Q+-_", "QU JD", "QUJD====", "Q=U=J=D"]
for _ in range(400):
cases.append("".join(random.choice(alpha) for _ in range(random.randint(0, 14))))
# One line per case: hex(input) TAB hex(decoded) or "error".
with open(sys.argv[1], "w") as f:
for c in cases:
try: r = base64.urlsafe_b64decode(c + "==").hex()
except Exception: r = "error"
f.write(c.encode().hex() + "\t" + r + "\n")
@@ -0,0 +1 @@
/�äxîÒÝfPpVJך�*uÁ”qPp÷_I#D‰H®8
@@ -0,0 +1,413 @@
51554a44 414243
515549 4142
5155 41
51 error
51554a443d51554a44 414243414243
51553d4a44 414243
3d51554a44 414243
51554a443d3d 414243
512b2d5f 43efbf
5155204a44 414243
51554a443d3d3d3d 414243
513d553d4a3d44 414243
2d436e590a45 error
517662595f4249632d3145495a44 42f6d8fc121cfb510864
42694d472b6c463a 062306fa51
6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
2d error
7620506247426135733d58597764 bcf6c605ae6c5d8c1d
30426974344a68763574203d41 d018ade0986fe6d0
5931455f324b5f2038736a3d 63513fd8affcb2
78653053 c5ed12
78456466743a68 c4475fb6
576e4f482d635f52616873443d77 error
34704f77746d4873316b2e3939 e293b0b661ecd64f7d
3657393d213a e96f
3d4469366e7142622167616230 0e2ea7a816e069bd
79737352 cacb11
734673 b05b
356f43 e680
736665 b1f7
5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
53484b 4872
63 error
424b 04
75685f48695155354f36704431 error
713468526c6c ab885196
2e6d3d49593452547358376f6867 988638453b17ee8860
2f2047312b2f78613355 error
4c42 2c
392e41426a450a333a f4006313
655374574a5776745f error
205635452b356a2f44 57913ee63fc3
4d536b664c2b6753 31291f2fe812
71554c5a765a7449 a942d9bd9b48
31586946722e4c46725968395f d57885acb16b621f7f
4e6d6b662135 error
4244 04
31536f43796f d52a02ca
735065433754 b0f782ed
2e615f33326635696d3162 6bfdf67f98a6d5
2f5f49362e586c664e546a42 fff23a5e57cd4e30
7441454c61426144 b4010b681683
3d484f6b 1ce9
50724f2f51536c39585962214651 error
683669545a316a59 87a8936758d8
62 error
4159512e4a5a64 01840965
6f3821595a794f6b792b33394731 error
6c2e4777763a 946c2f
69383a77476c544a3d43512f20 8bcc0695324243
4169 02
485a6557626441692177325a 1d97966dd022c366
4e35697578642d526465634a78 error
3146752f393965 d45bbff7d7
394321356378 error
57575632 596576
72592d4b4a303470673a38 ad8f8a274e2983
4b6775457758776751525a754e error
58437a50623643316438 5c2ccf6fa0b577
64380a20320a3859644e6a 77cdbc61d363
0a7777706b2d error
384c65426a7334692f555345 f0b7818ece22fd4484
3a65 error
6e3a7035727863712b4d6874666d error
78784f32627455386c error
6f error
7076794b55513a494471 error
2e0a476d344f4b3a630a4a7239 error
6a error
653163627068680a2f435474 7b571ba6187f093b
52787467454c77553a 471b6010bc14
6f694130737a4d3164 error
426a4c6f45635f79 0632e811cff2
514a4b63336b 40929cde
2b6e fa
7321506547217030746a b0f786a74b63
796564494d47504334316567 c9e7483063c2e357a0
76 error
20786374453379674a473048 c5cb44df28091b41
35714c7743 error
59794620756947 63216e88
784f2162 c4e6
213d4545 10
327a5453310a4b db34d2d4
50534b395071424f6a56213659 3d22bd3ea04e8d5e98
48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
45666c7471685a2f7375 11f96daa167fb2
76 error
73 error
7331714c34577a2d b35a8be16cfe
5353425a6c6453 49205995d4
2e4764663a3a35 19d7f9
4a2f51762d37334a3521 error
2d49 f8
4c4b6575 2ca7ae
743848485277 b7c1c747
6d69546d6f38312e6d7a error
6675617876364769577471 7ee6b1bfa1a25ada
205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
38652e706137715437777a f1ea5aeea4fbc3
48562d6a20714445 1d5fa3a831
6947 88
4462526121 0db45a
56464c39586475396d error
2b757953683638722148213858 faec9287af2b1fc5
7a64356b4a306e cdde642749
3d6d7a 9b
32205632634a31746f70 error
6e37684a52 error
5a0a6b 66
56722f582e2030485f48536775 56bfd7d07fc74a0b
6d64363368516b75 99deb785092e
7a error
786d5f4351 error
6133 6b
4156 01
3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
677945667865526c36632f386c2d 83211fc5e465e9cffc97
383051775a3a764e6d67500a4475 f3443066f36680f0ee
676c5277564269725851 8254705418ab5d
473d68376f54 error
3a382d4431576f6d3d684f error
415021 00
21532e3331460a 4b7d45
782e642e63513754514c4a4563 c5d710ed340b2447
385a6e21307821 error
7864686958 error
62374457 6fb0d6
704666694835 a457e21f
2152576f322b error
566d306b473d69576b3d51554e 566d241a25a44143
6258304634336a654a2d516774 error
52 error
736346346b6343493961 b1c17891c088f5
3a4143202b46333d43 002f85dc
346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
3a206a582b2e4f356b6d 8d7f8ee649
5336652b5051574354466367 4ba7be3d05824c5720
74626d2e733d513058 b5b9ac4345
55422173784f456b206231583448 501b3138491bd57e07
5a4b314252364d620a216e2e6659 64ad4147a31b9df6
58646b3a464953366c 5dd905212ea5
7566656c302b32 b9f7a5d3ed
774b c0
59304471 6340ea
5a error
5357357472736c205a2e6b54 496e6daec95991
470a error
7271 ae
2033795268393668 df2461f7a8
733453640a74696b2b7a3d723161 b3849db6293ecebd5a
5739 5b
6c2e713359544f6775 96add84ce82e
533843612d error
53742f2b6872516161657055 4adffe86b41a69ea54
5a48312b4e6c426f206e696652 647d7e3650689e27d1
3a4a error
34447950 e03c8f
772b535a76486f4350743a3141 c3e499bc7a023edd40
52 error
77414f c003
794d53787a426750687552434b64 c8c4b1cc180f86e44229
4d6b2f37496b 324ffb22
2b3131793132203334 fb5d72d76df8
75214852683a2f470a5463 b87461fc64dc
6735526b 839464
6e error
484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
6771537969742f3964303756542e error
46745a5f75563a65 16d67fb957
50 error
313549 d792
6e4b79364955664a 9cacba2147c9
572f31785521 error
33513031537a55354856707773 error
4334452b5663662d4e5a4a5a 0b813e55c7fe359259
36727a eabc
696c4d526b4a4433792d533d59 8a53119090f7cbe498
7653416e56 error
0a7978692b cb18be
6f796e35473149315635 a329f91b523557
4435532d3a6c5f5255725042 0f94be97f454acf0
5f39 ff
6f747331674d674c3932 a2db3580c80bf7
5f66562b74393672483064 fdf57eb7deab1f47
30363d6950 d3a88f
35505934446643650a e4f6380df09e
4b6d372f34546358 2a6effe13717
2f3277 ff6c
217021454c544b5276723a50 error
69357a6664774b4d 8b9cdf77028c
5a58 65
53663671616f2149 49feaa6a82
4c205175300a6c77346b7665 2d0bb4970e24bd
735137543a59552164376c7556 b10ed361477b96e5
703744 a7b0
614579595547785a63764c 684c98506c5972f2
3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
5855 5d
50514f2b5a58 3d03be65
623242 6f60
46316947526d414a4a47355a65 error
3877444c56576b440a4a error
4f4f456f 38e128
4c586e734746425a5521 error
535959 4986
2b764e0a5249660a58 faf35121f5
3630543936 error
6672473d55 7eb194
41686a5372213879682d79384f63 error
5667422d667131750a44 error
705744534d702b a560d2329f
687577 86ec
2164386f2e696b584f725348 77ca229173ab48
65326e75756b2f6b7849 7b69eeba4fe4c4
6c657374 95eb2d
3a744f b4
375267 ed18
6f4c214668 a0b161
795278456b2d5f69 c91c4493efe2
3d372e error
6a397434516530673239 8fdb7841ed20db
38206b44372034576a46 f240fbe168c5
3554393a55433231412d3770 e53f540b6d40fbba
3a6b46 90
6c63 95
4e48496758366d715a53597659 error
21566556 55e5
495442684a3d747a 21306126dc
0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
734d3d62414a2b4534723a7949 b0c6c027e138af22
6b66534c655759445220535f 91f48b796603452f
4d6a4659795277424943 323158c91c0120
46433a662e4943 error
2d614e713864 f9a36af1
7a4277713777454c4f4a cc1c2aef010b38
4730 1b
66744a412d517347446c3462 7ed240f90b060e5e1b
77 error
6621 error
6f643a4e4f7366 a1d34eb1
50374b73756e495537374a347631 3fb2acba7214efb278bf
32720a da
534137334d642f4e44516f61 480ef731dfcd0d0a1a
636664734a0a4a38656b4f2b354a error
4449706d 0c8a66
705a2b345248204671517a322b63 error
6e305220427a787a 9f4441cf1c
6170363a587774334b34783074 6a9e97c2ddcae31d2d
4376317a34 error
79 error
2d640a49593669596b f9d218ea2624
6968446b0a344447595841317766 error
754221467743552e2b b81170094f
65434d37 78233b
6379354a2b696b41455f453337 error
2e363a740a346432 error
4a error
445075 0cfb
6b694247 922046
4b656b397370520a31456f6651 29e93db294751287d0
6e7165375461645750564c3274 error
5f77437a2b78542145312e6f57 ff00b3fb14c4d685
43652b7121 09efaa
436e3569547056 0a7e624e95
342b2f736e70646f0a765744554b error
692b6b306b743731 8be93492def5
50647478715f68322166 error
333953375258 dfd4bb45
70576474342b3730590a error
37 error
35 error
312078336f2f4d5144657978 d71de8fcc4037b2c
5a484c504d366a384b346c483a 6472cf33a8fc2b8947
2d563d2d616c352f6977 error
5f4375434579 fc2b8213
75753951644176 baef50740b
7430 b7
33476857 dc6856
2d6b706355633443634f fa4a5c51ce0270
544237215f703d516776745253 4c1effa5082fb514
51764e6b46 error
6236624c 6fa6cb
7678 bf
4a2b4f5554 error
4a6d 26
4a66394f304668763a79304f3658 error
313645 d7a1
66707944706942 7e9c83a620
3452532f532f3454 e114bf4bfe13
754d627951382b50 b8c6f243cf8f
4e7650424c52 36f3c12d
742d5f214453675544 b7efc34a0503
50547932625572 3d3cb66d4a
71586e34 a979f8
49456b514f36214a2f465a577547 error
722f af
5248 44
324a3079596b d89d3262
314f6d79666a487973622171 d4e9b27e31f2b1ba
2b375332445f77 fbb4b60ffc
385f30 f3fd
2177574e7266652b622b error
6c2f682d316a2e776f79 error
2e6f4837746b error
3059 d1
5a7739343561626b4f3330 670f78e5a6e43b7d
536e4479 4a70f2
716249 a9b2
2b46345a4a34 f85e1927
33384f57 dfc396
5a58636430 error
496e20765f484876644c5847 227bff1c7bdd2d71
732f747147547a2e b3fb6a193c
307173585320662f436c6945 d2ab1749ffc29621
57656745376f72 59e804ee8a
554f526843335954 50e4610b7613
6e38 9f
6c5a79506c644a6473426e52 959c8f95d25db019d1
2e
4f5973466f78744c337648 398b05a31b4bdef1
77683537524b7355216d354c c21e7b44ab149b92
4d552e4f3637774d6138 error
5275507154573053323d4566 46e3ea4d6d12d847
4850 1c
4d6f33 328d
3a36713a4f662d3162 eaa39ffb56
576d303949634155 5a6d3d21c014
6c4937493d 948ec8
7720394c5a62 error
6b72574455797a622d error
7139574854365343 abd5874fa482
2f304b7055 error
0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
6777343769 error
506b756b6a error
6c7877466b455869552f63552b35 971c059045e253f714fb
55677457692b435a5a54 520b568be09965
30 error
364e72206a32552031 e8dae3d94d
3449203463542e724d750a6d73 e08e1c4eb32e9a
4f21736c6d464544354978 3ac9661440f923
2f397464695230 ffdb5d891d
5f3a error
46 error
5159794c535f5774342f 418c8b4bf5ade3
2b416e7a3957763d463731 f809f3f56bc5ef
76484b585562 bc729751
57 error
617741655a3861396b670a42 6b001e67c6bd9200
3047475f5533656531456e56 d061bf53779ed449d5
4c745a 2ed6
39 error
457579626f7a6a4d 12ec9ba338cc
4b2d5f 2bef
55537a676f68614a4a692d21 512ce0a21689262f
493d3979380a72686e 23dcbcae19
584779596d2d4b484b57693036 error
416668575334 01f8564b
2e6a756e2147 8ee9c6
6b47424d212d594b7a67697a 90604cf982b3822c
397771554b6163 f70a9429a7
4836213a 1f
44474d575a error
7653780a44592f79 bd2c4363fc
50786c6834422d3a6d56503442 3f1961e01fa654fe01
56214b782b686c4951797a2d 54ac7e865210cb3f
53336130596d704c43 error
30 error
2b error
7774 c2
515651762e693a7a2074 41542f8b3b
7049673a7a71724d36756c4f a48833aab33aba53
1
2 51554a44 414243
3 515549 4142
4 5155 41
5 51 error
6 51554a443d51554a44 414243414243
7 51553d4a44 414243
8 3d51554a44 414243
9 51554a443d3d 414243
10 512b2d5f 43efbf
11 5155204a44 414243
12 51554a443d3d3d3d 414243
13 513d553d4a3d44 414243
14 2d436e590a45 error
15 517662595f4249632d3145495a44 42f6d8fc121cfb510864
16 42694d472b6c463a 062306fa51
17 6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
18 2d error
19 7620506247426135733d58597764 bcf6c605ae6c5d8c1d
20
21 30426974344a68763574203d41 d018ade0986fe6d0
22 5931455f324b5f2038736a3d 63513fd8affcb2
23 78653053 c5ed12
24 78456466743a68 c4475fb6
25 576e4f482d635f52616873443d77 error
26 34704f77746d4873316b2e3939 e293b0b661ecd64f7d
27 3657393d213a e96f
28 3d4469366e7142622167616230 0e2ea7a816e069bd
29 79737352 cacb11
30 734673 b05b
31 356f43 e680
32 736665 b1f7
33 5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
34 53484b 4872
35
36 63 error
37 424b 04
38 75685f48695155354f36704431 error
39 713468526c6c ab885196
40 2e6d3d49593452547358376f6867 988638453b17ee8860
41 2f2047312b2f78613355 error
42 4c42 2c
43 392e41426a450a333a f4006313
44
45 655374574a5776745f error
46 205635452b356a2f44 57913ee63fc3
47 4d536b664c2b6753 31291f2fe812
48 71554c5a765a7449 a942d9bd9b48
49 31586946722e4c46725968395f d57885acb16b621f7f
50 4e6d6b662135 error
51 4244 04
52
53 31536f43796f d52a02ca
54 735065433754 b0f782ed
55 2e615f33326635696d3162 6bfdf67f98a6d5
56 2f5f49362e586c664e546a42 fff23a5e57cd4e30
57 7441454c61426144 b4010b681683
58
59 3d484f6b 1ce9
60
61 50724f2f51536c39585962214651 error
62 683669545a316a59 87a8936758d8
63 62 error
64 4159512e4a5a64 01840965
65 6f3821595a794f6b792b33394731 error
66 6c2e4777763a 946c2f
67 69383a77476c544a3d43512f20 8bcc0695324243
68 4169 02
69 485a6557626441692177325a 1d97966dd022c366
70 4e35697578642d526465634a78 error
71 3146752f393965 d45bbff7d7
72 394321356378 error
73 57575632 596576
74 72592d4b4a303470673a38 ad8f8a274e2983
75 4b6775457758776751525a754e error
76 58437a50623643316438 5c2ccf6fa0b577
77 64380a20320a3859644e6a 77cdbc61d363
78 0a7777706b2d error
79 384c65426a7334692f555345 f0b7818ece22fd4484
80
81 3a65 error
82 6e3a7035727863712b4d6874666d error
83 78784f32627455386c error
84 6f error
85 7076794b55513a494471 error
86 2e0a476d344f4b3a630a4a7239 error
87 6a error
88 653163627068680a2f435474 7b571ba6187f093b
89 52787467454c77553a 471b6010bc14
90 6f694130737a4d3164 error
91 426a4c6f45635f79 0632e811cff2
92 514a4b63336b 40929cde
93 2b6e fa
94 7321506547217030746a b0f786a74b63
95 796564494d47504334316567 c9e7483063c2e357a0
96 76 error
97 20786374453379674a473048 c5cb44df28091b41
98 35714c7743 error
99 59794620756947 63216e88
100 784f2162 c4e6
101 213d4545 10
102 327a5453310a4b db34d2d4
103 50534b395071424f6a56213659 3d22bd3ea04e8d5e98
104 48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
105 45666c7471685a2f7375 11f96daa167fb2
106 76 error
107 73 error
108 7331714c34577a2d b35a8be16cfe
109 5353425a6c6453 49205995d4
110 2e4764663a3a35 19d7f9
111 4a2f51762d37334a3521 error
112 2d49 f8
113 4c4b6575 2ca7ae
114 743848485277 b7c1c747
115 6d69546d6f38312e6d7a error
116 6675617876364769577471 7ee6b1bfa1a25ada
117 205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
118 38652e706137715437777a f1ea5aeea4fbc3
119 48562d6a20714445 1d5fa3a831
120 6947 88
121
122
123 4462526121 0db45a
124
125
126 56464c39586475396d error
127
128 2b757953683638722148213858 faec9287af2b1fc5
129 7a64356b4a306e cdde642749
130 3d6d7a 9b
131 32205632634a31746f70 error
132 6e37684a52 error
133 5a0a6b 66
134 56722f582e2030485f48536775 56bfd7d07fc74a0b
135 6d64363368516b75 99deb785092e
136 7a error
137 786d5f4351 error
138 6133 6b
139 4156 01
140 3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
141 677945667865526c36632f386c2d 83211fc5e465e9cffc97
142 383051775a3a764e6d67500a4475 f3443066f36680f0ee
143 676c5277564269725851 8254705418ab5d
144 473d68376f54 error
145 3a382d4431576f6d3d684f error
146
147 415021 00
148 21532e3331460a 4b7d45
149 782e642e63513754514c4a4563 c5d710ed340b2447
150 385a6e21307821 error
151 7864686958 error
152 62374457 6fb0d6
153 704666694835 a457e21f
154 2152576f322b error
155 566d306b473d69576b3d51554e 566d241a25a44143
156 6258304634336a654a2d516774 error
157 52 error
158 736346346b6343493961 b1c17891c088f5
159 3a4143202b46333d43 002f85dc
160 346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
161 3a206a582b2e4f356b6d 8d7f8ee649
162 5336652b5051574354466367 4ba7be3d05824c5720
163 74626d2e733d513058 b5b9ac4345
164 55422173784f456b206231583448 501b3138491bd57e07
165 5a4b314252364d620a216e2e6659 64ad4147a31b9df6
166 58646b3a464953366c 5dd905212ea5
167 7566656c302b32 b9f7a5d3ed
168 774b c0
169
170 59304471 6340ea
171 5a error
172 5357357472736c205a2e6b54 496e6daec95991
173 470a error
174 7271 ae
175 2033795268393668 df2461f7a8
176 733453640a74696b2b7a3d723161 b3849db6293ecebd5a
177 5739 5b
178 6c2e713359544f6775 96add84ce82e
179 533843612d error
180 53742f2b6872516161657055 4adffe86b41a69ea54
181 5a48312b4e6c426f206e696652 647d7e3650689e27d1
182
183
184 3a4a error
185 34447950 e03c8f
186
187 772b535a76486f4350743a3141 c3e499bc7a023edd40
188 52 error
189
190 77414f c003
191 794d53787a426750687552434b64 c8c4b1cc180f86e44229
192 4d6b2f37496b 324ffb22
193 2b3131793132203334 fb5d72d76df8
194 75214852683a2f470a5463 b87461fc64dc
195 6735526b 839464
196 6e error
197
198 484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
199 6771537969742f3964303756542e error
200 46745a5f75563a65 16d67fb957
201 50 error
202 313549 d792
203 6e4b79364955664a 9cacba2147c9
204 572f31785521 error
205 33513031537a55354856707773 error
206 4334452b5663662d4e5a4a5a 0b813e55c7fe359259
207 36727a eabc
208 696c4d526b4a4433792d533d59 8a53119090f7cbe498
209 7653416e56 error
210 0a7978692b cb18be
211 6f796e35473149315635 a329f91b523557
212
213 4435532d3a6c5f5255725042 0f94be97f454acf0
214 5f39 ff
215 6f747331674d674c3932 a2db3580c80bf7
216 5f66562b74393672483064 fdf57eb7deab1f47
217 30363d6950 d3a88f
218 35505934446643650a e4f6380df09e
219 4b6d372f34546358 2a6effe13717
220 2f3277 ff6c
221 217021454c544b5276723a50 error
222 69357a6664774b4d 8b9cdf77028c
223 5a58 65
224 53663671616f2149 49feaa6a82
225 4c205175300a6c77346b7665 2d0bb4970e24bd
226 735137543a59552164376c7556 b10ed361477b96e5
227 703744 a7b0
228 614579595547785a63764c 684c98506c5972f2
229 3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
230 5855 5d
231 50514f2b5a58 3d03be65
232 623242 6f60
233 46316947526d414a4a47355a65 error
234 3877444c56576b440a4a error
235 4f4f456f 38e128
236 4c586e734746425a5521 error
237 535959 4986
238 2b764e0a5249660a58 faf35121f5
239 3630543936 error
240 6672473d55 7eb194
241 41686a5372213879682d79384f63 error
242 5667422d667131750a44 error
243 705744534d702b a560d2329f
244 687577 86ec
245 2164386f2e696b584f725348 77ca229173ab48
246 65326e75756b2f6b7849 7b69eeba4fe4c4
247 6c657374 95eb2d
248 3a744f b4
249 375267 ed18
250 6f4c214668 a0b161
251 795278456b2d5f69 c91c4493efe2
252 3d372e error
253
254 6a397434516530673239 8fdb7841ed20db
255 38206b44372034576a46 f240fbe168c5
256 3554393a55433231412d3770 e53f540b6d40fbba
257 3a6b46 90
258 6c63 95
259 4e48496758366d715a53597659 error
260 21566556 55e5
261 495442684a3d747a 21306126dc
262 0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
263 734d3d62414a2b4534723a7949 b0c6c027e138af22
264 6b66534c655759445220535f 91f48b796603452f
265 4d6a4659795277424943 323158c91c0120
266 46433a662e4943 error
267 2d614e713864 f9a36af1
268 7a4277713777454c4f4a cc1c2aef010b38
269 4730 1b
270 66744a412d517347446c3462 7ed240f90b060e5e1b
271 77 error
272 6621 error
273 6f643a4e4f7366 a1d34eb1
274 50374b73756e495537374a347631 3fb2acba7214efb278bf
275 32720a da
276 534137334d642f4e44516f61 480ef731dfcd0d0a1a
277 636664734a0a4a38656b4f2b354a error
278 4449706d 0c8a66
279 705a2b345248204671517a322b63 error
280 6e305220427a787a 9f4441cf1c
281 6170363a587774334b34783074 6a9e97c2ddcae31d2d
282 4376317a34 error
283 79 error
284 2d640a49593669596b f9d218ea2624
285 6968446b0a344447595841317766 error
286 754221467743552e2b b81170094f
287 65434d37 78233b
288 6379354a2b696b41455f453337 error
289 2e363a740a346432 error
290 4a error
291 445075 0cfb
292 6b694247 922046
293 4b656b397370520a31456f6651 29e93db294751287d0
294 6e7165375461645750564c3274 error
295 5f77437a2b78542145312e6f57 ff00b3fb14c4d685
296 43652b7121 09efaa
297 436e3569547056 0a7e624e95
298 342b2f736e70646f0a765744554b error
299 692b6b306b743731 8be93492def5
300 50647478715f68322166 error
301 333953375258 dfd4bb45
302 70576474342b3730590a error
303 37 error
304 35 error
305 312078336f2f4d5144657978 d71de8fcc4037b2c
306 5a484c504d366a384b346c483a 6472cf33a8fc2b8947
307 2d563d2d616c352f6977 error
308 5f4375434579 fc2b8213
309 75753951644176 baef50740b
310 7430 b7
311 33476857 dc6856
312 2d6b706355633443634f fa4a5c51ce0270
313 544237215f703d516776745253 4c1effa5082fb514
314 51764e6b46 error
315 6236624c 6fa6cb
316 7678 bf
317 4a2b4f5554 error
318 4a6d 26
319 4a66394f304668763a79304f3658 error
320 313645 d7a1
321 66707944706942 7e9c83a620
322 3452532f532f3454 e114bf4bfe13
323 754d627951382b50 b8c6f243cf8f
324 4e7650424c52 36f3c12d
325 742d5f214453675544 b7efc34a0503
326 50547932625572 3d3cb66d4a
327
328 71586e34 a979f8
329 49456b514f36214a2f465a577547 error
330 722f af
331 5248 44
332 324a3079596b d89d3262
333 314f6d79666a487973622171 d4e9b27e31f2b1ba
334 2b375332445f77 fbb4b60ffc
335 385f30 f3fd
336 2177574e7266652b622b error
337 6c2f682d316a2e776f79 error
338 2e6f4837746b error
339 3059 d1
340
341 5a7739343561626b4f3330 670f78e5a6e43b7d
342 536e4479 4a70f2
343 716249 a9b2
344 2b46345a4a34 f85e1927
345
346 33384f57 dfc396
347 5a58636430 error
348 496e20765f484876644c5847 227bff1c7bdd2d71
349 732f747147547a2e b3fb6a193c
350 307173585320662f436c6945 d2ab1749ffc29621
351 57656745376f72 59e804ee8a
352 554f526843335954 50e4610b7613
353 6e38 9f
354
355 6c5a79506c644a6473426e52 959c8f95d25db019d1
356 2e
357 4f5973466f78744c337648 398b05a31b4bdef1
358 77683537524b7355216d354c c21e7b44ab149b92
359 4d552e4f3637774d6138 error
360 5275507154573053323d4566 46e3ea4d6d12d847
361 4850 1c
362 4d6f33 328d
363 3a36713a4f662d3162 eaa39ffb56
364
365 576d303949634155 5a6d3d21c014
366 6c4937493d 948ec8
367 7720394c5a62 error
368 6b72574455797a622d error
369 7139574854365343 abd5874fa482
370 2f304b7055 error
371 0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
372 6777343769 error
373 506b756b6a error
374 6c7877466b455869552f63552b35 971c059045e253f714fb
375 55677457692b435a5a54 520b568be09965
376 30 error
377 364e72206a32552031 e8dae3d94d
378 3449203463542e724d750a6d73 e08e1c4eb32e9a
379 4f21736c6d464544354978 3ac9661440f923
380 2f397464695230 ffdb5d891d
381 5f3a error
382 46 error
383 5159794c535f5774342f 418c8b4bf5ade3
384 2b416e7a3957763d463731 f809f3f56bc5ef
385 76484b585562 bc729751
386 57 error
387 617741655a3861396b670a42 6b001e67c6bd9200
388 3047475f5533656531456e56 d061bf53779ed449d5
389
390 4c745a 2ed6
391 39 error
392 457579626f7a6a4d 12ec9ba338cc
393 4b2d5f 2bef
394 55537a676f68614a4a692d21 512ce0a21689262f
395 493d3979380a72686e 23dcbcae19
396 584779596d2d4b484b57693036 error
397 416668575334 01f8564b
398 2e6a756e2147 8ee9c6
399 6b47424d212d594b7a67697a 90604cf982b3822c
400 397771554b6163 f70a9429a7
401 4836213a 1f
402
403 44474d575a error
404 7653780a44592f79 bd2c4363fc
405 50786c6834422d3a6d56503442 3f1961e01fa654fe01
406
407 56214b782b686c4951797a2d 54ac7e865210cb3f
408 53336130596d704c43 error
409 30 error
410 2b error
411 7774 c2
412 515651762e693a7a2074 41542f8b3b
413 7049673a7a71724d36756c4f a48833aab33aba53
+143
View File
@@ -0,0 +1,143 @@
//! Durable form of a signed message that has not finished delivery.
use super::*;
/// The signed header (destination, source, signature) ends here, and an LXMF
/// payload would begin.
const HEADER_LEN: usize = 96;
/// `0xC1` is never valid MessagePack, so no LXMF parser reads a stored form as
/// a message.
const MAGIC: [u8; 4] = [0xc1, b'L', b'X', b'R'];
const VERSION: u8 = 2;
/// Version 1 stored an integer floor; it is still read.
const VERSION_INTEGER_FLOOR: u8 = 1;
const DIGEST_LEN: usize = 16;
const FLOOR_AT: usize = HEADER_LEN + MAGIC.len() + 1;
const STAMP_AT: usize = FLOOR_AT + 2;
/// A signed, unstamped message stored so delivery can resume after a restart.
///
/// Version 2 holds, in order:
/// - the signed header: destination, source and signature (96 bytes);
/// - the bytes `0xC1`, `L`, `X`, `R`, then the version byte;
/// - the stamp cost the message was signed under, as a big-endian fixed-point
/// cost on the 1/256 grid, 0 meaning none (version 1 held a presence byte
/// and an integer cost);
/// - reserved slots for a finished recipient stamp (a length byte of 0, 16
/// or 32, then the stamp) and a propagation envelope (a big-endian `u32`
/// length, then the envelope). Both are written empty, and a reader of
/// this version ignores filled slots and redoes that work;
/// - the signed payload;
/// - the first 16 bytes of the SHA-256 of everything before them.
///
/// It is not a wire message: [`LxMessage::unpack`] rejects it, because byte
/// 96 is `0xC1`. Restore it with
/// [`LxmRouter::restore_signed`](crate::router::LxmRouter::restore_signed).
#[derive(Clone, PartialEq, Eq)]
pub struct ResumableLxMessage {
bytes: Bytes,
stamp_cost_floor: Option<u16>,
payload_at: usize,
}
impl std::fmt::Debug for ResumableLxMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResumableLxMessage")
.field("len", &self.bytes.len())
.finish_non_exhaustive()
}
}
impl ResumableLxMessage {
pub(super) fn new(wire: &[u8], stamp_cost: Option<f64>) -> Self {
let floor_fp = stamp_cost
.and_then(|cost| crate::stamper::cost_to_fp(cost).ok())
.unwrap_or(0);
let stamp_cost = (floor_fp > 0).then_some(floor_fp);
let mut bytes = Vec::with_capacity(wire.len() + STAMP_AT + 5 + DIGEST_LEN);
bytes.extend_from_slice(&wire[..HEADER_LEN]);
bytes.extend_from_slice(&MAGIC);
bytes.push(VERSION);
bytes.extend_from_slice(&floor_fp.to_be_bytes());
bytes.push(0);
bytes.extend_from_slice(&0u32.to_be_bytes());
let payload_at = bytes.len();
bytes.extend_from_slice(&wire[HEADER_LEN..]);
let digest = sha256(&bytes);
bytes.extend_from_slice(&digest[..DIGEST_LEN]);
Self {
bytes: bytes.into(),
stamp_cost_floor: stamp_cost,
payload_at,
}
}
/// Check a stored form's structure and digest. The signature is checked
/// when the message is restored, against the sender's key.
pub fn from_bytes(bytes: impl Into<Bytes>) -> Result<Self, MessageError> {
let bytes = bytes.into();
let invalid =
|reason: &str| MessageError::UnpackFailed(format!("resumable message: {reason}"));
if bytes.len() < STAMP_AT + 5 + 1 + DIGEST_LEN {
return Err(invalid("too short"));
}
if bytes[HEADER_LEN..HEADER_LEN + MAGIC.len()] != MAGIC {
return Err(invalid("not a stored message"));
}
let version = bytes[HEADER_LEN + MAGIC.len()];
if version != VERSION && version != VERSION_INTEGER_FLOOR {
return Err(invalid("unsupported version"));
}
let digest_at = bytes.len() - DIGEST_LEN;
if sha256(&bytes[..digest_at])[..DIGEST_LEN] != bytes[digest_at..] {
return Err(invalid("damaged"));
}
let floor = [bytes[FLOOR_AT], bytes[FLOOR_AT + 1]];
let stamp_cost_floor = match (version, floor) {
(_, [0, 0]) => None,
(VERSION_INTEGER_FLOOR, [1, cost]) => Some(u16::from(cost.min(100)) * 256),
(VERSION, _) if u16::from_be_bytes(floor) <= crate::stamper::STAMP_COST_CAP_FP => {
Some(u16::from_be_bytes(floor))
}
_ => return Err(invalid("invalid stamp cost")),
};
let stamp_len = usize::from(bytes[STAMP_AT]);
if !matches!(stamp_len, 0 | 16 | 32) {
return Err(invalid("invalid recipient stamp"));
}
let envelope_len_at = STAMP_AT + 1 + stamp_len;
let envelope_len = bytes
.get(envelope_len_at..envelope_len_at + 4)
.map(|len| u32::from_be_bytes(len.try_into().expect("four bytes")) as usize)
.ok_or_else(|| invalid("truncated"))?;
let payload_at = (envelope_len_at + 4)
.checked_add(envelope_len)
.filter(|at| *at < digest_at)
.ok_or_else(|| invalid("truncated"))?;
if bytes[payload_at] != 0x94 {
return Err(invalid("payload is not a signed, unstamped body"));
}
Ok(Self {
bytes,
stamp_cost_floor,
payload_at,
})
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub(crate) fn stamp_cost_floor(&self) -> Option<f64> {
self.stamp_cost_floor
.map(|fp| crate::stamper::cost_from_fp(u32::from(fp)))
}
/// The signed, unstamped message. Its signature is not yet checked.
pub(crate) fn unverified_message(&self) -> Result<LxMessage, MessageError> {
let digest_at = self.bytes.len() - DIGEST_LEN;
let mut wire = Vec::with_capacity(HEADER_LEN + digest_at - self.payload_at);
wire.extend_from_slice(&self.bytes[..HEADER_LEN]);
wire.extend_from_slice(&self.bytes[self.payload_at..digest_at]);
LxMessage::unpack_owned(wire.into(), MessageDecodeLimits::default())
}
}
File diff suppressed because it is too large. Load diff
+305 -194
View File
@@ -14,9 +14,9 @@ type LegacyStoredPeer = (
Vec<u8>,
f64,
u32,
u8,
Option<u8>,
Option<u8>,
f64,
Option<f64>,
Option<f64>,
bool,
bool,
Vec<Vec<u8>>,
@@ -60,19 +60,37 @@ struct StoredPeerV2 {
destination_hash: Vec<u8>,
last_sync: f64,
unreachable_count: u32,
peering_cost: u8,
stamp_cost: Option<u8>,
stamp_cost_flexibility: Option<u8>,
peering_cost: f64,
stamp_cost: Option<f64>,
stamp_cost_flexibility: Option<f64>,
autopeered: bool,
is_static: bool,
handled_ids: Vec<Vec<u8>>,
peering_timebase: f64,
propagation_transfer_limit: Option<f64>,
propagation_sync_limit: Option<f64>,
peering_key: Option<(Vec<u8>, u32)>,
peering_key: Option<(Vec<u8>, f64)>,
metadata: Option<HashMap<u8, Vec<u8>>>,
last_heard: f64,
alive: bool,
#[serde(default)]
link_establishment_rate: f64,
#[serde(default)]
sync_transfer_rate: f64,
#[serde(default)]
last_sync_attempt: f64,
#[serde(default)]
offered: u64,
#[serde(default)]
outgoing: u64,
#[serde(default)]
incoming: u64,
#[serde(default)]
rx_bytes: u64,
#[serde(default)]
tx_bytes: u64,
#[serde(default)]
unhandled_ids: Option<Vec<Vec<u8>>>,
}
/// Immutable inputs for one outbound propagation offer.
@@ -84,18 +102,20 @@ struct StoredPeerV2 {
pub struct OutboundOfferPolicy {
pub peer_hash: [u8; 16],
pub handled_messages: HashSet<PropagationTransientId>,
pub stamp_cost: Option<u8>,
pub stamp_cost_flexibility: Option<u8>,
pub minimum_stamp_cost: u8,
pub peering_cost: u8,
pub stamp_cost: Option<f64>,
pub stamp_cost_flexibility: Option<f64>,
pub minimum_stamp_cost: f64,
pub peering_cost: f64,
pub propagation_transfer_limit: Option<f64>,
pub propagation_sync_limit: Option<f64>,
pub peering_key: Vec<u8>,
pub peering_key_value: Option<u32>,
pub peering_key_value: Option<f64>,
pub peering_timebase: f64,
pub autopeered: bool,
pub is_static: bool,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
/// Messages queued for this peer; `None` offers every live store entry.
pub unhandled_messages: Option<HashSet<PropagationTransientId>>,
}
impl OutboundOfferPolicy {
@@ -109,7 +129,7 @@ impl OutboundOfferPolicy {
handled_messages: HashSet::new(),
stamp_cost: None,
stamp_cost_flexibility: None,
minimum_stamp_cost: 0,
minimum_stamp_cost: 0.0,
peering_cost: PEERING_COST,
propagation_transfer_limit: None,
propagation_sync_limit: None,
@@ -119,6 +139,7 @@ impl OutboundOfferPolicy {
autopeered: false,
is_static: false,
metadata: None,
unhandled_messages: None,
}
}
@@ -156,19 +177,18 @@ pub struct LxmPeer {
pub state: PeerState,
pub sync_strategy: SyncStrategy,
pub last_sync: f64,
unhandled_count: u32,
unhandled_count_cached: bool,
pub unreachable_count: u32,
pub autopeered: bool,
pub stamp_cost: Option<u8>,
pub stamp_cost_flexibility: Option<u8>,
pub stamp_cost: Option<f64>,
pub stamp_cost_flexibility: Option<f64>,
/// Peering cost used for outbound peering-key generation.
pub peering_cost: u8,
/// Generated peering key `(stamp, value)`. `None` until [`LxmPeer::generate_peering_key`] succeeds.
pub peering_key: Option<([u8; 32], u32)>,
/// Per-transfer propagation limit in KB.
pub peering_cost: f64,
/// 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], f64)>,
/// Per-transfer propagation limit in decimal kilobytes (1 kB = 1000 bytes).
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 currently_transferring_messages: Option<Vec<PropagationTransientId>>,
pub link_alive: bool,
@@ -197,6 +217,8 @@ pub struct LxmPeer {
pub is_static: bool,
/// Message hashes already handled by this peer, for sync filtering.
pub handled_messages: HashSet<PropagationTransientId>,
/// Messages distributed to this peer and not yet handled by it.
pub unhandled_messages: HashSet<PropagationTransientId>,
}
impl LxmPeer {
@@ -207,8 +229,6 @@ impl LxmPeer {
state: PeerState::Idle,
sync_strategy: SyncStrategy::default(),
last_sync: 0.0,
unhandled_count: 0,
unhandled_count_cached: false,
unreachable_count: 0,
autopeered: false,
stamp_cost: None,
@@ -220,8 +240,8 @@ impl LxmPeer {
currently_transferring_messages: None,
link_alive: false,
created_at: now,
last_heard: now,
alive: true,
last_heard: 0.0,
alive: false,
peering_timebase: 0.0,
link_establishment_rate: 0.0,
sync_transfer_rate: 0.0,
@@ -237,6 +257,7 @@ impl LxmPeer {
last_offer_generation: 0,
is_static: false,
handled_messages: HashSet::new(),
unhandled_messages: HashSet::new(),
}
}
@@ -250,9 +271,9 @@ impl LxmPeer {
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
stamp_cost: Option<f64>,
stamp_flexibility: Option<f64>,
peering_cost: Option<f64>,
) -> Self {
Self::from_announce_with_metadata(
destination_hash,
@@ -273,9 +294,9 @@ impl LxmPeer {
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
stamp_cost: Option<f64>,
stamp_flexibility: Option<f64>,
peering_cost: Option<f64>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> Self {
let mut peer = Self::new(destination_hash);
@@ -287,22 +308,27 @@ impl LxmPeer {
peer.peering_cost = peering_cost.unwrap_or(PEERING_COST);
peer.metadata = bounded_peer_metadata(metadata);
peer.autopeered = true;
peer.alive = true;
peer.last_heard = now_f64();
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
/// messages and static-peer status remain owned by the existing peer.
/// Returns `true` when updated. Handled messages and static-peer status are
/// 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)]
pub fn refresh_from_announce(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
stamp_cost: Option<f64>,
stamp_flexibility: Option<f64>,
peering_cost: Option<f64>,
) -> bool {
let metadata = self.metadata.clone();
self.refresh_from_announce_with_metadata(
@@ -316,16 +342,18 @@ 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)]
pub fn refresh_from_announce_with_metadata(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
stamp_cost: Option<f64>,
stamp_flexibility: Option<f64>,
peering_cost: Option<f64>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> bool {
if timebase <= self.peering_timebase {
@@ -352,7 +380,7 @@ impl LxmPeer {
// the daemon must generate a replacement before taking a snapshot.
if self
.peering_key
.is_some_and(|(_, value)| value < self.peering_cost as u32)
.is_some_and(|(_, value)| value < self.peering_cost)
{
self.peering_key = None;
}
@@ -364,12 +392,12 @@ impl LxmPeer {
/// Effective minimum stamp cost this peer will accept, using the peer's
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
pub fn minimum_accepted_stamp_cost(&self) -> f64 {
match self.stamp_cost {
Some(cost) => {
cost.saturating_sub(self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX))
(cost - self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX)).max(0.0)
}
None => 0,
None => 0.0,
}
}
@@ -382,18 +410,19 @@ impl LxmPeer {
OutboundOfferPolicy::from(self)
}
pub fn add_unhandled_message(&mut self) {
self.unhandled_count_cached = false;
self.unhandled_count += 1;
/// Queue a message for this peer unless it already handled it.
pub fn add_unhandled_message(&mut self, hash: &PropagationTransientId) {
if !self.handled_messages.contains(hash) {
self.unhandled_messages.insert(*hash);
}
}
pub fn unhandled_messages(&self) -> u32 {
self.unhandled_count
pub fn remove_unhandled_message(&mut self, hash: &PropagationTransientId) {
self.unhandled_messages.remove(hash);
}
pub fn set_unhandled_count(&mut self, count: u32) {
self.unhandled_count = count;
self.unhandled_count_cached = true;
pub fn unhandled_message_count(&self) -> usize {
self.unhandled_messages.len()
}
pub fn heard(&mut self) {
@@ -405,6 +434,7 @@ impl LxmPeer {
pub fn add_handled_message(&mut self, hash: &PropagationTransientId) {
self.handled_messages.insert(*hash);
self.unhandled_messages.remove(hash);
}
pub fn has_handled(&self, hash: &PropagationTransientId) -> bool {
@@ -423,6 +453,9 @@ impl LxmPeer {
pub fn to_bytes_with_handled(&self) -> Vec<u8> {
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
handled.sort();
let mut unhandled: Vec<Vec<u8>> =
self.unhandled_messages.iter().map(|h| h.to_vec()).collect();
unhandled.sort();
let data = StoredPeerV2 {
version: STORED_PEER_VERSION,
destination_hash: self.destination_hash.to_vec(),
@@ -443,6 +476,15 @@ impl LxmPeer {
metadata: self.metadata.clone(),
last_heard: self.last_heard,
alive: self.alive,
link_establishment_rate: self.link_establishment_rate,
sync_transfer_rate: self.sync_transfer_rate,
last_sync_attempt: self.last_sync_attempt,
offered: self.offered,
outgoing: self.outgoing,
incoming: self.incoming,
rx_bytes: self.rx_bytes,
tx_bytes: self.tx_bytes,
unhandled_ids: Some(unhandled),
};
rmp_serde::to_vec_named(&data).unwrap_or_default()
}
@@ -451,8 +493,15 @@ impl LxmPeer {
///
/// [`to_bytes_with_handled`]: Self::to_bytes_with_handled
pub fn from_bytes_with_handled(data: &[u8]) -> Option<Self> {
Self::decode_stored(data).map(|(peer, _)| peer)
}
/// Decode a stored peer and report whether the record predates per-peer
/// unhandled sets, when every unhandled store entry was offered.
pub(crate) fn decode_stored(data: &[u8]) -> Option<(Self, bool)> {
if let Ok(stored) = rmp_serde::from_slice::<StoredPeerV2>(data) {
return Self::from_stored_v2(stored);
let legacy = stored.unhandled_ids.is_none();
return Self::from_stored_v2(stored).map(|peer| (peer, legacy));
}
let (
@@ -472,6 +521,9 @@ impl LxmPeer {
let mut dest_hash = [0u8; 16];
dest_hash.copy_from_slice(&dest_hash_vec);
let mut peer = Self::new(dest_hash);
// The legacy record kept no liveness; treat the peer as just heard.
peer.alive = true;
peer.last_heard = now_f64();
peer.last_sync = last_sync;
peer.unreachable_count = unreachable_count;
peer.peering_cost = peering_cost;
@@ -491,7 +543,7 @@ impl LxmPeer {
}
})
.collect();
Some(peer)
Some((peer, true))
}
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
@@ -519,20 +571,57 @@ impl LxmPeer {
peer.metadata = stored.metadata;
peer.last_heard = stored.last_heard;
peer.alive = stored.alive;
peer.link_establishment_rate = stored.link_establishment_rate;
peer.sync_transfer_rate = stored.sync_transfer_rate;
peer.last_sync_attempt = stored.last_sync_attempt;
peer.offered = stored.offered;
peer.outgoing = stored.outgoing;
peer.incoming = stored.incoming;
peer.rx_bytes = stored.rx_bytes;
peer.tx_bytes = stored.tx_bytes;
peer.handled_messages = stored
.handled_ids
.into_iter()
.filter_map(|value| value.try_into().ok())
.collect();
peer.unhandled_messages = stored
.unhandled_ids
.unwrap_or_default()
.into_iter()
.filter_map(|value| value.try_into().ok())
.collect();
Some(peer)
}
pub fn mark_unreachable(&mut self) {
self.unreachable_count += 1;
let now = now_f64();
if now - self.last_heard > MAX_UNREACHABLE as f64 {
}
/// Opening checks of Python `LXMPeer.sync()`: record the attempt and
/// report whether the backoff has elapsed. An attempt during backoff
/// marks a peer not heard since its last attempt as unreachable.
pub fn sync_attempt(&mut self, now: f64) -> bool {
self.last_sync_attempt = now;
if now > self.next_sync_attempt {
return true;
}
if self.last_sync_attempt > self.last_heard {
self.alive = false;
}
false
}
/// A path request for this peer went unanswered within
/// [`PATH_REQUEST_GRACE`]; defer the sync as Python `LXMPeer.sync()` does.
pub fn path_request_failed(&mut self, now: f64) {
self.sync_backoff += SYNC_BACKOFF_STEP as f64;
self.next_sync_attempt = now + self.sync_backoff;
self.alive = false;
}
/// Whether this peer has been silent longer than [`MAX_UNREACHABLE`].
pub fn unreachable_too_long(&self, now: f64) -> bool {
now > self.last_heard + MAX_UNREACHABLE as f64
}
pub fn should_sync(&self) -> bool {
@@ -548,23 +637,26 @@ impl LxmPeer {
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 {
let now = now_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 {
if let Some((_, value)) = self.peering_key {
value >= self.peering_cost as u32
value >= self.peering_cost
} else {
false
}
}
/// Peering-key value (leading zero bits), if generated.
pub fn peering_key_value(&self) -> Option<u32> {
/// 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<f64> {
self.peering_key.map(|(_, value)| value)
}
@@ -573,11 +665,17 @@ impl LxmPeer {
/// 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.
///
/// 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 until found or `ctl`
/// stops it; a peering cost above `STAMP_COST_CAP` fails at once.
///
/// Python reference: `LXMPeer.generate_peering_key`.
pub fn generate_peering_key(
&mut self,
peer_identity_hash: &[u8; 16],
our_identity_hash: &[u8; 16],
ctl: &crate::stamper::StampControl,
) -> bool {
if self.peering_key.is_some() {
return true;
@@ -587,18 +685,17 @@ impl LxmPeer {
key_material.extend_from_slice(peer_identity_hash);
key_material.extend_from_slice(our_identity_hash);
// Bounded search (stamper::stamp_iteration_cap): an announce-supplied
// hostile peering_cost can no longer pin this thread forever.
match crate::stamper::generate_stamp(
&key_material,
self.peering_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
ctl,
) {
Some((stamp, value)) => {
Ok(Some((stamp, value))) if value >= self.peering_cost => {
self.peering_key = Some((stamp, value));
true
}
None => false,
_ => false,
}
}
@@ -625,7 +722,7 @@ impl LxmPeer {
/// `next_sync_attempt` so sync can proceed immediately, updates `last_heard`, and marks the
/// 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>) {
if let Some(rate) = establishment_rate {
self.link_establishment_rate = rate;
@@ -634,15 +731,14 @@ impl LxmPeer {
self.next_sync_attempt = 0.0;
self.last_heard = now_f64();
self.alive = true;
self.sync_backoff = 0.0;
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
/// treats it as a sync failure.
///
/// Python reference: LXMPeer.py:540-542.
/// If the previous state was active, clear the in-flight transfer list.
/// This callback does not itself increment backoff or mark the peer unreachable.
pub fn link_closed(&mut self) {
let was_active = self.state != PeerState::Idle;
self.link_alive = false;
@@ -672,7 +768,7 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
fn from(peer: &LxmPeer) -> Self {
let peering_key = peer
.peering_key
.filter(|(_, value)| *value >= peer.peering_cost as u32)
.filter(|(_, value)| *value >= peer.peering_cost)
.map(|(stamp, _)| stamp.to_vec())
.unwrap_or_default();
Self {
@@ -690,66 +786,46 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
autopeered: peer.autopeered,
is_static: peer.is_static,
metadata: peer.metadata.clone(),
unhandled_messages: Some(peer.unhandled_messages.clone()),
}
}
}
/// Select the best peer to sync with from a set of candidates.
/// Choose the next peer to sync as Python `LXMRouter.sync_peers()` does.
///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
/// mix in unknown-speed peers, and fall back to unresponsive peers that have passed their sync
/// backoff.
pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> {
if peers.is_empty() {
return None;
}
/// Alive idle peers with unhandled messages form the waiting pool; the pick is
/// random among the [`FASTEST_N_RANDOM_POOL`] fastest of them plus as many
/// peers of unknown speed. With no waiting peer, the pick is random among
/// unreachable idle peers whose backoff has elapsed. Returns an input index.
pub fn select_sync_peer(peers: &[&LxmPeer], now: f64) -> Option<usize> {
use rand::seq::SliceRandom;
let mut alive_with_unhandled: Vec<(usize, &LxmPeer)> = peers
.iter()
.enumerate()
.filter(|(_, p)| p.alive && p.state == PeerState::Idle && p.unhandled_messages() > 0)
.map(|(i, p)| (i, *p))
let candidate =
|peer: &LxmPeer| peer.state == PeerState::Idle && !peer.unhandled_messages.is_empty();
let mut waiting: Vec<usize> = (0..peers.len())
.filter(|&i| candidate(peers[i]) && peers[i].alive)
.collect();
if !alive_with_unhandled.is_empty() {
alive_with_unhandled.sort_by(|a, b| {
b.1.sync_transfer_rate
.partial_cmp(&a.1.sync_transfer_rate)
.unwrap_or(std::cmp::Ordering::Equal)
});
let pool_size = alive_with_unhandled.len().min(FASTEST_N_RANDOM_POOL);
let unknown_speed: Vec<(usize, &LxmPeer)> = alive_with_unhandled
let pool: Vec<usize> = if !waiting.is_empty() {
let unknown_speed: Vec<usize> = waiting
.iter()
.filter(|(_, p)| p.sync_transfer_rate == 0.0)
.copied()
.filter(|&i| peers[i].sync_transfer_rate == 0.0)
.collect();
let mut pool: Vec<usize> = alive_with_unhandled[..pool_size]
.iter()
.map(|(i, _)| *i)
.collect();
for (i, _) in unknown_speed.iter().take(pool_size) {
if !pool.contains(i) {
pool.push(*i);
}
}
// Deterministic first-of-pool pick; callers that want randomization do it themselves.
return pool.into_iter().next();
}
let unresponsive: Vec<(usize, &LxmPeer)> = peers
.iter()
.enumerate()
.filter(|(_, p)| {
!p.alive && p.state == PeerState::Idle && p.unhandled_messages() > 0 && p.should_sync()
})
.map(|(i, p)| (i, *p))
.collect();
unresponsive.first().map(|(i, _)| *i)
waiting.sort_by(|&a, &b| {
peers[b]
.sync_transfer_rate
.total_cmp(&peers[a].sync_transfer_rate)
});
waiting.truncate(FASTEST_N_RANDOM_POOL);
let fastest = waiting.len();
waiting.extend(unknown_speed.into_iter().take(fastest));
waiting
} else {
(0..peers.len())
.filter(|&i| candidate(peers[i]) && !peers[i].alive && now > peers[i].next_sync_attempt)
.collect()
};
pool.choose(&mut rand::thread_rng()).copied()
}
fn now_f64() -> f64 {
@@ -772,45 +848,46 @@ mod tests {
let peer = LxmPeer::new([0xAA; 16]);
assert_eq!(peer.state, PeerState::Idle);
assert_eq!(peer.sync_strategy, SyncStrategy::Persistent);
assert!(peer.alive);
assert!(!peer.alive);
assert_eq!(peer.last_heard, 0.0);
assert_eq!(peer.unreachable_count, 0);
}
#[test]
fn test_minimum_stamp_cost() {
let mut peer = LxmPeer::new([0; 16]);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0.0);
peer.stamp_cost = Some(16);
assert_eq!(peer.minimum_accepted_stamp_cost(), 13);
peer.stamp_cost = Some(16.0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 13.0);
// cost < flex must saturate at 0.
peer.stamp_cost = Some(2);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
peer.stamp_cost = Some(2.0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0.0);
// Announced flexibility overrides the default.
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(5);
assert_eq!(peer.minimum_accepted_stamp_cost(), 11);
peer.stamp_cost_flexibility = Some(0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
peer.stamp_cost = Some(16.0);
peer.stamp_cost_flexibility = Some(5.0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 11.0);
peer.stamp_cost_flexibility = Some(0.0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 16.0);
}
#[test]
fn outbound_offer_policy_captures_authoritative_peer_state() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(3);
peer.stamp_cost = Some(16.0);
peer.stamp_cost_flexibility = Some(3.0);
peer.propagation_transfer_limit = Some(1.5);
peer.propagation_sync_limit = Some(4.5);
peer.peering_cost = 18;
peer.peering_key = Some(([0x77; 32], 18));
peer.peering_cost = 18.0;
peer.peering_key = Some(([0x77; 32], 18.0));
peer.add_handled_message(&tid(0x11));
let policy = peer.outbound_offer_policy();
assert_eq!(policy.peer_hash, [0xAA; 16]);
assert_eq!(policy.minimum_stamp_cost, 13);
assert_eq!(policy.minimum_stamp_cost, 13.0);
assert_eq!(policy.propagation_transfer_limit, Some(1.5));
assert_eq!(policy.propagation_sync_limit, Some(4.5));
assert_eq!(policy.peering_key, vec![0x77; 32]);
@@ -824,27 +901,34 @@ mod tests {
200.0,
Some(2.0),
Some(8.0),
Some(16),
Some(3),
Some(18),
Some(16.0),
Some(3.0),
Some(18.0),
);
assert!(!peer.refresh_from_announce(
199.0,
Some(1.0),
Some(4.0),
Some(8),
Some(1),
Some(4),
Some(8.0),
Some(1.0),
Some(4.0),
));
assert_eq!(peer.peering_timebase, 200.0);
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
assert_eq!(peer.stamp_cost, Some(16));
assert_eq!(peer.stamp_cost, Some(16.0));
peer.peering_key = Some(([0x55; 32], 18));
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
peer.peering_key = Some(([0x55; 32], 18.0));
assert!(peer.refresh_from_announce(
201.0,
Some(3.0),
None,
Some(20.0),
Some(4.0),
Some(19.0),
));
assert_eq!(peer.propagation_sync_limit, Some(3.0));
assert_eq!(peer.stamp_cost, Some(20));
assert_eq!(peer.stamp_cost, Some(20.0));
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
}
@@ -855,11 +939,11 @@ mod tests {
1234.0,
Some(1.25),
Some(9.5),
Some(16),
Some(3),
Some(18),
Some(16.0),
Some(3.0),
Some(18.0),
);
peer.peering_key = Some(([0x66; 32], 19));
peer.peering_key = Some(([0x66; 32], 19.0));
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
peer.add_handled_message(&tid(0x22));
@@ -867,7 +951,7 @@ mod tests {
assert_eq!(restored.peering_timebase, 1234.0);
assert_eq!(restored.propagation_transfer_limit, Some(1.25));
assert_eq!(restored.propagation_sync_limit, Some(9.5));
assert_eq!(restored.peering_key, Some(([0x66; 32], 19)));
assert_eq!(restored.peering_key, Some(([0x66; 32], 19.0)));
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
assert!(restored.has_handled(&tid(0x22)));
@@ -875,9 +959,9 @@ mod tests {
vec![0xBB; 16],
42.0,
2,
18,
Some(12),
Some(2),
18.0,
Some(12.0),
Some(2.0),
true,
false,
vec![tid(0x33).to_vec()],
@@ -885,7 +969,7 @@ mod tests {
let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap();
let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap();
assert_eq!(restored_legacy.destination_hash, [0xBB; 16]);
assert_eq!(restored_legacy.stamp_cost, Some(12));
assert_eq!(restored_legacy.stamp_cost, Some(12.0));
assert!(restored_legacy.has_handled(&tid(0x33)));
}
@@ -903,9 +987,9 @@ mod tests {
10.0,
Some(1.0),
Some(2.0),
Some(12),
Some(3),
Some(18),
Some(12.0),
Some(3.0),
Some(18.0),
Some(metadata),
);
let retained = peer.metadata.as_ref().unwrap();
@@ -932,15 +1016,15 @@ mod tests {
#[test]
fn newer_policy_invalidates_processed_store_generation() {
let mut peer =
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None);
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16.0), Some(3.0), None);
peer.mark_offer_generation_processed(7);
assert!(!peer.needs_offer_generation(7));
assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None));
assert!(peer.refresh_from_announce(11.0, None, None, Some(12.0), Some(3.0), None));
assert!(peer.needs_offer_generation(7));
peer.mark_offer_generation_processed(7);
assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None));
assert!(peer.refresh_from_announce(12.0, None, None, Some(12.0), Some(3.0), None));
assert!(
!peer.needs_offer_generation(7),
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
@@ -952,20 +1036,41 @@ mod tests {
#[test]
fn test_generate_peering_key_capped() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.peering_cost = 255;
assert!(!peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
let ctl = crate::stamper::StampControl::default();
peer.peering_cost = 255.0;
assert!(!peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16], &ctl));
assert!(peer.peering_key.is_none());
peer.peering_cost = 4;
assert!(peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16]));
peer.peering_cost = 4.5;
assert!(peer.generate_peering_key(&[0xBB; 16], &[0xCC; 16], &ctl));
assert!(peer.peering_key.is_some_and(|(_, value)| value >= 4.5));
assert!(peer.peering_key.is_some());
}
#[test]
fn test_mark_unreachable() {
fn sync_attempt_during_backoff_marks_unheard_peer_unreachable() {
let mut peer = LxmPeer::new([0; 16]);
peer.last_heard = 0.0;
peer.mark_unreachable();
peer.alive = true;
peer.last_heard = 100.0;
peer.next_sync_attempt = 500.0;
assert!(!peer.sync_attempt(200.0));
assert_eq!(peer.last_sync_attempt, 200.0);
assert!(!peer.alive);
peer.alive = true;
peer.last_heard = 300.0;
assert!(!peer.sync_attempt(250.0));
assert!(peer.alive, "a peer heard after the attempt stays alive");
assert!(peer.sync_attempt(600.0));
}
#[test]
fn unanswered_path_request_adds_backoff_and_marks_unreachable() {
let mut peer = LxmPeer::new([0; 16]);
peer.alive = true;
peer.path_request_failed(1000.0);
assert_eq!(peer.sync_backoff, SYNC_BACKOFF_STEP as f64);
assert_eq!(peer.next_sync_attempt, 1000.0 + SYNC_BACKOFF_STEP as f64);
assert!(!peer.alive);
}
@@ -1021,11 +1126,16 @@ mod tests {
#[test]
fn test_add_unhandled() {
let mut peer = LxmPeer::new([0; 16]);
assert_eq!(peer.unhandled_messages(), 0);
assert_eq!(peer.unhandled_message_count(), 0);
peer.add_unhandled_message();
peer.add_unhandled_message();
assert_eq!(peer.unhandled_messages(), 2);
peer.add_unhandled_message(&tid(1));
peer.add_unhandled_message(&tid(1));
peer.add_unhandled_message(&tid(2));
assert_eq!(peer.unhandled_message_count(), 2);
peer.add_handled_message(&tid(1));
peer.add_unhandled_message(&tid(1));
assert_eq!(peer.unhandled_message_count(), 1);
}
#[test]
@@ -1035,16 +1145,16 @@ mod tests {
1000.0,
Some(256.0),
Some(10240.0),
Some(16),
Some(3),
Some(18),
Some(16.0),
Some(3.0),
Some(18.0),
);
assert_eq!(peer.peering_timebase, 1000.0);
assert_eq!(peer.propagation_transfer_limit, Some(256.0));
assert_eq!(peer.propagation_sync_limit, Some(10240.0));
assert_eq!(peer.stamp_cost, Some(16));
assert_eq!(peer.stamp_cost_flexibility, Some(3));
assert_eq!(peer.peering_cost, 18);
assert_eq!(peer.stamp_cost, Some(16.0));
assert_eq!(peer.stamp_cost_flexibility, Some(3.0));
assert_eq!(peer.peering_cost, 18.0);
assert!(peer.autopeered);
}
@@ -1063,40 +1173,41 @@ mod tests {
let mut peer = LxmPeer::new([0; 16]);
assert!(!peer.stamp_costs_known());
peer.stamp_cost = Some(16);
peer.stamp_cost = Some(16.0);
assert!(!peer.stamp_costs_known());
peer.stamp_cost_flexibility = Some(3);
peer.stamp_cost_flexibility = Some(3.0);
assert!(peer.stamp_costs_known());
}
#[test]
fn test_select_sync_peer_basic() {
let mut peer1 = LxmPeer::new([0x01; 16]);
peer1.add_unhandled_message();
peer1.sync_transfer_rate = 100.0;
peer1.add_unhandled_message(&tid(1));
peer1.alive = true;
let mut peer2 = LxmPeer::new([0x02; 16]);
peer2.add_unhandled_message();
peer2.sync_transfer_rate = 200.0;
peer2.add_unhandled_message(&tid(1));
peer2.next_sync_attempt = f64::MAX;
let peers: Vec<&LxmPeer> = vec![&peer1, &peer2];
let selected = select_sync_peer(&peers);
assert!(selected.is_some());
assert_eq!(selected.unwrap(), 1);
assert_eq!(select_sync_peer(&peers, 1.0), Some(0));
peer1.alive = false;
let peers: Vec<&LxmPeer> = vec![&peer1, &peer2];
assert_eq!(select_sync_peer(&peers, 1.0), Some(0));
}
#[test]
fn test_select_sync_peer_empty() {
let peers: Vec<&LxmPeer> = vec![];
assert!(select_sync_peer(&peers).is_none());
assert!(select_sync_peer(&peers, 1.0).is_none());
}
#[test]
fn test_select_sync_peer_no_unhandled() {
let peer = LxmPeer::new([0x01; 16]);
let peers: Vec<&LxmPeer> = vec![&peer];
assert!(select_sync_peer(&peers).is_none());
assert!(select_sync_peer(&peers, 1.0).is_none());
}
#[test]
+157 -172
View File
@@ -1,29 +1,78 @@
//! Persistent router state — matches Python `<storagepath>/lxmf/` layout.
//! Router state files in a caller-supplied directory.
//!
//! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//! * `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
//! treated as "no prior state" and do not raise errors — a fresh daemon is a
//! valid state.
//! Stamp costs, tickets, and delivered and processed transient IDs live in
//! `state.db` ([`crate::state_store`]). `delivery_claims`, which earlier
//! releases appended to, is only read here so its records can be imported.
//!
//! Missing files yield empty/default state. Other I/O, malformed-data and
//! capacity errors propagate to the caller.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::{Ticket, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
pub const TICKETS_FILE: &str = "available_tickets";
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
pub const NODE_STATS_FILE: &str = "node_stats";
/// Delivered/processed claims that earlier releases appended before delivery callbacks ran.
const DELIVERY_CLAIMS_FILE: &str = "delivery_claims";
const CLAIM_DELIVERED: u8 = 0;
const CLAIM_PROCESSED: u8 = 1;
const CLAIM_RECORD_LEN: usize = 1 + 32 + 8;
/// Read appended claims as (delivered, processed). A torn trailing record is ignored.
#[allow(clippy::type_complexity)]
pub(crate) fn load_delivery_claims(
dir: &Path,
) -> io::Result<(
Vec<(PropagationTransientId, f64)>,
Vec<(PropagationTransientId, f64)>,
)> {
let mut records = Vec::new();
for path in [claims_saving(dir), dir.join(DELIVERY_CLAIMS_FILE)] {
match fs::read(path) {
Ok(bytes) => {
let whole = bytes.len() - bytes.len() % CLAIM_RECORD_LEN;
records.extend_from_slice(&bytes[..whole]);
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
let (mut delivered, mut processed) = (Vec::new(), Vec::new());
for record in records.chunks_exact(CLAIM_RECORD_LEN) {
let id: PropagationTransientId = record[1..33].try_into().expect("32 bytes");
let at = f64::from_le_bytes(record[33..].try_into().expect("8 bytes"));
match record[0] {
CLAIM_DELIVERED => delivered.push((id, at)),
CLAIM_PROCESSED => processed.push((id, at)),
_ => {}
}
}
Ok((delivered, processed))
}
fn claims_saving(dir: &Path) -> std::path::PathBuf {
dir.join(format!("{DELIVERY_CLAIMS_FILE}.saving"))
}
/// Remove every claim file once its records are committed to the LXMF state store.
pub(crate) fn clear_delivery_claims(dir: &Path) -> io::Result<()> {
for path in [claims_saving(dir), dir.join(DELIVERY_CLAIMS_FILE)] {
match fs::remove_file(path) {
Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
_ => {}
}
}
Ok(())
}
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -34,52 +83,75 @@ pub struct PersistedNodeStats {
pub unpeered_propagation_rx_bytes: u64,
}
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
///
/// Tmp name is `<path>.tmp.<pid>.<16 random hex>` so concurrent writers (or
/// other processes) never collide; the tmp file is unlinked on error. An fsync
/// failure is logged as a warning and is non-fatal, matching Python
/// `LXMessage.write_to_directory` — LXMessage.py:674-696 (1.0.1).
/// Publish exact bytes through the strict platform durability boundary.
/// CommitUncertain remains an error: readback alone cannot authorize a receipt.
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write;
rns_identity::persistence::durable_write(path, data)
.map(|_| ())
.map_err(io::Error::other)
}
let random: [u8; 8] = rand::random();
let tmp_name = format!(
"{}.tmp.{}.{}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
std::process::id(),
hex::encode(random)
);
let tmp = path.with_file_name(tmp_name);
/// Suppression state cannot authorize a remote purge. Adapters nevertheless
/// persist it before allowing the next automatic wants selection.
pub fn save_suppression(
dir: &Path,
ledger: &crate::admission::SuppressionLedger,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_suppression_v1"), ledger)
}
let result = (|| {
let mut file = fs::File::create(&tmp)?;
file.write_all(data)?;
file.flush()?;
if let Err(e) = file.sync_all() {
tracing::warn!(
"Error while waiting for persist fsync for {}: {e}",
tmp.display()
);
}
drop(file);
fs::rename(&tmp, path)
})();
if result.is_err()
&& tmp.exists()
&& let Err(e) = fs::remove_file(&tmp)
{
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
pub fn load_suppression(dir: &Path) -> io::Result<crate::admission::SuppressionLedger> {
// Preserve the existing one-field wrapper while rejecting duplicate keys,
// mismatched embedded scope and quota violations before hydration.
#[derive(serde::Deserialize)]
struct Wire {
#[serde(deserialize_with = "suppression_records")]
records: Vec<crate::admission::SuppressionRecord>,
}
let wire: Option<Wire> =
read_mpk_bounded(&dir.join("propagation_suppression_v1"), 65536 * 512 + 4096)?;
crate::admission::SuppressionLedger::from_records(
wire.map_or_else(Vec::new, |wire| wire.records),
)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
fn suppression_records<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Vec<crate::admission::SuppressionRecord>, D::Error> {
struct Records;
impl<'de> serde::de::Visitor<'de> for Records {
type Value = Vec<crate::admission::SuppressionRecord>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("bounded unique suppression map")
}
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut seen = std::collections::HashSet::new();
let mut records = Vec::new();
while let Some((scope,record))=map.next_entry::<crate::admission::AdmissionScope,crate::admission::SuppressionRecord>()? {
if scope!=record.scope || !seen.insert(scope) || records.len()>=crate::admission::SuppressionLedger::GLOBAL {
return Err(serde::de::Error::custom("invalid suppression scope or capacity"));
}
records.push(record);
}
Ok(records)
}
}
deserializer.deserialize_map(Records)
}
result
pub fn save_node_policies(
dir: &Path,
policies: &HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_node_policies_v1"), policies)
}
pub fn load_node_policies(
dir: &Path,
) -> io::Result<HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>> {
Ok(read_mpk(&dir.join("propagation_node_policies_v1"))?.unwrap_or_default())
}
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
@@ -92,64 +164,33 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
}
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
match fs::read(path) {
Ok(bytes) => {
let value = rmp_serde::from_slice(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(value))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
read_mpk_bounded(path, 64 * 1024 * 1024)
}
fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
path: &Path,
limit: usize,
) -> io::Result<Option<T>> {
use std::io::Read;
let file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut bytes = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > limit {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"router state exceeds bounded capacity",
));
}
}
pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> {
write_mpk(&dir.join(STAMP_COSTS_FILE), costs)
}
pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEntry>> {
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PersistedTickets {
Directional(TicketStoreSnapshot),
Legacy(Vec<Ticket>),
}
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
None => (TicketStoreSnapshot::default(), None),
})
}
pub fn save_local_deliveries(
dir: &Path,
ids: &HashMap<PropagationTransientId, f64>,
) -> io::Result<()> {
write_mpk(&dir.join(LOCAL_DELIVERIES_FILE), ids)
}
pub fn load_local_deliveries(dir: &Path) -> io::Result<HashMap<PropagationTransientId, f64>> {
Ok(read_mpk(&dir.join(LOCAL_DELIVERIES_FILE))?.unwrap_or_default())
}
pub fn save_locally_processed(
dir: &Path,
ids: &HashMap<PropagationTransientId, f64>,
) -> io::Result<()> {
write_mpk(&dir.join(LOCALLY_PROCESSED_FILE), ids)
}
pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTransientId, f64>> {
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
// Allocation-free structural walk precedes serde's collection size hints.
// It also rejects trailing roots, deep nesting and truncated huge lengths.
let encoded = crate::message::EncodedFieldValue::new(bytes.into())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
rmp_serde::from_slice(encoded.encoded())
.map(Some)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
@@ -168,71 +209,15 @@ mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn stamp_costs_roundtrip() {
let tmp = TempDir::new().unwrap();
let mut costs = HashMap::new();
costs.insert(
[0xAA; 16],
StampCostEntry {
cost: 12,
recorded_at: 1_700_000_000.0,
},
);
save_stamp_costs(tmp.path(), &costs).unwrap();
let loaded = load_stamp_costs(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[&[0xAA; 16]].cost, 12);
}
#[test]
fn tickets_roundtrip() {
let tmp = TempDir::new().unwrap();
let tickets = TicketStoreSnapshot {
version: 1,
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
};
save_tickets(tmp.path(), &tickets).unwrap();
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
assert!(legacy.is_none());
assert_eq!(loaded, tickets);
}
#[test]
fn legacy_flat_tickets_are_detected_for_migration() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(snapshot, TicketStoreSnapshot::default());
assert_eq!(legacy.unwrap(), tickets);
}
#[test]
fn local_deliveries_roundtrip() {
let tmp = TempDir::new().unwrap();
let mut ids = HashMap::new();
ids.insert([0x03; 32], 1_700_000_000.0);
save_local_deliveries(tmp.path(), &ids).unwrap();
let loaded = load_local_deliveries(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
}
#[test]
fn missing_file_returns_default() {
let tmp = TempDir::new().unwrap();
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(tickets, TicketStoreSnapshot::default());
assert!(legacy.is_none());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
load_node_stats(tmp.path()).unwrap(),
PersistedNodeStats::default()
);
let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap();
assert!(delivered.is_empty() && processed.is_empty());
}
#[test]
@@ -270,7 +255,7 @@ mod tests {
write_file_atomic(&path, b"first").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"first");
// Replaces existing content (os.replace semantics — LXMessage.py:687).
// Replaces existing content (os.replace semantics — LXMessage.py).
write_file_atomic(&path, b"second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"second");
@@ -287,7 +272,7 @@ mod tests {
fn write_file_atomic_cleans_tmp_on_error() {
let tmp = TempDir::new().unwrap();
// Destination is a directory: the final rename fails, and the tmp
// file must be unlinked (LXMessage.py:691-693).
// file must be unlinked (LXMessage.py).
let dir_path = tmp.path().join("collide");
fs::create_dir(&dir_path).unwrap();
+121 -4
View File
@@ -5,12 +5,34 @@ use unicode_normalization::UnicodeNormalization;
/// Maximum retained characters for an advertised LXMF display/node name.
pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name.
/// Normalize and bound an untrusted display name for presentation.
///
/// The result is NFKC-normalized, contains no control or presentation-control
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is
/// truncated by Unicode scalar values rather than UTF-8 bytes.
/// This is an application display policy; the announce helpers in
/// [`crate::handlers`] return names unfiltered, as Python LXMF does.
///
/// Applies NFKC normalization and filters control characters, bidi controls,
/// private-use characters, selected zero-width characters, variation selectors,
/// 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 {
let mut output = sanitize_name_pass(input, max_chars);
let rounds = output.nfkd().count().saturating_add(2);
for _ in 0..rounds {
let next = sanitize_name_pass(&output, max_chars);
if next == output {
return output;
}
output = next;
}
debug_assert!(
false,
"name normalization exceeded its derived stabilization bound"
);
String::new()
}
fn sanitize_name_pass(input: &str, max_chars: usize) -> String {
if max_chars == 0 {
return String::new();
}
@@ -114,6 +136,85 @@ fn is_emoji(codepoint: u32) -> bool {
)
}
/// Python `str.isspace()`: Unicode White_Space plus U+001C..U+001F.
pub fn is_python_space(character: char) -> bool {
character.is_whitespace() || matches!(character, '\u{1c}'..='\u{1f}')
}
/// Python `str.strip()` with no arguments.
pub fn python_strip(text: &str) -> &str {
text.trim_matches(is_python_space)
}
/// The name filter `lxmd --peers` applies (Python `lxmd.sanitize_name`):
/// NFKC, then keep letters, numbers, punctuation and spacing marks, map
/// separators to a space, drop the emoji, control and private-use blocks,
/// collapse whitespace and strip. Truncation is left to the caller.
pub fn sanitize_name_lxmd(input: &str) -> String {
use unicode_general_category::{GeneralCategory as C, get_general_category};
let mut kept = String::new();
for character in input.nfkc() {
let category = get_general_category(character);
let mapped = match category {
C::SpaceSeparator | C::LineSeparator | C::ParagraphSeparator => ' ',
C::UppercaseLetter
| C::LowercaseLetter
| C::TitlecaseLetter
| C::ModifierLetter
| C::OtherLetter
| C::DecimalNumber
| C::LetterNumber
| C::OtherNumber
| C::ConnectorPunctuation
| C::DashPunctuation
| C::OpenPunctuation
| C::ClosePunctuation
| C::InitialPunctuation
| C::FinalPunctuation
| C::OtherPunctuation
| C::SpacingMark => character,
_ => continue,
};
if !is_lxmd_stripped(mapped as u32) {
kept.push(mapped);
}
}
let mut output = String::with_capacity(kept.len());
for word in kept.split(is_python_space).filter(|w| !w.is_empty()) {
if !output.is_empty() {
output.push(' ');
}
output.push_str(word);
}
output
}
// STRIP_BLOCKS_RE, STRIP_CONTROL_RE and STRIP_PRIVATE_RE of Python lxmd.
fn is_lxmd_stripped(codepoint: u32) -> bool {
matches!(
codepoint,
0x1F300..=0x1FAFF
| 0x1F1E0..=0x1F1FF
| 0x2600..=0x27BF
| 0xFE00..=0xFE0F
| 0xE0100..=0xE01EF
| 0x00..=0x08
| 0x0B
| 0x0C
| 0x0E..=0x1F
| 0x7F..=0x9F
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0xFEFF
| 0xFFF0..=0xFFF8
| 0xD800..=0xDFFF
| 0xE000..=0xFAFF
| 0xFE10..=0xFE2F
| 0xF0000..=0x10FFFF
)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -146,6 +247,22 @@ mod tests {
assert_eq!(sanitize_name("A B", 3), "A B");
}
#[test]
fn normalization_reaches_fixed_point_after_filtered_separators() {
for input in [
"A\u{0000}\u{030A}",
"e\u{034f}\u{0301}",
"o\u{200d}\u{0308}",
] {
for limit in 0..8 {
let once = sanitize_name(input, limit);
assert_eq!(sanitize_name(&once, limit), once);
assert_eq!(once.nfkc().collect::<String>(), once);
}
}
assert_eq!(sanitize_name("™", 128), "TM");
}
proptest! {
#[test]
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
+126 -43
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::time::{SystemTime, UNIX_EPOCH};
@@ -14,10 +15,11 @@ pub struct PropagationEntry {
pub message_hash: [u8; 32],
pub destination_hash: [u8; 16],
pub stored_at: f64,
pub stamp_value: u8,
/// Quantized stamp value, as Python stores it.
pub stamp_value: f64,
pub size: usize,
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.
pub stamped: bool,
@@ -29,7 +31,7 @@ impl PropagationEntry {
message_hash: [u8; 32],
destination_hash: [u8; 16],
size: usize,
stamp_value: u8,
stamp_value: f64,
) -> Self {
Self {
transient_id,
@@ -48,7 +50,7 @@ impl PropagationEntry {
message_hash: [u8; 32],
destination_hash: [u8; 16],
size: usize,
stamp_value: u8,
stamp_value: f64,
) -> Self {
let mut entry = Self::new(
transient_id,
@@ -61,39 +63,49 @@ impl PropagationEntry {
entry
}
/// Format: `{hex_transient_id}_{timestamp}_{stamp_value}`.
/// Python's message-store name `{hex_transient_id}_{received}_{stamp_value}`,
/// with both numbers in Python float form and no value part for value 0.
pub fn filename(&self) -> String {
let value = if self.stamp_value > 0.0 {
format!("_{:?}", self.stamp_value)
} else {
String::new()
};
format!(
"{}_{:.0}_{}",
"{}_{:?}{value}",
hex_encode(&self.transient_id),
self.stored_at,
self.stamp_value
self.stored_at
)
}
/// Accepts canonical 64-hex transient IDs in both the 3-component format
/// and the older 2-component `{transient_id}_{timestamp}` form (stamp_value
/// defaults to 0). Pre-fix 32-hex transient IDs are rejected.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
/// 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, f64)> {
let parts: Vec<&str> = filename.split('_').collect();
match parts.len() {
3 => {
let tid = hex_decode_32(parts[0])?;
let ts: f64 = parts[1].parse().ok()?;
let sv: u8 = parts[2].parse().ok()?;
Some((tid, ts, sv))
let sv: f64 = parts[2].parse().ok()?;
Some((tid, ts, crate::stamper::quantize_cost(sv).ok()?))
}
2 => {
let tid = hex_decode_32(parts[0])?;
let ts: f64 = parts[1].parse().ok()?;
Some((tid, ts, 0))
Some((tid, ts, 0.0))
}
_ => None,
}
}
}
/// 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)]
pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>,
@@ -106,7 +118,8 @@ pub struct PropagationStore {
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[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>,
}
@@ -116,10 +129,21 @@ impl PropagationStore {
}
/// 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 {
if self.ignored_destinations.contains(&entry.destination_hash) {
return false;
}
self.insert_admitted(entry)
}
/// Account for an entry whose admission policy was checked before its
/// durable publication. Later ignore-list changes affect future admissions,
/// not a write already accepted under the node's reservation authority.
pub(crate) fn insert_admitted(&mut self, entry: PropagationEntry) -> bool {
self.total_size += entry.size;
self.entries.insert(entry.transient_id, entry);
true
@@ -171,11 +195,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
/// (oldest + largest + non-prioritised). Matches Python
/// `clean_message_store()` in LXMRouter.py.
/// Score = priority_weight * age_weight * size. Highest scores go first,
/// using Python `LXMRouter.get_weight`'s formula. This updates the in-memory
/// index and byte count; it does not delete message files.
pub fn cull_by_weight(&mut self, limit_bytes: usize) {
if self.total_size <= limit_bytes {
return;
@@ -233,7 +258,7 @@ impl PropagationStore {
priority_weight * age_weight * entry.size as f64
}
pub fn get_stamp_value(&self, transient_id: &PropagationTransientId) -> Option<u8> {
pub fn get_stamp_value(&self, transient_id: &PropagationTransientId) -> Option<f64> {
self.entries.get(transient_id).map(|e| e.stamp_value)
}
@@ -271,6 +296,22 @@ impl PropagationStore {
.insert(transient_id, crate::now_f64());
}
/// Record `transient_id` as processed unless it already is; the first-seen time is kept.
/// Returns false when it was already processed.
pub fn claim_processed(&mut self, transient_id: PropagationTransientId, now: f64) -> bool {
match self.locally_processed_ids.entry(transient_id) {
std::collections::hash_map::Entry::Occupied(_) => false,
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(now);
true
}
}
}
pub(crate) fn unclaim_processed(&mut self, transient_id: &PropagationTransientId) {
self.locally_processed_ids.remove(transient_id);
}
pub fn is_locally_processed(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_processed_ids.contains_key(transient_id)
}
@@ -283,6 +324,18 @@ impl PropagationStore {
&self.locally_processed_ids
}
/// Merge a loaded delivered ID, keeping the later timestamp.
pub fn restore_locally_delivered(&mut self, id: PropagationTransientId, at: f64) {
let entry = self.locally_delivered_ids.entry(id).or_insert(at);
*entry = entry.max(at);
}
/// Merge a loaded processed ID, keeping the later timestamp.
pub fn restore_locally_processed(&mut self, id: PropagationTransientId, at: f64) {
let entry = self.locally_processed_ids.entry(id).or_insert(at);
*entry = entry.max(at);
}
pub fn replace_locally_delivered(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_delivered_ids = ids;
}
@@ -292,7 +345,7 @@ impl PropagationStore {
}
/// 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
/// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) {
@@ -377,7 +430,7 @@ mod tests {
message_hash: [0xBB; 32],
destination_hash: [0xCC; 16],
stored_at: 1234567890.0,
stamp_value: 8,
stamp_value: 8.0,
size: 500,
collected: false,
stamped: false,
@@ -388,7 +441,8 @@ mod tests {
);
let parts: Vec<&str> = fname.split('_').collect();
assert_eq!(parts.len(), 3);
assert_eq!(parts[2], "8");
assert_eq!(parts[1], "1234567890.0");
assert_eq!(parts[2], "8.0");
}
#[test]
@@ -398,7 +452,30 @@ mod tests {
let (tid, ts, sv) = PropagationEntry::parse_filename(fname).unwrap();
assert_eq!(tid[0], 0xaa);
assert_eq!(ts, 1234567890.0);
assert_eq!(sv, 16);
assert_eq!(sv, 16.0);
}
#[test]
fn parse_filename_reads_python_float_names() {
let tid = "ab".repeat(32);
for (name, value) in [
(format!("{tid}_1794274814.6018312_8.0"), 8.0),
(format!("{tid}_1794274814.6018312_16.25"), 16.25),
(format!("{tid}_1794274814.6018312_0.7421875"), 0.7421875),
] {
let (_, ts, sv) = PropagationEntry::parse_filename(&name).unwrap();
assert_eq!(ts, 1794274814.6018312);
assert_eq!(sv, value);
}
}
#[test]
fn filename_omits_zero_value_and_writes_fractional_value() {
let mut entry = PropagationEntry::new(tid(0xAA), [0; 32], [0; 16], 10, 16.25);
entry.stored_at = 1794274814.6018312;
assert!(entry.filename().ends_with("_1794274814.6018312_16.25"));
entry.stamp_value = 0.0;
assert!(entry.filename().ends_with("_1794274814.6018312"));
}
#[test]
@@ -407,7 +484,7 @@ mod tests {
let (tid, ts, sv) = PropagationEntry::parse_filename(&fname).unwrap();
assert_eq!(tid[0], 0xaa);
assert_eq!(ts, 1234567890.0);
assert_eq!(sv, 0);
assert_eq!(sv, 0.0);
}
#[test]
@@ -421,7 +498,7 @@ mod tests {
let mut store = PropagationStore::new();
assert!(store.is_empty());
let entry = PropagationEntry::new(tid(0xAA), [0xBB; 32], [0xCC; 16], 500, 8);
let entry = PropagationEntry::new(tid(0xAA), [0xBB; 32], [0xCC; 16], 500, 8.0);
store.insert(entry);
assert_eq!(store.len(), 1);
@@ -438,14 +515,14 @@ mod tests {
[0xBB; 32],
[0xCC; 16],
500,
8,
8.0,
));
store.insert(PropagationEntry::new(
tid(0xDD),
[0xEE; 32],
[0xCC; 16],
300,
4,
4.0,
));
assert_eq!(store.total_size(), 800);
@@ -461,9 +538,9 @@ mod tests {
let dest1 = [0xAA; 16];
let dest2 = [0xBB; 16];
store.insert(PropagationEntry::new(tid(0x01), [0; 32], dest1, 100, 0));
store.insert(PropagationEntry::new(tid(0x02), [0; 32], dest1, 200, 0));
store.insert(PropagationEntry::new(tid(0x03), [0; 32], dest2, 300, 0));
store.insert(PropagationEntry::new(tid(0x01), [0; 32], dest1, 100, 0.0));
store.insert(PropagationEntry::new(tid(0x02), [0; 32], dest1, 200, 0.0));
store.insert(PropagationEntry::new(tid(0x03), [0; 32], dest2, 300, 0.0));
assert_eq!(store.entries_for_destination(&dest1).len(), 2);
assert_eq!(store.entries_for_destination(&dest2).len(), 1);
@@ -472,8 +549,8 @@ mod tests {
#[test]
fn test_transient_ids() {
let mut store = PropagationStore::new();
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0));
store.insert(PropagationEntry::new(tid(0x02), [0; 32], [0; 16], 200, 0));
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0.0));
store.insert(PropagationEntry::new(tid(0x02), [0; 32], [0; 16], 200, 0.0));
let ids = store.transient_ids();
assert_eq!(ids.len(), 2);
@@ -487,16 +564,16 @@ mod tests {
store.ignore_destination(ignored_dest);
let entry1 = PropagationEntry::new(tid(0x01), [0; 32], ignored_dest, 100, 0);
let entry1 = PropagationEntry::new(tid(0x01), [0; 32], ignored_dest, 100, 0.0);
assert!(!store.insert(entry1));
assert_eq!(store.len(), 0);
let entry2 = PropagationEntry::new(tid(0x02), [0; 32], allowed_dest, 200, 0);
let entry2 = PropagationEntry::new(tid(0x02), [0; 32], allowed_dest, 200, 0.0);
assert!(store.insert(entry2));
assert_eq!(store.len(), 1);
store.unignore_destination(&ignored_dest);
let entry3 = PropagationEntry::new(tid(0x03), [0; 32], ignored_dest, 100, 0);
let entry3 = PropagationEntry::new(tid(0x03), [0; 32], ignored_dest, 100, 0.0);
assert!(store.insert(entry3));
assert_eq!(store.len(), 2);
}
@@ -554,12 +631,12 @@ mod tests {
fn test_cull_by_weight() {
let mut store = PropagationStore::new();
let mut entry1 = PropagationEntry::new(tid(0x01), [0; 32], [0xAA; 16], 500, 0);
let mut entry1 = PropagationEntry::new(tid(0x01), [0; 32], [0xAA; 16], 500, 0.0);
entry1.stored_at = 1000.0;
store.entries.insert(entry1.transient_id, entry1.clone());
store.total_size += 500;
let mut entry2 = PropagationEntry::new(tid(0x02), [0; 32], [0xBB; 16], 300, 0);
let mut entry2 = PropagationEntry::new(tid(0x02), [0; 32], [0xBB; 16], 300, 0.0);
entry2.stored_at = now_f64();
store.entries.insert(entry2.transient_id, entry2.clone());
store.total_size += 300;
@@ -603,7 +680,7 @@ mod tests {
message_hash: [0; 32],
destination_hash: [0xAA; 16],
stored_at: now,
stamp_value: 0,
stamp_value: 0.0,
size: 1000,
collected: false,
stamped: false,
@@ -626,9 +703,15 @@ mod tests {
#[test]
fn test_get_stamp_value() {
let mut store = PropagationStore::new();
store.insert(PropagationEntry::new(tid(0xAA), [0; 32], [0; 16], 100, 12));
store.insert(PropagationEntry::new(
tid(0xAA),
[0; 32],
[0; 16],
100,
12.0,
));
assert_eq!(store.get_stamp_value(&tid(0xAA)), Some(12));
assert_eq!(store.get_stamp_value(&tid(0xAA)), Some(12.0));
assert_eq!(store.get_stamp_value(&tid(0xBB)), None);
}
}
+37 -13
View File
@@ -23,11 +23,11 @@ use crate::constants::PN_STAMP_THROTTLE;
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;
/// Smallest accepted configured inbound-sync limit.
/// Lower bound applied to the configured inbound-sync threshold.
pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1;
/// Duration applied after a known peer submits an invalid-stamp batch.
/// Default duration applied after a known peer submits an invalid-stamp batch.
pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE);
/// Policy applied to inbound propagation-node offers.
@@ -40,10 +40,14 @@ pub struct PnInboundAdmissionConfig {
/// The LXMF default is `false`, so a configured static peer bypasses both
/// admission gates.
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,
/// Accept propagation offers only from configured static peers.
pub from_static_only: bool,
/// Throttle installed after a known peer submits invalid stamps.
pub invalid_stamp_throttle: Duration,
}
impl Default for PnInboundAdmissionConfig {
@@ -53,6 +57,7 @@ impl Default for PnInboundAdmissionConfig {
static_sequential: false,
max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS,
from_static_only: false,
invalid_stamp_throttle: PN_INVALID_STAMP_THROTTLE,
}
}
}
@@ -286,7 +291,8 @@ impl PnInboundAdmission {
///
/// A successful preflight creates no admission record. The returned
/// 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(
&mut self,
link_id: [u8; 16],
@@ -461,6 +467,7 @@ impl PnInboundAdmission {
}
/// 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> {
self.transition(
link_id,
@@ -480,7 +487,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
/// throttle is possible only for a known peer retained in a valid record.
@@ -514,7 +521,7 @@ impl PnInboundAdmission {
Ok(PnCleanupResult::Removed(PnInboundState::Validating))
}
/// Install the standard throttle after invalid stamp validation for a
/// Install the configured throttle after invalid stamp validation for a
/// known peer, including an unsolicited Resource with no offer record.
///
/// `peer_destination_hash` must be the peer's already-derived
@@ -531,7 +538,7 @@ impl PnInboundAdmission {
return Err(PnThrottleInstallError::UnknownPeerDestination);
}
let requested_deadline = now.saturating_add(PN_INVALID_STAMP_THROTTLE);
let requested_deadline = now.saturating_add(self.config.invalid_stamp_throttle);
let deadline = self
.throttle_deadlines
.entry(peer_destination_hash)
@@ -680,9 +687,9 @@ mod tests {
static_sequential: false,
max_inbound_syncs: 3,
from_static_only: false,
invalid_stamp_throttle: Duration::from_secs(300),
}
);
assert_eq!(PN_INVALID_STAMP_THROTTLE, Duration::from_secs(180));
let floored = PnInboundAdmission::new(PnInboundAdmissionConfig {
max_inbound_syncs: 0,
@@ -1465,15 +1472,15 @@ mod tests {
);
assert_eq!(
admission.throttle_deadline(&bad_destination, Duration::from_secs(100)),
Some(Duration::from_secs(280))
Some(Duration::from_secs(400))
);
assert!(matches!(
admission.preflight_offer(link(4), Some(bad_identity), Duration::from_millis(279_999),),
admission.preflight_offer(link(4), Some(bad_identity), Duration::from_millis(399_999),),
Err(PnOfferRejection::InvalidStampThrottle)
));
// No global or zero-key throttle is created for unrelated peers.
let unrelated_now = Duration::from_millis(279_999);
let unrelated_now = Duration::from_millis(399_999);
let unrelated = admission
.preflight_offer(link(5), Some(identity(5)), unrelated_now)
.unwrap();
@@ -1483,7 +1490,7 @@ mod tests {
);
assert!(!admission.is_peer_throttled(&[0; 16], unrelated_now));
let deadline = Duration::from_secs(280);
let deadline = Duration::from_secs(400);
let expired = admission
.preflight_offer(link(6), Some(bad_identity), deadline)
.unwrap();
@@ -1494,6 +1501,23 @@ mod tests {
assert_eq!(admission.throttle_count(), 0);
}
#[test]
fn invalid_stamp_throttle_lasts_the_configured_time() {
let throttle = Duration::from_secs(600);
let mut admission = PnInboundAdmission::new(PnInboundAdmissionConfig {
invalid_stamp_throttle: throttle,
..PnInboundAdmissionConfig::default()
});
let bad_identity = identity(0xA3);
let bad_destination = PnInboundAdmission::peer_destination_hash(&bad_identity);
let deadline = admission
.install_invalid_stamp_throttle(bad_destination, TEST_NOW)
.unwrap();
assert_eq!(deadline, TEST_NOW + throttle);
assert!(admission.is_peer_throttled(&bad_destination, deadline - Duration::from_secs(1)));
assert!(!admission.is_peer_throttled(&bad_destination, deadline));
}
#[test]
fn unsolicited_invalid_stamp_throttle_is_expiring_and_peer_scoped() {
let mut admission = PnInboundAdmission::default();
File diff suppressed because it is too large. Load diff
+525 -106
View File
@@ -1,4 +1,5 @@
//! In-process encrypted peers: every emitted packet is checked at the real MTU.
use super::tests::{downloaded_bytes, fixture_download};
use super::*;
use rmpv::Value;
use rns_wire::{context::PacketContext as Context, flags::PacketType};
@@ -15,6 +16,8 @@ struct Peer {
drop_hmu: bool,
drop_request: bool,
retries: usize,
admission_dir: tempfile::TempDir,
admitted: Vec<Vec<u8>>,
}
impl Peer {
@@ -44,9 +47,52 @@ impl Peer {
drop_hmu: false,
drop_request: false,
retries: 0,
admission_dir: tempfile::tempdir().unwrap(),
admitted: Vec::new(),
}
}
/// Protocol-unit-test recipient seam. The simulated decryptor maps each
/// opaque response to distinct actually signed bytes; FileAdmissionStore
/// must commit them before the client is allowed to send its purge.
fn accept_downloads(&mut self) {
use crate::admission::{
AdmissionRecord, DownloadAdmissionOutcome, DurableAdmissionReceipt, DurableDisposition,
};
let store = crate::admission_store::FileAdmissionStore::open(
self.admission_dir.path(),
&self.admission_dir.path().join("messages"),
)
.unwrap();
for downloaded in self.client.take_downloaded_messages() {
let (data, token) = downloaded.into_parts();
let scope = token.scope();
let message = crate::message::test_message(
[1; 16],
[2; 16],
&hex::encode(scope.transient_id),
"simulated recipient decryption",
crate::constants::DeliveryMethod::Propagated,
);
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: rns_crypto::sha::full_hash(message.wire_bytes()),
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
let receipt =
DurableAdmissionReceipt::commit(store.prepare(record, message.wire_owned(), false))
.unwrap();
self.admitted.push(data.to_vec());
token
.resolve(DownloadAdmissionOutcome::Accepted(receipt))
.unwrap();
}
self.client.poll_admissions();
}
fn inject(&mut self, context: Context, payload: &[u8]) {
let raw = PropagationClient::link_packet_bytes(
self.link.link_id,
@@ -65,6 +111,7 @@ impl Peer {
self.client
.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: raw.into(),
interface_id: 7,
metrics: Default::default(),
@@ -146,7 +193,9 @@ impl Peer {
packets += 1;
assert!(packets < 20_000, "bounded request peer loop");
if self.rx.is_empty() {
receiver.last_activity = Instant::now() - Duration::from_secs(1000);
// Past this peer's watchdog (seconds at its 10 ms RTT), yet within
// a freshly booted Windows clock.
receiver.last_activity = Instant::now() - Duration::from_secs(30);
receiver.req_sent = Some(receiver.last_activity);
let TransferAction::SendRequest(request) = receiver.check_timeout() else {
panic!("receiver should retry its missing window");
@@ -242,6 +291,7 @@ impl Peer {
Some(id.to_vec()),
true,
Some(&encrypt),
None,
)
.unwrap()
.segments
@@ -279,19 +329,20 @@ impl Peer {
}
}
fn blob(index: usize) -> Vec<u8> {
let mut data = (0u64..5)
.flat_map(|v| rns_crypto::sha::full_hash(&v.to_be_bytes()))
.collect::<Vec<_>>();
data[..8].copy_from_slice(&(index as u64).to_be_bytes());
data
}
fn ids(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| rns_crypto::sha::full_hash(&(i as u64).to_be_bytes()).to_vec())
.map(|i| rns_crypto::sha::full_hash(&blob(i)).to_vec())
.collect()
}
fn blobs(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| {
let mut data = ids(5).concat();
data[..8].copy_from_slice(&(i as u64).to_be_bytes());
data
})
.collect()
(0..n).map(blob).collect()
}
fn binary_list(items: &[Vec<u8>]) -> Value {
Value::Array(items.iter().cloned().map(Value::Binary).collect())
@@ -353,12 +404,22 @@ fn fifty_downloaded_messages_survive_get_and_purge_resource_round_trip() {
assert_eq!(request.as_array().unwrap()[0], binary_list(&wants));
peer.response(get_id, binary_list(&messages), true);
assert_eq!(peer.client.received_count(), 50);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
let (purge_id, request, _) = peer.request(true);
assert_eq!(request, Value::Array(vec![Value::Nil, binary_list(&wants)]));
peer.response(purge_id, empty(), true);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.transfer_status().result, Some(50));
assert_eq!(peer.client.take_received_messages(), messages);
let counts = peer.client.transfer_status().admission;
assert_eq!(counts.downloaded, 50);
assert_eq!(counts.committed, 50);
assert_eq!(counts.rejected, 0);
assert_eq!(counts.retryable, 0);
assert_eq!(peer.admitted, messages);
assert_eq!(peer.resource_requests, 2);
assert_eq!(peer.client.unread_bytes, 0);
}
@@ -381,6 +442,7 @@ fn early_response_retires_sender_and_ignores_late_proof_cancel_and_receipt() {
.resource
.resource_hash;
peer.response(old_id, binary_list(&blobs(1)), false);
peer.accept_downloads();
let new_request = peer.client.request.as_ref().unwrap();
assert_ne!(old_id, new_request.id);
let generation = new_request.generation;
@@ -450,23 +512,23 @@ fn purge_errors_never_complete_or_advance_chunk() {
#[test]
fn capacity_failure_precedes_publication_purge_and_cursor_advance() {
let mut peer = Peer::new();
peer.client.unread_limit = 100;
peer.client.received_messages.push(vec![1; 20]);
peer.client.unread_bytes = 20;
peer.client.available_messages = ids(2);
peer.client.unread_limit = 80;
let retained = vec![fixture_download(&peer.client, vec![1; 20])];
let over_limit = vec![vec![2; 60], vec![3; 30]];
peer.client.available_messages = over_limit
.iter()
.map(|bytes| rns_crypto::sha::full_hash(bytes).to_vec())
.collect();
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&[vec![2; 60], vec![3; 30]]), false);
peer.response(id, binary_list(&over_limit), false);
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.pending_wants.len(), 2);
assert!(peer.client.received_ids.is_empty());
assert_eq!(peer.client.received_messages, vec![vec![1; 20]]);
assert_eq!(peer.client.unread_bytes, 20);
assert!(peer.client.received_messages.is_empty());
assert_eq!(peer.client.unread_bytes, 0);
assert_eq!(downloaded_bytes(&retained), vec![vec![1; 20]]);
assert!(peer.rx.try_recv().is_err(), "overflow must not queue purge");
assert!(!peer.client.start_download());
peer.client.cancel_download();
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), vec![vec![1; 20]]);
}
#[test]
@@ -474,18 +536,18 @@ fn request_resource_progress_is_not_a_fixed_120_second_operation() {
let mut peer = Peer::new();
peer.client.received_ids = ids(50);
peer.client.send_purge_request();
peer.client.started_at = Some(Instant::now() - Duration::from_secs(600));
peer.client.started_at = Some(ago_or_skip!(Duration::from_secs(600)));
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested);
let (id, _, _) = peer.request(true);
let request = peer.client.request.as_mut().unwrap();
request.waiting_since = Some(Instant::now() - request.timeout - Duration::from_secs(1));
request.waiting_since = Some(ago_or_skip!(request.timeout + Duration::from_secs(1)));
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.state(), PropagationClientState::TransferFailed);
assert!(peer.client.request.is_none());
// No late response can resurrect a cleaned-up request.
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.state(), PropagationClientState::TransferFailed);
}
#[test]
@@ -504,7 +566,7 @@ fn lost_advertisement_retries_same_resource_and_eventually_fails() {
.outbound
.as_mut()
.unwrap()
.started_at = Instant::now() - Duration::from_secs(100_000);
.started_at = ago_or_skip!(Duration::from_secs(100_000));
peer.client.drive_outbound_request();
if peer.client.state() != PropagationClientState::Failed {
let (context, payload, _) = peer.packet();
@@ -518,40 +580,39 @@ fn lost_advertisement_retries_same_resource_and_eventually_fails() {
}
#[test]
fn oversized_logical_sets_advance_after_empty_and_partial_chunks() {
fn one_get_request_ends_the_sync_even_when_wants_exceed_one_segment() {
let mut peer = Peer::new();
let selected = ids(30_845);
peer.client.max_messages = Some(30_840);
peer.client.available_messages = selected.clone();
peer.client.available_messages.push(selected[0].clone());
peer.client.send_get_request();
let first = peer.client.request.as_ref().unwrap();
let RequestKind::Get(first_count) = first.kind else {
panic!()
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Get(count, 0) = request.kind else {
panic!("one get request expected")
};
assert!(first_count < 30_840);
assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS);
if let Some(transfer) = &request.outbound {
assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE);
}
let (id, data, _) = peer.request(true);
assert_eq!(data.as_array().unwrap()[0], binary_list(&selected[..count]));
peer.response(id, binary_list(&[blob(0)]), false);
assert!(
first
.outbound
.as_ref()
.unwrap()
.resource
.advertisement_data_size
<= MAX_EFFICIENT_SIZE
peer.client.pending_wants.is_empty(),
"unserved wants wait for the next list"
);
let id = first.id;
// Correlated early empty response skips the complete requested chunk.
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
assert!(matches!(
peer.client.request.as_ref().unwrap().kind,
RequestKind::Purge(1)
));
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
let RequestKind::Get(tail_count) = peer.client.request.as_ref().unwrap().kind else {
panic!()
};
assert_eq!(first_count + tail_count, 30_840);
let tail = peer.client.request.as_ref().unwrap().id;
peer.response(tail, binary_list(&blobs(1)), false);
assert!(peer.client.pending_wants.is_empty());
assert_eq!(peer.client.received_ids.len(), 1);
let purge = peer.client.request.as_ref().unwrap().id;
peer.response(purge, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.transfer_status().result, Some(1));
}
@@ -563,18 +624,20 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() {
peer.client.available_messages = selected.clone();
peer.client.replace_local_message_ids(selected);
peer.client.send_get_request();
let RequestKind::Haves(first) = peer.client.request.as_ref().unwrap().kind else {
panic!()
};
assert!(first < 30_840);
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
assert_eq!(peer.client.pending_haves.len(), 30_840 - first);
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
assert!(peer.client.pending_haves.is_empty());
let mut chunks = 0;
while !peer.client.pending_haves.is_empty() {
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Haves(count) = request.kind else {
panic!("haves chunk expected")
};
assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS);
let id = request.id;
peer.response(id, empty(), false);
chunks += 1;
assert!(chunks <= 8);
}
assert_eq!(chunks, 8);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
let mut peer = Peer::new();
peer.client.available_messages = ids(2);
peer.client.replace_local_message_ids(ids(1));
@@ -583,7 +646,12 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() {
let (id, data, _) = peer.request(true);
assert_eq!(data.as_array().unwrap()[0], binary_list(&ids(2)[1..]));
assert_eq!(data.as_array().unwrap()[1], empty());
peer.response(id, binary_list(&blobs(1)), false);
peer.response(id, binary_list(&[blob(1)]), false);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
assert!(matches!(
peer.client.request.as_ref().unwrap().kind,
RequestKind::Purge(1)
@@ -604,15 +672,21 @@ fn hashmap_updates_and_split_responses_keep_exact_request_identity() {
assert_eq!(peer.client.state(), PropagationClientState::Complete);
let mut peer = Peer::new();
peer.client.available_messages = ids(1);
let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100];
peer.client.available_messages = vec![rns_crypto::sha::full_hash(&blob).to_vec()];
peer.client.set_delivery_limit(2000.0);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100];
peer.response(id, binary_list(std::slice::from_ref(&blob)), true);
assert_eq!(peer.client.received_messages, vec![blob]);
assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested);
assert_eq!(downloaded_bytes(&peer.client.received_messages), vec![blob]);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
assert!(peer.client.inbound_split_resources.is_empty());
peer.accept_downloads();
assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested);
}
#[test]
@@ -640,22 +714,23 @@ fn every_id_branch_switches_at_real_packet_boundary() {
peer.client.send_purge_request();
}
}
assert_eq!(
peer.client.request.as_ref().unwrap().outbound.is_some(),
count > 11
);
if branch != 2 {
assert_eq!(
peer.client.request.as_ref().unwrap().outbound.is_some(),
count > 11
);
}
let (id, body, _) = peer.request(true);
let fields = body.as_array().unwrap();
assert_eq!(
fields[if branch == 0 { 0 } else { 1 }],
binary_list(&selected)
);
peer.response(id, empty(), false);
if branch == 2 {
let (id, body, _) = peer.request(true);
assert_eq!(body.as_array().unwrap()[0], binary_list(&[vec![0xee; 32]]));
peer.response(id, empty(), false);
// One `[wants, haves, limit]` request carries both lists.
assert_eq!(fields[0], binary_list(&[vec![0xee; 32]]));
}
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
}
}
@@ -777,10 +852,9 @@ fn advertisement_requires_matching_request_id_and_response_direction() {
}
#[test]
fn malformed_batch_is_atomic_and_preserves_prior_results() {
fn malformed_batch_is_atomic_and_preserves_external_payload_owners() {
let mut peer = Peer::new();
peer.client.received_messages.push(vec![0xab; 20]);
peer.client.unread_bytes = 20;
let retained = vec![fixture_download(&peer.client, vec![0xab; 20])];
peer.client.available_messages = ids(2);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
@@ -790,14 +864,15 @@ fn malformed_batch_is_atomic_and_preserves_prior_results() {
false,
);
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.received_messages, vec![vec![0xab; 20]]);
assert_eq!(peer.client.unread_bytes, 20);
assert_eq!(downloaded_bytes(&retained), vec![vec![0xab; 20]]);
assert!(peer.client.received_messages.is_empty());
assert_eq!(peer.client.unread_bytes, 0);
assert!(peer.client.received_ids.is_empty());
assert_eq!(peer.client.pending_wants.len(), 2);
}
#[test]
fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained() {
fn durable_results_survive_purge_failure_and_external_owners_survive_cancellation() {
for failure in 0..3 {
let mut peer = Peer::new();
let messages = blobs(50);
@@ -806,40 +881,67 @@ fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained()
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&messages), true);
assert_eq!(peer.client.received_count(), 50);
match failure {
0 => {
let (id, _, _) = peer.request(true);
peer.response(id, Value::from(0xf0), false);
peer.client.tick();
}
1 => peer.client.cancel_download(),
_ => {
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
if failure == 0 {
peer.accept_downloads();
let (id, _, _) = peer.request(true);
peer.response(id, Value::from(0xf0), false);
peer.client.tick();
assert_eq!(peer.admitted, messages);
assert_eq!(peer.client.local_messages.len(), 50);
let store = crate::admission_store::FileAdmissionStore::open(
peer.admission_dir.path(),
&peer.admission_dir.path().join("messages"),
)
.unwrap();
assert_eq!(store.haves([0; 16], [0xe8; 16], 101).len(), 50);
} else {
let downloaded = peer.client.take_downloaded_messages();
if failure == 1 {
peer.client.cancel_download();
} else {
let teardown = peer.link.teardown(CloseReason::DestinationClosed).unwrap();
peer.inject(Context::LinkClose, &teardown);
}
assert!(peer.client.received_messages.is_empty());
assert_eq!(downloaded_bytes(&downloaded), messages);
assert!(
downloaded
.iter()
.all(|item| !item.scope().transient_id.iter().all(|b| *b == 0))
);
for item in downloaded {
let (_, token) = item.into_parts();
assert!(!token.is_current());
}
peer.client.poll_admissions();
assert!(peer.client.local_messages.is_empty());
assert!(peer.client.received_ids.is_empty());
assert!(peer.client.start_download());
assert!(peer.client.take_downloaded_messages().is_empty());
}
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), messages);
assert_eq!(peer.client.unread_bytes, 0);
assert!(peer.client.start_download());
assert!(peer.client.take_received_messages().is_empty());
}
}
#[test]
fn transport_result_deadline_is_finite_and_retains_results() {
let mut peer = Peer::new();
peer.client.received_messages.push(vec![0x33; 10]);
peer.client.unread_bytes = 10;
let retained = vec![fixture_download(&peer.client, vec![0x33; 10])];
peer.client.received_ids = ids(50);
peer.client.send_purge_request();
let pending = peer.client.pending_endpoint_sends.last_mut().unwrap();
pending.queued_at = Instant::now() - Duration::from_secs(121);
pending.queued_at = ago_or_skip!(Duration::from_secs(121));
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert!(peer.client.request.is_none());
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), vec![vec![0x33; 10]]);
assert_eq!(downloaded_bytes(&retained), vec![vec![0x33; 10]]);
for item in retained {
let (_, token) = item.into_parts();
assert!(!token.is_current());
}
}
#[test]
@@ -854,7 +956,7 @@ fn packet_response_wait_begins_after_transport_admission() {
.waiting_since
.is_none()
);
peer.client.started_at = Some(Instant::now() - Duration::from_secs(600));
peer.client.started_at = Some(ago_or_skip!(Duration::from_secs(600)));
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::ListRequested);
let (id, _, _) = peer.request(true);
@@ -892,7 +994,7 @@ fn slow_segment_gets_a_fresh_proof_admission_deadline() {
peer.inject(Context::ResourceAdv, &peer.link.encrypt(&adv).unwrap());
let (context, request, _) = peer.packet();
assert_eq!(context, Context::ResourceReq);
peer.client.started_at = Some(Instant::now() - Duration::from_secs(600));
peer.client.started_at = Some(ago_or_skip!(Duration::from_secs(600)));
peer.client
.request
.as_mut()
@@ -900,7 +1002,7 @@ fn slow_segment_gets_a_fresh_proof_admission_deadline() {
.response
.as_mut()
.unwrap()
.waiting_since = Instant::now() - Duration::from_secs(600);
.waiting_since = ago_or_skip!(Duration::from_secs(600));
for action in sender.handle_request(&peer.link.decrypt(&request).unwrap()) {
let TransferAction::SendPart(_, data) = action else {
panic!()
@@ -924,7 +1026,7 @@ fn slow_segment_gets_a_fresh_proof_admission_deadline() {
let (context, proof, _) = peer.packet();
assert_eq!(context, Context::ResourcePrf);
assert!(sender.handle_proof(&proof));
assert_eq!(peer.client.received_messages, messages);
assert_eq!(downloaded_bytes(&peer.client.received_messages), messages);
}
#[test]
@@ -934,6 +1036,7 @@ fn response_resource_before_request_proof_retires_only_its_sender() {
peer.client.send_get_request();
let (id, _, proof) = peer.request(false);
peer.response(id, binary_list(&blobs(50)), true);
peer.accept_downloads();
let successor = peer.client.request.as_ref().unwrap().id;
let generation = peer.client.request.as_ref().unwrap().generation;
peer.inject(Context::ResourcePrf, &proof.unwrap());
@@ -942,11 +1045,11 @@ fn response_resource_before_request_proof_retires_only_its_sender() {
let (id, _, _) = peer.request(true);
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.received_count(), 50);
assert_eq!(peer.admitted.len(), 50);
}
#[test]
fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
fn full_then_closed_transport_fails_request_without_releasing_external_payload() {
let mut peer = Peer::new();
while peer
.client
@@ -954,8 +1057,7 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
.try_send(TransportMessage::DeregisterDestination { hash: [0; 16] })
.is_ok()
{}
peer.client.received_messages.push(vec![1; 12]);
peer.client.unread_bytes = 12;
let retained = vec![fixture_download(&peer.client, vec![1; 12])];
peer.client.received_ids = ids(50);
peer.client.send_purge_request();
assert_eq!(peer.client.pending_transport.len(), 1);
@@ -964,5 +1066,322 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert!(peer.client.request.is_none());
assert_eq!(peer.client.take_received_messages(), vec![vec![1; 12]]);
assert_eq!(downloaded_bytes(&retained), vec![vec![1; 12]]);
}
#[test]
fn expired_durable_haves_are_downloaded_instead_of_purged() {
use crate::admission::DurableHave;
let mut peer = Peer::new();
let expired = [0x81; 32];
let visible = [0x82; 32];
peer.client.replace_durable_haves([
DurableHave {
transient_id: expired,
expires_at: Some(0),
},
DurableHave {
transient_id: visible,
expires_at: None,
},
]);
peer.client.available_messages = vec![expired.to_vec(), visible.to_vec()];
peer.client.send_get_request();
let (_, request, _) = peer.request(true);
assert_eq!(
request,
Value::Array(vec![
binary_list(&[expired.to_vec()]),
binary_list(&[visible.to_vec()]),
Value::F64(1000.0),
])
);
assert!(!peer.client.local_messages.contains(expired.as_slice()));
}
#[test]
fn expiry_preserves_the_counted_request_and_prunes_the_next_purge() {
use crate::admission::DurableHave;
let mut peer = Peer::new();
let all = ids(MAX_DOWNLOAD_ITEMS + 1);
let expires_later: [u8; 32] = all.last().unwrap().as_slice().try_into().unwrap();
peer.client
.replace_durable_haves(all.iter().map(|id| DurableHave {
transient_id: id.as_slice().try_into().unwrap(),
expires_at: None,
}));
peer.client.available_messages = all.clone();
peer.client.send_get_request();
let (id, request, _) = peer.request(true);
assert_eq!(
request.as_array().unwrap()[1].as_array().unwrap().len(),
MAX_DOWNLOAD_ITEMS
);
assert!(matches!(
peer.client.request.as_ref().unwrap().kind,
RequestKind::Haves(MAX_DOWNLOAD_ITEMS)
));
peer.client
.local_message_expiry
.insert(expires_later.to_vec(), 1);
peer.client.prune_expired_haves(1);
// The in-flight response still accounts for exactly its original prefix.
assert_eq!(
peer.client
.pending_haves
.iter()
.cloned()
.collect::<Vec<_>>(),
all
);
assert!(
!peer
.client
.local_messages
.contains(expires_later.as_slice())
);
peer.response(id, empty(), false);
assert!(peer.client.pending_haves.is_empty());
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert!(
peer.rx.is_empty(),
"expired tail must not produce another purge"
);
// Fresh accepted receipts use the same last-moment check before purge.
peer.client.received_ids = vec![expires_later.to_vec()];
peer.client.send_next_chunk();
assert!(peer.client.received_ids.is_empty());
assert!(peer.rx.is_empty());
}
#[test]
fn discard_receipts_expire_after_ninety_days_and_visible_receipts_do_not() {
use crate::admission::{AdmissionRecord, AdmissionScope, DurableDisposition, DurableHave};
for disposition in [
DurableDisposition::Committed,
DurableDisposition::Duplicate,
DurableDisposition::PolicyDiscard,
DurableDisposition::UserDeleted,
] {
let record = AdmissionRecord {
scope: AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [3; 32],
},
message_id: [4; 32],
received_wire_hash: [5; 32],
stored_message_wire_hash: None,
disposition,
committed_at: 100,
};
let have = DurableHave::from_record(&record);
if matches!(
disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) {
assert_eq!(have.expires_at, Some(100 + 90 * 86400));
assert!(have.active(100 + 90 * 86400 - 1));
assert!(!have.active(100 + 90 * 86400));
} else {
assert_eq!(have.expires_at, None);
assert!(have.active(u64::MAX));
}
}
}
#[test]
fn stale_suppression_checkpoint_cannot_acknowledge_newer_pruning_or_epochs() {
use crate::admission::{AdmissionEpochs, AdmissionScope, SuppressionLedger, SuppressionReason};
for expired in [true, false] {
let mut peer = Peer::new();
let mut ledger = SuppressionLedger::default();
let epochs = AdmissionEpochs::default();
let at = if expired { 0 } else { crate::now_f64() as u64 };
ledger
.record_failure(
AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [3; 32],
},
SuppressionReason::InvalidStamp,
epochs,
at,
)
.unwrap();
peer.client.set_suppression_ledger(ledger, epochs);
let checkpoint = peer.client.suppression_revision();
if expired {
peer.client.prune_suppression();
} else {
peer.client.update_admission_epochs(AdmissionEpochs {
policy: [1; 32],
..epochs
});
}
peer.client.suppression_persist_failed = true;
assert_eq!(peer.client.suppression_ledger().records().count(), 0);
assert_ne!(peer.client.suppression_revision(), checkpoint);
assert!(!peer.client.acknowledge_suppression_persistence(checkpoint));
assert!(peer.client.suppression_persistence_pending());
assert!(peer.client.suppression_persist_failed);
assert!(
peer.client
.acknowledge_suppression_persistence(peer.client.suppression_revision())
);
assert!(!peer.client.suppression_persistence_pending());
assert!(!peer.client.suppression_persist_failed);
assert_eq!(peer.client.suppression_ledger().records().count(), 0);
}
}
#[test]
fn rejected_downloads_never_become_local_haves_and_only_definitive_ones_are_purged() {
use crate::admission::{DownloadAdmissionOutcome, SuppressionReason};
let mut peer = Peer::new();
let messages = blobs(2);
peer.client.available_messages = ids(2);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&messages), false);
for (item, reason) in peer.client.take_downloaded_messages().into_iter().zip([
SuppressionReason::InvalidSignature,
SuppressionReason::MissingKey,
]) {
let (_, token) = item.into_parts();
token
.resolve(DownloadAdmissionOutcome::Rejected(reason))
.unwrap();
}
peer.client.poll_admissions();
let counts = peer.client.transfer_status().admission;
assert_eq!(counts.downloaded, 2);
assert_eq!(counts.rejected, 2);
assert_eq!(counts.retryable, 1);
assert_eq!(
counts.committed + counts.duplicate + counts.policy_discarded + counts.user_deleted,
0
);
assert!(peer.client.local_messages.is_empty());
assert!(peer.client.received_ids.is_empty());
// LXMRouter.message_get_response purges every downloaded message; the one
// refused for a passing local reason (a missing key) stays on the node.
let (id, body, _) = peer.request(true);
assert_eq!(
body,
Value::Array(vec![Value::Nil, binary_list(&ids(2)[..1])])
);
peer.response(id, empty(), false);
let revision = peer.client.suppression_revision();
assert!(peer.client.acknowledge_suppression_persistence(revision));
peer.client.poll_admissions();
assert_eq!(peer.client.state(), PropagationClientState::Partial);
assert_eq!(peer.client.transfer_status().result, Some(2));
}
#[test]
fn node_error_codes_end_list_and_get_in_their_own_states() {
for (code, state) in [
(0xf0, PropagationClientState::NoIdentityReceived),
(0xf1, PropagationClientState::NoAccess),
] {
for get in [false, true] {
let mut peer = Peer::new();
if get {
peer.client.available_messages = ids(1);
peer.client.send_get_request();
} else {
peer.client.send_list_request();
}
let (id, _, _) = peer.request(true);
peer.response(id, Value::from(code), false);
assert_eq!(peer.client.state(), state);
assert!(peer.client.link.is_none(), "the Link is torn down");
assert!(peer.client.take_downloaded_messages().is_empty());
assert!(peer.client.acknowledge_transfer());
}
}
}
#[test]
fn changing_the_node_tears_down_the_link_to_the_previous_one() {
let mut peer = Peer::new();
peer.client.set_propagation_node([0xe8; 16]);
assert!(peer.client.link.is_some(), "same node keeps the Link");
peer.client.send_list_request();
let _ = peer.request(true);
peer.client.set_propagation_node([0xe9; 16]);
assert!(peer.client.link.is_none());
assert_eq!(peer.client.state(), PropagationClientState::TransferFailed);
assert!(peer.client.acknowledge_transfer());
}
#[test]
fn completed_sync_keeps_the_link_and_the_next_sync_reuses_it() {
let mut peer = Peer::new();
peer.client.link.as_mut().unwrap().state = LinkState::Active;
peer.client.send_list_request();
let (id, _, _) = peer.request(true);
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert!(peer.client.acknowledge_transfer());
assert!(peer.client.link.is_some(), "acknowledgement keeps the Link");
assert!(peer.client.start_download());
assert_eq!(peer.client.state(), PropagationClientState::LinkEstablished);
peer.client.tick();
let (_, body, _) = peer.request(true);
assert_eq!(body, Value::Array(vec![Value::Nil, Value::Nil]));
}
#[test]
fn response_resource_starts_from_link_facts_with_any_segment_count() {
let mut peer = Peer::new();
peer.client.received_ids = ids(12);
peer.client.send_purge_request();
let (id, _, _) = peer.request(true);
peer.client.last_inbound_resource = Some((7, Some(1234.0)));
let mut sender = OutboundTransfer::new_encrypted(
Link::pack_response(&id, &[0x90]).unwrap(),
false,
Duration::from_millis(10),
peer.link.session_keys().unwrap(),
)
.unwrap();
sender.resource.flags.is_response = true;
sender.resource.request_id = Some(id.to_vec());
let TransferAction::SendAdvertisement(bytes) = sender.tick() else {
panic!()
};
let mut adv = ResourceAdvertisement::unpack(&bytes).unwrap();
// Resource.py has no segment limit.
adv.flags.split = true;
adv.total_segments = 1000;
adv.original_hash = [0x72; 32];
peer.inject(
Context::ResourceAdv,
&peer.link.encrypt(&adv.pack()).unwrap(),
);
assert_eq!(peer.client.state(), PropagationClientState::Receiving);
let inbound = &peer.client.inbound_resources[&adv.resource_hash];
let link = peer.client.link.as_ref().unwrap();
assert_eq!(inbound.establishment_cost, link.establishment_cost);
assert_eq!(inbound.resource.window.window, 7);
assert_eq!(inbound.previous_eifr, Some(1234.0));
}
#[test]
fn link_data_but_not_keepalives_refreshes_last_data() {
let mut peer = Peer::new();
let past = Instant::now() - Duration::from_secs(60);
peer.client.link.as_mut().unwrap().keepalive.last_data = past;
peer.inject(
Context::Keepalive,
&[rns_link::constants::KEEPALIVE_RESPONSE],
);
assert!(peer.client.link.as_ref().unwrap().no_data_for() >= Duration::from_secs(59));
let payload = peer.link.encrypt(b"data").unwrap();
peer.inject(Context::None, &payload);
assert!(peer.client.link.as_ref().unwrap().no_data_for() < Duration::from_secs(5));
}
File diff suppressed because it is too large. Load diff
+30 -11
View File
@@ -13,7 +13,10 @@ use crate::types::PropagationTransientId;
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
/// A peering-key-validated offer and the subset not present in local storage.
/// 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)]
pub enum PnOfferEvaluation {
HaveAll,
@@ -76,7 +79,7 @@ pub(crate) fn evaluate<F>(
request_data: &[u8],
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: u8,
peering_cost: f64,
max_offer_size: usize,
contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
@@ -97,14 +100,14 @@ pub(crate) fn evaluate_decoded<F>(
offer: DecodedOffer,
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: u8,
peering_cost: f64,
mut contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
where
F: FnMut(&PropagationTransientId) -> bool,
{
let peering_key_valid = match offer.peering_key {
DecodedPeeringKey::Empty => peering_cost == 0,
DecodedPeeringKey::Empty => peering_cost == 0.0,
DecodedPeeringKey::Key(key) => {
let mut peering_id = [0u8; 32];
peering_id[..16].copy_from_slice(local_identity_hash);
@@ -238,7 +241,7 @@ mod tests {
for request in malformed {
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
@@ -246,7 +249,7 @@ mod tests {
let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![]));
trailing.push(0xc0);
assert_eq!(
evaluate(&trailing, &[1; 16], &[2; 16], 0, 1024, |_| false),
evaluate(&trailing, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
@@ -255,7 +258,7 @@ mod tests {
fn decode_rejects_requests_over_the_bounded_sync_budget() {
let request = vec![0xc0; 65];
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 64, |_| false),
evaluate(&request, &[1; 16], &[2; 16], 0.0, 64, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
@@ -268,11 +271,27 @@ mod tests {
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false),
evaluate(&request, &[1; 16], &[2; 16], 0.0, usize::MAX, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn a_non_expanded_peering_key_is_accepted() {
// Upstream LXMF 1.3.1 `validate_peering_key` accepts this key at cost 8
// for the peering id `[0x11; 16] || [0x22; 16]`.
let key = hex::decode("d63d05f5dbe354b33213745d275a343924b38da05098d2b7cbc521ca4ff103d1")
.unwrap();
let request = encode_offer(
Value::Binary(key),
Value::Array(vec![Value::Binary(id(3).to_vec())]),
);
assert_eq!(
evaluate(&request, &[0x11; 16], &[0x22; 16], 8.0, 1024, |_| false),
Ok(PnOfferEvaluation::WantAll)
);
}
#[test]
fn empty_key_is_valid_only_when_peering_work_is_disabled() {
let request = encode_offer(
@@ -280,11 +299,11 @@ mod tests {
Value::Array(vec![Value::Binary(id(3).to_vec())]),
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Ok(PnOfferEvaluation::WantAll)
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false),
evaluate(&request, &[1; 16], &[2; 16], 1.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidKey)
);
}
@@ -302,7 +321,7 @@ mod tests {
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]),
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |id| *id == [1; 32]),
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
);
}
+416
View File
@@ -0,0 +1,416 @@
//! Shared propagation preparation for daemon and embedding applications.
use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN;
use crate::message::{LxMessage, MessageError};
use crate::stamper::StampControl;
use bytes::Bytes;
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct AdvertisedNodePolicy {
/// Announced propagation stamp cost; generation clamps it to `0..=100`.
pub stamp_cost: f64,
pub transfer_limit_kb: f64,
pub recorded_at: f64,
}
impl AdvertisedNodePolicy {
/// The policy in a propagation node's announce `app_data`, heard at Unix
/// time `heard_at`; `None` when Python `pn_announce_data_is_valid` refuses
/// the data. The cost is the one a sender stamps to
/// (`LXMRouter.get_outbound_propagation_cost`): slot 7's when present, else
/// slot 5's as announced. The transfer limit is whole kilobytes, as the
/// announce handler reads it (Handlers.py).
pub fn from_announce(app_data: &[u8], heard_at: f64) -> Option<Self> {
let announced = crate::handlers::parse_pn_announce_data(app_data)?;
Some(Self {
stamp_cost: crate::handlers::pn_stamp_cost_from_app_data(app_data)?,
transfer_limit_kb: announced.transfer_limit.as_f64().trunc(),
recorded_at: heard_at,
})
}
}
/// Which recipient key material an envelope's ciphertext was made for. A
/// sender compares it to learn that the recipient's key or ratchet changed and
/// the message has to be encrypted again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EncryptionBinding([u8; 32]);
impl EncryptionBinding {
/// The binding for a recipient's 64-byte public key and the ratchet the
/// message is encrypted to, if any.
pub fn for_recipient(public_key: &[u8; 64], ratchet: Option<&[u8; 32]>) -> Self {
let mut material = [0u8; 96];
material[..64].copy_from_slice(public_key);
let len = match ratchet {
Some(ratchet) => {
material[64..].copy_from_slice(ratchet);
96
}
None => 64,
};
Self(rns_crypto::sha::full_hash(&material[..len]))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingPropagationInput {
NodeIdentity,
NodePath,
NodePolicy,
RecipientIdentity,
}
#[derive(Debug, Clone, Copy)]
pub struct PreparedNode {
pub node: [u8; 16],
pub policy: AdvertisedNodePolicy,
}
/// Check the node identity, node path, advertised policy and recipient key.
/// 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(
node: [u8; 16],
node_identity_known: bool,
node_path_known: bool,
policy: Option<AdvertisedNodePolicy>,
recipient_identity_known: bool,
now: f64,
) -> Result<PreparedNode, MissingPropagationInput> {
if !node_identity_known {
return Err(MissingPropagationInput::NodeIdentity);
}
if !node_path_known {
return Err(MissingPropagationInput::NodePath);
}
let policy = policy
.filter(|p| {
p.recorded_at.is_finite()
&& p.recorded_at <= now
&& now - p.recorded_at < NODE_METADATA_MAX_AGE
&& p.transfer_limit_kb.is_finite()
&& p.transfer_limit_kb >= 0.
})
.ok_or(MissingPropagationInput::NodePolicy)?;
if !recipient_identity_known {
return Err(MissingPropagationInput::RecipientIdentity);
}
Ok(PreparedNode { node, policy })
}
/// One send-owned encryption result. Retrying changes the outer timestamp and,
/// if the saved stamp no longer meets the node's cost, regenerates the PN stamp.
/// Ciphertext and transient ID stay fixed.
#[derive(Debug, Clone)]
pub struct PropagationEnvelope {
message: LxMessage,
ciphertext: Bytes,
transient_id: [u8; 32],
encryption_binding: EncryptionBinding,
stamp: [u8; 32],
stamp_value: f64,
required_cost: f64,
}
/// Python `get_outbound_propagation_cost` clamps the node's cost into `0..=100`.
fn outbound_pn_cost(cost: f64) -> f64 {
cost.clamp(0.0, crate::stamper::STAMP_COST_CAP)
}
fn generate_pn_stamp(
transient_id: &[u8; 32],
cost: f64,
ctl: &StampControl,
) -> Result<([u8; 32], f64), MessageError> {
crate::stamper::generate_stamp(
transient_id,
outbound_pn_cost(cost),
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
ctl,
)
.map_err(|e| MessageError::PackFailed(format!("PN stamp generation failed: {e}")))?
.ok_or_else(|| MessageError::PackFailed("PN stamp generation cancelled".into()))
}
impl PropagationEnvelope {
pub fn new<F>(
message: LxMessage,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
Self::new_cancellable(
message,
encryption_binding,
required_cost,
encrypt,
&StampControl::default(),
)
}
pub fn new_cancellable<F>(
message: LxMessage,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
ctl: &StampControl,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
let encrypted = encrypt(&message.wire_bytes()[16..])?;
let mut ciphertext = Vec::with_capacity(16 + encrypted.len());
ciphertext.extend_from_slice(&message.destination_hash());
ciphertext.extend_from_slice(&encrypted);
let transient_id = rns_crypto::sha::full_hash(&ciphertext);
let (stamp, stamp_value) = generate_pn_stamp(&transient_id, required_cost, ctl)?;
Ok(Self {
message,
ciphertext: ciphertext.into(),
transient_id,
encryption_binding,
stamp,
stamp_value,
required_cost,
})
}
pub fn message(&self) -> &LxMessage {
&self.message
}
pub fn transient_id(&self) -> [u8; 32] {
self.transient_id
}
pub fn ciphertext(&self) -> &Bytes {
&self.ciphertext
}
pub fn stamp(&self) -> &[u8; 32] {
&self.stamp
}
pub fn stamp_value(&self) -> f64 {
self.stamp_value
}
/// Whether the saved stamp already meets a node's announced cost.
pub fn meets(&self, cost: f64) -> bool {
crate::stamper::value_meets(self.stamp_value, outbound_pn_cost(cost))
}
pub fn matches(&self, message: &LxMessage, encryption_binding: &EncryptionBinding) -> bool {
self.message.wire_bytes() == message.wire_bytes()
&& &self.encryption_binding == encryption_binding
}
/// 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(
&mut self,
node: PreparedNode,
timestamp: f64,
) -> Result<Vec<u8>, MessageError> {
self.pack_for_cancellable(node, timestamp, &StampControl::default())
}
pub fn pack_for_cancellable(
&mut self,
node: PreparedNode,
timestamp: f64,
ctl: &StampControl,
) -> Result<Vec<u8>, MessageError> {
if !timestamp.is_finite() {
return Err(MessageError::PackFailed(
"propagation timestamp must be finite".into(),
));
}
if !self.meets(node.policy.stamp_cost) {
(self.stamp, self.stamp_value) =
generate_pn_stamp(&self.transient_id, node.policy.stamp_cost, ctl)?;
}
self.required_cost = node.policy.stamp_cost;
let blob_len = self
.ciphertext
.len()
.checked_add(32)
.ok_or_else(|| MessageError::PackFailed("PN envelope size overflow".into()))?;
let bin_header = if blob_len < 256 {
2
} else if blob_len < 65536 {
3
} else {
5
};
let packed_len = blob_len
.checked_add(11 + bin_header)
.ok_or_else(|| MessageError::PackFailed("PN wrapper size overflow".into()))?;
let limit = (node.policy.transfer_limit_kb * 1000.).floor();
if packed_len as f64 > limit {
return Err(MessageError::TooLarge {
size: packed_len,
limit: limit as usize,
});
}
let mut out = Vec::with_capacity(packed_len);
rmp::encode::write_array_len(&mut out, 2).expect("Vec writer");
rmp::encode::write_f64(&mut out, timestamp).expect("Vec writer");
rmp::encode::write_array_len(&mut out, 1).expect("Vec writer");
rmp::encode::write_bin_len(
&mut out,
u32::try_from(blob_len)
.map_err(|_| MessageError::PackFailed("PN blob too large".into()))?,
)
.expect("Vec writer");
out.extend_from_slice(&self.ciphertext);
out.extend_from_slice(&self.stamp);
debug_assert_eq!(out.len(), packed_len);
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::DeliveryMethod;
use crate::message::LxMessageDraft;
#[test]
fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() {
let policy = AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
assert!(propagation_readiness([1; 16], true, true, Some(policy), true, 101.).is_ok());
assert_eq!(
propagation_readiness([1; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert_eq!(
propagation_readiness([1; 16], true, true, Some(policy), false, 101.).unwrap_err(),
MissingPropagationInput::RecipientIdentity
);
}
#[test]
fn retry_and_cost_increase_keep_ciphertext_and_transient_id() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[3; 32]);
let msg = LxMessageDraft::new([1; 16], [2; 16], "", "test", DeliveryMethod::Propagated)
.unwrap()
.sign(&key)
.unwrap()
.finalize(None)
.unwrap();
let binding = EncryptionBinding::for_recipient(&[4; 64], None);
let mut envelope = PropagationEnvelope::new(msg, binding, 0.0, |p| Ok(p.to_vec())).unwrap();
let before = envelope.ciphertext.clone();
let tid = envelope.transient_id();
assert_eq!(
envelope.stamp_value(),
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp(),
)
);
let mut prepared = PreparedNode {
node: [5; 16],
policy: AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
},
};
let first = envelope.pack_for(prepared, 101.).unwrap();
prepared.policy.stamp_cost = 4.5;
let next = envelope.pack_for(prepared, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &before);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4.5);
assert_ne!(first, next);
assert!(
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp()
) >= 4.5
);
}
/// A node announce as Python packs it; `fractional` adds the transitional slot 7.
fn announce(
limit: rmpv::Value,
slot5: [rmpv::Value; 3],
fractional: Option<[f64; 3]>,
) -> Vec<u8> {
use rmpv::Value;
let mut slots = vec![
Value::Boolean(false),
Value::from(1_700_000_000i64),
Value::Boolean(true),
limit,
Value::from(10240),
Value::Array(slot5.to_vec()),
Value::Map(Vec::new()),
];
if let Some(costs) = fractional {
slots.push(Value::Array(costs.map(Value::F64).to_vec()));
}
crate::encode_value(&Value::Array(slots))
}
#[test]
fn announce_policy_takes_the_cost_a_sender_stamps_to_and_whole_kilobytes() {
use rmpv::Value;
let ints = [Value::from(14), Value::from(3), Value::from(18)];
// Slot 7 wins over slot 5's rounded-up costs.
let policy = AdvertisedNodePolicy::from_announce(
&announce(Value::from(256), ints.clone(), Some([13.5, 3.0, 18.0])),
100.,
)
.unwrap();
assert_eq!(
(
policy.stamp_cost,
policy.transfer_limit_kb,
policy.recorded_at
),
(13.5, 256., 100.)
);
// Without slot 7, slot 5's cost is taken as announced, not through int().
let floats = [Value::F64(13.5), Value::F64(3.0), Value::F64(18.0)];
let policy =
AdvertisedNodePolicy::from_announce(&announce(Value::F64(256.9), floats, None), 100.)
.unwrap();
assert_eq!((policy.stamp_cost, policy.transfer_limit_kb), (13.5, 256.));
let policy =
AdvertisedNodePolicy::from_announce(&announce(Value::from(256), ints, None), 100.)
.unwrap();
assert_eq!(policy.stamp_cost, 14.);
// What `get_propagation_node_app_data` packs reads back the same way.
let node =
crate::handlers::PropagationNodeAnnounceData::new(true, 1024, 2048, 23.25, 3., 0.);
let policy = AdvertisedNodePolicy::from_announce(
&crate::handlers::get_propagation_node_app_data(&node),
5.,
)
.unwrap();
assert_eq!(
(policy.stamp_cost, policy.transfer_limit_kb),
(23.25, 1024.)
);
assert!(AdvertisedNodePolicy::from_announce(b"not an announce", 100.).is_none());
assert!(AdvertisedNodePolicy::from_announce(&[], 100.).is_none());
}
#[test]
fn encryption_binding_is_the_hash_of_the_key_then_the_ratchet() {
let (key, ratchet) = ([7u8; 64], [9u8; 32]);
assert_eq!(
EncryptionBinding::for_recipient(&key, None).0,
rns_crypto::sha::full_hash(&key)
);
let mut both = key.to_vec();
both.extend_from_slice(&ratchet);
assert_eq!(
EncryptionBinding::for_recipient(&key, Some(&ratchet)).0,
rns_crypto::sha::full_hash(&both)
);
assert_ne!(
EncryptionBinding::for_recipient(&key, None),
EncryptionBinding::for_recipient(&key, Some(&ratchet))
);
}
}
@@ -0,0 +1,479 @@
//! Provenance-gated relay storage and conservative offline migration.
//!
//! Private local manifests record accepted opaque ingress. They are not an
//! encryption oracle, and old files acquire no authority from their names or
//! apparent envelope shape. Callers exclude external writers from these paths.
#[cfg(target_os = "android")]
mod android_container;
mod migration;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod mobile;
#[cfg(target_os = "android")]
pub use mobile::begin_android_container_migration;
#[cfg(target_os = "ios")]
pub use mobile::begin_ios_container_migration;
mod offline;
mod recovery;
pub(crate) use migration::open_locked_store;
pub use migration::{
MigrationReport, QuarantineSummary, migrate_store_offline, open_store, quarantine_summary,
};
pub use offline::{OfflineMigrationGuard, begin_offline_migration};
pub use recovery::{
RecoveryEntry, RecoveryPolicy, RecoveryReport, TrustedRecoveryManifest,
import_trusted_recovery_manifest,
};
use rns_identity::persistence::{durable_reconcile, durable_remove, durable_write};
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
const TOMBSTONE: &[u8] =
b"LXMF relay store moved to v2; legacy hosting and sync must remain disabled.\n";
const FORMAT: &[u8] = b"LXMF opaque relay store v2; objects and per-entry provenance\n";
const MAX_MANIFEST_BYTES: usize = 4096;
static STORE_MUTATION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Debug, thiserror::Error)]
#[error(
"MigrationRequired: stop all legacy relay writers and run explicit offline store migration"
)]
pub struct MigrationRequired;
pub fn is_migration_required(error: &io::Error) -> bool {
error
.get_ref()
.is_some_and(|inner| inner.is::<MigrationRequired>())
}
fn err(error: impl std::fmt::Display) -> io::Error {
io::Error::other(error.to_string())
}
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
fn sibling(path: &Path, suffix: &str) -> io::Result<PathBuf> {
let mut name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?
.to_os_string();
name.push(suffix);
Ok(path.with_file_name(name))
}
fn read_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > maximum as u64 {
return Err(invalid("store record is not a bounded regular file"));
}
let mut data = Vec::new();
File::open(path)?
.take(maximum as u64 + 1)
.read_to_end(&mut data)?;
if data.len() > maximum {
return Err(invalid("store record grew beyond its bound"));
}
Ok(data)
}
fn canonical_legacy(path: &Path) -> io::Result<PathBuf> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let parent = fs::canonicalize(parent)?;
let name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?;
if name == "." || name == ".." {
return Err(invalid("invalid store path"));
}
let path = parent.join(name);
if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(invalid("store root cannot be a symbolic link"));
}
Ok(path)
}
pub(crate) fn manifest_path(path: &Path) -> PathBuf {
sibling(path, ".entry").expect("validated object path")
}
pub(crate) fn deletion_path(path: &Path) -> PathBuf {
sibling(path, ".delete").expect("validated object path")
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum OpaqueIngress {
ValidatedPropagation,
TrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum AdmissionProtocol {
StampedPropagation,
ExplicitTrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum PublicationState {
Committed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EntryManifest {
pub version: u8,
admission_id: [u8; 16],
pub transient_id: [u8; 32],
pub content_hash: [u8; 32],
pub destination: [u8; 16],
pub size: usize,
pub stamp_value: f64,
pub stored_at: f64,
pub stamped: bool,
pub origin: OpaqueIngress,
protocol: AdmissionProtocol,
publication: PublicationState,
}
impl EntryManifest {
pub(crate) fn from_entry(entry: &crate::propagation::PropagationEntry, bytes: &[u8]) -> Self {
Self {
version: 2,
admission_id: rand::random(),
transient_id: entry.transient_id,
content_hash: rns_crypto::sha::full_hash(bytes),
destination: entry.destination_hash,
size: bytes.len(),
stamp_value: entry.stamp_value,
stored_at: entry.stored_at,
stamped: entry.stamped,
origin: OpaqueIngress::ValidatedPropagation,
protocol: AdmissionProtocol::StampedPropagation,
publication: PublicationState::Committed,
}
}
pub(crate) fn validate(&self, data: &[u8]) -> bool {
let tail = if self.stamped { 32 } else { 0 };
self.version == 2
&& self.stored_at.is_finite()
&& self.stored_at >= 0.0
&& self.size <= rns_protocol::resource::MAX_RESOURCE_SIZE
&& data.len() == self.size
&& data.len() > 16 + tail
&& data[..16] == self.destination
&& rns_crypto::sha::full_hash(data) == self.content_hash
&& rns_crypto::sha::full_hash(&data[..data.len() - tail]) == self.transient_id
&& matches!(
(self.origin, self.protocol),
(
OpaqueIngress::ValidatedPropagation,
AdmissionProtocol::StampedPropagation
) | (
OpaqueIngress::TrustedRecovery,
AdmissionProtocol::ExplicitTrustedRecovery
)
)
&& (self.origin == OpaqueIngress::TrustedRecovery || self.stamped)
}
/// Relay object name. Integer values keep the form older stores wrote.
pub(crate) fn filename(&self) -> String {
format!(
"{}_{:.0}_{}_{}",
hex::encode(self.transient_id),
self.stored_at,
self.stamp_value,
hex::encode(self.admission_id)
)
}
pub(crate) fn entry(&self) -> crate::propagation::PropagationEntry {
let mut entry = crate::propagation::PropagationEntry::new(
self.transient_id,
self.transient_id,
self.destination,
self.size,
self.stamp_value,
);
entry.stored_at = self.stored_at;
entry.stamped = self.stamped;
entry
}
}
pub(crate) fn read_manifest(path: &Path) -> io::Result<(EntryManifest, Vec<u8>)> {
let encoded = read_bounded(&manifest_path(path), MAX_MANIFEST_BYTES)?;
let meta: EntryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if meta.filename() != path.file_name().and_then(|s| s.to_str()).unwrap_or("") {
return Err(invalid(
"relay object filename does not match its provenance record",
));
}
Ok((meta, encoded))
}
#[derive(Debug, Serialize, Deserialize)]
struct ActiveIndex {
version: u8,
object: String,
manifest_hash: [u8; 32],
}
fn index_path(object: &Path, id: &[u8; 32]) -> io::Result<PathBuf> {
Ok(object
.parent()
.ok_or_else(|| invalid("object has no parent"))?
.join(format!("{}.active", hex::encode(id))))
}
fn check_index(object: &Path, meta: &EntryManifest, encoded: &[u8]) -> io::Result<()> {
let index: ActiveIndex = rmp_serde::from_slice(&read_bounded(
&index_path(object, &meta.transient_id)?,
MAX_MANIFEST_BYTES,
)?)
.map_err(err)?;
if index.version != 2
|| index.object != meta.filename()
|| index.manifest_hash != rns_crypto::sha::full_hash(encoded)
{
return Err(invalid(
"object is not the active committed relay admission",
));
}
Ok(())
}
pub(crate) fn indexed_object(index_path: &Path) -> io::Result<PathBuf> {
let index: ActiveIndex =
rmp_serde::from_slice(&read_bounded(index_path, MAX_MANIFEST_BYTES)?).map_err(err)?;
if index.version != 2
|| Path::new(&index.object).components().count() != 1
|| !matches!(
Path::new(&index.object).components().next(),
Some(std::path::Component::Normal(_))
)
{
return Err(invalid("invalid relay active index"));
}
let object = index_path
.parent()
.ok_or_else(|| invalid("active index has no parent"))?
.join(index.object);
let (meta, encoded) = read_manifest(&object)?;
if self::index_path(&object, &meta.transient_id)? != index_path {
return Err(invalid("relay index TID mismatch"));
}
check_index(&object, &meta, &encoded)?;
Ok(object)
}
/// Publish object, provenance, then its per-TID commit index. A cancelled
/// in-memory callback cannot cause retry to replace the first committed image.
pub(crate) fn publish_object(
object: &Path,
meta: &EntryManifest,
data: &[u8],
) -> io::Result<(EntryManifest, PathBuf)> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let index = index_path(object, &meta.transient_id)?;
match fs::symlink_metadata(&index) {
Ok(_) => {
let existing = indexed_object(&index)?;
let (first, encoded) = read_manifest(&existing)?;
let retained = read_validated_file(&existing)?;
durable_reconcile(&existing, &retained).map_err(err)?;
durable_reconcile(&manifest_path(&existing), &encoded).map_err(err)?;
let index_bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &index_bytes).map_err(err)?;
return Ok((first, existing));
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if !meta.validate(data)
|| object.file_name().and_then(|s| s.to_str()) != Some(meta.filename().as_str())
{
return Err(invalid("invalid relay publication"));
}
let encoded = rmp_serde::to_vec_named(meta).map_err(err)?;
durable_write(object, data).map_err(err)?;
durable_write(&manifest_path(object), &encoded).map_err(err)?;
let active = ActiveIndex {
version: 2,
object: meta.filename(),
manifest_hash: rns_crypto::sha::full_hash(&encoded),
};
durable_write(&index, &rmp_serde::to_vec_named(&active).map_err(err)?).map_err(err)?;
Ok((meta.clone(), object.to_owned()))
}
/// Verify the complete indexed admission and renew all three publication
/// barriers. Serialize against retirement so successful return has a concrete
/// committed point, even when a purge was prepared concurrently.
pub(crate) fn verify_committed_object(path: &Path) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let (meta, encoded) = read_manifest(path)?;
let data = read_validated_file(path)?;
durable_reconcile(path, &data).map_err(err)?;
durable_reconcile(&manifest_path(path), &encoded).map_err(err)?;
let index = index_path(path, &meta.transient_id)?;
let bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &bytes).map_err(err)?;
check_index(path, &meta, &encoded)
}
/// Startup check for an indexed record: readable, committed size and
/// destination prefix. Publication completed its barriers before any proof,
/// duplicates renew them, and every read revalidates the body, so restart must
/// not reread and re-flush the whole store.
pub(crate) fn check_committed_on_load(path: &Path, meta: &EntryManifest) -> io::Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.len() != meta.size as u64 {
return Err(invalid("relay object does not match its committed size"));
}
let mut destination = [0u8; 16];
File::open(path)?.read_exact(&mut destination)?;
if destination != meta.destination {
return Err(invalid(
"relay object does not match its committed destination",
));
}
Ok(())
}
/// Both the manifest and complete bytes are checked at the final read boundary.
/// An unresolved durable deletion always defeats a previously prepared read.
pub(crate) fn read_validated_file(path: &Path) -> io::Result<Vec<u8>> {
read_validated_file_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)
}
/// Refuse oversized metadata before allocating or opening the payload. The
/// caller can therefore reserve its complete GET response budget first.
pub(crate) fn read_validated_file_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object has a pending durable deletion"));
}
let (meta, encoded) = read_manifest(path)?;
check_index(path, &meta, &encoded)?;
if meta.size > maximum.min(rns_protocol::resource::MAX_RESOURCE_SIZE) {
return Err(invalid("relay object exceeds Resource capacity"));
}
let data = read_bounded(path, meta.size)?;
if !meta.validate(&data) {
return Err(invalid("relay object changed after validated admission"));
}
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object retired while being read"));
}
check_index(path, &meta, &encoded)?;
Ok(data)
}
#[derive(Debug, Serialize, Deserialize)]
struct DeletionRecord {
version: u8,
object: String,
content_hash: [u8; 32],
transient_id: [u8; 32],
}
/// The durable deletion intent is committed before either indexed file is
/// removed. Keep it across every uncertain cleanup; startup resumes cleanup
/// before loading any active objects.
pub(crate) fn retire_object(path: &Path) -> io::Result<()> {
retire_object_inner(path, false)
}
fn retire_object_inner(path: &Path, fail_after_intent: bool) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let marker = deletion_path(path);
let encoded = match read_bounded(&marker, MAX_MANIFEST_BYTES) {
Ok(encoded) => encoded,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (meta, _) = read_manifest(path)?;
let record = DeletionRecord {
version: 2,
object: path
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| invalid("invalid object name"))?
.to_string(),
content_hash: meta.content_hash,
transient_id: meta.transient_id,
};
rmp_serde::to_vec_named(&record).map_err(err)?
}
Err(e) => return Err(e),
};
let record: DeletionRecord = rmp_serde::from_slice(&encoded).map_err(err)?;
if record.version != 2
|| Path::new(&record.object).components().count() != 1
|| path.file_name().and_then(|s| s.to_str()) != Some(&record.object)
{
return Err(invalid("deletion record path mismatch"));
}
let witness = durable_write(&marker, &encoded).map_err(err)?;
if fail_after_intent {
return Err(io::Error::other(
"injected interruption after durable deletion intent",
));
}
let cleanup = (|| -> io::Result<()> {
let index = index_path(path, &record.transient_id)?;
if let Ok(active) = indexed_object(&index)
&& active == path
{
durable_remove(&index, &witness).map_err(err)?;
}
durable_remove(path, &witness).map_err(err)?;
durable_remove(&manifest_path(path), &witness).map_err(err)?;
// A separate, retained FORMAT witness may retire the journal only once both
// removals have acknowledged barriers. Failure leaves the journal reusable.
let root = path
.parent()
.and_then(Path::parent)
.ok_or_else(|| invalid("object outside v2 objects directory"))?;
let format = durable_reconcile(&root.join("FORMAT"), FORMAT).map_err(err)?;
durable_remove(&marker, &format).map_err(err)?;
Ok(())
})();
if let Err(error) = cleanup {
tracing::warn!(%error, "committed relay deletion retains pending cleanup evidence");
}
Ok(())
}
pub(crate) fn reconcile_deletions(root: &Path) -> io::Result<()> {
for entry in fs::read_dir(root.join("objects"))? {
let path = entry?.path();
if path.extension().and_then(|s| s.to_str()) != Some("delete") {
continue;
}
let object = path.with_extension("");
retire_object(&object)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deletion_intent_survives_interruption_and_revokes_all_read_authority() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
let root = open_store(&legacy).unwrap();
let mut data = [2; 16].to_vec();
data.extend_from_slice(
&rns_identity::identity::Identity::new()
.encrypt(b"private payload", None)
.unwrap(),
);
let tid = rns_crypto::sha::full_hash(&data);
data.extend_from_slice(&[0; 32]);
let mut entry =
crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0.0);
entry.stamped = true;
let meta = EntryManifest::from_entry(&entry, &data);
let object = root.join("objects").join(meta.filename());
publish_object(&object, &meta, &data).unwrap();
assert_eq!(read_validated_file(&object).unwrap(), data);
assert!(retire_object_inner(&object, true).is_err());
assert!(object.exists());
assert!(deletion_path(&object).exists());
assert!(read_validated_file(&object).is_err());
assert!(verify_committed_object(&object).is_err());
open_store(&legacy).unwrap();
assert!(!object.exists());
assert!(!index_path(&object, &tid).unwrap().exists());
assert!(!deletion_path(&object).exists());
}
}
@@ -0,0 +1,207 @@
//! Android framework metadata, rather than process-list visibility or guessed
//! /data prefixes, establishes a single-package private-container boundary.
use super::*;
use jni::{
JNIEnv,
objects::{JObject, JString, JValue},
};
use std::os::unix::fs::MetadataExt;
fn take_string(env: &JNIEnv<'_>, value: JObject<'_>) -> io::Result<String> {
if value.is_null() {
return Err(invalid("Android application metadata is missing"));
}
let result: String = env.get_string(JString::from(value)).map_err(err)?.into();
env.delete_local_ref(value).map_err(err)?;
Ok(result)
}
pub(super) fn private_root<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
let result = private_root_inner(env, context);
// Return a Rust failure without leaving an unrelated pending Java exception
// on the embedding application's worker thread.
if result.is_err() && env.exception_check().unwrap_or(true) {
let _ = env.exception_clear();
}
result
}
fn private_root_inner<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
if context.is_null()
|| !env
.is_instance_of(context, "android/content/Context")
.map_err(err)?
{
return Err(invalid(
"an initialized Android application context is required",
));
}
let uid = env
.call_static_method("android/os/Process", "myUid", "()I", &[])
.map_err(err)?
.i()
.map_err(err)?;
if uid < 0 || uid % 100_000 < 10_000 {
return Err(invalid(
"relay recovery requires a private Android application UID",
));
}
let manager = env
.call_method(
context,
"getPackageManager",
"()Landroid/content/pm/PackageManager;",
&[],
)
.map_err(err)?
.l()
.map_err(err)?;
let packages = env
.call_method(
manager,
"getPackagesForUid",
"(I)[Ljava/lang/String;",
&[JValue::Int(uid)],
)
.map_err(err)?
.l()
.map_err(err)?;
if packages.is_null() || env.get_array_length(packages.into_inner()).map_err(err)? != 1 {
return Err(invalid(
"shared or unknown Android UID cannot authorize relay migration",
));
}
let package = take_string(
env,
env.get_object_array_element(packages.into_inner(), 0)
.map_err(err)?,
)?;
let context_package = take_string(
env,
env.call_method(context, "getPackageName", "()Ljava/lang/String;", &[])
.map_err(err)?
.l()
.map_err(err)?,
)?;
if package != context_package {
return Err(invalid("Android context does not own this application UID"));
}
let mut cmdline = Vec::new();
File::open("/proc/self/cmdline")?
.take(4097)
.read_to_end(&mut cmdline)?;
if cmdline.len() > 4096 || cmdline.split(|b| *b == 0).next() != Some(package.as_bytes()) {
return Err(invalid(
"relay migration is restricted to the default Android app process",
));
}
let package_string = env.new_string(&package).map_err(err)?;
// Resolve all four component classes, including disabled declarations. A
// secondary process can own the same private UID even if it is not running.
const FLAGS: i32 = 1 | 2 | 4 | 8 | 512;
let info = env
.call_method(
manager,
"getPackageInfo",
"(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",
&[JValue::Object(package_string.into()), JValue::Int(FLAGS)],
)
.map_err(err)?
.l()
.map_err(err)?;
if !env
.get_field(info, "sharedUserId", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?
.is_null()
{
return Err(invalid(
"sharedUserId applications cannot authorize relay migration",
));
}
let application = env
.get_field(
info,
"applicationInfo",
"Landroid/content/pm/ApplicationInfo;",
)
.map_err(err)?
.l()
.map_err(err)?;
if env
.get_field(application, "uid", "I")
.map_err(err)?
.i()
.map_err(err)?
!= uid
{
return Err(invalid("Android application UID changed"));
}
let process = take_string(
env,
env.get_field(application, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
if process != package {
return Err(invalid(
"custom Android application process is not qualified",
));
}
for (field, signature) in [
("activities", "[Landroid/content/pm/ActivityInfo;"),
("receivers", "[Landroid/content/pm/ActivityInfo;"),
("services", "[Landroid/content/pm/ServiceInfo;"),
("providers", "[Landroid/content/pm/ProviderInfo;"),
] {
let components = env
.get_field(info, field, signature)
.map_err(err)?
.l()
.map_err(err)?;
if components.is_null() {
continue;
}
let count = env.get_array_length(components.into_inner()).map_err(err)?;
if !(0..=4096).contains(&count) {
return Err(invalid(
"Android component inventory exceeds migration bound",
));
}
for index in 0..count {
let component = env
.get_object_array_element(components.into_inner(), index)
.map_err(err)?;
let process = take_string(
env,
env.get_field(component, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
env.delete_local_ref(component).map_err(err)?;
if process != package {
return Err(invalid(
"multi-process Android apps cannot authorize relay migration",
));
}
}
env.delete_local_ref(components).map_err(err)?;
}
let root = fs::canonicalize(take_string(
env,
env.get_field(application, "dataDir", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?)?;
let metadata = fs::metadata(&root)?;
if !metadata.is_dir() || metadata.uid() != uid as u32 || metadata.mode() & 0o022 != 0 {
return Err(invalid(
"Android data directory lacks exclusive application ownership",
));
}
Ok(root)
}
@@ -0,0 +1,470 @@
use super::*;
use rns_identity::persistence::{
DurableFileReceipt, durable_create_dir_all, durable_reconcile_hash, durable_rename_directory,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
const MAX_INVENTORY: usize = 65_536;
const MAX_JOURNAL: usize = 32 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(super) struct InventoryEntry {
pub path: PathBuf,
pub bytes: u64,
pub hash: Option<[u8; 32]>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MigrationJournal {
version: u8,
legacy: PathBuf,
archive: PathBuf,
v2: PathBuf,
inventory: Vec<InventoryEntry>,
had_legacy: bool,
phase: u8,
renewal: Option<PathBuf>,
renewal_sequence: u64,
}
#[derive(Debug, Clone)]
pub struct MigrationReport {
pub store: PathBuf,
pub quarantine: QuarantineSummary,
}
#[derive(Debug, Clone)]
pub struct QuarantineSummary {
pub files: usize,
pub bytes: u64,
pub reason: &'static str,
}
fn summary(j: &MigrationJournal) -> QuarantineSummary {
QuarantineSummary {
files: j.inventory.iter().filter(|e| e.hash.is_some()).count(),
bytes: j
.inventory
.iter()
.fold(0u64, |n, e| n.saturating_add(e.bytes)),
reason: "Preserved legacy files have no trusted per-entry opaque-ingress provenance",
}
}
fn encode(j: &MigrationJournal) -> io::Result<Vec<u8>> {
let encoded = rmp_serde::to_vec_named(j).map_err(err)?;
if encoded.len() > MAX_JOURNAL {
return Err(invalid("migration inventory exceeds journal bound"));
}
Ok(encoded)
}
fn paths(legacy: &Path) -> io::Result<(PathBuf, PathBuf, PathBuf)> {
Ok((
sibling(legacy, ".migration")?,
sibling(legacy, ".legacy-quarantine")?,
sibling(legacy, ".v2")?,
))
}
fn save(j: &MigrationJournal) -> io::Result<DurableFileReceipt> {
durable_write(&paths(&j.legacy)?.0, &encode(j)?).map_err(err)
}
fn read_journal(legacy: &Path) -> io::Result<MigrationJournal> {
let (path, archive, v2) = paths(legacy)?;
let j: MigrationJournal =
rmp_serde::from_slice(&read_bounded(&path, MAX_JOURNAL)?).map_err(err)?;
if j.version != 2
|| j.phase > 4
|| j.legacy != legacy
|| j.archive != archive
|| j.v2 != v2
|| j.inventory.len() > MAX_INVENTORY
{
return Err(invalid("migration journal path/version/phase mismatch"));
}
let mut unique = BTreeSet::new();
for entry in &j.inventory {
if !safe_relative(&entry.path) || !unique.insert(entry.path.clone()) {
return Err(invalid("invalid inventory path"));
}
}
if let Some(path) = &j.renewal
&& *path != sibling(&archive, &format!(".renewal-{}", j.renewal_sequence))?
{
return Err(invalid("directory renewal path mismatch"));
}
Ok(j)
}
pub fn quarantine_summary(legacy: &Path) -> io::Result<QuarantineSummary> {
Ok(summary(&read_journal(&canonical_legacy(legacy)?)?))
}
fn safe_relative(path: &Path) -> bool {
!path.as_os_str().is_empty()
&& path.as_os_str().len() <= 4096
&& path.components().count() <= 32
&& path
.components()
.all(|p| matches!(p, std::path::Component::Normal(_)))
}
fn hash_file(path: &Path) -> io::Result<(u64, [u8; 32])> {
let before = fs::symlink_metadata(path)?;
if !before.is_file() || before.file_type().is_symlink() {
return Err(invalid("legacy inventory contains a nonregular file"));
}
let mut file = File::open(path)?;
let mut hash = Sha256::new();
let mut count = 0u64;
let mut buffer = [0; 8192];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
count = count
.checked_add(n as u64)
.ok_or_else(|| invalid("legacy size overflow"))?;
hash.update(&buffer[..n]);
}
let after = file.metadata()?;
if count != before.len() || after.len() != count || before.modified()? != after.modified()? {
return Err(invalid("legacy file changed during inventory"));
}
Ok((count, hash.finalize().into()))
}
fn inventory(root: &Path) -> io::Result<Vec<InventoryEntry>> {
let metadata = fs::symlink_metadata(root)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(invalid("legacy root is not a real directory"));
}
let mut todo = vec![PathBuf::new()];
let mut result = Vec::new();
while let Some(relative) = todo.pop() {
for entry in fs::read_dir(root.join(&relative))? {
let entry = entry?;
let relative = relative.join(entry.file_name());
if !safe_relative(&relative) || result.len() >= MAX_INVENTORY {
return Err(invalid("legacy inventory exceeds safe path/count bound"));
}
let m = fs::symlink_metadata(entry.path())?;
if m.file_type().is_symlink() {
return Err(invalid(
"legacy symbolic links require explicit operator recovery",
));
}
if m.is_dir() {
result.push(InventoryEntry {
path: relative.clone(),
bytes: 0,
hash: None,
});
todo.push(relative);
} else if m.is_file() {
let (bytes, hash) = hash_file(&entry.path())?;
result.push(InventoryEntry {
path: relative,
bytes,
hash: Some(hash),
});
} else {
return Err(invalid(
"legacy special files require explicit operator recovery",
));
}
}
}
result.sort_by(|a, b| a.path.cmp(&b.path));
Ok(result)
}
fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> {
if inventory(root)? != j.inventory {
return Err(invalid(
"legacy inventory changed; preserve original and investigate before recovery",
));
}
Ok(())
}
/// Initialize a truly absent store or validate a completed v2 store. An
/// 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> {
Ok(open_locked_store(legacy)?.0)
}
pub(crate) fn open_locked_store(legacy: &Path) -> io::Result<(PathBuf, File)> {
let legacy = canonical_legacy(legacy)?;
let lock = offline::lock_store(&legacy)?;
let (journal, archive, v2) = paths(&legacy)?;
if journal.exists() {
let j = read_journal(&legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
reconcile_deletions(&v2)?;
return Ok((v2, lock));
}
if fs::symlink_metadata(&legacy).is_ok()
|| fs::symlink_metadata(&archive).is_ok()
|| fs::symlink_metadata(&v2).is_ok()
{
return Err(io::Error::other(MigrationRequired));
}
let j = MigrationJournal {
version: 2,
legacy: legacy.clone(),
archive,
v2,
inventory: Vec::new(),
had_legacy: false,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
let report = run(j, None)?;
Ok((report.store, lock))
}
fn verify_published(j: &MigrationJournal) -> io::Result<()> {
if read_bounded(&j.legacy, 256)? != TOMBSTONE
|| read_bounded(&j.v2.join("FORMAT"), 256)? != FORMAT
{
return Err(invalid("v2 format or old-path guard mismatch"));
}
let objects = fs::symlink_metadata(j.v2.join("objects"))?;
if !objects.is_dir() || objects.file_type().is_symlink() {
return Err(invalid("v2 objects directory invalid"));
}
durable_reconcile(&j.legacy, TOMBSTONE).map_err(err)?;
durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
Ok(())
}
/// Migrate the canonical path protected by the guard. Keep the constructor's
/// 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> {
migrate(&guard.legacy, None)
}
fn migrate(legacy: &Path, fault: Option<u8>) -> io::Result<MigrationReport> {
let canonical = canonical_legacy(legacy)?;
let legacy = canonical.as_path();
let (journal, archive, v2) = paths(legacy)?;
let j = if journal.exists() {
read_journal(legacy)?
} else {
if archive.exists() || v2.exists() {
return Err(invalid(
"unowned archive/v2 path already exists; refusing overwrite",
));
}
let had_legacy = fs::symlink_metadata(legacy).is_ok();
let inventory = if had_legacy {
inventory(legacy)?
} else {
Vec::new()
};
let j = MigrationJournal {
version: 2,
legacy: legacy.to_owned(),
archive,
v2,
inventory,
had_legacy,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
fail(fault, 0)?;
j
};
run(j, fault)
}
fn fail(fault: Option<u8>, stage: u8) -> io::Result<()> {
if fault == Some(stage) {
Err(io::Error::other(format!(
"injected migration boundary {stage}"
)))
} else {
Ok(())
}
}
/// Re-publish a renamed archive through two fresh sibling transitions. This is
/// valid on Windows WRITE_THROUGH and avoids pretending existing directories
/// can be acknowledged by a generic file flush. Every recovery target is journaled.
fn renew_archive(j: &mut MigrationJournal, fault: Option<u8>) -> io::Result<()> {
if let Some(temporary) = j.renewal.clone() {
match (j.archive.exists(), temporary.exists()) {
(false, true) => {
verify_inventory(&temporary, j)?;
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
return Ok(());
}
(true, false) => {
j.renewal = None;
}
_ => {
return Err(invalid(
"ambiguous archive renewal state; originals preserved",
));
}
}
}
verify_inventory(&j.archive, j)?;
j.renewal_sequence = j
.renewal_sequence
.checked_add(1)
.ok_or_else(|| invalid("renewal generation exhausted"))?;
let temporary = sibling(&j.archive, &format!(".renewal-{}", j.renewal_sequence))?;
if fs::symlink_metadata(&temporary).is_ok() {
return Err(invalid("recovery target already exists"));
}
j.renewal = Some(temporary.clone());
let witness = save(j)?;
durable_rename_directory(&j.archive, &temporary, &witness).map_err(err)?;
fail(fault, 5)?;
// Rewrite the journal after the first acknowledged move; if this write is
// uncertain the existing intent still describes both permitted locations.
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
Ok(())
}
fn run(mut j: MigrationJournal, fault: Option<u8>) -> io::Result<MigrationReport> {
if j.had_legacy {
if j.legacy.is_dir() {
if j.phase != 0 || j.archive.exists() || j.renewal.is_some() {
return Err(invalid("ambiguous legacy archive state"));
}
verify_inventory(&j.legacy, &j)?;
// Renew barriers for every retained file before its directory move.
for entry in j.inventory.iter().filter(|e| e.hash.is_some()) {
let maximum = usize::try_from(entry.bytes).map_err(err)?;
durable_reconcile_hash(&j.legacy.join(&entry.path), entry.hash.unwrap(), maximum)
.map_err(err)?;
}
let witness = save(&j)?;
durable_rename_directory(&j.legacy, &j.archive, &witness).map_err(err)?;
fail(fault, 1)?;
} else {
renew_archive(&mut j, fault)?;
}
verify_inventory(&j.archive, &j)?;
} else if j.archive.exists() || j.renewal.is_some() {
return Err(invalid("unexpected archive for a fresh store"));
}
if j.phase < 1 {
j.phase = 1;
save(&j)?;
}
match fs::symlink_metadata(&j.legacy) {
Ok(_) if read_bounded(&j.legacy, 256)? != TOMBSTONE => {
return Err(invalid("unknown old-path guard"));
}
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
durable_write(&j.legacy, TOMBSTONE).map_err(err)?;
fail(fault, 2)?;
if j.phase < 2 {
j.phase = 2;
save(&j)?;
}
let witness = save(&j)?;
durable_create_dir_all(&j.v2, &witness).map_err(err)?;
durable_create_dir_all(&j.v2.join("objects"), &witness).map_err(err)?;
durable_write(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
fail(fault, 3)?;
if j.phase < 3 {
j.phase = 3;
save(&j)?;
}
verify_published(&j)?;
j.phase = 4;
save(&j)?;
fail(fault, 4)?;
Ok(MigrationReport {
store: j.v2.clone(),
quarantine: summary(&j),
})
}
pub(super) fn verified_archive(
guard: &OfflineMigrationGuard,
) -> io::Result<(PathBuf, PathBuf, Vec<InventoryEntry>)> {
let j = read_journal(&guard.legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
verify_inventory(&j.archive, &j)?;
Ok((j.archive, j.v2, j.inventory))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn migration_preserves_inventory_and_never_promotes_legacy_bytes() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("opaque"), [3; 200]).unwrap();
fs::write(legacy.join("plaintext"), b"private message").unwrap();
assert!(is_migration_required(&open_store(&legacy).unwrap_err()));
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
b"private message"
);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert!(open_store(&legacy).is_ok());
}
#[test]
fn every_migration_and_renewal_boundary_resumes_without_losing_originals() {
for stage in 0..=6 {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"untouched").unwrap();
if stage >= 5 {
assert!(migrate(&legacy, Some(1)).is_err());
}
assert!(migrate(&legacy, Some(stage)).is_err());
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 1);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("message")
)
.unwrap(),
b"untouched"
);
assert!(open_store(&legacy).is_ok());
}
}
#[test]
fn changed_inventory_and_unowned_targets_fail_without_overwrite() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"original").unwrap();
assert!(migrate(&legacy, Some(0)).is_err());
fs::write(legacy.join("message"), b"changed").unwrap();
assert!(migrate(&legacy, None).is_err());
assert!(legacy.is_dir());
let other = temp.path().join("other");
fs::create_dir(sibling(&other, ".v2").unwrap()).unwrap();
assert!(open_store(&other).is_err());
assert!(!other.exists());
}
}
@@ -0,0 +1,167 @@
//! Restricted app-container migration authority. This is not an arbitrary-path
//! alternative to the desktop process probe. All current host workers must be
//! joined by the application before acquisition; the same v2 OS lock additionally
//! rejects live current hosts. iOS's main-app/container lifecycle excludes an
//! older installed bundle from concurrently owning this private data container.
use super::*;
fn contained_store(legacy: &Path, root: &Path) -> io::Result<PathBuf> {
let root = fs::canonicalize(root)?;
let legacy = canonical_legacy(legacy)?;
let parent = legacy
.parent()
.ok_or_else(|| invalid("store has no parent"))?;
if parent == root || !parent.starts_with(&root) {
return Err(invalid(
"relay migration requires a nested private app-container path",
));
}
Ok(legacy)
}
/// Acquire migration authority only inside the current native iOS main app's
/// private data container. App groups, extensions, external directories, and
/// command-line processes are refused. No caller-supplied root or skip flag is
/// accepted. Hold the application's identity/session lifecycle guard, stop all
/// hosted and sync writers, and join their actual workers before calling this.
#[cfg(target_os = "ios")]
pub fn begin_ios_container_migration(legacy: &Path) -> io::Result<offline::OfflineMigrationGuard> {
let root = native_ios_container()?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
/// Acquire migration authority for the platform Context's single-package,
/// single-process private Android data directory. Shared UIDs, declared remote
/// processes, mismatched contexts and external/group-writable roots are refused.
/// The caller must hold its lifecycle guard and join all hosted/sync writers;
/// the returned guard also retains the same OS lock used by current v2 hosts.
#[cfg(target_os = "android")]
pub fn begin_android_container_migration<'a>(
legacy: &Path,
env: &jni::JNIEnv<'a>,
context: jni::objects::JObject<'a>,
) -> io::Result<offline::OfflineMigrationGuard> {
let root = android_container::private_root(env, context)?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
#[cfg(target_os = "ios")]
fn native_ios_container() -> io::Result<PathBuf> {
use objc2::{
msg_send,
rc::autoreleasepool,
runtime::{AnyClass, AnyObject},
};
use std::ffi::CStr;
#[link(name = "Foundation", kind = "framework")]
unsafe extern "C" {
fn NSHomeDirectory() -> *mut AnyObject;
}
// SAFETY: both values are Foundation NSStrings, alive for the surrounding
// autorelease pool; UTF8String is copied before leaving that pool.
unsafe fn string(value: *mut AnyObject) -> io::Result<String> {
if value.is_null() {
return Err(invalid("native app-container metadata unavailable"));
}
let bytes: *const std::ffi::c_char = unsafe { msg_send![value, UTF8String] };
if bytes.is_null() {
return Err(invalid("native app-container path unavailable"));
}
unsafe { CStr::from_ptr(bytes) }
.to_str()
.map(str::to_owned)
.map_err(err)
}
autoreleasepool(|_| {
let class = AnyClass::get(c"NSBundle").ok_or_else(|| invalid("NSBundle unavailable"))?;
// SAFETY: documented synchronous Foundation getters, no ownership transfer.
let bundle: *mut AnyObject = unsafe { msg_send![class, mainBundle] };
if bundle.is_null() {
return Err(invalid("native main app bundle unavailable"));
}
let path: *mut AnyObject = unsafe { msg_send![bundle, bundlePath] };
let identifier: *mut AnyObject = unsafe { msg_send![bundle, bundleIdentifier] };
let bundle_path = PathBuf::from(unsafe { string(path)? });
if bundle_path.extension().and_then(|s| s.to_str()) != Some("app")
|| unsafe { string(identifier)? }.is_empty()
{
return Err(invalid("relay migration requires an iOS main application"));
}
let root = fs::canonicalize(unsafe { string(NSHomeDirectory())? })?;
if !ios_data_container_path(&root) {
return Err(invalid(
"native home is not a private iOS app data container",
));
}
Ok(root)
})
}
// The native home API, not this shape alone, supplies authority. Reject future
// unknown layouts instead of silently certifying a shared or group container.
#[cfg(any(target_os = "ios", test))]
fn ios_data_container_path(root: &Path) -> bool {
let Some(id) = root.file_name().and_then(|s| s.to_str()) else {
return false;
};
let valid_id = id.len() == 36
&& id.bytes().enumerate().all(|(index, byte)| {
if [8, 13, 18, 23].contains(&index) {
byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
valid_id
&& root
.parent()
.is_some_and(|p| p.ends_with("Containers/Data/Application"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_container_policy_rejects_groups_siblings_and_root_store() {
assert!(ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(ios_data_container_path(Path::new(
"/sim/device/data/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Shared/AppGroup/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Bundle/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let nested = root.join("Library/state");
fs::create_dir_all(&nested).unwrap();
assert!(contained_store(&nested.join("relay"), &root).is_ok());
assert!(contained_store(&root.join("relay"), &root).is_err());
assert!(contained_store(&temp.path().join("relay"), &root).is_err());
}
#[cfg(unix)]
#[test]
fn private_container_policy_rejects_symlink_escape() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let outside = temp.path().join("external");
fs::create_dir_all(&root).unwrap();
fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
assert!(contained_store(&root.join("escape/relay"), &root).is_err());
}
}
@@ -0,0 +1,167 @@
use super::*;
use std::process::{Command, Stdio};
/// Hold the OS lock shared with current v2 hosts during offline migration.
/// 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(super) legacy: PathBuf,
pub(super) _lock: File,
}
pub(super) fn lock_store(legacy: &Path) -> io::Result<File> {
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let path = sibling(legacy, ".store-lock")?;
if fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file() || m.file_type().is_symlink()) {
return Err(invalid("invalid relay store lock"));
}
let lock = options.open(path)?;
rns_identity::persistence::try_lock_exclusive(&lock)?;
Ok(lock)
}
/// The adapter must first stop its own hosting workers and service auto-restart.
/// This probes known app/daemon names and refuses if process enumeration fails.
/// Manually launching an old binary during migration remains unsupported.
pub fn begin_offline_migration(
legacy: &Path,
supervisor_writers_stopped: bool,
) -> io::Result<OfflineMigrationGuard> {
if !supervisor_writers_stopped {
return Err(invalid(
"stop relay writers and their service supervisors before migration",
));
}
let legacy = canonical_legacy(legacy)?;
let lock = lock_store(&legacy)?;
refuse_known_relay_processes()?;
Ok(OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
fn known_name(value: &str) -> bool {
let value = value
.trim_matches('"')
.rsplit(['/', '\\'])
.next()
.unwrap_or(value)
.to_ascii_lowercase();
matches!(
value.as_str(),
"ratspeak" | "ratspeak.exe" | "lxmd" | "lxmd.py" | "lxmd-rs" | "lxmd-rs.exe"
)
}
fn refuse_known_relay_processes() -> io::Result<()> {
#[cfg(unix)]
let mut command = {
let mut c = Command::new("ps");
c.args(["-axo", "pid=,comm=,args="]);
c
};
#[cfg(windows)]
let mut command = {
let mut c = Command::new("tasklist");
c.args(["/FO", "CSV", "/NH"]);
c
};
#[cfg(not(any(unix, windows)))]
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"process exclusion cannot be verified on this platform",
));
#[cfg(any(unix, windows))]
{
command.stdout(Stdio::piped()).stderr(Stdio::null());
let mut child = command.spawn()?;
let mut output = Vec::new();
let read = child
.stdout
.take()
.ok_or_else(|| invalid("process probe has no output"))?
.take(4 * 1024 * 1024 + 1)
.read_to_end(&mut output);
if read.is_err() || output.len() > 4 * 1024 * 1024 {
let _ = child.kill();
let _ = child.wait();
return Err(invalid("process inventory exceeds safe bound"));
}
if !child.wait()?.success() {
return Err(invalid(
"process enumeration unavailable; relay writer exclusion unverified",
));
}
let listing = std::str::from_utf8(&output).map_err(err)?;
check_listing(listing, std::process::id(), cfg!(windows))
}
}
fn check_listing(listing: &str, own_pid: u32, windows: bool) -> io::Result<()> {
for line in listing.lines().filter(|l| !l.trim().is_empty()) {
if windows {
let fields: Vec<_> = line.trim_matches('"').split("\",\"").collect();
if fields.len() < 2 {
return Err(invalid("unrecognized process inventory"));
}
let pid: u32 = fields[1].parse().map_err(err)?;
if pid != own_pid && known_name(fields[0]) {
return Err(invalid("a known relay app/daemon is still running"));
}
} else {
let mut fields = line.split_whitespace();
let pid: u32 = fields
.next()
.ok_or_else(|| invalid("missing process ID"))?
.parse()
.map_err(err)?;
let Some(comm) = fields.next() else {
return Err(invalid("missing process name"));
};
if pid == own_pid {
continue;
}
// For interpreted daemons, inspect only the executable/script prefix,
// not arbitrary argument text belonging to shells or other programs.
let python = comm
.rsplit('/')
.next()
.is_some_and(|c| c.starts_with("python"));
if known_name(comm) || (python && fields.take(3).any(known_name)) {
return Err(invalid("a known relay app/daemon is still running"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_process_probe_is_fail_closed_and_excludes_only_own_pid() {
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
8,
false
)
.is_err()
);
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
7,
false
)
.is_ok()
);
assert!(check_listing("9 python3 python3 /usr/bin/lxmd --service\n", 7, false).is_err());
assert!(check_listing("oops", 7, false).is_err());
assert!(check_listing("\"lxmd-rs.exe\",\"9\",\"Console\"", 7, true).is_err());
}
}
@@ -0,0 +1,330 @@
use super::*;
use std::collections::{HashMap, HashSet};
/// A local owner's independently verified ingress record. The approved manifest
/// digest is supplied separately by the recovery UI/CLI; a location or blanket
/// 'recover all' action is never an origin assertion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustedRecoveryManifest {
pub version: u8,
pub provenance: String,
pub entries: Vec<RecoveryEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryEntry {
pub archive_relative_path: PathBuf,
pub content_hash: [u8; 32],
pub transient_id: [u8; 32],
pub stamped: bool,
pub stored_at: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryPolicy {
pub maximum_store_bytes: usize,
pub maximum_message_bytes: usize,
pub minimum_stamp_cost: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryReport {
pub imported: usize,
pub already_present: usize,
}
fn validate(
record: &RecoveryEntry,
bytes: &[u8],
minimum_stamp_cost: f64,
) -> io::Result<EntryManifest> {
let tail = if record.stamped { 32 } else { 0 };
if bytes.len() < 112 + tail
|| !record.stored_at.is_finite()
|| record.stored_at < 0.0
|| rns_crypto::sha::full_hash(bytes) != record.content_hash
{
return Err(invalid("recovery content hash/length/time mismatch"));
}
let opaque = &bytes[..bytes.len() - tail];
if !(opaque.len() - 16 - 32 - rns_crypto::TOKEN_OVERHEAD).is_multiple_of(16)
|| rns_crypto::sha::full_hash(opaque) != record.transient_id
{
return Err(invalid("recovery envelope/TID mismatch"));
}
if crate::message::LxMessage::unpack(opaque).is_ok()
|| crate::message::LxMessage::unpack(bytes).is_ok()
{
return Err(invalid(
"raw plaintext LXMF is never eligible for relay recovery",
));
}
let stamp_value = if record.stamped {
let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().map_err(err)?;
crate::stamper::validated_stamp_value(
&record.transient_id,
stamp,
minimum_stamp_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| invalid("recovered stamp does not meet node policy"))?
} else {
if minimum_stamp_cost > 0.0 {
return Err(invalid("unstamped recovery does not meet node policy"));
}
0.0
};
let mut destination = [0; 16];
destination.copy_from_slice(&bytes[..16]);
let mut entry = crate::propagation::PropagationEntry::new(
record.transient_id,
record.transient_id,
destination,
bytes.len(),
stamp_value,
);
entry.stored_at = record.stored_at;
entry.stamped = record.stamped;
let mut manifest = EntryManifest::from_entry(&entry, bytes);
manifest.origin = OpaqueIngress::TrustedRecovery;
manifest.protocol = AdmissionProtocol::ExplicitTrustedRecovery;
Ok(manifest)
}
/// Import exact positively attested archive entries under the same offline
/// guard. Existing deletion journals are reconciled first. All selected entries
/// 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(
guard: &OfflineMigrationGuard,
path: &Path,
approved_manifest_sha256: [u8; 32],
policy: RecoveryPolicy,
) -> io::Result<RecoveryReport> {
let encoded = read_bounded(path, 32 * 1024 * 1024)?;
if rns_crypto::sha::full_hash(&encoded) != approved_manifest_sha256 {
return Err(invalid("recovery manifest changed after approval"));
}
let recovery: TrustedRecoveryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if recovery.version != 2
|| recovery.provenance.trim().is_empty()
|| recovery.provenance.len() > 4096
|| recovery.entries.len() > 65_536
{
return Err(invalid("invalid trusted recovery manifest"));
}
let (archive, root, inventory) = migration::verified_archive(guard)?;
let known: HashMap<_, _> = inventory
.into_iter()
.filter_map(|e| e.hash.map(|h| (e.path, (e.bytes, h))))
.collect();
let mut existing = HashMap::new();
let mut total = 0usize;
reconcile_deletions(&root)?;
for file in fs::read_dir(root.join("objects"))? {
let path = file?.path();
if path.extension().and_then(|s| s.to_str()) != Some("active") {
continue;
}
let object = indexed_object(&path)?;
let (meta, _) = read_manifest(&object)?;
let bytes = read_validated_file(&object)?;
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if existing
.insert(meta.transient_id, meta.content_hash)
.is_some()
{
return Err(invalid("duplicate active relay TID"));
}
}
let maximum = policy
.maximum_message_bytes
.min(rns_protocol::resource::MAX_RESOURCE_SIZE);
let mut selected = HashSet::new();
let mut plans = Vec::new();
let mut already_present = 0;
for record in &recovery.entries {
if !selected.insert(record.transient_id) {
return Err(invalid("duplicate recovery TID"));
}
let Some((length, hash)) = known.get(&record.archive_relative_path) else {
return Err(invalid(
"recovery entry is outside the committed legacy inventory",
));
};
if *hash != record.content_hash || *length > maximum as u64 {
return Err(invalid("recovery inventory hash/size mismatch"));
}
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
let meta = validate(record, &bytes, policy.minimum_stamp_cost)?;
if let Some(hash) = existing.get(&record.transient_id) {
if *hash != record.content_hash {
return Err(invalid(
"recovery would replace the first accepted relay image",
));
}
already_present += 1;
continue;
}
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if total > policy.maximum_store_bytes {
return Err(invalid(
"trusted recovery exceeds active relay storage quota",
));
}
plans.push((record, meta));
}
let mut imported = 0;
for (record, meta) in plans {
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
validate(record, &bytes, policy.minimum_stamp_cost)?;
let object = root.join("objects").join(meta.filename());
if object.exists() && read_bounded(&object, maximum)? != bytes {
return Err(invalid("recovery object target contains different bytes"));
}
publish_object(&object, &meta, &bytes)?;
imported += 1;
}
Ok(RecoveryReport {
imported,
already_present,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn guard(legacy: &Path) -> OfflineMigrationGuard {
let legacy = canonical_legacy(legacy).unwrap();
let lock = offline::lock_store(&legacy).unwrap();
OfflineMigrationGuard {
legacy,
_lock: lock,
}
}
fn write_manifest(path: &Path, manifest: &TrustedRecoveryManifest) -> [u8; 32] {
let bytes = rmp_serde::to_vec_named(manifest).unwrap();
fs::write(path, &bytes).unwrap();
rns_crypto::sha::full_hash(&bytes)
}
fn policy() -> RecoveryPolicy {
RecoveryPolicy {
maximum_store_bytes: 8192,
maximum_message_bytes: 4096,
minimum_stamp_cost: 0.0,
}
}
fn record(bytes: &[u8], name: &str) -> RecoveryEntry {
RecoveryEntry {
archive_relative_path: name.into(),
content_hash: rns_crypto::sha::full_hash(bytes),
transient_id: rns_crypto::sha::full_hash(bytes),
stamped: false,
stored_at: 1.0,
}
}
#[test]
fn only_exact_approved_inventory_entries_are_imported_and_retry_is_idempotent() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let recipient = rns_identity::identity::Identity::new();
let mut bytes = [2; 16].to_vec();
bytes.extend_from_slice(
&recipient
.encrypt(b"private recovery payload", None)
.unwrap(),
);
fs::write(legacy.join("opaque"), &bytes).unwrap();
fs::write(legacy.join("unknown"), b"never infer eligibility").unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
let manifest = TrustedRecoveryManifest {
version: 2,
provenance: "operator verified original opaque ingress record #42".into(),
entries: vec![record(&bytes, "opaque")],
};
let path = temp.path().join("recovery.msgpack");
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, [0; 32], policy()).is_err());
let first = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((first.imported, first.already_present), (1, 0));
let retry = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((retry.imported, retry.already_present), (0, 1));
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
3
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("unknown")
)
.unwrap(),
b"never infer eligibility"
);
drop(offline);
let reopened = crate::propagation_node::PropagationNode::with_storage(
crate::propagation_node::PropagationNodeConfig::default(),
[1; 16],
legacy,
)
.unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
fs::read(&reopened.plan_message_reads(&[rns_crypto::sha::full_hash(&bytes)])[0].path)
.unwrap(),
bytes
);
}
#[test]
fn plaintext_or_outside_inventory_recovery_cannot_publish_any_entry() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let message = crate::message::test_message(
[2; 16],
[3; 16],
"Private",
"Do not relay cleartext",
crate::constants::DeliveryMethod::Direct,
);
let bytes = message.wire_bytes();
fs::write(legacy.join("plaintext"), bytes).unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
let path = temp.path().join("recovery.msgpack");
let mut manifest = TrustedRecoveryManifest {
version: 2,
provenance: "inaccurate assertion does not override positive plaintext decode".into(),
entries: vec![record(bytes, "plaintext")],
};
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
manifest.entries[0].archive_relative_path = "../plaintext".into();
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
bytes
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
//! Medium-aware outbound timing: Python `LXMRouter` path and retry model.
//!
//! The embedder supplies a [`MediumSnapshot`] of Reticulum's view (lowest
//! online bitrate, medium path timeout and per-destination routes); the router
//! derives retry waits, attempt limits and receipt timeouts from it.
use std::collections::HashMap;
use std::time::Duration;
use rand::Rng;
use crate::constants::{
DELIVERY_RETRY_WAIT, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, PROCESSING_INTERVAL,
};
use crate::message::LxMessage;
pub const PATH_REQUEST_DEBOUNCE: f64 = 60.0;
pub const SLOW_INTERFACE_BITRATE: u64 = 2000;
pub const AIRTIME_AWARE_MTU_TIME: f64 = 0.5;
const PER_HOP_TIMEOUT: f64 = rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT;
/// Reticulum's current route to a destination.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RouteInfo {
pub hops: u8,
/// `Reticulum.get_first_hop_timeout` for the destination, in seconds.
pub first_hop_timeout: f64,
}
/// Reticulum inputs to outbound planning. A destination without an entry in
/// `routes` has no known path.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MediumSnapshot {
/// `Reticulum.get_lowest_interface_bitrate`.
pub lowest_interface_bitrate: Option<u64>,
/// `Reticulum.get_medium_path_timeout`; 0 when no bitrate is known.
pub medium_path_timeout: f64,
pub routes: HashMap<[u8; 16], RouteInfo>,
}
impl MediumSnapshot {
pub fn has_path(&self, destination: &[u8; 16]) -> bool {
self.routes.contains_key(destination)
}
pub fn route(&self, destination: &[u8; 16]) -> Option<RouteInfo> {
self.routes.get(destination).copied()
}
/// Python `LXMRouter.destination_round_trip`.
pub fn destination_round_trip(&self, destination: &[u8; 16]) -> f64 {
match self.routes.get(destination) {
None => self.medium_path_timeout,
Some(route) => {
2.0 * (route.first_hop_timeout - PER_HOP_TIMEOUT).max(0.0) + PER_HOP_TIMEOUT
}
}
}
/// Python `LXMRouter.path_request_wait`.
pub fn path_request_wait(&self) -> f64 {
(PATH_REQUEST_WAIT as f64).max(self.medium_path_timeout)
}
/// Python `LXMRouter.slow_interface_online`.
pub fn slow_interface_online(&self) -> bool {
self.lowest_interface_bitrate
.is_some_and(|bitrate| bitrate < SLOW_INTERFACE_BITRATE)
}
/// Window within which a repeated path request for one destination is skipped.
pub fn path_request_debounce(&self) -> f64 {
if self.slow_interface_online() {
PATH_REQUEST_DEBOUNCE
} else {
self.path_request_wait()
}
}
}
/// Python `LXMRouter.attempt_limit`.
pub fn attempt_limit(message: &LxMessage) -> u32 {
message
.max_delivery_attempts
.unwrap_or(MAX_DELIVERY_ATTEMPTS)
}
/// Python `LXMRouter.attempt_due`.
pub fn attempt_due(message: &LxMessage, has_path: bool, now: f64) -> bool {
now > message.next_delivery_attempt || (message.awaiting_path && has_path)
}
/// Python `LXMRouter.schedule_attempt`, given the round trip it would use:
/// the medium path timeout for a path request, else the destination round trip.
pub fn schedule_attempt(message: &mut LxMessage, round_trip: f64, path_request: bool, now: f64) {
let wait = if path_request {
message.awaiting_path = true;
(PATH_REQUEST_WAIT as f64).max(round_trip)
} else {
(DELIVERY_RETRY_WAIT as f64).max(round_trip)
};
message.next_delivery_attempt = now + wait;
let limit = if round_trip > DELIVERY_RETRY_WAIT as f64 {
// Python's round() rounds half to even.
let scaled = (MAX_DELIVERY_ATTEMPTS as f64 * DELIVERY_RETRY_WAIT as f64 / round_trip)
.round_ties_even() as u32;
scaled.max(3)
} else {
MAX_DELIVERY_ATTEMPTS
};
message.max_delivery_attempts = Some(limit);
let mtu_time = (round_trip - PER_HOP_TIMEOUT).max(0.0) / 2.0;
if mtu_time > AIRTIME_AWARE_MTU_TIME {
message.next_delivery_attempt += rand::thread_rng().gen_range(0.0..=mtu_time);
let retry_wait = (DELIVERY_RETRY_WAIT as f64).max(round_trip) + mtu_time;
let remaining = (i64::from(limit) - i64::from(message.delivery_attempts) + 1).max(1);
message.receipt_timeout = Some(retry_wait * remaining as f64 + PROCESSING_INTERVAL as f64);
} else {
message.receipt_timeout = None;
}
}
/// Timeout for an opportunistic delivery receipt: the RNS packet receipt
/// timeout (Packet.py), raised to the message's airtime-aware
/// `receipt_timeout` (LXMessage.py). Without a route Reticulum counts
/// `PATHFINDER_M` hops.
pub fn opportunistic_receipt_timeout(
route: Option<RouteInfo>,
receipt_timeout: Option<f64>,
) -> Duration {
let (first_hop, hops) = route
.map(|route| (route.first_hop_timeout, route.hops))
.unwrap_or((PER_HOP_TIMEOUT, rns_transport::constants::PATHFINDER_M));
let base = rns_wire::receipt::receipt_timeout_for_route(
Duration::from_secs_f64(first_hop.max(0.0)),
hops,
);
match receipt_timeout {
Some(timeout) if timeout.is_finite() && timeout > base.as_secs_f64() => {
Duration::from_secs_f64(timeout)
}
_ => base,
}
}
+253 -475
View File
@@ -1,235 +1,151 @@
//! LXMF Stamp system: Proof-of-Work generation and validation.
//! LXMF stamps: proof of work for messages, propagation and peering.
//!
//! Python reference: LXMF/LXStamper.py.
//! Python reference: `LXMF/LXStamper.py`, which takes the workblock, value,
//! validity and generation from `RNS.Stamps`. Only the expand-round counts per
//! stamp kind are LXMF's own (`STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}`
//! in constants.rs). Costs and values are fractional on the 1/256 grid.
//!
//! A single workblock construction is used for all stamp kinds (message,
//! propagation-node, peering), matching Python `LXStamper.stamp_workblock`:
//! per-round HKDF expansion concatenated into a `expand_rounds * 256` byte
//! workblock. Only the expand-round count differs per kind (see
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
//!
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`.
//! Validation accepts the non-expanded workblock (the material itself) as well
//! as the expanded one, as LXMF 1.3.1 does while senders move to it.
//! Generation stays expanded: LXMF 1.3.0 receivers accept only that form.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::Ordering;
use rand::RngCore;
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use sha2::{Digest, Sha256};
/// The same type as `rns_identity::stamps::StampError`, not an LXMF-specific error.
pub use rns_identity::stamps::StampError;
pub use rns_identity::stamps::{
STAMP_COST_CAP, STAMP_COST_CAP_FP, StampControl, cost_from_fp, cost_to_fp, quantize_cost,
stamp_value, stamp_workblock,
};
use crate::constants::{
LXMF_OVERHEAD, STAMP_SIZE, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
};
/// Parsed propagation-node stamp parts: `(transient_id, lxm_data, value, stamp)`.
pub type PropagationStampParts = ([u8; 32], Vec<u8>, u32, [u8; 32]);
pub type PropagationStampParts = ([u8; 32], Vec<u8>, f64, [u8; 32]);
/// Matches Python `LXStamper.stamp_workblock(material, expand_rounds)`:
///
/// For each round n in 0..expand_rounds:
/// salt = SHA256(material + msgpack.packb(n))
/// workblock += HKDF(length=256, derive_from=material, salt=salt, context=None)
///
/// Produces `expand_rounds * 256` bytes.
pub fn stamp_workblock(material: &[u8], expand_rounds: usize) -> Vec<u8> {
let mut workblock = Vec::with_capacity(expand_rounds * 256);
for n in 0..expand_rounds {
let n_packed = pack_msgpack_uint(n);
let mut salt_input = Vec::with_capacity(material.len() + n_packed.len());
salt_input.extend_from_slice(material);
salt_input.extend_from_slice(&n_packed);
let salt = sha256(&salt_input);
let chunk = hkdf_sha256(256, material, Some(&salt), None)
.expect("HKDF expand failed for stamp workblock");
workblock.extend_from_slice(&chunk);
}
workblock
/// Python `stamp_valid`: the stamp hash meets the fixed-point target of
/// `cost`. A cost of 0 always passes; a non-finite cost never does.
pub fn stamp_valid(stamp: &[u8], cost: f64, workblock: &[u8]) -> bool {
rns_identity::stamps::stamp_valid(stamp, cost, workblock).unwrap_or(false)
}
fn pack_msgpack_uint(n: usize) -> Vec<u8> {
let value = rmpv::Value::Integer(rmpv::Integer::from(n as u64));
crate::encode_value(&value)
/// Whether a stamp of `value` passes [`stamp_valid`] at `cost`.
pub fn value_meets(value: f64, cost: f64) -> bool {
quantize_cost(cost).is_ok_and(|cost| value >= cost)
}
fn leading_zero_bits(data: &[u8]) -> u32 {
let mut count = 0u32;
for &byte in data {
if byte == 0 {
count += 8;
} else {
count += byte.leading_zeros();
break;
}
}
count
}
/// Leading zero bits of `SHA-256(workblock || stamp)`. Matches Python `stamp_value()`.
pub fn stamp_value(workblock: &[u8], stamp: &[u8; 32]) -> u32 {
let mut hasher = Sha256::new();
hasher.update(workblock);
stamp_value_from_base(&hasher, stamp)
}
pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
if cost == 0 {
return true;
}
stamp_value(workblock, stamp) >= cost as u32
}
/// Give-up bound for stamp searches: 64× the expected `2^cost` work, so the
/// failure probability for an honest cost is ~e^-64 while a hostile cost can
/// no longer pin a thread forever. Costs ≥ 58 (cap would overflow u64) are
/// unsatisfiable on real hardware and fail immediately. Python has no cap and
/// blocks until success — deliberate divergence, see fix-registry.
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
if cost >= 58 {
return None;
}
Some(64u64 << cost)
}
/// Single-threaded brute-force stamp search. Bounded by
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
/// cost is unsatisfiable.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
if cost == 0 {
return Some(([0u8; 32], 0));
}
let started = std::time::Instant::now();
let max_iterations = stamp_iteration_cap(cost)?;
let workblock = stamp_workblock(material, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
let stamp = rand_bytes_from(&mut rng);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
let elapsed_ms = started.elapsed().as_millis() as u64;
if elapsed_ms > 250 {
tracing::info!(cost, value, elapsed_ms, "stamp generated");
}
return Some((stamp, value));
}
}
tracing::warn!(
cost,
elapsed_ms = started.elapsed().as_millis() as u64,
"stamp search exhausted iteration cap"
);
None
}
/// Stamp search with a configurable iteration limit (for tests).
pub fn generate_stamp_limited(
/// Python `LXStamper.generate_stamp`: a 32-byte stamp and its real value.
/// Costs outside `0..=100` are refused as Python refuses them; a cost of 0
/// still returns a random stamp. `None` means cancelled or past the deadline.
pub fn generate_stamp(
material: &[u8],
cost: u8,
cost: f64,
expand_rounds: usize,
max_iterations: u64,
) -> Option<[u8; 32]> {
if cost == 0 {
return Some([0u8; 32]);
}
let workblock = stamp_workblock(material, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
let stamp = rand_bytes_from(&mut rng);
if stamp_value_from_base(&base_hasher, &stamp) >= cost as u32 {
return Some(stamp);
}
}
None
ctl: &StampControl,
) -> Result<Option<([u8; 32], f64)>, StampError> {
let generated =
rns_identity::stamps::generate_stamp(material, cost, expand_rounds, STAMP_SIZE, ctl)?;
Ok(generated.map(|(stamp, value)| {
let stamp: [u8; 32] = stamp.try_into().expect("stamp size is 32");
(stamp, value)
}))
}
/// The stamp's value when it meets `cost` over the non-expanded workblock,
/// else over `expand_rounds`, from the workblock that passed (LXMF 1.3.1
/// `LXMessage.validate_stamp`, `LXStamper.validate_pn_stamp`). The value can
/// depend on `cost`: below about cost 4 an expanded stamp often passes the
/// non-expanded check too, and at cost 0 it always does.
pub fn validated_stamp_value(
material: &[u8],
stamp: &[u8],
cost: f64,
expand_rounds: usize,
) -> Option<f64> {
if stamp_valid(stamp, cost, material) {
return Some(stamp_value(material, stamp));
}
let workblock = stamp_workblock(material, expand_rounds);
stamp_valid(stamp, cost, &workblock).then(|| stamp_value(&workblock, stamp))
}
/// Whether `stamp` meets `cost` in either workblock form; see [`validated_stamp_value`].
pub fn validate_stamp(
message_id: &[u8; 32],
stamp: &[u8; 32],
cost: u8,
stamp: &[u8],
cost: f64,
expand_rounds: usize,
) -> bool {
let workblock = stamp_workblock(message_id, expand_rounds);
stamp_valid(stamp, cost, &workblock)
validated_stamp_value(message_id, stamp, cost, expand_rounds).is_some()
}
/// Python reference: LXStamper.py:48-51 (`validate_peering_key`).
///
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_cost: u8) -> bool {
let workblock = stamp_workblock(
/// Python reference: `LXStamper.validate_peering_key`.
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8], target_cost: f64) -> bool {
validated_stamp_value(
peering_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
stamp_valid(peering_key, target_cost, &workblock)
peering_key,
target_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
)
.is_some()
}
/// 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.
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<PropagationStampParts> {
let stamp_size = 32;
let lxmf_overhead = crate::constants::LXMF_OVERHEAD;
if transient_data.len() <= lxmf_overhead + stamp_size {
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: f64) -> Option<PropagationStampParts> {
if transient_data.len() <= LXMF_OVERHEAD + STAMP_SIZE {
return None;
}
let split = transient_data.len() - stamp_size;
let split = transient_data.len() - STAMP_SIZE;
let lxm_data = &transient_data[..split];
let stamp_bytes = &transient_data[split..];
let mut stamp = [0u8; 32];
stamp.copy_from_slice(stamp_bytes);
let stamp: [u8; 32] = transient_data[split..].try_into().ok()?;
let transient_id = rns_crypto::sha::full_hash(lxm_data);
let workblock = stamp_workblock(
let value = validated_stamp_value(
&transient_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = stamp_value(&workblock, &stamp);
if value < target_cost as u32 {
return None;
}
&stamp,
target_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)?;
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)]
pub struct DeferredStampHandle {
cancel: Arc<AtomicBool>,
ctl: StampControl,
}
impl DeferredStampHandle {
pub fn cancel(&self) {
self.cancel.store(true, Ordering::Relaxed);
self.ctl.cancel.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed)
self.ctl.cancel.load(Ordering::Relaxed)
}
}
#[derive(Debug)]
pub enum DeferredStampResult {
Success { stamp: [u8; 32], value: u32 },
Success {
stamp: [u8; 32],
value: f64,
},
Cancelled,
/// The cost cannot be generated, as Python's `generate_stamp` raises.
Failed(StampError),
}
/// Spawn a deferred stamp-generation task on a blocking worker.
///
/// Returns a cancellation handle and a oneshot receiver for the result.
/// # Panics
/// Panics when called outside a Tokio runtime.
#[tracing::instrument(
level = "debug",
name = "stamper.compute",
@@ -242,7 +158,7 @@ pub enum DeferredStampResult {
)]
pub fn spawn_deferred_stamp(
message_id: [u8; 32],
cost: u8,
cost: f64,
expand_rounds: usize,
) -> (
DeferredStampHandle,
@@ -252,367 +168,229 @@ pub fn spawn_deferred_stamp(
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
}
/// Handle-explicit variant: callable from `spawn_blocking` threads (no
/// implicit runtime context) — the manager tick runs there.
/// Spawn on an explicit runtime handle. The search runs until it succeeds or
/// the handle is cancelled; an invalid cost reports `Failed` at once.
pub fn spawn_deferred_stamp_on(
runtime: &tokio::runtime::Handle,
message_id: [u8; 32],
cost: u8,
cost: f64,
expand_rounds: usize,
) -> (
DeferredStampHandle,
tokio::sync::oneshot::Receiver<DeferredStampResult>,
) {
let cancel = Arc::new(AtomicBool::new(false));
let ctl = StampControl::default();
let (tx, rx) = tokio::sync::oneshot::channel();
let cancel_flag = cancel.clone();
let worker_ctl = ctl.clone();
runtime.spawn_blocking(move || {
if cost == 0 {
let _ = tx.send(DeferredStampResult::Success {
stamp: [0u8; 32],
value: 0,
});
return;
}
let workblock = stamp_workblock(&message_id, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
loop {
if cancel_flag.load(Ordering::Relaxed) {
let _ = tx.send(DeferredStampResult::Cancelled);
return;
}
// Check cancellation every 1000 iterations.
for _ in 0..1000 {
let stamp = rand_bytes_from(&mut rng);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
let _ = tx.send(DeferredStampResult::Success { stamp, value });
return;
}
}
}
let result = match generate_stamp(&message_id, cost, expand_rounds, &worker_ctl) {
Ok(Some((stamp, value))) => DeferredStampResult::Success { stamp, value },
Ok(None) => DeferredStampResult::Cancelled,
Err(error) => DeferredStampResult::Failed(error),
};
let _ = tx.send(result);
});
(DeferredStampHandle { cancel }, rx)
}
pub(crate) fn rand_bytes() -> [u8; 32] {
let mut rng = rand::thread_rng();
rand_bytes_from(&mut rng)
}
fn rand_bytes_from(rng: &mut impl RngCore) -> [u8; 32] {
let mut bytes = [0u8; 32];
rng.fill_bytes(&mut bytes);
bytes
}
fn stamp_value_from_base(base_hasher: &Sha256, stamp: &[u8; 32]) -> u32 {
let mut hasher = base_hasher.clone();
hasher.update(stamp);
let hash = hasher.finalize();
leading_zero_bits(&hash)
(DeferredStampHandle { ctl }, rx)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::{STAMP_WORKBLOCK_EXPAND_ROUNDS, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN};
use rns_crypto::sha::sha256;
#[test]
fn test_workblock_deterministic() {
let id = sha256(b"test message id");
let wb1 = stamp_workblock(&id, 10);
let wb2 = stamp_workblock(&id, 10);
assert_eq!(wb1, wb2);
assert_eq!(wb1.len(), 10 * 256);
// Upstream LXMF 1.3.1 / RNS 1.6.1 results: `LXMessage.validate_stamp`,
// `LXStamper.validate_pn_stamp` and `validate_peering_key` over the same
// inputs (gen_lxmf_ne.py in the K1 hand-back).
fn bytes32(hex: &str) -> [u8; 32] {
hex::decode(hex).unwrap().try_into().unwrap()
}
#[test]
fn test_workblock_different_rounds() {
let id = sha256(b"test");
let wb1 = stamp_workblock(&id, 10);
let wb2 = stamp_workblock(&id, 20);
assert_ne!(wb1, wb2);
fn message_stamps_validate_in_both_forms_as_upstream() {
let id = bytes32("179201d9189af65b2fee7b97dc90a4e9232121e084050aff94d27f171dc71f55");
let ne = bytes32("84276a6ab90c48763474eef01f7ce3e48b8ffad7f4b0eb1de8dd5761f9614ccd");
let ex = bytes32("a824ef0289c7542b417588d5e93fd3e8e2a0f624c6dc27c1a02e3f864c45fba4");
let rounds = STAMP_WORKBLOCK_EXPAND_ROUNDS;
assert_eq!(
validated_stamp_value(&id, &ne, 8.0, rounds),
Some(11.84765625)
);
assert_eq!(validated_stamp_value(&id, &ex, 8.0, rounds), Some(8.09375));
assert_eq!(
validated_stamp_value(&id, &ex, 0.0, rounds),
Some(0.37109375)
);
assert_eq!(validated_stamp_value(&id, &ne, 11.8515625, rounds), None);
assert!(validate_stamp(&id, &ne, 8.0, rounds));
}
/// Workblock for the default message expand rounds matches the Python
/// construction's size: 3000 rounds * 256 bytes.
#[test]
fn test_workblock_message_rounds_size() {
fn propagation_stamps_validate_in_both_forms_as_upstream() {
let lxm_data: Vec<u8> = (0..150).collect();
let entry = |stamp: &str| [lxm_data.clone(), bytes32(stamp).to_vec()].concat();
let ne = entry("228341ee29d47d4d9defe50c2704b1feb4bc2ef066a740637916cc690aaa4fd1");
let ex = entry("7e340b0726c99d8f60ae845912ecccc8aa7363db7a971a09132acd83c88ad771");
let value = |entry: &[u8], cost| validate_pn_stamp(entry, cost).map(|parts| parts.2);
assert_eq!(
validate_pn_stamp(&ne, 8.0).unwrap().0,
bytes32("f22b2e614e92d6453612b707385038300293d2cc292b148bc5335754b5ea30fd")
);
assert_eq!(value(&ne, 8.0), Some(8.0703125));
assert_eq!(value(&ex, 8.0), Some(8.1953125));
assert_eq!(value(&ex, 0.0), Some(2.19921875));
assert_eq!(value(&ne, 8.07421875), None);
}
#[test]
fn peering_keys_validate_in_both_forms_as_upstream() {
let id: Vec<u8> = [[0x11; 16], [0x22; 16]].concat();
let ne = bytes32("d63d05f5dbe354b33213745d275a343924b38da05098d2b7cbc521ca4ff103d1");
let ex = bytes32("4269201b6742c33c84098644f37c3f159c66235bda2c26f108cc7c824936ac7f");
assert!(validate_peering_key(&id, &ne, 8.0));
assert!(validate_peering_key(&id, &ex, 8.0));
assert!(!validate_peering_key(&id, &ne, 8.2578125));
}
fn found(material: &[u8], cost: f64, rounds: usize) -> ([u8; 32], f64) {
generate_stamp(material, cost, rounds, &StampControl::default())
.unwrap()
.unwrap()
}
#[test]
fn workblock_uses_lxmf_expand_rounds() {
let id = sha256(b"size check");
let wb = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
assert_eq!(wb.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS * 256);
assert_eq!(
stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS).len(),
STAMP_WORKBLOCK_EXPAND_ROUNDS * 256
);
assert_eq!(stamp_workblock(&id, 0), id.to_vec());
}
#[test]
fn test_leading_zero_bits() {
assert_eq!(leading_zero_bits(&[0xFF]), 0);
assert_eq!(leading_zero_bits(&[0x00, 0xFF]), 8);
assert_eq!(leading_zero_bits(&[0x00, 0x00, 0xFF]), 16);
assert_eq!(leading_zero_bits(&[0x0F]), 4);
assert_eq!(leading_zero_bits(&[0x01]), 7);
assert_eq!(leading_zero_bits(&[0x00, 0x01]), 15);
fn zero_cost_generates_a_random_stamp_with_its_real_value() {
let id = sha256(b"zero cost");
let (stamp, value) = found(&id, 0.0, 20);
assert_ne!(stamp, [0u8; 32]);
assert_eq!(value, stamp_value(&stamp_workblock(&id, 20), &stamp));
assert!(stamp_valid(&stamp, 0.0, &[]));
}
#[test]
fn test_stamp_valid_cost_zero() {
let stamp = [0u8; 32];
let workblock = [0u8; 32];
assert!(stamp_valid(&stamp, 0, &workblock));
}
#[test]
fn test_generate_stamp_cost_zero() {
let id = sha256(b"test");
let (stamp, value) = generate_stamp(&id, 0, 20).unwrap();
assert_eq!(stamp, [0u8; 32]);
assert_eq!(value, 0);
}
/// T0-4: the stamp search is bounded — an unsatisfiable (hostile) cost
/// returns `None` immediately instead of pinning the thread forever.
#[test]
fn test_generate_stamp_capped_for_hostile_cost() {
assert_eq!(stamp_iteration_cap(1), Some(128));
assert_eq!(stamp_iteration_cap(26), Some(64u64 << 26));
assert!(stamp_iteration_cap(57).is_some());
assert_eq!(stamp_iteration_cap(58), None);
assert_eq!(stamp_iteration_cap(255), None);
let id = sha256(b"hostile cost");
// Cost 255 must fail fast (cap is None — no workblock spin at all).
assert!(generate_stamp(&id, 255, 20).is_none());
// Sane costs still succeed.
assert!(generate_stamp(&id, 4, 20).is_some());
}
#[test]
fn test_generate_and_validate_stamp() {
let id = sha256(b"test message for stamping");
let cost = 4;
let stamp = generate_stamp_limited(&id, cost, STAMP_WORKBLOCK_EXPAND_ROUNDS, 1_000_000);
assert!(stamp.is_some(), "should find a stamp with cost={cost}");
let stamp = stamp.unwrap();
assert!(validate_stamp(
&id,
&stamp,
cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS
));
}
#[test]
fn test_validate_wrong_stamp() {
let id = sha256(b"test");
let wrong_stamp = [0xFFu8; 32];
assert!(!validate_stamp(&id, &wrong_stamp, 32, 20));
}
#[test]
fn test_generate_stamp_limited_fails() {
let id = sha256(b"test");
let result = generate_stamp_limited(&id, 128, 20, 10);
assert!(result.is_none());
}
#[test]
fn test_stamp_value_consistency() {
let id = sha256(b"consistency test");
let cost = 4;
if let Some(stamp) = generate_stamp_limited(&id, cost, 20, 1_000_000) {
let workblock = stamp_workblock(&id, 20);
let value = stamp_value(&workblock, &stamp);
assert!(value >= cost as u32);
assert!(stamp_valid(&stamp, cost, &workblock));
fn generation_refuses_costs_outside_the_cap() {
let ctl = StampControl::default();
for cost in [100.5, 150.0, 255.0, -1.0, f64::NAN] {
assert!(generate_stamp(&[7; 32], cost, 1, &ctl).is_err(), "{cost}");
}
}
#[test]
fn test_workblock_arbitrary_length_input() {
let short_material = b"short";
let wb = stamp_workblock(short_material, 5);
assert_eq!(wb.len(), 5 * 256);
let wb2 = stamp_workblock(short_material, 5);
assert_eq!(wb, wb2);
let wb3 = stamp_workblock(b"other", 5);
assert_ne!(wb, wb3);
fn fractional_cost_generates_and_validates() {
let id = sha256(b"fractional");
let (stamp, value) = found(&id, 4.5, 10);
assert!(value >= 4.5);
assert!(validate_stamp(&id, &stamp, 4.5, 10));
assert!(!validate_stamp(&id, &stamp, value + 1.0 / 256.0, 10));
}
#[test]
fn test_different_expand_round_constants() {
let id = sha256(b"test expand rounds");
let wb_pn = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
let wb_peering =
stamp_workblock(&id, crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
// Workblocks are prefix-stable per construction; only length differs.
assert_eq!(wb_pn[..wb_peering.len()], wb_peering[..]);
assert_eq!(wb_pn.len(), STAMP_WORKBLOCK_EXPAND_ROUNDS_PN * 256);
assert_eq!(
wb_peering.len(),
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING * 256
);
}
/// The first 256-byte chunk of the workblock is identical regardless of
/// total round count — Python builds it incrementally the same way.
#[test]
fn test_workblock_prefix_stability() {
let id = sha256(b"prefix stability");
let wb_small = stamp_workblock(&id, 2);
let wb_large = stamp_workblock(&id, 5);
assert_eq!(wb_small[..], wb_large[..2 * 256]);
fn non_finite_target_never_validates() {
assert!(!stamp_valid(&[0u8; 32], f64::NAN, b"x"));
}
#[test]
fn test_deferred_stamp_handle_cancel() {
fn peering_key_validates_at_its_value() {
let peering_id = [0xAA; 32];
let (key, value) = found(&peering_id, 3.25, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING);
assert!(validate_peering_key(&peering_id, &key, 3.25));
assert!(validate_peering_key(&peering_id, &key, value));
assert!(!validate_peering_key(
&peering_id,
&key,
value + 1.0 / 256.0
));
assert!(validate_peering_key(&peering_id, &[0xFF; 32], 0.0));
}
#[test]
fn pn_stamp_too_short_is_rejected() {
let short_data = vec![0u8; LXMF_OVERHEAD + 32];
assert!(validate_pn_stamp(&short_data, 0.0).is_none());
}
#[test]
fn pn_stamp_parts_carry_the_fractional_value() {
let lxm_data = vec![0xAB; LXMF_OVERHEAD + 64];
let tid = rns_crypto::sha::full_hash(&lxm_data);
// At cost 2.5 an expanded stamp often meets the non-expanded check too; keep one that doesn't.
let (stamp, value) = loop {
let (stamp, value) = found(&tid, 2.5, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
if !stamp_valid(&stamp, 2.5, &tid) {
break (stamp, value);
}
};
let mut transient_data = lxm_data.clone();
transient_data.extend_from_slice(&stamp);
let (transient_id, extracted, got, extracted_stamp) =
validate_pn_stamp(&transient_data, 2.5).unwrap();
assert_eq!(transient_id, tid);
assert_eq!(extracted, lxm_data);
assert_eq!(extracted_stamp, stamp);
assert_eq!(got, value);
assert!(validate_pn_stamp(&transient_data, value + 1.0 / 256.0).is_none());
}
#[test]
fn deferred_stamp_handle_cancel() {
let handle = DeferredStampHandle {
cancel: Arc::new(AtomicBool::new(false)),
ctl: StampControl::default(),
};
assert!(!handle.is_cancelled());
handle.cancel();
assert!(handle.is_cancelled());
}
/// End-to-end: a stamp worker running a high-cost PoW must observe the
/// cancellation flag and report `DeferredStampResult::Cancelled`
/// without panicking. This exercises the worker checkpoint rather than
/// only the handle state.
#[tokio::test]
async fn test_deferred_stamp_cancelled_mid_computation() {
// Cost 32 is intentionally high enough that the worker is still
// looping when cancellation is requested.
async fn deferred_stamp_cancelled_mid_computation() {
let id = sha256(b"mid-pow cancel");
let (handle, rx) = spawn_deferred_stamp(id, 32, 10);
// Allow the worker to enter its inner loop.
let (handle, rx) = spawn_deferred_stamp(id, 32.0, 10);
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
handle.cancel();
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
.await
.expect("worker should report back within 3s of cancel")
.expect("worker reports back after cancel")
.expect("oneshot sender dropped");
assert!(
matches!(result, DeferredStampResult::Cancelled),
"worker must report Cancelled after handle.cancel(), got {result:?}"
"{result:?}"
);
}
/// Cost=0 is the degenerate case: no work to do, oneshot fires
/// immediately with a zero stamp + value. Cancelling after the fact
/// must not race or produce a spurious Cancelled result.
#[tokio::test]
async fn test_deferred_stamp_zero_cost_completes_before_cancel() {
let id = sha256(b"zero cost");
let (handle, rx) = spawn_deferred_stamp(id, 0, 10);
async fn deferred_stamp_refuses_cost_above_cap() {
let (_handle, rx) = spawn_deferred_stamp([9; 32], 150.0, 1);
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
.await
.expect("cost=0 returns immediately")
.expect("oneshot sender dropped");
.unwrap()
.unwrap();
assert!(
matches!(result, DeferredStampResult::Success { value: 0, .. }),
"cost=0 returns Success with zero value, got {result:?}"
);
// The handle remains usable after completion; cancel is a no-op here.
handle.cancel();
assert!(handle.is_cancelled());
}
#[test]
fn test_workblock_peering_id_length() {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(&[0xAA; 16]);
peering_id.extend_from_slice(&[0xBB; 16]);
let wb = stamp_workblock(
&peering_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
assert_eq!(
wb.len(),
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING * 256
matches!(result, DeferredStampResult::Failed(_)),
"{result:?}"
);
}
#[test]
fn test_validate_peering_key_cost_zero() {
let peering_id = [0xAA; 32];
let peering_key = [0xFF; 32];
assert!(validate_peering_key(&peering_id, &peering_key, 0));
}
#[test]
fn test_validate_peering_key_invalid() {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(&[0xAA; 16]);
peering_id.extend_from_slice(&[0xBB; 16]);
let peering_key = [0xFF; 32];
assert!(!validate_peering_key(&peering_id, &peering_key, 32));
}
#[test]
fn test_validate_pn_stamp_too_short() {
let short_data = vec![0u8; crate::constants::LXMF_OVERHEAD + 32];
assert!(validate_pn_stamp(&short_data, 0).is_none());
}
#[test]
fn test_validate_pn_stamp_extracts_parts() {
let lxm_data = vec![0xAB; crate::constants::LXMF_OVERHEAD + 64];
let stamp = [0u8; 32];
let mut transient_data = lxm_data.clone();
transient_data.extend_from_slice(&stamp);
let result = validate_pn_stamp(&transient_data, 0);
assert!(result.is_some());
let (transient_id, extracted_lxm, value, extracted_stamp) = result.unwrap();
assert_eq!(extracted_lxm, lxm_data);
assert_eq!(extracted_stamp, stamp);
assert_eq!(transient_id, rns_crypto::sha::full_hash(&lxm_data));
let _ = value;
}
#[test]
fn test_stamp_value_matches_direct_sha256_of_workblock_and_stamp() {
let material = sha256(b"propagation transient id");
let workblock = stamp_workblock(&material, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
let stamp = [0x5Au8; 32];
let mut direct = Vec::with_capacity(workblock.len() + stamp.len());
direct.extend_from_slice(&workblock);
direct.extend_from_slice(&stamp);
let direct_hash = sha256(&direct);
assert_eq!(
stamp_value(&workblock, &stamp),
leading_zero_bits(&direct_hash)
);
}
#[test]
fn test_validate_pn_stamp_high_cost_fails() {
let lxm_data = vec![0xCD; crate::constants::LXMF_OVERHEAD + 100];
let stamp = [0xFF; 32];
let mut transient_data = lxm_data.clone();
transient_data.extend_from_slice(&stamp);
let result = validate_pn_stamp(&transient_data, 32);
assert!(result.is_none());
#[tokio::test]
async fn deferred_stamp_zero_cost_completes_with_real_value() {
let id = sha256(b"zero cost");
let (_handle, rx) = spawn_deferred_stamp(id, 0.0, 10);
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
.await
.unwrap()
.unwrap();
let DeferredStampResult::Success { stamp, value } = result else {
panic!("{result:?}");
};
assert_eq!(value, stamp_value(&stamp_workblock(&id, 10), &stamp));
}
}
File diff suppressed because it is too large. Load diff
+21 -10
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.
//! 2. A sends Offer { transient_ids }.
//! 2. A sends `/offer` with `[peering_key, transient_ids]`.
//! 3. B responds with one of:
//! - `true`: peer wants ALL offered messages.
//! - `false`: peer already has everything.
@@ -9,7 +11,11 @@
//! - integer error code: 0xF0 NoIdentity, 0xF1 NoAccess, 0xF3 InvalidKey,
//! 0xF4 InvalidData, 0xF5 InvalidStamp, 0xF6 Throttled.
//! 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).
@@ -23,10 +29,13 @@ use crate::types::PropagationTransientId;
pub const SYNC_MSG_OFFER: u16 = 0x0001;
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
/// bytes (Python `self.peering_key[0]`), required by the receiver for access control.
/// The `/offer` request uses `[peering_key, unhandled_ids]` with a MessagePack
/// 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)]
pub struct SyncOffer {
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)]
pub struct SyncGet {
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)]
pub enum OfferResponse {
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 {
let wanted: Vec<Vec<u8>> = offer
.transient_ids
@@ -365,7 +376,7 @@ mod tests {
let mut session = SyncSession::new(peer_hash);
let mut store = PropagationStore::new();
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0));
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0.0));
let offer = SyncOffer {
peering_key: vec![0xFF; 32],
+12 -5
View File
@@ -47,7 +47,9 @@ impl Ticket {
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> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
@@ -160,10 +162,15 @@ impl TicketStore {
return None;
}
if let Some(ticket) = self.inbound.iter().find(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
}) {
if let Some(ticket) = self
.inbound
.iter()
.filter(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
})
.max_by(|a, b| a.expires.total_cmp(&b.expires))
{
return Some(ticket.clone());
}
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::constants::DESTINATION_LENGTH;
/// Reticulum destination hash, as carried in LXMF wire messages.
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];
/// Canonical LXMF message id / SHA-256 digest.
+466
View File
@@ -0,0 +1,466 @@
//! Focused public-boundary regressions for durable propagation delivery.
use lxmf_core::admission::*;
use lxmf_core::admission_store::FileAdmissionStore;
use lxmf_core::constants::DeliveryMethod;
use lxmf_core::message::{LxMessage, LxMessageDraft, RecipientStamp};
use lxmf_core::propagation_send::*;
use rns_crypto::{ed25519::Ed25519PrivateKey, sha::full_hash};
// These tests deliberately exhaust the shared production admission budget.
// Exclude only other budget-exhaustion fixtures, without changing its limits.
static PROCESSING_BUDGET_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn message(stamp: Option<RecipientStamp>) -> LxMessage {
let mut draft = LxMessageDraft::new(
[1; 16],
[2; 16],
"title",
"body",
DeliveryMethod::Propagated,
)
.unwrap();
draft.set_timestamp(100.).unwrap();
draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(stamp)
.unwrap()
}
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [4; 16],
node: [5; 16],
transient_id: [n; 32],
}
}
fn record(msg: &LxMessage, n: u8, time: u64, disposition: DurableDisposition) -> AdmissionRecord {
AdmissionRecord {
scope: scope(n),
message_id: msg.message_id(),
received_wire_hash: full_hash(msg.wire_bytes()),
stored_message_wire_hash: None,
disposition,
committed_at: time,
}
}
fn commit(
store: &FileAdmissionStore,
msg: &LxMessage,
n: u8,
time: u64,
disposition: DurableDisposition,
) -> DurableAdmissionReceipt {
DurableAdmissionReceipt::commit(store.prepare(
record(msg, n, time, disposition),
msg.wire_owned(),
true,
))
.unwrap()
}
#[test]
fn duplicate_stamp_images_keep_first_archive_and_one_hook_across_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let first = message(None);
let second = message(Some(RecipientStamp::ProofOfWork([7; 32])));
assert_eq!(first.message_id(), second.message_id());
assert_ne!(first.wire_bytes(), second.wire_bytes());
commit(&store, &first, 1, 100, DurableDisposition::Committed);
let duplicate = commit(&store, &second, 2, 101, DurableDisposition::Committed);
assert_eq!(
duplicate.record().disposition,
DurableDisposition::Duplicate
);
assert_eq!(
duplicate.record().received_wire_hash,
full_hash(second.wire_bytes())
);
assert_eq!(
duplicate.record().stored_message_wire_hash,
Some(full_hash(first.wire_bytes()))
);
assert_eq!(
std::fs::read(bodies.join(format!("{}.lxm", hex::encode(first.message_id())))).unwrap(),
first.wire_bytes()
);
assert_eq!(store.pending_hooks().len(), 1);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
reopened.haves(scope(1).identity, scope(1).node, 102).len(),
2
);
assert_eq!(reopened.pending_hooks().len(), 1);
let event = reopened.pending_hooks()[0].0;
reopened.complete_hook(event).unwrap();
drop(reopened);
assert!(
FileAdmissionStore::open(temp.path(), &bodies)
.unwrap()
.pending_hooks()
.is_empty()
);
}
#[test]
fn published_body_intent_recovers_original_tid_after_missing_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 9, 100, DurableDisposition::Committed);
drop(store);
let dir = temp.path().join("download-admission-v1");
for file in std::fs::read_dir(&dir).unwrap() {
let path = file.unwrap().path();
if path.extension().is_some_and(|s| s == "commit") {
std::fs::remove_file(path).unwrap();
}
}
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope(9).identity, scope(9).node, 101),
vec![scope(9).transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
}
#[test]
fn damaged_archive_never_becomes_purge_authority_on_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::Committed);
drop(store);
let archive = bodies.join(format!("{}.lxm", hex::encode(msg.message_id())));
std::fs::write(&archive, b"preserved corrupt evidence").unwrap();
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert!(
reopened
.haves(scope(1).identity, scope(1).node, 101)
.is_empty()
);
assert!(reopened.pending_hooks().is_empty());
assert_eq!(
std::fs::read(archive).unwrap(),
b"preserved corrupt evidence"
);
}
#[test]
fn expired_policy_receipt_is_revalidated_and_user_deletion_outlives_tid_receipts() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::PolicyDiscard);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
let now = 101 + POLICY_RECEIPT_LIFETIME;
assert!(
store
.haves(scope(1).identity, scope(1).node, now)
.is_empty()
);
assert_eq!(
commit(&store, &msg, 1, now, DurableDisposition::Committed)
.record()
.disposition,
DurableDisposition::Committed
);
store
.mark_user_deleted(scope(1).identity, msg.message_id(), now + 1)
.unwrap();
assert!(store.pending_hooks().is_empty());
assert_eq!(
store.maintain(now + 2 + POLICY_RECEIPT_LIFETIME).unwrap(),
1
);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
commit(
&reopened,
&msg,
2,
now + 3 + POLICY_RECEIPT_LIFETIME,
DurableDisposition::Committed
)
.record()
.disposition,
DurableDisposition::UserDeleted
);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
}
#[test]
fn suppression_retries_transient_failures_and_revalidates_epoch_changes() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(ledger.get(&scope(1)).unwrap().active(101, epoch));
let mut new = epoch;
new.keys[0] = 1;
assert!(!ledger.get(&scope(1)).unwrap().active(101, new));
for _ in 0..20 {
ledger
.record_failure(scope(2), SuppressionReason::StorageBusy, epoch, 100)
.unwrap();
}
let retry = ledger.get(&scope(2)).unwrap();
assert!((3340..=4060).contains(&retry.next_retry));
assert!(!retry.active(retry.next_retry, epoch));
let wire = rmp_serde::to_vec(&ledger).unwrap();
let restored: SuppressionLedger = rmp_serde::from_slice(&wire).unwrap();
assert_eq!(restored.records().count(), 2);
}
#[test]
fn processing_admission_fails_promptly_without_partial_credit_deadlock() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
assert!(matches!(
ProcessingLease::try_acquire(usize::MAX),
Err(SuppressionReason::TooLarge)
));
let workers = (0..MAX_PROCESSORS)
.map(|_| ProcessingLease::try_acquire(100).unwrap())
.collect::<Vec<_>>();
assert!(matches!(
ProcessingLease::try_acquire(100),
Err(SuppressionReason::WorkerUnavailable)
));
drop(workers);
assert!(ProcessingLease::try_acquire(100).is_ok());
}
#[test]
fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
let msg = message(None);
let binding = EncryptionBinding::for_recipient(&[6; 64], None);
let mut envelope = PropagationEnvelope::new(msg, binding, 0.0, |p| Ok(p.to_vec())).unwrap();
let initial = envelope.ciphertext().clone();
let tid = envelope.transient_id();
let policy = AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
let mut ready = propagation_readiness([8; 16], true, true, Some(policy), true, 101.).unwrap();
envelope.pack_for(ready, 101.).unwrap();
ready.policy.stamp_cost = 4.0;
envelope.pack_for(ready, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &initial);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4.0);
assert_eq!(
propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok());
}
#[test]
#[cfg(feature = "sqlite-store")]
fn tickets_and_delivered_claims_are_in_the_state_store_before_they_are_acted_on() {
use lxmf_core::state_store::{FILE_NAME, SqliteStateStore, StateStore};
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
router.load_state(temp.path()).unwrap();
let stale = router.state_snapshot();
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
router.prepare_outbound(&mut draft).unwrap();
// A second connection reads the committed ticket while the router still runs.
let issued = SqliteStateStore::open(&temp.path().join(FILE_NAME))
.unwrap()
.get_inbound_tickets(&[1; 16])
.unwrap()
.expect("ticket committed before prepare_outbound returned");
let msg = draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(None)
.unwrap();
assert!(
msg.fields()
.get(lxmf_core::constants::FIELD_TICKET)
.is_some()
);
// The delivered claim is in the file before the delivery callback runs.
let db = temp.path().join(FILE_NAME);
let claimed_first = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen = claimed_first.clone();
router.register_delivery_callback(move |delivered| {
let claimed = SqliteStateStore::open(&db)
.unwrap()
.has_delivered(&delivered.message_id())
.unwrap();
seen.store(claimed, std::sync::atomic::Ordering::Relaxed);
});
assert!(router.deliver_inbound(&msg, false));
assert!(claimed_first.load(std::sync::atomic::Ordering::Relaxed));
// An older checkpoint written afterwards cannot take the ticket away.
stale.save_state(temp.path()).unwrap();
drop(router);
let mut restarted = lxmf_core::router::LxmRouter::new(Default::default());
restarted.load_state(temp.path()).unwrap();
assert_eq!(restarted.get_inbound_tickets(&[1; 16]), Some(issued));
}
#[test]
fn suppression_hydration_rejects_duplicate_scopes_and_node_quota() {
let mut ledger = SuppressionLedger::default();
let row = ledger
.record_failure(
scope(1),
SuppressionReason::InvalidSignature,
AdmissionEpochs::default(),
100,
)
.unwrap()
.clone();
assert!(SuppressionLedger::from_records([row.clone(), row.clone()]).is_err());
let mut keys = row.epochs;
keys.keys[0] = 1;
assert!(!row.active(101, keys));
let mut policy = row.epochs;
policy.policy[0] = 1;
assert!(!row.active(101, policy));
let rows = (0..=SuppressionLedger::PER_NODE).map(|index| {
let mut value = row.clone();
value.scope.transient_id[..8].copy_from_slice(&(index as u64).to_be_bytes());
value
});
assert!(matches!(
SuppressionLedger::from_records(rows),
Err(AdmissionError::DispositionLedgerFull)
));
assert_eq!(
SuppressionLedger::from_records([row])
.unwrap()
.records()
.count(),
1
);
}
#[test]
fn adapter_processing_memory_shares_peak_budget_without_second_worker() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
let worker = ProcessingLease::try_acquire(1).unwrap();
assert!(matches!(
ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::WorkerUnavailable)
));
let extra = ProcessingMemoryLease::try_acquire(8 * 1024 * 1024).unwrap();
drop(extra);
drop(worker);
let all = ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES).unwrap();
assert!(matches!(
ProcessingLease::try_acquire(1),
Err(SuppressionReason::WorkerUnavailable)
));
drop(all);
assert!(ProcessingLease::try_acquire(1).is_ok());
}
fn answer_node_path(
receiver: &mut tokio::sync::mpsc::Receiver<rns_transport::messages::TransportMessage>,
) {
use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse};
while let Ok(message) = receiver.try_recv() {
if let TransportMessage::Rpc {
query: TransportQuery::HasPath { .. },
response_tx,
} = message
{
response_tx
.send(TransportQueryResponse::BoolResult(true))
.unwrap();
}
}
}
fn reject_link_request(
receiver: &mut tokio::sync::mpsc::Receiver<rns_transport::messages::TransportMessage>,
) {
use rns_transport::messages::TransportMessage;
while let Ok(message) = receiver.try_recv() {
if let TransportMessage::SendLinkRequest { result_tx, .. } = message {
result_tx
.send(Err(
rns_transport::link_messages::LinkRequestDispatchError::Capacity(
rns_transport::InterfaceCapacityError::LinkCapacityUnavailable {
interface_id: 7,
clear_mtu: 499,
required: 500,
},
),
))
.unwrap();
return;
}
}
panic!("exact Link request dispatch channel was not staged");
}
#[test]
fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeout() {
use lxmf_core::link_delivery::{DeliveryResult, LinkDeliveryManager};
use lxmf_core::propagation_client::{PropagationClient, PropagationClientState};
use lxmf_core::propagation_sync::{PeerSyncTerminalState, PropagationSyncTask};
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut delivery = LinkDeliveryManager::new(tx.clone(), None, None);
delivery.start_delivery(message(None), [3; 16], 1).unwrap();
reject_link_request(&mut rx);
assert!(delivery.tick().iter().any(
|result| matches!(result,DeliveryResult::Failed {reason,..} if reason.contains("499"))
));
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
answer_node_path(&mut rx);
client.tick();
reject_link_request(&mut rx);
client.tick();
assert_eq!(
client.transfer_status().state,
PropagationClientState::Failed
);
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut sync = PropagationSyncTask::new(tx, [8; 16]);
assert!(sync.request_sync_now([3; 16]));
answer_node_path(&mut rx);
sync.tick();
reject_link_request(&mut rx);
sync.tick();
assert_eq!(
sync.take_terminal_peer_result().unwrap().state,
PeerSyncTerminalState::Failed
);
}
#[test]
fn canceled_download_closes_exact_request_admission_reply() {
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = lxmf_core::propagation_client::PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
answer_node_path(&mut rx);
client.tick();
client.cancel_download();
let mut found = false;
while let Ok(message) = rx.try_recv() {
if let rns_transport::messages::TransportMessage::SendLinkRequest { result_tx, .. } =
message
{
assert!(result_tx.is_closed());
found = true;
}
}
assert!(found);
}
+262
View File
@@ -0,0 +1,262 @@
use bytes::Bytes;
use lxmf_core::propagation_node::{
PropagationAdmission, PropagationAdmissionOutcome, PropagationNode, PropagationNodeConfig,
ValidatedOpaquePropagationBlob, read_planned_messages,
};
use rmpv::Value;
fn payload(destination: [u8; 16]) -> Bytes {
let recipient = rns_identity::identity::Identity::new();
let mut bytes = destination.to_vec();
bytes.extend_from_slice(&recipient.encrypt(b"private test payload", None).unwrap());
bytes.extend_from_slice(&[0; 32]);
bytes.into()
}
fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob {
ValidatedOpaquePropagationBlob::validate(bytes, 0.0).unwrap()
}
fn request(wants: Option<Vec<[u8; 32]>>, haves: Option<Vec<[u8; 32]>>) -> Vec<u8> {
let ids = |value: Option<Vec<[u8; 32]>>| {
value
.map(|v| Value::Array(v.into_iter().map(|id| Value::Binary(id.to_vec())).collect()))
.unwrap_or(Value::Nil)
};
encode(&Value::Array(vec![ids(wants), ids(haves)]))
}
fn reserve(
node: &mut PropagationNode,
bytes: Bytes,
) -> lxmf_core::propagation_node::PropagationStoreWritePlan {
match node.plan_opaque_admission(validated(bytes)) {
PropagationAdmission::Reserved(plan) => *plan,
other => panic!("expected new admission: {other:?}"),
}
}
#[tokio::test]
async fn duplicate_waits_for_exact_commit_and_rechecks_retained_files() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
let task = tokio::spawn(waiter.wait());
tokio::task::yield_now().await;
assert!(!task.is_finished());
assert!(node.commit_store_write(plan.persist().unwrap()));
assert_eq!(task.await.unwrap(), PropagationAdmissionOutcome::Committed);
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("committed duplicate")
};
check.verify().unwrap();
let path = node.plan_message_reads(&[tid]).pop().unwrap().path;
std::fs::write(&path, b"corruption").unwrap();
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes))
else {
panic!("duplicate requires file check")
};
assert!(check.verify().is_err());
drop(node);
assert!(PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).is_err());
}
#[test]
fn restart_skips_body_rereads_and_never_serves_a_damaged_body() {
let dir = tempfile::tempdir().unwrap();
let store = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], store.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes);
assert!(node.commit_store_write(plan.persist().unwrap()));
let path = node.plan_message_reads(&[tid]).pop().unwrap().path;
drop(node);
let mut damaged = std::fs::read(&path).unwrap();
*damaged.last_mut().unwrap() ^= 0xff;
std::fs::write(&path, &damaged).unwrap();
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], store).unwrap();
assert_eq!(reopened.message_count(), 1);
assert!(read_planned_messages(&reopened.plan_message_reads(&[tid])).is_empty());
}
#[tokio::test]
async fn cancelled_reservation_releases_waiters_without_authority_and_can_retry() {
let dir = tempfile::tempdir().unwrap();
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[1; 16],
dir.path().join("store"),
)
.unwrap();
let bytes = payload([2; 16]);
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan);
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let retry = reserve(&mut node, bytes);
assert!(node.commit_store_write(retry.persist().unwrap()));
}
#[tokio::test]
async fn lost_persisted_callback_reuses_first_image_and_restart_has_one_admission() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan.persist().unwrap());
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let objects = legacy.with_extension("v2").join("objects");
let first_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(first_files.len(), 3);
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let retry_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(retry_files, first_files);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
std::fs::read(&reopened.plan_message_reads(&[tid])[0].path).unwrap(),
bytes
);
}
#[test]
fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let destination = [2; 16];
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let objects = legacy.with_extension("v2").join("objects");
let unavailable = legacy.with_extension("v2").join("temporarily-unavailable");
std::fs::rename(&objects, &unavailable).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Nil)
);
assert!(node.contains(&tid));
std::fs::rename(&unavailable, &objects).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Array(vec![]))
);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert!(!reopened.contains(&tid));
}
#[test]
fn purge_is_durable_and_purged_message_is_not_readmitted() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let destination = [2; 16];
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let old_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
let stale = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
let purge = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
assert_eq!(purge.into_response(), encode(&Value::Array(vec![])));
assert!(!node.contains(&tid));
assert!(!old_path.exists());
// A purged message stays processed and is filtered on re-upload.
assert!(matches!(
node.plan_opaque_admission(validated(bytes.clone())),
PropagationAdmission::AlreadyProcessed
));
let _ = stale.into_response();
assert!(!node.contains(&tid));
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap();
assert!(!reopened.contains(&tid));
}
#[test]
fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() {
let dir = tempfile::tempdir().unwrap();
let config = PropagationNodeConfig {
max_storage: 0,
..Default::default()
};
let mut node =
PropagationNode::with_storage(config, [1; 16], dir.path().join("store")).unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes);
assert!(node.commit_store_write(plan.persist().unwrap()));
node.handle_get_request(&request(None, Some(vec![tid])), &[3; 16])
.into_response();
assert!(node.contains(&tid));
let maintenance = node.plan_maintenance();
assert!(!maintenance.is_empty());
assert!(node.contains(&tid));
maintenance.persist().unwrap();
assert!(!node.contains(&tid));
assert!(node.create_offer([4; 16], None).is_empty());
}
#[test]
fn legacy_trees_and_second_live_host_cannot_be_opened_implicitly() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("legacy");
std::fs::create_dir(&old).unwrap();
std::fs::write(old.join("private"), b"plaintext").unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.is_err()
);
assert_eq!(std::fs::read(old.join("private")).unwrap(), b"plaintext");
let fresh = dir.path().join("fresh");
let node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh.clone())
.unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh).is_err()
);
drop(node);
}
fn encode(value: &Value) -> Vec<u8> {
let mut out = Vec::new();
rmpv::encode::write_value(&mut out, value).unwrap();
out
}
+4 -2
View File
@@ -5,7 +5,7 @@ publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
license-file.workspace = true
autobins = false
[dependencies]
@@ -15,15 +15,17 @@ rns-identity = { workspace = true }
rns-transport = { workspace = true }
rns-wire = { workspace = true }
rns-crypto = { workspace = true }
rns-tools = { workspace = true }
clap = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
hex = { workspace = true }
base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
thiserror = { workspace = true }
zeroize = "1"
[dev-dependencies]
tempfile = { workspace = true }
File diff suppressed because it is too large. Load diff
+46 -31
View File
@@ -261,6 +261,7 @@ impl PnInboundRuntime {
logical_resource_id: LogicalResourceId,
data_size: usize,
peer_identity_hash: Option<[u8; 16]>,
app_flag: bool,
) -> bool {
if self.quarantined_links.contains(&link_id) {
return false;
@@ -274,7 +275,11 @@ impl PnInboundRuntime {
// A later split segment retains the original exact owner. If its
// advertisement is now rejected, the accounting conclusion owns
// terminal cleanup.
return self.resource_policy_allows(data_size, existing.peer_destination_hash);
return self.resource_policy_allows(
data_size,
existing.peer_destination_hash,
app_flag,
);
}
let admission_record = self
@@ -317,8 +322,8 @@ impl PnInboundRuntime {
let capacity_allows = self.resource_bypasses_limits(owner_peer_destination)
|| self.active_limited_resource_count() < self.admission.config().max_inbound_syncs;
let policy_allows =
capacity_allows && self.resource_policy_allows(data_size, owner_peer_destination);
let policy_allows = capacity_allows
&& self.resource_policy_allows(data_size, owner_peer_destination, app_flag);
if !policy_allows {
// A first AcceptApp rejection creates no Reticulum lifecycle event,
// so the offer record must be released synchronously here.
@@ -344,9 +349,12 @@ impl PnInboundRuntime {
&self,
data_size: usize,
peer_destination_hash: Option<[u8; 16]>,
app_flag: bool,
) -> bool {
// Client uploads set the Resource app flag and skip the static-peer gate.
data_size <= self.max_resource_bytes
&& (!self.admission.config().from_static_only
|| app_flag
|| peer_destination_hash
.as_ref()
.is_some_and(|peer| self.admission.is_static_peer(peer)))
@@ -720,6 +728,7 @@ mod tests {
LinkManagerAccountingEvent::ResourceCompletion(ResourceCompletion {
link_id,
resource_hash: resource_id,
last_segment_hash: resource_id,
data,
metadata: None,
})
@@ -774,7 +783,7 @@ mod tests {
Err(OfferResponse::ErrorThrottled)
);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
let job = runtime
.handle_accounting_event(completed(link(1), resource(3), vec![]))
@@ -793,7 +802,7 @@ mod tests {
);
assert_eq!(runtime.admission_state(&link(1)), None);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
let job = runtime
.handle_accounting_event(completed(link(1), resource(3), vec![1]))
@@ -805,7 +814,7 @@ mod tests {
runtime
.conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid)
.unwrap();
assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(4)));
let client_job = runtime
.handle_accounting_event(completed(link(1), resource(4), vec![2]))
@@ -824,7 +833,7 @@ mod tests {
identity(4),
&PnOfferEvaluation::WantAll,
);
assert!(runtime.accept_resource(link(3), resource(5), 10, Some(identity(4))));
assert!(runtime.accept_resource(link(3), resource(5), 10, Some(identity(4)), false));
runtime.handle_accounting_event(started(link(3), resource(5)));
runtime.handle_accounting_event(completed(link(3), resource(5), vec![6]));
assert_eq!(
@@ -836,7 +845,7 @@ mod tests {
runtime.commit_offer(postponed, &PnOfferEvaluation::HaveAll),
Err(OfferResponse::ErrorThrottled)
);
assert!(runtime.accept_resource(link(1), resource(7), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(7), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(7)));
let job = runtime
.handle_accounting_event(completed(link(1), resource(7), vec![8]))
@@ -857,9 +866,9 @@ mod tests {
100,
);
assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer)));
assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer), false));
assert!(
runtime.accept_resource(link(1), resource(3), 100, Some(identity(9))),
runtime.accept_resource(link(1), resource(3), 100, Some(identity(9)), false),
"later split advertisements retain the exact original owner"
);
}
@@ -873,8 +882,8 @@ mod tests {
identity(2),
&PnOfferEvaluation::WantAll,
);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
assert!(runtime.accept_resource(link(1), resource(4), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(4)));
let extra = runtime
@@ -916,7 +925,7 @@ mod tests {
);
assert_eq!(runtime.correlation_count(), 0);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
assert_eq!(
runtime.admission_state(&link(1)),
@@ -933,7 +942,7 @@ mod tests {
identity(2),
&PnOfferEvaluation::WantAll,
);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
let job = runtime
@@ -979,7 +988,7 @@ mod tests {
identity(2),
&PnOfferEvaluation::WantAll,
);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
let job = runtime
.handle_accounting_event(completed(link(1), resource(3), vec![4]))
@@ -1017,7 +1026,7 @@ mod tests {
identity(2),
&PnOfferEvaluation::WantAll,
);
assert!(!runtime.accept_resource(link(1), resource(3), 1_001, Some(identity(2))));
assert!(!runtime.accept_resource(link(1), resource(3), 1_001, Some(identity(2)), false));
assert_eq!(runtime.admission_state(&link(1)), None);
}
@@ -1034,9 +1043,12 @@ mod tests {
100,
);
assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer)));
assert!(!runtime.accept_resource(link(2), resource(4), 100, Some(identity(9))));
assert!(!runtime.accept_resource(link(3), resource(5), 100, None));
assert!(runtime.accept_resource(link(1), resource(3), 100, Some(peer), false));
assert!(!runtime.accept_resource(link(2), resource(4), 100, Some(identity(9)), false));
assert!(!runtime.accept_resource(link(3), resource(5), 100, None, false));
assert!(runtime.accept_resource(link(4), resource(6), 100, Some(identity(9)), true));
assert!(runtime.accept_resource(link(5), resource(7), 100, None, true));
assert!(!runtime.accept_resource(link(6), resource(8), 101, None, true));
}
#[test]
@@ -1048,7 +1060,7 @@ mod tests {
identity(2),
&PnOfferEvaluation::WantAll,
);
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2))));
assert!(runtime.accept_resource(link(1), resource(3), 10, Some(identity(2)), false));
runtime.handle_accounting_event(started(link(1), resource(3)));
runtime.handle_accounting_event(concluded(
link(1),
@@ -1082,7 +1094,8 @@ mod tests {
link_id,
resource_id,
10,
Some(identity(index as u8 + 20))
Some(identity(index as u8 + 20)),
false
));
runtime.handle_accounting_event(started(link_id, resource_id));
runtime.handle_accounting_event(concluded(link_id, resource_id, conclusion));
@@ -1112,7 +1125,7 @@ mod tests {
#[test]
fn invalid_unidentified_client_closes_without_shared_throttle_state() {
let mut runtime = runtime(PnInboundAdmissionConfig::default());
assert!(runtime.accept_resource(link(1), resource(3), 10, None));
assert!(runtime.accept_resource(link(1), resource(3), 10, None, false));
runtime.handle_accounting_event(started(link(1), resource(3)));
let job = runtime
.handle_accounting_event(completed(link(1), resource(3), vec![4]))
@@ -1127,7 +1140,7 @@ mod tests {
assert!(claim.should_close_link());
assert_eq!(runtime.throttle_count(), 0);
assert!(runtime.is_link_quarantined(&link(1)));
assert!(!runtime.accept_resource(link(1), resource(4), 10, None));
assert!(!runtime.accept_resource(link(1), resource(4), 10, None, false));
assert!(matches!(
runtime.preflight_offer(link(1), Some(identity(5))),
Err(OfferResponse::ErrorThrottled)
@@ -1141,8 +1154,8 @@ mod tests {
max_inbound_syncs: 1,
..PnInboundAdmissionConfig::default()
});
assert!(runtime.accept_resource(link(1), resource(2), 10, Some(identity(3))));
assert!(!runtime.accept_resource(link(4), resource(5), 10, Some(identity(6))));
assert!(runtime.accept_resource(link(1), resource(2), 10, Some(identity(3)), false));
assert!(!runtime.accept_resource(link(4), resource(5), 10, Some(identity(6)), false));
runtime.handle_accounting_event(started(link(1), resource(2)));
let job = runtime
@@ -1154,14 +1167,14 @@ mod tests {
LinkResourceConclusion::Complete,
));
assert!(
!runtime.accept_resource(link(4), resource(5), 10, Some(identity(6))),
!runtime.accept_resource(link(4), resource(5), 10, Some(identity(6)), false),
"a completed Resource retains its slot through stamp validation"
);
runtime
.conclude_validation(job.token(), job.link_id(), PnValidationOutcome::Valid)
.unwrap();
assert!(runtime.accept_resource(link(4), resource(5), 10, Some(identity(6))));
assert!(runtime.accept_resource(link(4), resource(5), 10, Some(identity(6)), false));
}
#[test]
@@ -1174,12 +1187,13 @@ mod tests {
static_sequential: false,
max_inbound_syncs: 1,
from_static_only: true,
..PnInboundAdmissionConfig::default()
},
[peer_destination],
100,
);
assert!(bypass.accept_resource(link(1), resource(3), 10, Some(peer)));
assert!(bypass.accept_resource(link(1), resource(4), 10, Some(peer)));
assert!(bypass.accept_resource(link(1), resource(3), 10, Some(peer), false));
assert!(bypass.accept_resource(link(1), resource(4), 10, Some(peer), false));
let mut limited = PnInboundRuntime::new(
PnInboundAdmissionConfig {
@@ -1187,11 +1201,12 @@ mod tests {
static_sequential: true,
max_inbound_syncs: 1,
from_static_only: true,
..PnInboundAdmissionConfig::default()
},
[peer_destination],
100,
);
assert!(limited.accept_resource(link(1), resource(3), 10, Some(peer)));
assert!(!limited.accept_resource(link(1), resource(4), 10, Some(peer)));
assert!(limited.accept_resource(link(1), resource(3), 10, Some(peer), false));
assert!(!limited.accept_resource(link(1), resource(4), 10, Some(peer), false));
}
}
File diff suppressed because it is too large. Load diff
+72 -86
View File
@@ -26,16 +26,21 @@ impl SendMethod {
}
}
/// The LXMF release `lxmd-rs` follows, named in its `--version` line and
/// announced as its propagation node version.
pub const LXMF_COMPAT_VERSION: &str = lxmf_core::constants::LXMF_COMPAT_VERSION;
#[derive(Parser)]
#[command(
name = "lxmd-rs",
bin_name = "lxmd-rs",
about = "LXMF Propagation Daemon",
version
disable_version_flag = true,
infer_long_args = true
)]
pub struct Args {
/// Path to configuration directory.
#[arg(short, long)]
#[arg(long, short_alias = 'c')]
pub config: Option<String>,
/// Path to alternative Reticulum configuration directory.
@@ -46,6 +51,23 @@ pub struct Args {
#[arg(short = 'p', long = "propagation-node")]
pub propagation_node: bool,
/// Quarantine the legacy relay store and initialize the separate v2 store.
/// Run only after stopping all old relay writers and their auto-restart jobs.
#[arg(long, requires = "relay_writers_stopped")]
pub migrate_propagation_store: bool,
/// Confirm all legacy app/daemon relay writers are stopped for migration.
#[arg(long, requires = "migrate_propagation_store")]
pub relay_writers_stopped: bool,
/// Import an independently verified legacy opaque-ingress recovery manifest.
#[arg(long, requires_all = ["migrate_propagation_store", "recovery_manifest_sha256"])]
pub recover_propagation_manifest: Option<PathBuf>,
/// Separately approved SHA-256 of the exact recovery manifest file.
#[arg(long, requires = "recover_propagation_manifest")]
pub recovery_manifest_sha256: Option<String>,
/// Executable to run when a message is received, overriding config.
#[arg(short = 'i', long = "on-inbound", value_name = "PATH")]
pub on_inbound: Option<String>,
@@ -62,11 +84,15 @@ pub struct Args {
#[arg(long)]
pub exampleconfig: bool,
/// Run as a system service (no interactive output).
/// Print version and exit.
#[arg(long, short_alias = 'V')]
pub version: bool,
/// Service mode; the process remains in the foreground.
#[arg(short = 's', long)]
pub service: bool,
/// Display local node status and exit.
/// Query node status over Reticulum and exit (use `--remote` for another node).
#[arg(long)]
pub status: bool,
@@ -90,30 +116,33 @@ pub struct Args {
#[arg(short = 'r', long, value_name = "DEST_HASH")]
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")]
pub identity: Option<PathBuf>,
/// Send a single message and exit: `--send <dest_hash> <content>`.
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
/// Send messages and exit: `--send <dest_hash> <content>...`, one message
/// per content, queued together.
#[arg(long, num_args = 1.., value_names = ["DEST_HASH", "CONTENT"])]
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")]
pub send_file: Option<PathBuf>,
/// Delivery method for --send.
/// Delivery method for `--send`.
#[arg(long, value_enum, default_value_t = SendMethod::Opportunistic)]
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)]
pub send_timeout_secs: u64,
/// Attach custom LXMF fields to the outgoing --send message. Accepts a
/// JSON object mapping field-id -> base64(value). Example:
/// --send-fields-json '{"1":"aGVsbG8=","42":"AAECA/8="}'
/// Only meaningful alongside --send.
/// Attach binary LXMF fields to `--send`. Accepts a JSON object mapping
/// decimal field IDs (0–255) to base64-encoded bytes. Example:
/// `--send-fields-json '{"200":"aGVsbG8=","201":"AAECA/8="}'`.
/// 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")]
pub send_fields_json: Option<String>,
}
@@ -162,83 +191,22 @@ pub fn parse_destination_hash(raw: &str) -> Result<[u8; 16], String> {
Ok(hash)
}
/// Python `lxmd.__default_lxmd_config__` (LXMF 1.3.0), printed by
/// `--exampleconfig` and written on first run.
pub fn example_config() -> &'static str {
r#"# This is an example LXM Daemon config file.
[propagation]
include_str!("lxmd_default_config.txt")
}
enable_node = no
# control_allowed = 7d7e542829b40f32364499b27438dba8, 437229f8e29598b2282b88bad5e44698
# node_name = Anonymous Propagation Node
announce_interval = 360
announce_at_start = yes
autopeer = yes
autopeer_maxdepth = 6
# Validate inbound propagation stamp batches sequentially by default.
# sequential_pn_stamp_validation = yes
# Let configured static peers bypass sequential validation and inbound limits.
# static_peers_bypass_sequential = yes
# Maximum concurrent inbound propagation sync transfers.
# max_inbound_syncs = 3
# message_storage_limit = 500
# propagation_message_max_accepted_size = 256
# propagation_sync_max_accepted_size = 10240
# propagation_stamp_cost_target = 16
# propagation_stamp_cost_flexibility = 3
# peering_cost = 18
# remote_peering_cost_max = 26
# max_peers = 20
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d, 5a2d0029b6e5ec87020abaea0d746da4
# prioritise_destinations = 4a594a8cced4a8f6adf23a8ac67b4011
# from_static_only = True
auth_required = no
[lxmf]
display_name = Anonymous Peer
announce_at_start = no
# announce_interval = 360
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
[logging]
loglevel = 4
"#
/// The file Python `create_default_config` writes: ConfigObj drops the
/// trailing blank line of the default text.
pub fn default_config_file_text() -> String {
format!("{}\n", example_config().trim_end_matches('\n'))
}
/// 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
/// 32-byte hex lines; comments and inline comments are ignored only because
/// their raw line length is not exactly 32 bytes.
/// Read errors return an empty list. Each line must contain exactly 32 ASCII
/// hexadecimal characters; a trailing CR is allowed for CRLF files. Whitespace
/// and comments are not stripped, so lines containing them are skipped.
///
/// Python reference: `lxmd.py` reads `ignored` / `allowed` from the config dir.
pub fn load_hash_list(path: &Path) -> Vec<[u8; 16]> {
@@ -304,6 +272,24 @@ mod tests {
assert_eq!(args.identity.as_deref(), Some(Path::new("/tmp/id")));
}
// lxmd.py has `--config` and `--version` only; the releases also took
// `-c` and `-V`, which still parse and stay out of the help.
#[test]
fn released_short_forms_still_parse_and_are_hidden() {
let args = Args::try_parse_from(["lxmd", "-c", "/tmp/lxmd"]).unwrap();
assert_eq!(args.config.as_deref(), Some("/tmp/lxmd"));
assert!(Args::try_parse_from(["lxmd", "-V"]).unwrap().version);
assert!(Args::try_parse_from(["lxmd", "--version"]).unwrap().version);
use clap::CommandFactory;
let help = Args::command().render_long_help().to_string();
assert!(help.contains("--config") && help.contains("--version"));
assert!(!help.contains("-c,") && !help.contains("-V,"), "{help}");
let error = Args::try_parse_from(["lxmd", "-x"]).err().unwrap();
assert_eq!(error.exit_code(), 2, "argparse exits 2");
}
#[test]
fn parse_destination_hash_accepts_pretty_hex() {
let hash =
+92 -54
View File
@@ -17,6 +17,8 @@ use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_transport::messages::TransportMessage;
use tokio::sync::mpsc;
const PATHFINDER_M: i64 = rns_transport::constants::PATHFINDER_M as i64;
pub const CONTROL_APP_NAME: &str = "lxmf.propagation.control";
pub const PROPAGATION_APP_NAME: &str = "lxmf.propagation";
@@ -62,11 +64,23 @@ pub async fn query_control(
path,
encode_control_payload(payload),
0,
Duration::from_secs_f64(timeout_secs.max(0.0)),
control_deadline(timeout_secs),
)
.await
}
/// Python adds the timeout to `time.time()`: a negative one has already
/// expired, and an infinite or NaN one never does.
fn control_deadline(timeout_secs: f64) -> Duration {
const NEVER: Duration = Duration::from_secs(u32::MAX as u64);
if timeout_secs.is_nan() {
return NEVER;
}
Duration::try_from_secs_f64(timeout_secs.max(0.0))
.unwrap_or(NEVER)
.min(NEVER)
}
fn encode_control_payload(payload: Vec<u8>) -> Vec<u8> {
// LinkClient accepts an encoded MessagePack value. Raw hash bytes can
// themselves form a complete value (e.g. 0xaf followed by 15 bytes), so
@@ -145,16 +159,13 @@ pub fn encode_control_success() -> Vec<u8> {
encode_value(&Value::Boolean(true))
}
pub fn encode_nil_response() -> Vec<u8> {
encode_value(&Value::Nil)
}
pub fn encode_router_control_stats(
router: &LxmRouter,
identity_hash: [u8; 16],
propagation_destination_hash: [u8; 16],
node: Option<&PropagationNode>,
now: f64,
hops_to: impl Fn(&[u8; 16]) -> u8,
) -> Vec<u8> {
let message_count = node
.map(PropagationNode::message_count)
@@ -182,8 +193,8 @@ pub fn encode_router_control_stats(
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.handled_messages))
.unwrap_or_else(|| peer.unhandled_messages() as usize);
.map(|node| node.unhandled_message_count(&peer.unhandled_messages))
.unwrap_or_else(|| peer.unhandled_message_count());
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -192,7 +203,14 @@ pub fn encode_router_control_stats(
Value::from(peer.state as u64),
),
(Value::String("alive".into()), Value::Boolean(peer.alive)),
(Value::String("name".into()), Value::Nil),
(
Value::String("name".into()),
peer.metadata
.as_ref()
.and_then(|metadata| metadata.get(&lxmf_core::constants::PN_META_NAME))
.and_then(|name| std::str::from_utf8(name).ok())
.map_or(Value::Nil, Value::from),
),
(
Value::String("last_heard".into()),
Value::from(peer.last_heard as i64),
@@ -231,20 +249,20 @@ pub fn encode_router_control_stats(
),
(
Value::String("target_stamp_cost".into()),
option_u8(peer.stamp_cost),
option_f64(peer.stamp_cost),
),
(
Value::String("stamp_cost_flexibility".into()),
option_u8(peer.stamp_cost_flexibility),
option_f64(peer.stamp_cost_flexibility),
),
(
Value::String("peering_cost".into()),
Value::from(peer.peering_cost as u64),
Value::F64(peer.peering_cost),
),
(Value::String("peering_key".into()), peering_key_value),
(
Value::String("network_distance".into()),
Value::from(255_u64),
Value::from(hops_to(hash)),
),
(Value::String("rx_bytes".into()), Value::from(peer.rx_bytes)),
(Value::String("tx_bytes".into()), Value::from(peer.tx_bytes)),
@@ -295,27 +313,27 @@ pub fn encode_router_control_stats(
),
(
Value::String("propagation_limit".into()),
Value::from(router.config.propagation_limit_kb as u64),
router.config.propagation_limit_kb.to_value(),
),
(
Value::String("sync_limit".into()),
Value::from(router.config.sync_limit_kb as u64),
router.config.sync_limit_kb.to_value(),
),
(
Value::String("target_stamp_cost".into()),
Value::from(router.config.propagation_stamp_cost as u64),
Value::F64(router.config.propagation_stamp_cost),
),
(
Value::String("stamp_cost_flexibility".into()),
Value::from(router.config.propagation_stamp_flex as u64),
Value::F64(router.config.propagation_stamp_flex),
),
(
Value::String("peering_cost".into()),
Value::from(router.config.ext.peering_cost as u64),
Value::F64(router.config.ext.peering_cost),
),
(
Value::String("max_peering_cost".into()),
Value::from(router.config.ext.max_peering_cost as u64),
Value::F64(router.config.ext.max_peering_cost),
),
(
Value::String("autopeer_maxdepth".into()),
@@ -506,13 +524,13 @@ pub fn format_remote_status(
));
out.push_str(&format!(
"Required propagation stamp cost is {}, flexibility is {}\n",
map_u64(stats, "target_stamp_cost").unwrap_or(0),
map_u64(stats, "stamp_cost_flexibility").unwrap_or(0),
map_python_str(stats, "target_stamp_cost"),
map_python_str(stats, "stamp_cost_flexibility"),
));
out.push_str(&format!(
"Peering cost is {}, max remote peering cost is {}\n",
map_u64(stats, "peering_cost").unwrap_or(0),
map_u64(stats, "max_peering_cost").unwrap_or(0),
map_python_str(stats, "peering_cost"),
map_python_str(stats, "max_peering_cost"),
));
out.push_str(&format!("Accepting propagated messages from {who}\n"));
out.push_str(&format!(
@@ -582,8 +600,8 @@ pub fn format_remote_status(
"Unreachable"
};
let last_heard_age = (now - map_f64(peer, "last_heard").unwrap_or(0.0)).max(0.0);
let hops = map_i64(peer, "network_distance").unwrap_or(255);
let hops_text = if hops == 255 {
let hops = map_i64(peer, "network_distance").unwrap_or(PATHFINDER_M);
let hops_text = if hops == PATHFINDER_M {
"hops unknown".to_string()
} else if hops == 1 {
"1 hop away".to_string()
@@ -604,7 +622,7 @@ pub fn format_remote_status(
_ => "never synced".to_string(),
};
let name =
lxmf_core::presentation::sanitize_name(map_str(peer, "name").unwrap_or(""), 46);
lxmf_core::presentation::sanitize_name_lxmd(map_str(peer, "name").unwrap_or(""));
let display_name = if name.chars().count() > 45 {
format!("{}...", name.chars().take(45).collect::<String>())
} else {
@@ -624,9 +642,9 @@ pub fn format_remote_status(
));
out.push_str(&format!(
" Costs : Propagation {} (flex {}), peering {}\n",
map_optional_display(peer, "target_stamp_cost"),
map_optional_display(peer, "stamp_cost_flexibility"),
map_optional_display(peer, "peering_cost"),
map_optional_cost(peer, "target_stamp_cost"),
map_optional_cost(peer, "stamp_cost_flexibility"),
map_optional_cost(peer, "peering_cost"),
));
out.push_str(&format!(" Sync key : {peering_key}\n"));
out.push_str(&format!(
@@ -712,13 +730,6 @@ fn map_display(value: &Value, key: &str) -> String {
.unwrap_or_else(|| "None".to_string())
}
fn map_optional_display(value: &Value, key: &str) -> String {
match map_value(value, key) {
Some(v) if !v.is_nil() => value_to_display(v),
_ => "unknown".to_string(),
}
}
fn value_to_display(value: &Value) -> String {
if value.is_nil() {
"None".to_string()
@@ -839,8 +850,21 @@ fn format_python_float(value: f64) -> String {
}
}
fn option_u8(value: Option<u8>) -> Value {
value.map(|v| Value::from(v as u64)).unwrap_or(Value::Nil)
fn map_optional_cost(value: &Value, key: &str) -> String {
match map_value(value, key) {
Some(v) if !v.is_nil() => map_python_str(value, key),
_ => "unknown".to_string(),
}
}
/// Python `str()` of a number: floats keep their decimal point.
fn map_python_str(value: &Value, key: &str) -> String {
match map_value(value, key) {
Some(Value::F64(f)) => format!("{f:?}"),
Some(Value::F32(f)) => format!("{:?}", f64::from(*f)),
Some(v) if !v.is_nil() => value_to_display(v),
_ => "0".to_string(),
}
}
fn option_f64(value: Option<f64>) -> Value {
@@ -857,6 +881,16 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[test]
fn control_deadline_accepts_every_python_float_timeout() {
assert_eq!(control_deadline(-1.0), Duration::ZERO);
assert_eq!(control_deadline(1.5), Duration::from_millis(1500));
let never = Duration::from_secs(u32::MAX as u64);
for timeout in [f64::INFINITY, f64::NAN, 1e300] {
assert_eq!(control_deadline(timeout), never, "{timeout}");
}
}
#[test]
fn control_payload_preserves_every_peer_hash_prefix_as_binary() {
for prefix in 0..=u8::MAX {
@@ -929,16 +963,16 @@ mod tests {
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(
RecalledDestinationRpcEntry {
dest_hash: remote_destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
},
)))
.send(TransportQueryResponse::RecalledDestination(Some({
let mut entry = RecalledDestinationRpcEntry::default();
entry.dest_hash = remote_destination_hash;
entry.public_key = public_key;
entry.app_data = None;
entry.ratchet = None;
entry.hops = 2;
entry.timestamp = 1.0;
entry
})))
.expect("return resolved identity");
assert!(transport_rx.try_recv().is_err());
});
@@ -1070,10 +1104,8 @@ mod tests {
use lxmf_core::peer::LxmPeer;
use lxmf_core::router::{LxmRouter, RouterConfig};
let mut config = RouterConfig {
propagation_enabled: true,
..Default::default()
};
let mut config = RouterConfig::default();
config.propagation_enabled = true;
config.delivery_limit_kb = 0.38;
config.ext.message_storage_limit = Some(500_000_000);
let mut router = LxmRouter::new(config);
@@ -1086,12 +1118,18 @@ mod tests {
let mut peer = LxmPeer::new(peer_hash);
peer.offered = 4;
peer.outgoing = 2;
peer.set_unhandled_count(1);
peer.add_unhandled_message(&[0x31; 32]);
router.peers.insert(peer_hash, peer);
router.static_peers.push(peer_hash);
let encoded =
encode_router_control_stats(&router, [0x11; 16], [0x22; 16], None, 1_700_003_600.0);
let encoded = encode_router_control_stats(
&router,
[0x11; 16],
[0x22; 16],
None,
1_700_003_600.0,
|_| rns_transport::constants::PATHFINDER_M,
);
let stats = decode_value(&encoded);
let keys = stats
.as_map()
@@ -0,0 +1,233 @@
# This is an example LXM Daemon config file.
# You should probably edit it to suit your
# intended usage.
[propagation]
# Whether to enable propagation node
enable_node = no
# You can specify identity hashes for remotes
# that are allowed to control and query status
# for this propagation node.
# control_allowed = 7d7e542829b40f32364499b27438dba8, 437229f8e29598b2282b88bad5e44698
# An optional name for this node, included
# in announces.
# node_name = Anonymous Propagation Node
# Automatic announce interval in minutes.
# 6 hours by default.
announce_interval = 360
# Whether to announce when the node starts.
announce_at_start = yes
# Wheter to automatically peer with other
# propagation nodes on the network.
autopeer = yes
# The maximum peering depth (in hops) for
# automatically peered nodes.
autopeer_maxdepth = 6
# The maximum amount of storage to use for
# the LXMF Propagation Node message store,
# specified in megabytes. When this limit
# is reached, LXMF will periodically remove
# messages in its message store. By default,
# LXMF prioritises keeping messages that are
# new and small. Large and old messages will
# be removed first. This setting is optional
# and defaults to 500 megabytes.
# message_storage_limit = 500
# The maximum accepted transfer size per in-
# coming propagation message, in kilobytes.
# This sets the upper limit for the size of
# single messages accepted onto this node.
# propagation_message_max_accepted_size = 256
# The maximum accepted transfer size per in-
# coming propagation node sync.
#
# If a node wants to propagate a larger number
# of messages to this node, than what can fit
# within this limit, it will prioritise sending
# the smallest messages first, and try again
# with any remaining messages at a later point.
# propagation_sync_max_accepted_size = 10240
# You can configure the target stamp cost
# required to deliver messages via this node.
# propagation_stamp_cost_target = 16.0
# If set higher than 0, the stamp cost flexi-
# bility option will make this node accept
# messages with a lower stamp cost than the
# target from other propagation nodes (but
# not from peers directly). This allows the
# network to gradually adjust stamp cost.
# propagation_stamp_cost_flexibility = 3.0
# If a peer delivers messages with stamp costs
# not conforming to this node's targets, it'll
# be throttled, by default for 5 minutes. You
# can configure the throttle period, and for
# constrained nodes, it may be a good idea to
# set a much higher throttle time. Real LXMF
# propagation nodes will never deliver messages
# with lower stamp values than required by the
# receiving node.
# propagation_stamp_throttle = 5
# The peering_cost option configures the target
# value required for a remote node to peer with
# and deliver messages to this node.
# peering_cost = 18.0
# You can configure the maximum peering cost
# of remote nodes that this node will peer with.
# Setting this to a higher number will allow
# this node to peer with other nodes requiring
# a higher peering key value, but will require
# more computation time during initial peering
# when generating the peering key.
# remote_peering_cost_max = 26.0
# You can tell the LXMF message router to
# prioritise storage for one or more
# destinations. If the message store reaches
# the specified limit, LXMF will prioritise
# keeping messages for destinations specified
# with this option. This setting is optional,
# and generally you do not need to use it.
# prioritise_destinations = 41d20c727598a3fbbdf9106133a3a0ed, d924b81822ca24e68e2effea99bcb8cf
# You can configure the maximum number of other
# propagation nodes that this node will peer
# with automatically. The default is 20.
# max_peers = 20
# You can configure a list of static propagation
# node peers, that this node will always be
# peered with, by specifying a list of
# destination hashes.
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d, 5a2d0029b6e5ec87020abaea0d746da4
# You can configure the propagation node to
# only accept incoming propagation messages
# from configured static peers.
# from_static_only = True
# By default, stamp validation jobs for PN
# sync batches will run sequentially. If
# a peer offers messages while another batch
# is already processing, it will receive a
# throttle response to indicate that it can
# retry later. If you have a fast system, you
# can disable this to accept and validate
# everything as soon as it is offered.
# sequential_pn_stamp_validation = yes
# You can configure whether static peers are
# allowed have their PN syncs processed as
# soon as they are offered, regardless of
# whether another batch is already validating.
# static_peers_bypass_sequential = yes
# You can configure how many concurrent inbound
# propagation sync transfers will be accepted.
# Once this number is reached, nodes offering
# messages will receive a throttle response to
# indicate that they can retry later. On a slow
# system, it's a good idea to change this to 1.
# max_inbound_syncs = 3
# By default, any destination is allowed to
# connect and download messages, but you can
# optionally restrict this. If you enable
# authentication, you must provide a list of
# allowed identity hashes in the a file named
# "allowed" in the lxmd config directory.
auth_required = no
[lxmf]
# The LXM Daemon will create an LXMF destination
# that it can receive messages on. This option sets
# the announced display name for this destination.
display_name = Anonymous Peer
# It is possible to announce the internal LXMF
# destination when the LXM Daemon starts up.
announce_at_start = no
# You can also announce the delivery destination
# at a specified interval. This is not enabled by
# default.
# announce_interval = 360
# You can configure the required stamp cost for
# incoming messages.
# stamp_cost = 12
# The maximum accepted unpacked size for mes-
# sages received directly from other peers,
# specified in kilobytes. Messages larger than
# this will be rejected before the transfer
# begins.
delivery_transfer_max_accepted_size = 1
# You can configure an external program to be run
# every time a message is received. The program
# will receive as an argument the full path to the
# message saved as a file. The example below will
# simply result in the message getting deleted as
# soon as it has been received.
# on_inbound = rm
[logging]
# Valid log levels are 0 through 7:
# 0: Log only critical information
# 1: Log errors and lower log levels
# 2: Log warnings and lower log levels
# 3: Log notices and lower log levels
# 4: Log info and lower (this is the default)
# 5: Verbose logging
# 6: Debug logging
# 7: Extreme logging
loglevel = 4
+49 -28
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
//! binary so CLI behavior can be tested directly.
//! Path selection reads environment variables and checks the filesystem;
//! these helpers do not start the daemon runtime.
use std::path::{Path, PathBuf};
@@ -19,8 +19,10 @@ pub struct LxmdPaths {
pub ratchets_dir: PathBuf,
pub ratchet_ring_path: PathBuf,
pub ratchet_control_path: PathBuf,
pub received_ratchets_dir: PathBuf,
pub known_identities_path: PathBuf,
/// Received-ratchet files of earlier releases; Reticulum keeps received ratchets now.
pub legacy_received_ratchets_dir: PathBuf,
/// Identity-key file of earlier releases; Reticulum keeps the known destinations.
pub legacy_known_identities_path: PathBuf,
pub legacy_lxmf_dir: PathBuf,
pub legacy_identity_path: PathBuf,
pub legacy_messages_dir: PathBuf,
@@ -40,8 +42,8 @@ impl LxmdPaths {
let ratchets_dir = lxmf_storage_dir.join("ratchets");
let ratchet_ring_path = ratchets_dir.join("ring");
let ratchet_control_path = ratchets_dir.join("ring.control");
let received_ratchets_dir = ratchets_dir.join("received");
let known_identities_path = ratchets_dir.join("known_identities");
let legacy_received_ratchets_dir = ratchets_dir.join("received");
let legacy_known_identities_path = ratchets_dir.join("known_identities");
let legacy_lxmf_dir = config_dir.join(".lxmf");
let legacy_identity_path = legacy_lxmf_dir.join("identity");
@@ -60,8 +62,8 @@ impl LxmdPaths {
ratchets_dir,
ratchet_ring_path,
ratchet_control_path,
received_ratchets_dir,
known_identities_path,
legacy_received_ratchets_dir,
legacy_known_identities_path,
legacy_lxmf_dir,
legacy_identity_path,
legacy_messages_dir,
@@ -88,7 +90,6 @@ pub struct LocalStatusView {
pub propagation_size: usize,
pub pending_outbound: usize,
pub pending_deferred_stamps: usize,
pub stamp_costs_cached: usize,
}
impl LocalStatusView {
@@ -105,7 +106,6 @@ impl LocalStatusView {
propagation_size: stats.propagation_size,
pending_outbound: stats.pending_outbound,
pending_deferred_stamps: stats.pending_deferred_stamps,
stamp_costs_cached: stats.stamp_costs_cached,
}
}
}
@@ -118,8 +118,7 @@ pub fn format_local_status(status: &LocalStatusView) -> String {
Propagation messages: {}\n\
Propagation storage bytes: {}\n\
Pending outbound: {}\n\
Pending deferred stamps: {}\n\
Cached stamp costs: {}\n",
Pending deferred stamps: {}\n",
hex::encode(status.lxmf_dest_hash),
if status.propagation_enabled {
"enabled"
@@ -131,7 +130,6 @@ pub fn format_local_status(status: &LocalStatusView) -> String {
status.propagation_size,
status.pending_outbound,
status.pending_deferred_stamps,
status.stamp_costs_cached,
)
}
@@ -163,7 +161,7 @@ pub fn format_local_peers(peers: &[LocalPeerView]) -> String {
out
}
pub fn delivery_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
pub fn delivery_announce_app_data(display_name: Option<&str>, stamp_cost: Option<f64>) -> Vec<u8> {
lxmf_core::handlers::get_announce_app_data(display_name, stamp_cost)
}
@@ -276,6 +274,16 @@ pub fn preflight_control_command(
.to_string(),
});
}
// Python `_remote_init` loads the identity before the remote hash is parsed.
if rns_identity::identity::Identity::from_file(&identity_path).is_err() {
return Err(ControlPreflightError {
exit_code: 4,
message: format!(
"Could not load the Primary Identity from {}",
identity_path.display()
),
});
}
let remote_hash = match remote_hash {
Some(raw) => Some(parse_python_control_hash(raw, "remote")?),
@@ -341,11 +349,11 @@ mod tests {
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring.control")
);
assert_eq!(
paths.received_ratchets_dir,
paths.legacy_received_ratchets_dir,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/received")
);
assert_eq!(
paths.known_identities_path,
paths.legacy_known_identities_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/known_identities")
);
}
@@ -417,7 +425,6 @@ mod tests {
propagation_size: 4096,
pending_outbound: 4,
pending_deferred_stamps: 5,
stamp_costs_cached: 6,
};
assert_eq!(
@@ -428,8 +435,7 @@ mod tests {
Propagation messages: 3\n\
Propagation storage bytes: 4096\n\
Pending outbound: 4\n\
Pending deferred stamps: 5\n\
Cached stamp costs: 6\n"
Pending deferred stamps: 5\n"
);
}
@@ -452,28 +458,37 @@ mod tests {
#[test]
fn delivery_announce_app_data_matches_python_msgpack() {
// Python 1.0.1: msgpack([display_name, stamp_cost, [SF_COMPRESSION]])
// — LXMRouter.py:999-1001.
// LXMF 1.3.0 LXMRouter.get_announce_app_data output.
assert_eq!(
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
"93c40454657374109100"
hex::encode(delivery_announce_app_data(Some("Test"), Some(16.0))),
"94c40454657374109100cb4030000000000000"
);
assert_eq!(
hex::encode(delivery_announce_app_data(Some("x"), Some(8.5))),
"94c40178099100cb4021000000000000"
);
assert_eq!(
hex::encode(delivery_announce_app_data(None, None)),
"93c0c09100"
"94c0c09100c0"
);
}
#[test]
fn propagation_announce_app_data_matches_python_msgpack() {
let mut data =
lxmf_core::handlers::PropagationNodeAnnounceData::new(true, 256, 10_240, 16, 3, 18);
let mut data = lxmf_core::handlers::PropagationNodeAnnounceData::new(
true, 256, 10_240, 16.25, 3.0, 18.5,
);
data.timebase = 1_700_000_000;
data.set_name("Node");
// Upstream metadata order: 0xFE impl name, 0x00 version, then binary 0x01 name.
// `LXMRouter.get_propagation_node_app_data` at LXMF 1.3.1, `time.time` fixed to the timebase.
assert_eq!(
hex::encode(propagation_announce_app_data(&data)),
"97c2ce6553f100c3cd0100cd2800931003128101c4044e6f6465"
concat!(
"98c2ce6553f100c3cd0100cd28009311031383ccfea46c786d6400a5312e332e3101c4044e6f6465",
"93cb4030400000000000cb4008000000000000cb4032800000000000"
)
);
}
@@ -544,6 +559,12 @@ mod tests {
let identity = temp.join("identity");
std::fs::write(&identity, b"identity").unwrap();
let unloadable = preflight_control_command(&temp, None, None, Some("zz")).unwrap_err();
assert_eq!(unloadable.exit_code, 4);
rns_identity::identity::Identity::new()
.to_file(&identity)
.unwrap();
let invalid_remote = preflight_control_command(&temp, None, None, Some("zz")).unwrap_err();
assert_eq!(invalid_remote.exit_code, 203);
assert!(
+217 -49
View File
@@ -59,6 +59,35 @@ fn write_rust_identity(path: &Path) {
.expect("write Rust identity");
}
/// Kills and reaps the daemon on every path out of the test, panics included.
#[cfg(unix)]
struct Daemon(Option<Child>);
#[cfg(unix)]
impl Daemon {
fn child(&mut self) -> &mut Child {
self.0.as_mut().expect("daemon still owned")
}
fn output(mut self) -> Output {
self.0
.take()
.expect("daemon still owned")
.wait_with_output()
.expect("collect lxmd-rs output")
}
}
#[cfg(unix)]
impl Drop for Daemon {
fn drop(&mut self) {
if let Some(mut child) = self.0.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
#[cfg(unix)]
fn wait_with_timeout(child: &mut Child, timeout: Duration) -> Option<std::process::ExitStatus> {
let deadline = Instant::now() + timeout;
@@ -96,7 +125,7 @@ fn help_lists_cli_surface_without_starting_runtime() {
#[cfg(unix)]
#[test]
fn ctrl_c_exits_during_startup_announce_wait() {
fn ctrl_c_exits_during_deferred_start() {
let lxmf_dir = TestDir::new("lxmf-ctrlc");
let rns_dir = TestDir::new("rns-ctrlc");
fs::write(
@@ -126,24 +155,27 @@ discover_interfaces = No
)
.expect("write no-interface Reticulum config");
let mut child = Command::new(env!("CARGO_BIN_EXE_lxmd-rs"))
.arg("--config")
.arg(lxmf_dir.path())
.arg("--rnsconfig")
.arg(rns_dir.path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("lxmd-rs subprocess should start");
// Declared after the directories so it is dropped first: the daemon must not outlive its config.
let mut daemon = Daemon(Some(
Command::new(env!("CARGO_BIN_EXE_lxmd-rs"))
.arg("--config")
.arg(lxmf_dir.path())
.arg("--rnsconfig")
.arg(rns_dir.path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("lxmd-rs subprocess should start"),
));
let identity_path = lxmf_dir.path().join("identity");
let startup_deadline = Instant::now() + Duration::from_secs(5);
// A loaded host can take seconds over a fresh debug binary's first exec.
let startup_deadline = Instant::now() + Duration::from_secs(30);
while !identity_path.exists() {
if let Some(status) = child.try_wait().expect("poll lxmd-rs startup") {
let output = child.wait_with_output().expect("collect lxmd-rs output");
if let Some(status) = daemon.child().try_wait().expect("poll lxmd-rs startup") {
panic!(
"lxmd-rs exited before startup announce wait ({status}):\n{}",
combined_output(&output)
combined_output(&daemon.output())
);
}
assert!(
@@ -155,31 +187,130 @@ discover_interfaces = No
std::thread::sleep(Duration::from_millis(100));
let signal_status = Command::new("kill")
.arg("-INT")
.arg(child.id().to_string())
.arg(daemon.child().id().to_string())
.status()
.expect("send SIGINT to lxmd-rs");
assert!(signal_status.success(), "kill -INT should succeed");
if wait_with_timeout(&mut child, Duration::from_secs(3)).is_none() {
let _ = child.kill();
let output = child.wait_with_output().expect("collect lxmd-rs output");
if wait_with_timeout(daemon.child(), Duration::from_secs(3)).is_none() {
let _ = daemon.child().kill();
panic!(
"lxmd-rs did not exit after Ctrl+C during startup announce wait:\n{}",
combined_output(&output)
combined_output(&daemon.output())
);
}
let output = child.wait_with_output().expect("collect lxmd-rs output");
let output = daemon.output();
assert!(
output.status.success(),
"expected clean shutdown after Ctrl+C, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Startup announce cancelled by shutdown"),
"expected startup announce cancellation log, got:\n{}",
combined_output(&output)
);
}
/// lxmd.py's startup lines with full `RNS.prettyhexrep` hashes: a loaded identity
/// with the propagation node on, a created one with it off.
#[cfg(unix)]
#[test]
fn startup_logs_full_identity_delivery_and_propagation_hashes() {
use rns_identity::destination::Destination;
use rns_identity::identity::Identity;
for propagation in [true, false] {
let lxmf_dir = TestDir::new("lxmf-startup-lines");
let rns_dir = TestDir::new("rns-startup-lines");
let identity_path = lxmf_dir.path().join("identity");
if propagation {
write_rust_identity(&identity_path);
}
fs::write(
lxmf_dir.path().join("config"),
format!(
"[lxmf]\n\n[propagation]\nenable_node = {}\n",
if propagation { "yes" } else { "no" }
),
)
.expect("write LXMF config");
fs::write(
rns_dir.path().join("config"),
"\
[reticulum]
share_instance = No
enable_transport = No
respond_to_probes = No
panic_on_interface_error = No
discover_interfaces = No
[interfaces]
",
)
.expect("write no-interface Reticulum config");
let log_path = rns_dir.path().join("lxmd-rs.log");
let log = fs::File::create(&log_path).expect("create lxmd-rs log");
let log_err = log.try_clone().expect("clone lxmd-rs log");
let mut daemon = Daemon(Some(
Command::new(env!("CARGO_BIN_EXE_lxmd-rs"))
.arg("--config")
.arg(lxmf_dir.path())
.arg("--rnsconfig")
.arg(rns_dir.path())
.stdout(log)
.stderr(log_err)
.spawn()
.expect("lxmd-rs subprocess should start"),
));
let read_log = || fs::read_to_string(&log_path).unwrap_or_default();
let deadline = Instant::now() + Duration::from_secs(30);
while !read_log().contains("LXMF Daemon running") {
if let Some(status) = daemon.child().try_wait().expect("poll lxmd-rs startup") {
panic!("lxmd-rs exited during startup ({status}):\n{}", read_log());
}
assert!(
Instant::now() < deadline,
"lxmd-rs did not finish startup:\n{}",
read_log()
);
std::thread::sleep(Duration::from_millis(50));
}
drop(daemon);
let text = read_log();
let identity = Identity::from_file(&identity_path).expect("read lxmd-rs identity");
let pretty = |hash: &[u8]| format!("<{}>", hex::encode(hash));
let delivery =
Destination::hash_from_name_and_identity("lxmf.delivery", Some(&identity.hash));
let node =
Destination::hash_from_name_and_identity("lxmf.propagation", Some(&identity.hash));
let identity_line = if propagation {
format!("Loaded Primary Identity {}", pretty(&identity.hash))
} else {
format!("Created new Primary Identity {}", pretty(&identity.hash))
};
let delivery_line = format!("LXMF Router ready to receive on {}", pretty(&delivery));
let node_line = format!("LXMF Propagation Node started on {}", pretty(&node));
let position = |line: &str| {
text.find(line)
.unwrap_or_else(|| panic!("missing {line:?} in lxmd-rs output:\n{text}"))
};
let running = position("LXMF Daemon running");
assert!(
position(&identity_line) < position(&delivery_line),
"{text}"
);
if propagation {
assert!(position(&delivery_line) < position(&node_line), "{text}");
assert!(position(&node_line) < running, "{text}");
} else {
assert!(position(&delivery_line) < running, "{text}");
assert!(
!text.contains("LXMF Propagation Node started on"),
"propagation line without a propagation node:\n{text}"
);
}
}
}
#[test]
@@ -193,7 +324,12 @@ fn version_reports_binary_name_and_package_version() {
);
assert_eq!(
stdout(&output).trim(),
format!("lxmd-rs {}", env!("CARGO_PKG_VERSION"))
format!(
"lxmd-rs {} (LXMF {}, Reticulum {})",
env!("CARGO_PKG_VERSION"),
lxmf_tools::lxmd_cli::LXMF_COMPAT_VERSION,
rns_tools::RETICULUM_COMPAT_VERSION
)
);
assert!(stderr(&output).is_empty());
}
@@ -209,11 +345,51 @@ fn rust_binary_runs_cli() {
);
assert_eq!(
stdout(&output).trim(),
format!("lxmd-rs {}", env!("CARGO_PKG_VERSION"))
format!(
"lxmd-rs {} (LXMF {}, Reticulum {})",
env!("CARGO_PKG_VERSION"),
lxmf_tools::lxmd_cli::LXMF_COMPAT_VERSION,
rns_tools::RETICULUM_COMPAT_VERSION
)
);
assert!(stderr(&output).is_empty());
}
/// `-c` and `-V` are spellings the 1.3 and 1.4 releases accepted and
/// upstream never had: they still work and are announced on stderr.
#[test]
fn released_short_spellings_work_with_a_warning() {
let long = lxmd(&["--config", "/nonexistent/lxmd", "--exampleconfig"]);
assert!(long.status.success(), "{}", combined_output(&long));
assert!(stderr(&long).is_empty());
for short in [
&["-c", "/nonexistent/lxmd", "--exampleconfig"][..],
&["-c/nonexistent/lxmd", "--exampleconfig"],
] {
let output = lxmd(short);
assert!(output.status.success(), "{}", combined_output(&output));
assert_eq!(stdout(&output), stdout(&long), "{short:?}");
assert_eq!(
stderr(&output),
"lxmd-rs: warning: -c is deprecated, use --config\n",
"{short:?}"
);
}
let version = lxmd(&["--version"]);
let short = lxmd(&["-V"]);
assert!(short.status.success(), "{}", combined_output(&short));
assert_eq!(stdout(&short), stdout(&version));
assert_eq!(
stderr(&short),
"lxmd-rs: warning: -V is deprecated, use --version\n"
);
let help = stdout(&lxmd(&["--help"]));
assert!(help.contains("--config") && help.contains("--version"));
assert!(!help.contains("-c,") && !help.contains("-V,"), "{help}");
}
#[test]
fn example_config_exits_before_runtime_initialisation() {
let output = lxmd(&["--exampleconfig"]);
@@ -285,11 +461,11 @@ fn clap_requires_send_argument() {
"expected Clap usage failure, got:\n{}",
combined_output(&output)
);
assert!(stderr(&output).contains("a value is required for '--send <DEST_HASH> <CONTENT>'"));
assert!(stderr(&output).contains("a value is required for '--send <DEST_HASH> <CONTENT>...'"));
}
#[test]
fn status_and_peers_fail_before_link_without_an_online_interface() {
fn status_and_peers_time_out_without_a_reachable_node() {
let lxmf_dir = TestDir::new("lxmf");
let rns_dir = TestDir::new("rns");
write_rust_identity(&lxmf_dir.path().join("identity"));
@@ -308,6 +484,8 @@ discover_interfaces = No
)
.expect("write no-interface Reticulum config");
// Python `if not args.timeout` turns 0 into the 5 s default.
let started = std::time::Instant::now();
let output = Command::new(env!("CARGO_BIN_EXE_lxmd-rs"))
.arg("--config")
.arg(lxmf_dir.path())
@@ -317,38 +495,28 @@ discover_interfaces = No
.arg("--peers")
.arg("--timeout")
.arg("0")
.arg("-v")
.output()
.expect("lxmd-rs subprocess should run");
assert_eq!(
output.status.code(),
Some(200),
"expected interface-readiness failure, got:\n{}",
"expected the control query to time out, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output)
.contains("No online Reticulum interface became available, exiting now"),
"expected specific interface-readiness error, got:\n{}",
combined_output(&output)
assert_eq!(
stdout(&output),
"Getting lxmd statistics timed out, exiting now\n",
"control commands print only the result on stdout"
);
assert!(
lxmf_dir.path().join("identity").is_file(),
"--config should use the configured lxmd identity path"
(4..9).contains(&started.elapsed().as_secs()),
"--timeout 0 must fall back to the default"
);
assert!(
!lxmf_dir.path().join("storage").exists(),
"--status/--peers should not start local daemon state"
);
let logs = combined_output(&output);
assert!(
logs.contains("Using default configuration"),
"missing LXMF config should fall back to defaults, got logs:\n{logs}"
);
assert!(
logs.contains("interfaces=0"),
"test config should avoid live Reticulum interfaces, got logs:\n{logs}"
!lxmf_dir.path().join("storage").exists() && !lxmf_dir.path().join("config").exists(),
"--status/--peers must not start local daemon state"
);
}
+8 -3
View File
@@ -70,9 +70,14 @@ def verify(directory: Path, tag: str) -> None:
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--tag", required=True)
parser.add_argument("--directory", type=Path, required=True)
parser = argparse.ArgumentParser(
description="Check the three release archives, then write SHA256SUMS."
)
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()
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:
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(description=__doc__)
tags = parser.add_mutually_exclusive_group()
tags.add_argument("--release-tag")
tags.add_argument("--candidate-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", help="also verify vX.Y.Z matches the workspace version and has no local tag yet")
args = parser.parse_args()
version, reticulum_version = check_packages(metadata())
+13 -4
View File
@@ -97,7 +97,7 @@ def validate_metadata(
) -> list[dict[str, object]]:
require_keys(
config, {"schemaVersion", "tool", "baseline", "compatibilityFloor", "packages"},
"metadata",
"metadata", {"approvedBreakingChanges"},
)
if config["schemaVersion"] != 2:
fail("unsupported api-stability schema")
@@ -111,6 +111,10 @@ def validate_metadata(
"compatibility floor",
)
if "approvedBreakingChanges" in config:
require_keys(config["approvedBreakingChanges"],
{"releaseLine", "migrationGuide", "removed"}, "approved break")
tool = config.get("tool")
if not isinstance(tool, dict):
fail("tool contract is missing")
@@ -270,10 +274,15 @@ def render_snapshot(
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--metadata-only", action="store_true")
parser = argparse.ArgumentParser(
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",
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",
help="optional HEAD guard for --update; includes uncommitted source changes")
args = parser.parse_args()
+57 -7
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env python3
"""Reject removals from the reviewed public-API compatibility floor."""
"""Reject unapproved removals from the retained public-API compatibility floor."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
@@ -45,6 +46,48 @@ def load_floor_ledger(commit: str) -> dict[str, object]:
fail(f"cannot read API ledger at compatibility floor {commit}")
def approved_removals(ledger: dict[str, object], version: str) -> dict[str, set[str]]:
"""A breaking release allows exact reviewed lines, never a blanket waiver."""
record = ledger.get("approvedBreakingChanges")
if record is None:
return {}
if not isinstance(record, dict) or set(record) != {"releaseLine", "migrationGuide", "removed"}:
fail("approved break needs releaseLine, migrationGuide and exact removed lines")
release_line = record["releaseLine"]
if not isinstance(release_line, str) or not re.fullmatch(r"\d+\.\d+", release_line):
fail("approved break release line is invalid")
if version.split(".")[:2] != release_line.split("."):
fail("approved break does not match the current workspace release line")
guide = record["migrationGuide"]
if not isinstance(guide, str) or not guide.startswith("api/migrations/"):
fail("approved break must link a public API migration guide")
guide_path = (ROOT / guide).resolve()
if not guide_path.is_relative_to(ROOT / "api/migrations") or not guide_path.is_file():
fail("approved break migration guide is missing or outside its directory")
removed = record["removed"]
packages = {package["name"] for package in ledger["packages"]}
if not isinstance(removed, dict) or not removed or not set(removed).issubset(packages):
fail("approved removals must name existing packages")
result = {}
for package, lines in removed.items():
if (not isinstance(lines, list) or not lines
or not all(isinstance(line, str) and line.strip() for line in lines)
or len(set(lines)) != len(lines)):
fail("approved removals must be unique nonempty exact API lines")
result[package] = set(lines)
return result
def validate_removed(package: str, removed: set[str], approved: dict[str, set[str]]) -> None:
allowed = approved.get(package, set())
if removed != allowed:
for line in sorted(removed - allowed):
print(f"unapproved removal: {line}", file=sys.stderr)
for line in sorted(allowed - removed):
print(f"unused removal approval: {line}", file=sys.stderr)
fail(f"{package} removals differ from the exact approved migration")
def main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
@@ -52,6 +95,16 @@ def main() -> None:
if metadata.returncode != 0:
fail("snapshot metadata is invalid")
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
metadata_result = subprocess.run(
["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"],
cwd=ROOT, capture_output=True, text=True,
)
if metadata_result.returncode:
fail("cannot resolve workspace release version")
versions = {package["version"] for package in json.loads(metadata_result.stdout)["packages"]}
if len(versions) != 1:
fail("workspace release versions disagree")
approved = approved_removals(ledger, versions.pop())
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
if not isinstance(floor, str):
fail("api/stability.json has no compatibility-floor commit")
@@ -79,12 +132,9 @@ def main() -> None:
if removed:
for line in removed:
print(f"- {line}", file=sys.stderr)
if total_removed:
fail(
f"{total_removed} public API lines were removed from the compatibility floor; "
"the current policy permits additions only"
)
print(f"api compatibility: additive-only (+{total_added}, -0)")
validate_removed(package["name"], set(removed), approved)
print(f"api compatibility: checked (+{total_added}, -{total_removed}); "
"unapproved removals forbidden")
if __name__ == "__main__":
+4 -2
View File
@@ -122,12 +122,14 @@ def render_contract() -> str:
def main() -> None:
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(
description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json."
)
parser.add_argument(
"--print",
action="store_true",
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()
rendered = render_contract()