Compare commits

..
72 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
60 changed files with 15785 additions and 7281 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
api-compat:
+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.4.0
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
RSLXMF_RSRETICULUM_VERSION: 1.5.1
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
verify:
+29
View File
@@ -2,6 +2,35 @@
## 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.
Generated
+252 -47
View File
@@ -14,6 +14,18 @@ dependencies = [
"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]]
name = "anstream"
version = "1.0.0"
@@ -133,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 0.5.2",
]
[[package]]
name = "bytes"
version = "1.11.1"
@@ -166,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"
@@ -326,6 +339,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"pem-rfc7468",
"zeroize",
]
@@ -336,6 +350,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
@@ -381,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"
@@ -393,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"
@@ -451,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"
@@ -466,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"
@@ -603,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"
@@ -622,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"
@@ -645,13 +716,13 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2 0.6.5",
"objc2",
"proptest",
"rand 0.8.5",
"rmp",
@@ -663,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.4.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
@@ -685,13 +758,14 @@ 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",
]
@@ -763,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"
@@ -770,22 +879,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[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"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
"objc2-encode",
"libm",
]
[[package]]
@@ -799,12 +893,11 @@ dependencies = [
[[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 0.5.2",
"objc2",
"objc2-foundation",
]
@@ -816,14 +909,12 @@ 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 0.5.2",
"objc2",
]
[[package]]
@@ -861,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"
@@ -877,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"
@@ -1066,7 +1183,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"aes",
"cbc",
@@ -1084,7 +1201,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
@@ -1104,7 +1221,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1113,7 +1230,7 @@ dependencies = [
"libc",
"md-5",
"mio",
"objc2 0.5.2",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
@@ -1133,7 +1250,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
@@ -1150,7 +1267,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"bzip2",
"hex",
@@ -1167,7 +1284,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1186,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.4.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1204,6 +1349,7 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"rusqlite",
"serde",
"subtle",
"thiserror 2.0.18",
@@ -1213,13 +1359,47 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.4.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"
@@ -1366,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"
@@ -1382,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",
]
@@ -1411,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"
@@ -1627,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"
@@ -1660,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"
+16 -11
View File
@@ -6,25 +6,26 @@ members = [
]
[workspace.package]
version = "1.4.0"
version = "1.5.1"
edition = "2024"
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.4.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.4.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.4.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.4.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.4.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.4.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.4.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.4.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.4.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"
+28 -38
View File
@@ -6,8 +6,8 @@
[![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)
[![Supplementary release reference: LXMF 1.1.0](https://img.shields.io/badge/supplementary%20release%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![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) |
@@ -22,11 +22,7 @@
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. The Python reference
implementation remains the source of truth. See [License](#license).
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.
reference's wire behavior release by release.
## Contents
@@ -37,12 +33,11 @@ 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.4.0 release, [v1.4.0](https://github.com/ratspeak/rsLXMF/releases/tag/v1.4.0), built with rsReticulum [v1.4.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.4.0); it is the source line Ratspeak builds from. For the 1.3.0 daemon, use [the v1.3.0 README](https://github.com/ratspeak/rsLXMF/blob/v1.3.0/README.md) and that build's `--help`. The 1.4 message and durable relay APIs require a coordinated source migration.
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:
@@ -58,12 +53,12 @@ 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.4.0
git -C rsLXMF checkout --detach v1.4.0
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.
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
@@ -244,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:
@@ -282,7 +277,7 @@ 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`, `sequential_pn_stamp_validation`, `static_peers_bypass_sequential`, `max_inbound_syncs`, `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` |
@@ -295,6 +290,13 @@ Optional hash-list files live next to `<config-dir>/config`:
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
LXMF supports several delivery shapes. rsLXMF exposes them through the router
@@ -325,15 +327,14 @@ payload MessagePack([timestamp, title, content, fields, optional_stamp
`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 1.4 library preserves signed
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.
In the 1.4 API, construct `LxMessageDraft` and set `include_ticket` before
calling `LxmRouter::prepare_outbound`. Persist the returned ticket intent before
signing; a pending intent blocks signing. Signing consumes the draft, and
finalization produces an immutable message. See the [1.4 migration guide](api/migrations/1.4.md)
for stamp work, typed fields, inbound verification and propagation storage.
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
@@ -343,33 +344,22 @@ for stamp work, typed fields, inbound verification and propagation storage.
| 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 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 corpus and live matrix for 1.3.0 and 1.4.0 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. Later source changes include selected LXMF 1.2.0 behavior; that
does not establish complete compatibility with every later Python release.
## 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
+13 -9
View File
@@ -1,17 +1,20 @@
# Rust API
This guide describes the 1.4.0 API, published as v1.4.0, not the 1.3.0
daemon. Application code should use `lxmf_core::message_api`, which
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.4 migration guide](migrations/1.4.md) explains
the source-breaking change from mutable messages to drafts, signed messages
and immutable finalized messages.
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,
@@ -23,9 +26,10 @@ provisional module-qualified APIs.
integration target.
Choosing the facade instead of the equivalent module-qualified path does not
change behavior. Upgrading from 1.3 to 1.4 does change message and persistence
APIs; follow the migration guide. Further reductions to the broader module tree
require a reviewed API diff, downstream migration and an explicit version decision.
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.
## Delivery-owner integration
@@ -36,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
+117 -7
View File
@@ -14,6 +14,18 @@ dependencies = [
"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]]
name = "autocfg"
version = "1.5.1"
@@ -80,6 +92,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"
@@ -221,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"
@@ -248,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"
@@ -336,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"
@@ -353,7 +422,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lxmf-core"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
@@ -370,11 +439,13 @@ dependencies = [
"rns-protocol",
"rns-transport",
"rns-wire",
"rusqlite",
"serde",
"sha2",
"thiserror 2.0.20",
"tokio",
"tracing",
"unicode-general-category",
"unicode-normalization",
]
@@ -471,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"
@@ -569,7 +646,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"aes",
"cbc",
@@ -587,7 +664,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
@@ -607,7 +684,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"hex",
"libc",
@@ -624,7 +701,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"bzip2",
"hex",
@@ -641,7 +718,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -651,6 +728,7 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"rusqlite",
"serde",
"subtle",
"thiserror 2.0.20",
@@ -660,13 +738,27 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.4.0"
version = "1.5.1"
dependencies = [
"rns-crypto",
"sha2",
"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]]
name = "rustc_version"
version = "0.4.1"
@@ -748,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"
@@ -941,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"
@@ -956,6 +1060,12 @@ 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"
+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.
File diff suppressed because it is too large. Load diff
+47 -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,20 +77,21 @@ 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<()>
@@ -106,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
@@ -127,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>
@@ -158,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>
+71 -28
View File
@@ -4,10 +4,18 @@
"packages": [
{
"name": "lxmf-core",
"version": "1.4.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",
@@ -105,7 +113,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -116,7 +124,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -127,7 +135,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -138,7 +146,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -149,9 +157,9 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
@@ -160,12 +168,25 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.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,
@@ -225,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,
@@ -262,7 +294,7 @@
},
{
"name": "lxmf-tools",
"version": "1.4.0",
"version": "1.5.1",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -330,7 +362,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -352,7 +384,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -363,7 +395,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -374,7 +406,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -382,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.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
@@ -398,7 +441,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -415,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,
@@ -439,17 +493,6 @@
"features": [],
"sourceKind": "registry"
},
{
"name": "tracing-subscriber",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.3",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "zeroize",
"rename": null,
+209 -70
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": 2227,
"sha256": "30d1006f3149b0e812c3d772f226467887cbba036beb23d686ae79d3c50860ee"
"itemCount": 2458,
"sha256": "93bd001beb46ae13e2ece84d355e9fd4ffc8198029233de3a397b1a645b77651"
},
{
"name": "lxmf-tools",
@@ -33,77 +33,216 @@
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 190,
"sha256": "c8591cf56d1d315da43ecab8149057447ff02726fa371e01439a4106be45976f"
"itemCount": 214,
"sha256": "61656c05c28423f95c71f716998a834e0e9bc8855d0ddd29617aed1a0ee3045b"
}
],
"approvedBreakingChanges": {
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"releaseLine": "1.5",
"migrationGuide": "api/migrations/1.5.md",
"removed": {
"lxmf-core": [
"pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self",
"pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted<F>(&mut self, F) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId), 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::message::LxMessage::pack_propagated_encrypted_with_stamp<F>(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId, u32), 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::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec<u8>)",
"pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec<u8>) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign_with<F, E>(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display",
"pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> bool",
"pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool",
"pub fn lxmf_core::propagation_client::PropagationClient::take_received_messages(&mut self) -> alloc::vec::Vec<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_propagated_blob(&mut self, &[u8], u8) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_message(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_propagated_blob(&mut self, &[u8], u8) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_sync::PropagationSyncTask::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::message::LxMessage>",
"pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessage) -> core::result::Result<(), lxmf_core::router::TicketPreparationError>",
"pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::message::LxMessage",
"pub lxmf_core::message::LxMessage::auto_compress: bool",
"pub lxmf_core::message::LxMessage::callbacks: lxmf_core::message::MessageCallbacks",
"pub lxmf_core::message::LxMessage::content: alloc::string::String",
"pub lxmf_core::message::LxMessage::delivery_attempts: u32",
"pub lxmf_core::message::LxMessage::destination_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::hash: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::include_ticket: bool",
"pub lxmf_core::message::LxMessage::incoming: bool",
"pub lxmf_core::message::LxMessage::last_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::message_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::method: lxmf_core::constants::DeliveryMethod",
"pub lxmf_core::message::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::message::LxMessage::next_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::outbound_ticket: core::option::Option<[u8; 16]>",
"pub lxmf_core::message::LxMessage::progress: f64",
"pub lxmf_core::message::LxMessage::propagation_stamp: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation",
"pub lxmf_core::message::LxMessage::signature: core::option::Option<[u8; 64]>",
"pub lxmf_core::message::LxMessage::signature_validated: bool",
"pub lxmf_core::message::LxMessage::source_blackholed: bool",
"pub lxmf_core::message::LxMessage::source_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::stamp: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message::LxMessage::stamp_value: core::option::Option<u16>",
"pub lxmf_core::message::LxMessage::state: lxmf_core::constants::MessageState",
"pub lxmf_core::message::LxMessage::timestamp: f64",
"pub lxmf_core::message::LxMessage::title: alloc::string::String",
"pub lxmf_core::message::LxMessage::transient_id: core::option::Option<lxmf_core::types::PropagationTransientId>",
"pub lxmf_core::message::LxMessage::transport_encrypted: bool",
"pub lxmf_core::message::LxMessage::transport_encryption: core::option::Option<alloc::string::String>",
"pub lxmf_core::message::LxMessage::unverified_reason: core::option::Option<lxmf_core::constants::UnverifiedReason>",
"pub lxmf_core::message::LxMessage::wire_payload: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::LxMessage>"
"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"
]
}
}
+8
View File
@@ -7,6 +7,12 @@ edition.workspace = true
rust-version.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 }
rns-crypto = { workspace = true }
@@ -27,6 +33,8 @@ 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"
+109 -4
View File
@@ -43,6 +43,8 @@ struct UserDeletedMessage {
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>,
}
@@ -85,6 +87,24 @@ 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()
@@ -103,6 +123,7 @@ impl FileAdmissionStore {
let mut inner = Inner {
journal,
bodies: bodies.to_owned(),
legacy_bodies: legacy_bodies.map(Path::to_owned),
committed: HashMap::new(),
deleted: HashMap::new(),
};
@@ -265,7 +286,13 @@ impl FileAdmissionStore {
.committed
.values()
.filter(|c| !c.hook_completed)
.filter_map(|c| Some((c.intent.hook_event?, c.intent.body_path.clone()?)))
.filter_map(|c| {
c.intent.body_path.as_ref()?;
Some((
c.intent.hook_event?,
inner.body_path(&c.intent.record.message_id),
))
})
.collect()
}
@@ -413,6 +440,9 @@ impl DurableAdmissionBackend for FileAdmissionCommit {
}
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)))
}
@@ -431,12 +461,21 @@ impl Inner {
return Err(other("message was explicitly deleted"));
}
if let Some(path) = &intent.body_path {
if path.parent() != Some(self.bodies.as_path())
|| path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
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"));
@@ -606,4 +645,70 @@ mod tests {
.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());
}
}
}
+39 -22
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;
@@ -156,6 +163,10 @@ pub const LXMF_OVERHEAD: usize =
/// 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;
@@ -163,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).
@@ -173,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;
/// Python propagation-link inactivity limit, in seconds; retained as a reference value.
/// 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;
@@ -186,13 +197,17 @@ 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;
@@ -276,6 +291,8 @@ pub const JOB_LINKS_INTERVAL: u64 = 1;
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 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;
@@ -297,7 +314,7 @@ mod tests {
assert_eq!(LXMF_OVERHEAD, 112);
}
/// LXMF 1.2.0 `ENCRYPTED_PACKET_MAX_CONTENT` (LXMessage.py:64-79, 3fc60af).
/// 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);
@@ -335,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]
@@ -374,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);
}
@@ -396,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);
+28 -3
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;
@@ -74,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,
@@ -83,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 {
@@ -189,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
}
@@ -201,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,
@@ -209,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);
@@ -285,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)
}
@@ -383,6 +397,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
@@ -396,6 +411,7 @@ mod tests {
101,
101.5,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Coalesced)
));
@@ -410,6 +426,7 @@ mod tests {
102,
102.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert_eq!(unpack_announce(&raw).1.ratchet, Some(initial_public));
@@ -422,6 +439,7 @@ mod tests {
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let rotated_public = unpack_announce(&raw).1.ratchet.unwrap();
@@ -459,6 +477,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
@@ -483,6 +502,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert!(!unpack_announce(&raw).0.flags.context_flag);
@@ -501,6 +521,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let live_public = state.ring.current_public_key();
@@ -515,6 +536,7 @@ mod tests {
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::PersistControl { .. })
));
@@ -535,6 +557,7 @@ mod tests {
101,
101.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
let committed_wire = state.control.last_announce_wire();
@@ -546,6 +569,7 @@ mod tests {
101,
102.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
assert_eq!(
@@ -574,6 +598,7 @@ mod tests {
101,
f64::NAN,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Destination(_))
));
+85 -136
View File
@@ -1,23 +1,19 @@
//! LXMF-backed stamper for Reticulum interface discovery.
//!
//! # Layering
//!
//! Python `RNS.Discovery.InterfaceAnnouncer` loads `LXMF.LXStamper` when
//! initialized, requiring LXMF for on-network discovery. 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)`
//! in `InterfaceAnnouncer`, 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,87 +22,51 @@ 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;
/// Default attempt budget for one discovery stamp search. Exhaustion returns
/// `None`, allowing the announcer to skip this preparation attempt and retry.
/// The budget limits attempts, not elapsed time. The requested generation cost
/// comes from the per-interface announce configuration.
/// 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. Zero selects
/// [`DISCOVERY_MAX_ITERATIONS`], as does [`LxmfDiscoveryStamper::default`].
/// This differs from [`generate_discovery_stamp`], where zero allows no attempts.
pub fn with_max_iterations(max_iterations: u64) -> Self {
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)
}
}
/// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
/// explicit attempt limit. Uses the same construction as
/// [`crate::stamper::generate_stamp_limited`], without a transport runtime.
/// [`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],
@@ -114,12 +74,12 @@ pub fn generate_discovery_stamp(
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);
}
}
@@ -130,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]
@@ -216,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
+56
View File
@@ -161,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 {
@@ -250,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 {
@@ -286,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,
@@ -333,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::*;
+1
View File
@@ -84,6 +84,7 @@ 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;
File diff suppressed because it is too large. Load diff
+212 -54
View File
@@ -14,6 +14,7 @@ use std::io::Write;
use std::ops::{Deref, DerefMut, Range};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) mod canonical;
mod draft;
mod field;
mod resumable;
@@ -47,6 +48,11 @@ fn bounded_lossy_text(bytes: &[u8]) -> Cow<'_, str> {
}
pub type MessageCallback = Arc<dyn Fn(&LxMessage) + Send + Sync>;
fn run_isolated_callback(callback: &MessageCallback, message: &LxMessage, kind: &str) {
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(message))).is_err() {
tracing::error!(callback = kind, "an external message callback panicked");
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AudioField<'a> {
pub mode: u8,
@@ -65,12 +71,25 @@ impl std::fmt::Debug for MessageCallbacks {
.finish()
}
}
pub const ENCRYPTION_DESCRIPTION_AES: &str = "AES-256";
pub const ENCRYPTION_DESCRIPTION_EC: &str = "Curve25519";
pub const ENCRYPTION_DESCRIPTION_UNENCRYPTED: &str = "Unencrypted";
/// Physical-layer readings of the packet or Link a message arrived on.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct PhyStats {
pub rssi: Option<f64>,
pub snr: Option<f64>,
pub q: Option<f64>,
}
/// Mutable delivery observations; none can change a message's authenticated bytes.
#[derive(Debug, Clone)]
pub struct MessageMetadata {
pub state: MessageState,
pub method: DeliveryMethod,
pub ratchet_id: Option<[u8; 32]>,
/// The ratchet ID (10 bytes) or Link ID (16 bytes) the message travelled under.
pub ratchet_id: Option<Vec<u8>>,
pub delivery_attempts: u32,
pub last_delivery_attempt: f64,
pub next_delivery_attempt: f64,
@@ -83,6 +102,18 @@ pub struct MessageMetadata {
pub progress: f64,
pub auto_compress: bool,
pub callbacks: MessageCallbacks,
/// Retry state owned by the outbound router; never persisted.
pub awaiting_path: bool,
pub sent_on_path: bool,
pub sent_on_slow_path: bool,
pub path_request_retried: bool,
pub max_delivery_attempts: Option<u32>,
pub receipt_timeout: Option<f64>,
pub rssi: Option<f64>,
pub snr: Option<f64>,
pub q: Option<f64>,
pub stamp_valid: bool,
pub stamp_checked: bool,
}
impl Default for MessageMetadata {
fn default() -> Self {
@@ -102,6 +133,17 @@ impl Default for MessageMetadata {
progress: 0.,
auto_compress: true,
callbacks: MessageCallbacks::default(),
awaiting_path: false,
sent_on_path: false,
sent_on_slow_path: false,
path_request_retried: false,
max_delivery_attempts: None,
receipt_timeout: None,
rssi: None,
snr: None,
q: None,
stamp_valid: false,
stamp_checked: false,
}
}
}
@@ -309,11 +351,9 @@ impl LxMessage {
pub fn verify_signature(&self, key: &rns_crypto::ed25519::Ed25519PublicKey) -> bool {
let mut signed = Vec::with_capacity(self.wire.len() + 32);
signed.extend_from_slice(&self.wire[..32]);
if let Some(body) = first_four_msgpack_array_body(&self.wire[96..]) {
signed.push(0x94);
signed.extend_from_slice(body);
} else {
signed.extend_from_slice(&self.wire[96..]);
match canonical::hashed_payload(&self.wire[96..]) {
Ok(payload) => signed.extend_from_slice(&payload),
Err(_) => return false,
}
signed.extend_from_slice(&self.message_id);
key.verify(&signed, &self.signature()).is_ok()
@@ -354,6 +394,7 @@ impl LxMessage {
if wire.len() < 97 {
return Err(MessageError::TooShort(wire.len()));
}
canonical::validate_leading(&wire[96..])?;
let mut input = &wire[96..];
let count = read_msgpack_array_len(&mut input)?;
if count < 4 {
@@ -400,7 +441,7 @@ impl LxMessage {
};
let destination = wire[..16].try_into().expect("header");
let source = wire[16..32].try_into().expect("header");
let message_id = Self::message_id_from_payload(&destination, &source, &wire[96..]);
let message_id = Self::message_id_from_payload(&destination, &source, &wire[96..])?;
Ok(Self {
wire,
indexes: indexes.into(),
@@ -419,16 +460,16 @@ impl LxMessage {
/// Stamp checking is pure; the returned value is valid only for this request's policy.
pub fn validate_stamp_with_tickets(
&self,
target_cost: u8,
target_cost: f64,
tickets: Option<&[Vec<u8>]>,
) -> bool {
self.validated_stamp_value(target_cost, tickets).is_some()
}
pub fn validated_stamp_value(
&self,
target_cost: u8,
target_cost: f64,
tickets: Option<&[Vec<u8>]>,
) -> Option<u16> {
) -> Option<f64> {
let stamp = self.stamp.as_ref()?.as_bytes();
if let Some(tickets) = tickets {
for ticket in tickets {
@@ -444,9 +485,12 @@ impl LxMessage {
}
}
let stamp = <&[u8; 32]>::try_from(stamp).ok()?;
let work = crate::stamper::stamp_workblock(&self.message_id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
crate::stamper::stamp_valid(stamp, target_cost, &work)
.then(|| crate::stamper::stamp_value(&work, stamp) as u16)
crate::stamper::validated_stamp_value(
&self.message_id,
stamp,
target_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS,
)
}
/// Update [`auto_compress`](MessageMetadata::auto_compress) based on a peer's cached announce app_data.
///
@@ -479,18 +523,20 @@ impl LxMessage {
}
/// Invoke the delivery callback, if registered. Every call invokes it again;
/// the caller must prevent duplicate notifications when required.
/// the caller must prevent duplicate notifications when required. A
/// panicking callback is logged and contained.
pub fn notify_delivered(&self) {
if let Some(ref cb) = self.callbacks.on_delivered {
cb(self);
run_isolated_callback(cb, self, "delivery");
}
}
/// Invoke the failure callback, if registered. Every call invokes it again;
/// the caller must prevent duplicate notifications when required.
/// the caller must prevent duplicate notifications when required. A
/// panicking callback is logged and contained.
pub fn notify_failed(&self) {
if let Some(ref cb) = self.callbacks.on_failed {
cb(self);
run_isolated_callback(cb, self, "failed");
}
}
@@ -564,17 +610,12 @@ impl LxMessage {
destination_hash: &[u8; 16],
source_hash: &[u8; 16],
payload: &[u8],
) -> [u8; 32] {
) -> Result<[u8; 32], MessageError> {
let mut hasher = Sha256::new();
hasher.update(destination_hash);
hasher.update(source_hash);
if let Some(body) = first_four_msgpack_array_body(payload) {
hasher.update([0x94]);
hasher.update(body);
} else {
hasher.update(payload);
}
hasher.finalize().into()
hasher.update(canonical::hashed_payload(payload)?);
Ok(hasher.finalize().into())
}
/// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is
@@ -644,14 +685,83 @@ impl LxMessage {
full_hash(lxmf_data)
}
/// Python `LXMessage.determine_transport_encryption` for the current method
/// and the recipient destination type.
pub fn determine_transport_encryption(
&mut self,
destination_type: rns_wire::flags::DestinationType,
) {
use rns_wire::flags::DestinationType;
let by_type = match destination_type {
DestinationType::Single => (true, ENCRYPTION_DESCRIPTION_EC),
DestinationType::Group => (true, ENCRYPTION_DESCRIPTION_AES),
_ => (false, ENCRYPTION_DESCRIPTION_UNENCRYPTED),
};
let (encrypted, description) = match self.method {
DeliveryMethod::Direct => (true, ENCRYPTION_DESCRIPTION_EC),
DeliveryMethod::Opportunistic | DeliveryMethod::Propagated | DeliveryMethod::Paper => {
by_type
}
};
self.transport_encrypted = encrypted;
self.transport_encryption = Some(description.to_string());
}
/// Python `lxmf_delivery` receive metadata: a ratchet ID is kept if already
/// set, and transport encryption follows the destination type the message
/// arrived on (`None` when unknown).
pub fn record_delivery(
&mut self,
destination_type: Option<rns_wire::flags::DestinationType>,
ratchet_id: Option<&[u8]>,
method: Option<DeliveryMethod>,
phy: Option<PhyStats>,
) {
use rns_wire::flags::DestinationType;
if let Some(id) = ratchet_id.filter(|id| !id.is_empty())
&& self.ratchet_id.is_none()
{
self.ratchet_id = Some(id.to_vec());
}
if let Some(method) = method {
self.method = method;
}
if let Some(phy) = phy {
self.rssi = phy.rssi;
self.snr = phy.snr;
self.q = phy.q;
}
let (encrypted, description) = match destination_type {
Some(DestinationType::Single | DestinationType::Link) => {
(true, Some(ENCRYPTION_DESCRIPTION_EC))
}
Some(DestinationType::Group) => (true, Some(ENCRYPTION_DESCRIPTION_AES)),
_ => (false, None),
};
self.transport_encrypted = encrypted;
self.transport_encryption = description.map(str::to_string);
}
/// Record the result of an inbound stamp check against `required_cost`
/// (Python `lxmf_delivery`); whether to drop on failure is the caller's policy.
pub fn check_stamp(&mut self, required_cost: f64, tickets: Option<&[Vec<u8>]>) -> bool {
self.stamp_valid = self.validate_stamp_with_tickets(required_cost, tickets);
self.stamp_checked = true;
self.stamp_valid
}
pub fn cancel(&mut self) {
if self.state == MessageState::Outbound || self.state == MessageState::Sending {
self.state = MessageState::Cancelled;
}
}
/// Python `fail_message`: progress resets and a rejected message stays rejected.
pub fn mark_failed(&mut self) {
self.state = MessageState::Failed;
self.progress = 0.0;
if self.state != MessageState::Rejected {
self.state = MessageState::Failed;
}
self.notify_failed();
}
@@ -659,8 +769,13 @@ impl LxMessage {
self.state = MessageState::Rejected;
}
/// Mark the message delivered; repeated calls notify only once.
pub fn mark_delivered(&mut self) {
if self.state == MessageState::Delivered {
return;
}
self.state = MessageState::Delivered;
self.progress = 1.0;
self.notify_delivered();
}
@@ -712,15 +827,18 @@ impl LxMessage {
}
/// Decode an `lxm://` paper URI and return `(destination_hash, encrypted_data)`.
///
/// Follows Python `LXMRouter.ingest_lxm_uri`: the scheme check ignores case,
/// every exact `lxm://` and every `/` is removed, and the rest is decoded with
/// the lenient rules of `base64.urlsafe_b64decode(data + "==")`.
pub fn decode_paper_uri(uri: &str) -> Result<([u8; 16], Vec<u8>), MessageError> {
use base64::Engine;
let data = uri
.strip_prefix("lxm://")
.ok_or_else(|| MessageError::InvalidUri("missing lxm:// prefix".to_string()))?;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(data)
.map_err(|e| MessageError::InvalidUri(format!("base64url decode failed: {e}")))?;
if !uri.to_lowercase().starts_with("lxm://") {
return Err(MessageError::InvalidUri(
"missing lxm:// prefix".to_string(),
));
}
let data = uri.replace("lxm://", "").replace('/', "") + "==";
let bytes = python_urlsafe_b64decode(&data)?;
if bytes.len() < LXMF_OVERHEAD {
return Err(MessageError::TooShort(bytes.len()));
@@ -736,6 +854,7 @@ impl LxMessage {
/// The caller supplies destination-identity decryption. This method restores
/// the destination prefix, parses the message, and marks its representation
/// as Paper. Authenticate the sender separately with [`Self::verify`].
/// Router ingest with duplicate handling is `LxmRouter::ingest_lxm_uri`.
pub fn from_paper_uri<F>(uri: &str, decrypt_fn: F) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -769,11 +888,8 @@ impl LxMessage {
/// Pack the message into a container for file storage.
///
/// Writes a five-element MessagePack array in this order:
/// `[state, lxmf_bytes, transport_encrypted, transport_encryption, method]`.
/// `lxmf_bytes` is binary and `transport_encryption` is a string or nil.
/// Python's `packed_container` writes a named-field map; its file reader
/// does not accept this Rust array layout.
/// Writes the MessagePack map of Python `packed_container`:
/// `{state, lxmf_bytes, transport_encrypted, transport_encryption, method}`.
pub fn pack_container(&self) -> Result<Vec<u8>, MessageError> {
let container = MessageContainerRef {
state: self.state as u8,
@@ -782,7 +898,7 @@ impl LxMessage {
transport_encryption: self.transport_encryption.as_deref(),
method: self.method as u8,
};
rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
rmp_serde::to_vec_named(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
}
/// Decode a container array or a map with matching field names, then parse
@@ -931,6 +1047,58 @@ fn parse_propagation_wrapper(
Ok((timestamp, entries))
}
/// Python `base64.urlsafe_b64decode` (non-strict `binascii.a2b_base64`):
/// characters outside the alphabet are skipped, and padding only completes a
/// trailing partial quantum.
fn python_urlsafe_b64decode(data: &str) -> Result<Vec<u8>, MessageError> {
// A str argument must encode as ASCII before decoding.
if !data.is_ascii() {
return Err(MessageError::InvalidUri(
"non-ASCII base64 data".to_string(),
));
}
let mut out = Vec::with_capacity(data.len() * 3 / 4);
let (mut quad_pos, mut pads, mut left) = (0u8, 0u8, 0u32);
for byte in data.bytes() {
if byte == b'=' {
if quad_pos >= 2 {
pads = pads.saturating_add(1);
}
continue;
}
let value = match byte {
b'A'..=b'Z' => byte - b'A',
b'a'..=b'z' => byte - b'a' + 26,
b'0'..=b'9' => byte - b'0' + 52,
b'-' | b'+' => 62,
b'_' | b'/' => 63,
_ => continue,
};
pads = 0;
left = (left << 6) | u32::from(value);
quad_pos = (quad_pos + 1) % 4;
match quad_pos {
2 => out.push((left >> 4) as u8),
3 => out.push((left >> 2) as u8),
0 => out.push(left as u8),
_ => {}
}
left &= match quad_pos {
2 => 0x0f,
3 => 0x03,
1 => 0x3f,
_ => 0,
};
}
if quad_pos == 0 || (quad_pos >= 2 && quad_pos + pads >= 4) {
Ok(out)
} else {
Err(MessageError::InvalidUri(
"incorrect base64 padding".to_string(),
))
}
}
fn read_msgpack_array_len(input: &mut &[u8]) -> Result<u32, MessageError> {
let marker = take_msgpack(input, 1)?[0];
match marker {
@@ -1001,20 +1169,10 @@ fn take_msgpack<'a>(input: &mut &'a [u8], length: usize) -> Result<&'a [u8], Mes
Ok(value)
}
fn first_four_msgpack_array_body(payload: &[u8]) -> Option<&[u8]> {
let mut input = payload;
let count = read_msgpack_array_len(&mut input).ok()?;
if count <= 4 {
return None;
}
let body = input;
for _ in 0..4 {
skip_msgpack_value(&mut input, 0).ok()?;
}
Some(&body[..body.len() - input.len()])
}
fn read_msgpack_float(input: &mut &[u8]) -> Result<f64, MessageError> {
if matches!(input.first(), Some(0x00..=0x7f | 0xcc..=0xd3 | 0xe0..=0xff)) {
return Ok(read_msgpack_integer(input)? as f64);
}
match take_msgpack(input, 1)?[0] {
0xca => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
take_msgpack(input, 4)?.try_into().expect("exact length"),
@@ -1023,7 +1181,7 @@ fn read_msgpack_float(input: &mut &[u8]) -> Result<f64, MessageError> {
take_msgpack(input, 8)?.try_into().expect("exact length"),
))),
_ => Err(MessageError::UnpackFailed(
"timestamp is not float".to_string(),
"timestamp is not a number".to_string(),
)),
}
}
+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());
}
}
+97 -59
View File
@@ -18,8 +18,7 @@ pub struct LxMessageDraft {
pub metadata: MessageMetadata,
pub include_ticket: bool,
pub outbound_ticket: Option<[u8; 16]>,
pub stamp_cost: Option<u8>,
ticket_barrier: Option<Arc<()>>,
pub stamp_cost: Option<f64>,
}
impl Deref for LxMessageDraft {
type Target = MessageMetadata;
@@ -37,7 +36,7 @@ impl DerefMut for LxMessageDraft {
pub struct SignedLxMessage {
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<u8>,
stamp_cost: Option<f64>,
}
impl Deref for SignedLxMessage {
type Target = MessageMetadata;
@@ -100,7 +99,6 @@ impl LxMessageDraft {
include_ticket: false,
outbound_ticket: None,
stamp_cost: None,
ticket_barrier: None,
};
draft.checked_wire_len()?;
Ok(draft)
@@ -123,21 +121,6 @@ impl LxMessageDraft {
pub fn fields(&self) -> &BTreeMap<FieldId, FieldValue> {
&self.fields
}
pub(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) {
self.ticket_barrier = Some(owner);
}
pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool {
if self
.ticket_barrier
.as_ref()
.is_some_and(|pending| Arc::ptr_eq(pending, owner))
{
self.ticket_barrier = None;
true
} else {
false
}
}
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
self.fields.get(&id.into())
}
@@ -186,17 +169,38 @@ impl LxMessageDraft {
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(
id,
FieldValue::MessagePack(EncodedFieldValue::new(bytes.into())?),
)
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 id = id.into();
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);
}
@@ -218,24 +222,25 @@ impl LxMessageDraft {
self.fields.remove(&id.into())
}
pub fn set_image_field(&mut self, format: &str, bytes: &[u8]) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&ImageFieldRef { format, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_IMAGE, encoded)
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> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&AudioFieldRef { mode, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_AUDIO, encoded)
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> {
self.limits.check_wire(bytes.len())?;
let encoded =
rmp_serde::to_vec(&FileAttachmentsFieldRef { file_name, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_FILE_ATTACHMENTS, encoded)
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> {
@@ -281,29 +286,29 @@ impl LxMessageDraft {
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>(self, sign: F) -> Result<SignedLxMessage, MessageError>
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,
{
if self.ticket_barrier.is_some() {
return Err(MessageError::TicketNotCommitted);
}
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)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.destination);
wire.extend_from_slice(&self.source);
wire.extend_from_slice(&signature);
wire.extend_from_slice(&signed[32..signed.len() - 32]);
drop(signed);
let mut message = LxMessage::unpack_owned(wire.into(), self.limits)?;
// 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;
@@ -318,7 +323,7 @@ impl SignedLxMessage {
pub(crate) fn restored(
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<u8>,
stamp_cost: Option<f64>,
) -> Self {
Self {
message,
@@ -367,16 +372,35 @@ impl SignedLxMessage {
pub fn fields(&self) -> Fields<'_> {
self.message.fields()
}
pub fn stamp_cost(&self) -> Option<u8> {
/// 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; proof of work uses [`crate::stamper::generate_stamp`]
/// and its attempt budget.
/// 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);
@@ -386,29 +410,43 @@ impl SignedLxMessage {
let Some(cost) = self.stamp_cost else {
return Ok(None);
};
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS)
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 failed"))
.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);
};
let size = 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"))?;
self.message.limits.check_wire(size)?;
message.limits.check_wire(size)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.message.wire);
wire.extend_from_slice(&message.wire);
wire[96] = 0x95;
write_bin(&mut wire, stamp.as_bytes())?;
let mut message = LxMessage::unpack_owned(wire.into(), self.message.limits)?;
debug_assert_eq!(message.message_id, self.message.message_id);
message.metadata = self.message.metadata;
Ok(message)
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 {
+18 -3
View File
@@ -72,9 +72,25 @@ impl EncodedFieldValue {
}
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)]
@@ -102,7 +118,7 @@ impl<'de> Deserialize<'de> for FieldValue {
}
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?;
EncodedFieldValue::new(bytes.into())
EncodedFieldValue::canonical(bytes.into())
.map(Self::MessagePack)
.map_err(serde::de::Error::custom)
}
@@ -115,8 +131,7 @@ pub struct FieldValueRef<'a> {
}
impl<'a> FieldValueRef<'a> {
/// Borrow exactly one structurally valid value without decoding or copying it.
/// Duplicate map keys remain opaque until a recognized schema asks for
/// `unique_map`; binary payloads are never interpreted implicitly.
/// 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)?;
@@ -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,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
+26 -12
View File
@@ -7,20 +7,24 @@ 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 = 1;
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 1 holds, in order:
/// 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: a presence byte and a value;
/// - 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). Version 1 writes both empty, and a reader of
/// 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.
@@ -31,7 +35,7 @@ const STAMP_AT: usize = FLOOR_AT + 2;
#[derive(Clone, PartialEq, Eq)]
pub struct ResumableLxMessage {
bytes: Bytes,
stamp_cost_floor: Option<u8>,
stamp_cost_floor: Option<u16>,
payload_at: usize,
}
@@ -44,12 +48,16 @@ impl std::fmt::Debug for ResumableLxMessage {
}
impl ResumableLxMessage {
pub(super) fn new(wire: &[u8], stamp_cost: Option<u8>) -> Self {
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(&[u8::from(stamp_cost.is_some()), stamp_cost.unwrap_or(0)]);
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();
@@ -75,16 +83,21 @@ impl ResumableLxMessage {
if bytes[HEADER_LEN..HEADER_LEN + MAGIC.len()] != MAGIC {
return Err(invalid("not a stored message"));
}
if bytes[HEADER_LEN + MAGIC.len()] != VERSION {
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 stamp_cost_floor = match bytes[FLOOR_AT..STAMP_AT] {
[0, 0] => None,
[1, cost] => Some(cost),
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]);
@@ -114,8 +127,9 @@ impl ResumableLxMessage {
&self.bytes
}
pub(crate) fn stamp_cost_floor(&self) -> Option<u8> {
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.
+229 -50
View File
@@ -22,12 +22,7 @@ fn payload(fields: &[u8], stamp: Option<&[u8]>) -> Vec<u8> {
fn wire(payload: &[u8]) -> Vec<u8> {
let mut signed = vec![1; 16];
signed.extend_from_slice(&[2; 16]);
if let Some(body) = first_four_msgpack_array_body(payload) {
signed.push(0x94);
signed.extend_from_slice(body);
} else {
signed.extend_from_slice(payload);
}
signed.extend_from_slice(&canonical::hashed_payload(payload).unwrap());
let hash = sha256(&signed);
signed.extend_from_slice(&hash);
let mut out = vec![1; 16];
@@ -201,10 +196,7 @@ fn field_id_duplicate_numeric_encodings_rejected() {
vec![0x82, 1, 0xc0, 0xd1, 0, 1, 0xc0],
vec![0x82, 0xcf, 0, 0, 0, 0, 0, 0, 0, 1, 0xc0, 0xcc, 1, 0xc0],
] {
assert!(matches!(
LxMessage::unpack(&wire(&payload(&map, None))),
Err(MessageError::DuplicateField)
));
assert!(LxMessage::unpack(&wire(&payload(&map, None))).is_err());
let mut dto = vec![0x94, 0xcb];
dto.extend_from_slice(&0f64.to_be_bytes());
dto.extend_from_slice(&[0xc4, 0, 0xc4, 0]);
@@ -229,15 +221,20 @@ fn field_id_coherent_replacement_and_binary_is_not_structure() {
assert_eq!(freeze(d).audio_field().unwrap().unwrap().bytes, &[1, 2]);
}
#[test]
fn field_id_opaque_nested_duplicate_map_is_preserved() {
fn field_id_nested_duplicate_map_is_rejected() {
let raw = vec![0x82, 1, 0x01, 0xd1, 0, 1, 0x02];
let mut d = draft();
d.set_msgpack_field(300u64, raw.clone()).unwrap();
let m = freeze(d);
assert_eq!(m.get_field(300u64).unwrap().encoded(), raw);
assert_eq!(
LxMessage::unpack(m.wire_bytes()).unwrap().pack().unwrap(),
m.wire_bytes()
assert!(d.set_msgpack_field(300u64, raw.clone()).is_err());
assert!(
LxMessage::unpack(&wire(&payload(
&[0x81, 0xcd, 1, 44]
.iter()
.copied()
.chain(raw)
.collect::<Vec<_>>(),
None
)))
.is_err()
);
}
#[test]
@@ -362,7 +359,7 @@ fn recipient_stamp_array_range_and_malformed_dispositions() {
assert_eq!(m.wire_bytes(), bytes);
assert!(m.verify_signature(&key().public_key()));
if !valid {
assert!(!m.validate_stamp_with_tickets(0, None));
assert!(!m.validate_stamp_with_tickets(0.0, None));
}
}
for stamp in [vec![0xc0], vec![0x91, 0], vec![0xc4, 1, 0], vec![0xa0]] {
@@ -378,19 +375,34 @@ fn recipient_stamp_array_range_and_malformed_dispositions() {
}
}
#[test]
fn non_expanded_recipient_stamp_validates_with_its_own_value() {
let signed = draft().sign(&key()).unwrap();
let (stamp, value) = crate::stamper::generate_stamp(
&signed.message_id(),
6.0,
0,
&crate::stamper::StampControl::default(),
)
.unwrap()
.unwrap();
let mut m = signed.finalize(RecipientStamp::from_bytes(&stamp)).unwrap();
assert_eq!(m.validated_stamp_value(6.0, None), Some(value));
assert!(m.check_stamp(6.0, None));
}
#[test]
fn recipient_ticket_stamp_and_missing_stamp_policy() {
let mut d = draft();
d.outbound_ticket = Some([3; 16]);
let signed = d.sign(&key()).unwrap();
let stamp = signed.generate_recipient_stamp().unwrap();
let m = signed.finalize(stamp).unwrap();
assert!(m.validate_stamp_with_tickets(255, Some(&[vec![3; 16]])));
assert!(m.validate_stamp_with_tickets(255.0, Some(&[vec![3; 16]])));
assert_eq!(
m.validated_stamp_value(255, Some(&[vec![3; 16]])),
m.validated_stamp_value(255.0, Some(&[vec![3; 16]])),
Some(COST_TICKET)
);
assert!(!m.validate_stamp_with_tickets(1, Some(&[vec![4; 16]])));
assert!(!freeze(draft()).validate_stamp_with_tickets(0, None));
assert!(!m.validate_stamp_with_tickets(1.0, Some(&[vec![4; 16]])));
assert!(!freeze(draft()).validate_stamp_with_tickets(0.0, None));
let signed = draft().sign(&key()).unwrap();
assert_eq!(signed.generate_recipient_stamp().unwrap(), None);
}
@@ -584,10 +596,17 @@ fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
vec![0x81, 0xc3, 0],
] {
let mut d = draft();
d.set_msgpack_field(300u64, encoded).unwrap();
let m = freeze(d);
assert!(m.get_field(300u64).unwrap().unique_map().is_err());
assert!(m.verify_signature(&key().public_key()));
let map = vec![0x81, 0xcd, 1, 44].into_iter().chain(encoded.clone());
if encoded[0] == 0x81 {
// A single bool key is valid MessagePack; only the schema reader rejects it.
d.set_msgpack_field(300u64, encoded).unwrap();
let m = freeze(d);
assert!(m.get_field(300u64).unwrap().unique_map().is_err());
assert!(m.verify_signature(&key().public_key()));
} else {
assert!(d.set_msgpack_field(300u64, encoded).is_err());
assert!(LxMessage::unpack(&wire(&payload(&map.collect::<Vec<_>>(), None))).is_err());
}
}
let mut d = draft();
d.set_msgpack_field(300u64, vec![0x82, 0xa1, b'a', 0xc4, 1, 7, 0x01, 0x02])
@@ -604,22 +623,6 @@ fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
&[2]
);
}
#[test]
fn signed_body_finalization_ticket_barrier_blocks_signer() {
let owner = Arc::new(());
let mut d = draft();
d.mark_ticket_pending(owner.clone());
assert!(!d.release_ticket_barrier(&Arc::new(())));
assert!(matches!(
d.clone()
.sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }),
Err(MessageError::TicketNotCommitted)
));
assert!(d.release_ticket_barrier(&owner));
assert!(!d.release_ticket_barrier(&owner));
assert!(d.sign(&key()).is_ok());
}
#[test]
fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() {
for bytes in [
@@ -740,7 +743,7 @@ fn resumable_identity() -> rns_identity::identity::Identity {
fn resumable_signed(
identity: &rns_identity::identity::Identity,
cost: Option<u8>,
cost: Option<f64>,
) -> SignedLxMessage {
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
@@ -761,14 +764,18 @@ fn resumable_signed(
#[test]
fn resumable_form_bytes_are_pinned() {
let signed = resumable_signed(&resumable_identity(), Some(8));
let signed = resumable_signed(&resumable_identity(), Some(8.5));
let stored = signed.to_resumable();
let bytes = stored.as_bytes().to_vec();
let wire = signed.finalize(None).unwrap().wire_bytes().to_vec();
assert_eq!(bytes[..96], wire[..96], "the signed header leads");
assert_eq!(bytes[96..100], [0xc1, b'L', b'X', b'R']);
assert_eq!(bytes[100], 1, "version");
assert_eq!(bytes[101..103], [1, 8], "stamp-cost floor");
assert_eq!(bytes[100], 2, "version");
assert_eq!(
bytes[101..103],
[8, 0x80],
"stamp-cost floor 8.5 in fixed point"
);
assert_eq!(bytes[103], 0, "no recipient stamp yet");
assert_eq!(bytes[104..108], [0; 4], "no propagation envelope yet");
let digest_at = bytes.len() - 16;
@@ -782,6 +789,25 @@ fn resumable_form_bytes_are_pinned() {
assert_eq!(
hex::encode(&bytes),
concat!(
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
"58ead48e0227a546df7a9712ea53572c",
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
"8a900be403ca81baac788cf29bd9d64cab486ff0c3923571f11e4a21b4c34005",
"c14c5852",
"02",
"0880",
"00",
"00000000",
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
"cc26bb944896b6a1d957f3b3ac4510ea",
)
);
}
#[test]
fn resumable_form_with_integer_floor_still_loads() {
let stored = ResumableLxMessage::from_bytes(
hex::decode(concat!(
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
"58ead48e0227a546df7a9712ea53572c",
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
@@ -793,8 +819,11 @@ fn resumable_form_bytes_are_pinned() {
"00000000",
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
"370fdcdb14f43dd52931349474302403",
)
);
))
.unwrap(),
)
.unwrap();
assert_eq!(stored.stamp_cost_floor(), Some(8.0));
}
#[test]
@@ -815,7 +844,7 @@ fn resumable_form_is_not_a_wire_message() {
#[test]
fn resumable_form_round_trips_and_rejects_damage() {
let stored = resumable_signed(&resumable_identity(), Some(8)).to_resumable();
let stored = resumable_signed(&resumable_identity(), Some(8.0)).to_resumable();
let bytes = stored.as_bytes().to_vec();
assert_eq!(
ResumableLxMessage::from_bytes(bytes.clone()).unwrap(),
@@ -836,7 +865,7 @@ fn resumable_form_round_trips_and_rejects_damage() {
bytes[at..].copy_from_slice(&digest[..16]);
bytes
};
for (at, value) in [(100, 2), (101, 2), (103, 7), (108, 0x95)] {
for (at, value) in [(100, 3), (101, 0x65), (103, 7), (108, 0x95)] {
let mut unknown = bytes.clone();
unknown[at] = value;
assert!(
@@ -845,3 +874,153 @@ fn resumable_form_round_trips_and_rejects_damage() {
);
}
}
#[test]
fn paper_uri_base64_matches_python_urlsafe_b64decode() {
let corpus = include_str!("fixtures/python-urlsafe-b64decode.tsv");
for line in corpus.lines() {
let (input, want) = line.split_once('\t').unwrap();
let data = String::from_utf8(hex::decode(input).unwrap()).unwrap() + "==";
let got = python_urlsafe_b64decode(&data).ok().map(hex::encode);
let want = (want != "error").then(|| want.to_string());
assert_eq!(got, want, "input {data:?}");
}
assert!(python_urlsafe_b64decode("QUJD\u{e9}==").is_err());
}
#[test]
fn paper_uri_accepts_padding_slashes_and_rejects_upper_case_prefix() {
let mut m = freeze(draft());
m.method = DeliveryMethod::Paper;
let uri = m.to_paper_uri(|tail| Ok(tail.to_vec())).unwrap();
for variant in [
format!("{uri}/"),
format!("{uri}=="),
uri.replacen("lxm://", "lxm:///", 1),
] {
let read = LxMessage::from_paper_uri(&variant, |tail| Ok(tail.to_vec())).unwrap();
assert_eq!(read.wire_bytes(), m.wire_bytes(), "{variant}");
}
// Upstream only strips the lower-case prefix, so "LXM:" stays in the base64 input.
let upper = uri.replacen("lxm://", "LXM://", 1);
let decoded = LxMessage::from_paper_uri(&upper, |tail| Ok(tail.to_vec()));
assert!(decoded.map_or(true, |read| read.wire_bytes() != m.wire_bytes()));
}
#[test]
fn integer_timestamp_is_accepted_and_hashed_as_received() {
let mut p = payload(&[0x80], None);
p.splice(1..10, [0xce, 0x65, 0x53, 0xf1, 0x00]);
let m = LxMessage::unpack(&wire(&p)).unwrap();
assert_eq!(m.timestamp(), 1_700_000_000.0);
assert!(m.verify_signature(&key().public_key()));
}
#[test]
fn nested_duplicate_map_keys_are_rejected_on_send_and_receive() {
let mut d = draft();
assert!(
d.set_msgpack_field(2u8, vec![0x82, 0x01, 0x01, 0x01, 0x02])
.is_err()
);
assert!(
d.set_msgpack_field(2u8, vec![0x81, 0x81, 0x01, 0x01, 0x02])
.is_err()
);
let p = payload(&[0x81, 0x02, 0x82, 0x01, 0x01, 0x01, 0x02], None);
assert!(LxMessage::unpack(&wire(&p)).is_err());
}
#[test]
fn msgpack_fields_are_stored_canonically() {
let mut d = draft();
d.set_msgpack_field(2u8, vec![0x91, 0xca, 0x3f, 0xc0, 0, 0])
.unwrap();
assert_eq!(
d.get_field(2u8),
Some(&FieldValue::MessagePack(
EncodedFieldValue::new(Bytes::from_static(&[
0x91, 0xcb, 0x3f, 0xf8, 0, 0, 0, 0, 0, 0
]))
.unwrap()
))
);
}
#[test]
fn container_is_a_named_map() {
let m = freeze(draft());
let value = rmpv::decode::read_value(&mut &m.pack_container().unwrap()[..]).unwrap();
let keys: Vec<_> = value
.as_map()
.unwrap()
.iter()
.map(|(k, _)| k.as_str().unwrap())
.collect();
assert_eq!(
keys,
[
"state",
"lxmf_bytes",
"transport_encrypted",
"transport_encryption",
"method"
]
);
}
/// Media fields are written once at their size, and the bytes are the
/// canonical encoding the generic msgpack path produces.
#[test]
fn media_fields_encode_canonically_in_one_pass() {
for (name, len) in [
("a.bin", 3usize),
(&"n".repeat(40) as &str, 300),
("é.jpg", 70_000),
] {
let bytes: Vec<u8> = (0..len).map(|i| i as u8).collect();
let mut d = draft();
d.set_file_attachment_field(name, &bytes).unwrap();
d.set_image_field(name, &bytes).unwrap();
d.set_audio_field(7, &bytes).unwrap();
let reference = [
(
FIELD_FILE_ATTACHMENTS,
rmp_serde::to_vec(&FileAttachmentsFieldRef {
file_name: name,
bytes: &bytes,
}),
),
(
FIELD_IMAGE,
rmp_serde::to_vec(&ImageFieldRef {
format: name,
bytes: &bytes,
}),
),
(
FIELD_AUDIO,
rmp_serde::to_vec(&AudioFieldRef {
mode: 7,
bytes: &bytes,
}),
),
];
for (id, encoded) in reference {
let encoded = canonical::canonicalize(&encoded.unwrap()).unwrap();
let Some(FieldValue::MessagePack(value)) = d.get_field(id) else {
panic!("field {id} missing");
};
assert_eq!(
value.encoded(),
encoded.as_slice(),
"field {id}, {len} bytes"
);
}
}
}
/// The wire built in place is `destination, source, signature, payload`,
/// signed over `destination, source, payload, id`.
#[test]
fn signing_builds_the_wire_in_place() {
let mut d = draft();
d.set_file_attachment_field("f", &[9; 5000]).unwrap();
let payload = d.pack_payload().unwrap();
let message = freeze(d);
assert_eq!(message.wire_bytes(), wire(&payload).as_slice());
}
+278 -181
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,17 +177,15 @@ 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,
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], u32)>,
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 decimal kilobytes (1 kB = 1000 bytes).
@@ -198,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 {
@@ -208,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,
@@ -221,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,
@@ -238,6 +257,7 @@ impl LxmPeer {
last_offer_generation: 0,
is_static: false,
handled_messages: HashSet::new(),
unhandled_messages: HashSet::new(),
}
}
@@ -251,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,
@@ -274,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);
@@ -288,6 +308,8 @@ 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
}
@@ -304,9 +326,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>,
) -> bool {
let metadata = self.metadata.clone();
self.refresh_from_announce_with_metadata(
@@ -329,9 +351,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>>>,
) -> bool {
if timebase <= self.peering_timebase {
@@ -358,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;
}
@@ -370,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,
}
}
@@ -388,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) {
@@ -411,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 {
@@ -429,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(),
@@ -449,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()
}
@@ -457,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 (
@@ -478,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;
@@ -497,7 +543,7 @@ impl LxmPeer {
}
})
.collect();
Some(peer)
Some((peer, true))
}
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
@@ -525,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 {
@@ -565,7 +648,7 @@ impl LxmPeer {
/// 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
}
@@ -573,7 +656,7 @@ impl LxmPeer {
/// Cached peering-key work value (leading zero bits), if present.
/// Restored or caller-supplied values are returned without recomputation.
pub fn peering_key_value(&self) -> Option<u32> {
pub fn peering_key_value(&self) -> Option<f64> {
self.peering_key.map(|(_, value)| value)
}
@@ -584,14 +667,15 @@ impl LxmPeer {
///
/// Returns immediately when a key is already cached; it does not revalidate
/// that key against a changed cost. Use [`Self::peering_key_ready`] for that
/// check. Otherwise runs synchronous proof of work with
/// [`crate::stamper::generate_stamp`]'s attempt budget.
/// 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;
@@ -601,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,
}
}
@@ -648,6 +731,7 @@ 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;
}
@@ -684,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 {
@@ -702,68 +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()),
}
}
}
/// Return the input index of an idle peer with unhandled messages.
/// Choose the next peer to sync as Python `LXMRouter.sync_peers()` does.
///
/// Alive peers take priority: sort them by descending transfer rate and choose
/// the first. This selection is deterministic; adding unknown-speed peers to
/// the candidate pool does not randomize the choice as Python `sync_peers()` does.
/// If no alive peer qualifies, choose the first unresponsive peer whose backoff
/// has elapsed. Backoff is not checked in the alive-peer branch.
pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> {
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 {
@@ -786,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]);
@@ -838,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");
}
@@ -869,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));
@@ -881,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)));
@@ -889,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()],
@@ -899,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)));
}
@@ -917,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();
@@ -946,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"
@@ -966,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);
}
@@ -1035,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]
@@ -1049,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);
}
@@ -1077,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]
+63 -198
View File
@@ -1,33 +1,78 @@
//! Router state files in a caller-supplied directory.
//!
//! Files:
//! * `outbound_stamp_costs` — destination stamp costs and observation times
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — delivered transient IDs and timestamps
//! * `locally_processed` — processed transient IDs and timestamps
//! * `node_stats` — propagation-node counters
//! * `propagation_suppression_v1` — bounded download suppression records
//! * `propagation_node_policies_v1` — recorded propagation-node policies
//!
//! These files use the Rust types' MessagePack representations; matching Python
//! filenames does not establish interchangeable contents. Missing files yield
//! empty/default state. Other I/O, malformed-data and capacity errors propagate
//! to the caller.
//! 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)]
@@ -148,130 +193,6 @@ fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
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())
}
/// Process-local revision of a captured ticket state. All production ticket
/// writes pass through the same path coordinator, so a delayed checkpoint can
/// never replace a ticket that a newer signing intent already committed.
#[derive(Debug, Clone)]
pub(crate) struct TicketPersistenceSnapshot {
revision: u64,
snapshot: std::sync::Arc<TicketStoreSnapshot>,
}
impl TicketPersistenceSnapshot {
pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
// Rust 1.99 renamed this operation; keep the identical Rust 1.89 API.
#[allow(deprecated)]
let revision = NEXT
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
.expect("ticket checkpoint revision exhausted");
Self {
revision,
snapshot: std::sync::Arc::new(snapshot),
}
}
pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> {
use std::sync::{Mutex, OnceLock};
struct Latest {
revision: u64,
committed: bool,
}
static WRITERS: OnceLock<Mutex<HashMap<std::path::PathBuf, Latest>>> = OnceLock::new();
fs::create_dir_all(dir)?;
let path = fs::canonicalize(dir)?.join(TICKETS_FILE);
let mut writers = WRITERS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?;
if !writers.contains_key(&path) && writers.len() >= 4096 {
return Err(io::Error::other("ticket persistence path quota exhausted"));
}
let latest = writers.entry(path.clone()).or_insert(Latest {
revision: self.revision,
committed: false,
});
if self.revision < latest.revision {
if !latest.committed {
return Err(io::Error::other(
"newer ticket checkpoint is uncertain and must be retried",
));
}
if let Some(required) = required {
let (stored, _) = load_tickets(dir)?;
if !stored.inbound.contains(required) {
return Err(io::Error::other(
"newer ticket state no longer contains this signing intent",
));
}
}
return Ok(());
}
if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) {
return Err(io::Error::other(
"ticket snapshot does not contain this signing intent",
));
}
latest.revision = self.revision;
latest.committed = false;
// Even an uncertain publication raises the revision floor. Older
// snapshots fail closed until this or a newly captured current state
// reestablishes the strict barrier. No failed payload is retained by
// this bounded process-wide metadata coordinator.
write_mpk(&path, &*self.snapshot)?;
latest.committed = true;
Ok(())
}
}
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None)
}
#[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())
}
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
let bytes = rmp_serde::to_vec_named(stats)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
@@ -288,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]
@@ -390,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");
@@ -407,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();
+83 -1
View File
@@ -5,7 +5,10 @@ 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.
///
/// 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,
@@ -133,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::*;
+96 -32
View File
@@ -15,7 +15,8 @@ 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,
/// When true, the stored file contains `lxmf_data || propagation_stamp`.
@@ -30,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,
@@ -49,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,
@@ -62,13 +63,18 @@ 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
)
}
@@ -79,19 +85,19 @@ impl PropagationEntry {
/// # Panics
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
/// Validate that untrusted filenames are ASCII before calling.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, 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,
}
@@ -252,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)
}
@@ -290,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)
}
@@ -302,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;
}
@@ -396,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,
@@ -407,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]
@@ -417,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]
@@ -426,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]
@@ -440,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);
@@ -457,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);
@@ -480,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);
@@ -491,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);
@@ -506,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);
}
@@ -573,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;
@@ -622,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,
@@ -645,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);
}
}
+28 -8
View File
@@ -27,7 +27,7 @@ const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation";
pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3;
/// 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.
@@ -46,6 +46,8 @@ pub struct PnInboundAdmissionConfig {
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 {
@@ -55,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,
}
}
}
@@ -518,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
@@ -535,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)
@@ -684,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,
@@ -1469,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();
@@ -1487,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();
@@ -1498,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
+157 -45
View File
@@ -291,6 +291,7 @@ impl Peer {
Some(id.to_vec()),
true,
Some(&encrypt),
None,
)
.unwrap()
.segments
@@ -542,11 +543,11 @@ fn request_resource_progress_is_not_a_fixed_120_second_operation() {
let request = peer.client.request.as_mut().unwrap();
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]
@@ -579,42 +580,37 @@ 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 mut consumed = 0;
loop {
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Get(count) = request.kind else {
panic!("get chunk expected")
};
assert!(count <= crate::admission::MAX_DOWNLOAD_ITEMS);
assert!(count > 0);
if let Some(transfer) = &request.outbound {
assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE);
}
let id = request.id;
if consumed + count < 30_840 {
peer.response(id, empty(), false);
consumed += count;
continue;
}
assert_eq!(consumed + count, 30_840);
peer.response(id, binary_list(&[blob(consumed)]), false);
break;
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Get(count, 0) = request.kind else {
panic!("one get request expected")
};
assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS);
if let Some(transfer) = &request.outbound {
assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE);
}
assert!(peer.client.pending_wants.is_empty());
assert!(peer.client.received_ids.is_empty());
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!(
peer.client.pending_wants.is_empty(),
"unserved wants wait for the next list"
);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
assert_eq!(peer.client.received_ids.len(), 1);
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);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
@@ -718,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);
}
}
@@ -1090,18 +1087,16 @@ fn expired_durable_haves_are_downloaded_instead_of_purged() {
]);
peer.client.available_messages = vec![expired.to_vec(), visible.to_vec()];
peer.client.send_get_request();
let (id, request, _) = peer.request(true);
assert_eq!(
request,
Value::Array(vec![Value::Nil, binary_list(&[visible.to_vec()])])
);
assert!(!peer.client.local_messages.contains(expired.as_slice()));
peer.response(id, empty(), false);
let (_, request, _) = peer.request(true);
assert_eq!(
request.as_array().unwrap()[0],
binary_list(&[expired.to_vec()])
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]
@@ -1243,7 +1238,7 @@ fn stale_suppression_checkpoint_cannot_acknowledge_newer_pruning_or_epochs() {
}
#[test]
fn rejected_and_retryable_download_counts_never_become_purge_authority() {
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);
@@ -1271,5 +1266,122 @@ fn rejected_and_retryable_download_counts_never_become_purge_authority() {
);
assert!(peer.client.local_messages.is_empty());
assert!(peer.client.received_ids.is_empty());
assert!(peer.rx.is_empty(), "no durable acceptance means no purge");
// 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
+26 -10
View File
@@ -79,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>
@@ -100,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);
@@ -241,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)
);
}
@@ -249,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)
);
}
@@ -258,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)
);
}
@@ -271,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(
@@ -283,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)
);
}
@@ -305,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)]))
);
}
+175 -56
View File
@@ -1,18 +1,59 @@
//! 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;
use std::sync::atomic::AtomicBool;
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct AdvertisedNodePolicy {
pub stamp_cost: u8,
/// 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,
@@ -68,17 +109,37 @@ pub struct PropagationEnvelope {
message: LxMessage,
ciphertext: Bytes,
transient_id: [u8; 32],
encryption_binding: [u8; 32],
encryption_binding: EncryptionBinding,
stamp: [u8; 32],
stamp_value: u32,
required_cost: u8,
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: [u8; 32],
required_cost: u8,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
) -> Result<Self, MessageError>
where
@@ -89,15 +150,15 @@ impl PropagationEnvelope {
encryption_binding,
required_cost,
encrypt,
&AtomicBool::new(false),
&StampControl::default(),
)
}
pub fn new_cancellable<F>(
message: LxMessage,
encryption_binding: [u8; 32],
required_cost: u8,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
cancel: &AtomicBool,
ctl: &StampControl,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
@@ -107,28 +168,7 @@ impl PropagationEnvelope {
ciphertext.extend_from_slice(&message.destination_hash());
ciphertext.extend_from_slice(&encrypted);
let transient_id = rns_crypto::sha::full_hash(&ciphertext);
let (stamp, generated_value) = crate::stamper::generate_stamp_cancellable(
&transient_id,
required_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp generation failed".into()))?;
// The general stamper's cost-zero shortcut reports the required lower
// bound. Envelopes carry the measured value used by strict relay ingress.
let stamp_value = if required_cost == 0 {
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
&stamp,
)
} else {
generated_value
};
if cancel.load(std::sync::atomic::Ordering::Acquire) {
return Err(MessageError::PackFailed(
"PN stamp generation cancelled".into(),
));
}
let (stamp, stamp_value) = generate_pn_stamp(&transient_id, required_cost, ctl)?;
Ok(Self {
message,
ciphertext: ciphertext.into(),
@@ -151,10 +191,14 @@ impl PropagationEnvelope {
pub fn stamp(&self) -> &[u8; 32] {
&self.stamp
}
pub fn stamp_value(&self) -> u32 {
pub fn stamp_value(&self) -> f64 {
self.stamp_value
}
pub fn matches(&self, message: &LxMessage, encryption_binding: &[u8; 32]) -> bool {
/// 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
}
@@ -166,27 +210,22 @@ impl PropagationEnvelope {
node: PreparedNode,
timestamp: f64,
) -> Result<Vec<u8>, MessageError> {
self.pack_for_cancellable(node, timestamp, &AtomicBool::new(false))
self.pack_for_cancellable(node, timestamp, &StampControl::default())
}
pub fn pack_for_cancellable(
&mut self,
node: PreparedNode,
timestamp: f64,
cancel: &AtomicBool,
ctl: &StampControl,
) -> Result<Vec<u8>, MessageError> {
if !timestamp.is_finite() {
return Err(MessageError::PackFailed(
"propagation timestamp must be finite".into(),
));
}
if self.stamp_value < u32::from(node.policy.stamp_cost) {
(self.stamp, self.stamp_value) = crate::stamper::generate_stamp_cancellable(
&self.transient_id,
node.policy.stamp_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp regeneration failed".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
@@ -205,13 +244,10 @@ impl PropagationEnvelope {
.checked_add(11 + bin_header)
.ok_or_else(|| MessageError::PackFailed("PN wrapper size overflow".into()))?;
let limit = (node.policy.transfer_limit_kb * 1000.).floor();
let resource_limit = rns_protocol::resource::MAX_EFFICIENT_SIZE
.checked_mul(rns_protocol::resource::MAX_SEGMENTS)
.unwrap_or(0);
if packed_len as f64 > limit || packed_len > resource_limit {
if packed_len as f64 > limit {
return Err(MessageError::TooLarge {
size: packed_len,
limit: (limit as usize).min(resource_limit),
limit: limit as usize,
});
}
let mut out = Vec::with_capacity(packed_len);
@@ -239,7 +275,7 @@ mod tests {
#[test]
fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() {
let policy = AdvertisedNodePolicy {
stamp_cost: 0,
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
@@ -262,7 +298,8 @@ mod tests {
.unwrap()
.finalize(None)
.unwrap();
let mut envelope = PropagationEnvelope::new(msg, [4; 32], 0, |p| Ok(p.to_vec())).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!(
@@ -275,23 +312,105 @@ mod tests {
let mut prepared = PreparedNode {
node: [5; 16],
policy: AdvertisedNodePolicy {
stamp_cost: 0,
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
},
};
let first = envelope.pack_for(prepared, 101.).unwrap();
prepared.policy.stamp_cost = 4;
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);
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
) >= 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))
);
}
}
+8 -4
View File
@@ -121,7 +121,7 @@ pub(crate) struct EntryManifest {
pub content_hash: [u8; 32],
pub destination: [u8; 16],
pub size: usize,
pub stamp_value: u8,
pub stamp_value: f64,
pub stored_at: f64,
pub stamped: bool,
pub origin: OpaqueIngress,
@@ -168,10 +168,13 @@ impl EntryManifest {
)
&& (self.origin == OpaqueIngress::TrustedRecovery || self.stamped)
}
/// Relay object name. Integer values keep the form older stores wrote.
pub(crate) fn filename(&self) -> String {
format!(
"{}_{}",
self.entry().filename(),
"{}_{:.0}_{}_{}",
hex::encode(self.transient_id),
self.stored_at,
self.stamp_value,
hex::encode(self.admission_id)
)
}
@@ -456,7 +459,8 @@ mod tests {
);
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);
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());
@@ -22,7 +22,7 @@ pub struct RecoveryEntry {
pub struct RecoveryPolicy {
pub maximum_store_bytes: usize,
pub maximum_message_bytes: usize,
pub minimum_stamp_cost: u8,
pub minimum_stamp_cost: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryReport {
@@ -33,7 +33,7 @@ pub struct RecoveryReport {
fn validate(
record: &RecoveryEntry,
bytes: &[u8],
minimum_stamp_cost: u8,
minimum_stamp_cost: f64,
) -> io::Result<EntryManifest> {
let tail = if record.stamped { 32 } else { 0 };
if bytes.len() < 112 + tail
@@ -58,20 +58,18 @@ fn validate(
}
let stamp_value = if record.stamped {
let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().map_err(err)?;
let workblock = crate::stamper::stamp_workblock(
crate::stamper::validated_stamp_value(
&record.transient_id,
stamp,
minimum_stamp_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8;
if value < minimum_stamp_cost {
return Err(invalid("recovered stamp does not meet node policy"));
}
value
)
.ok_or_else(|| invalid("recovered stamp does not meet node policy"))?
} else {
if minimum_stamp_cost > 0 {
if minimum_stamp_cost > 0.0 {
return Err(invalid("unstamped recovery does not meet node policy"));
}
0
0.0
};
let mut destination = [0; 16];
destination.copy_from_slice(&bytes[..16]);
@@ -216,7 +214,7 @@ mod tests {
RecoveryPolicy {
maximum_store_bytes: 8192,
maximum_message_bytes: 4096,
minimum_stamp_cost: 0,
minimum_stamp_cost: 0.0,
}
}
fn record(bytes: &[u8], name: &str) -> RecoveryEntry {
+463 -60
View File
@@ -19,20 +19,23 @@ use std::time::{Duration, Instant};
use bytes::Bytes;
use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use rns_link::link::{CloseReason, Link, LinkAction};
use rns_link::handshake::EphemeralKeys;
use rns_link::link::{CloseReason, Link, LinkAction, LinkState};
use rns_link::stamp::{LinkRequestStamper, LinkStampPolicy};
use rns_protocol::resource::{
MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundTransfer, ResourceError, TransferAction,
MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundResource, OutboundTransfer, ResourceError,
TransferAction,
};
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
TransportMessage,
TransportMessage, TransportQuery, TransportQueryResponse,
};
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::{mpsc, oneshot};
use crate::constants::OFFER_REQUEST_PATH;
use crate::constants::{OFFER_REQUEST_PATH, PATH_REQUEST_GRACE};
use crate::peer::{LxmPeer, OutboundOfferPolicy};
use crate::propagation::hex_encode;
use crate::propagation_node::{
@@ -45,17 +48,31 @@ use crate::types::PropagationTransientId;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncTaskState {
Idle,
/// Checking for, or waiting on, a path to the peer before linking.
PathRequested,
Establishing,
Offering,
AwaitingResponse,
Transferring,
Complete,
/// No path to the peer arrived within the path request grace.
NoPath,
/// The peer answered the offer with `ERROR_THROTTLED`.
Throttled,
/// The peer answered the offer with `ERROR_NO_ACCESS`.
NoAccess,
Failed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerSyncTerminalState {
Complete,
/// The path request was not answered; no link was attempted.
NoPath,
/// The node answered the offer with `ERROR_THROTTLED`.
Throttled,
/// The node answered the offer with `ERROR_NO_ACCESS`.
NoAccess,
Failed,
}
@@ -108,29 +125,44 @@ fn prepare_outbound_resource_transfers(
auto_compress: bool,
rtt: Duration,
link_keys: rns_link::key_derivation::LinkKeys,
link_sdu: usize,
link_mdu: usize,
) -> Result<VecDeque<OutboundTransfer>, ResourceError> {
// Parts follow the link's SDU and advertisements its MDU (Resource.py).
let encrypt = |plaintext: &[u8]| {
rns_link::encryption::link_encrypt(&link_keys, plaintext)
.unwrap_or_else(|_| plaintext.to_vec())
};
let link_transfer = |resource| {
let mut transfer = OutboundTransfer::from_prebuilt(resource, rtt);
transfer.advertisement_mdu = link_mdu;
transfer
};
if payload.len() <= MAX_EFFICIENT_SIZE {
return Ok(VecDeque::from([OutboundTransfer::new_encrypted(
let resource = OutboundResource::with_options(
payload,
auto_compress,
rtt,
link_keys,
)?]));
None,
Some(link_sdu),
Some(&encrypt),
)?;
return Ok(VecDeque::from([link_transfer(resource)]));
}
// Reticulum encrypts each logical Resource segment as one assembled blob
// before chunking it into raw RESOURCE packets. MultiSegmentOutbound also
// enforces the protocol's MAX_RESOURCE_SIZE / MAX_SEGMENTS bounds.
let encrypt = |plaintext: &[u8]| {
rns_link::encryption::link_encrypt(&link_keys, plaintext)
.unwrap_or_else(|_| plaintext.to_vec())
};
let resources =
MultiSegmentOutbound::with_encrypt(payload, auto_compress, Some(&encrypt))?.segments;
Ok(resources
.into_iter()
.map(|resource| OutboundTransfer::from_prebuilt(resource, rtt))
.collect())
let resources = MultiSegmentOutbound::with_options(
payload,
auto_compress,
None,
None,
false,
Some(&encrypt),
Some(link_sdu),
)?
.segments;
Ok(resources.into_iter().map(link_transfer).collect())
}
pub struct PropagationSyncTask {
@@ -166,12 +198,17 @@ pub struct PropagationSyncTask {
offer_preparation_rx: Option<oneshot::Receiver<PreparedSyncOffer>>,
ready_prepared_offer: Option<PreparedSyncOffer>,
handled_updates: Vec<PropagationTransientId>,
dropped_unhandled_updates: Vec<PropagationTransientId>,
runtime_handle: Option<tokio::runtime::Handle>,
identity_pub: Option<[u8; 64]>,
identity_key: Option<Ed25519PrivateKey>,
link_stamper: LinkRequestStamper,
prepared_link_keys: Option<([u8; 16], EphemeralKeys)>,
mtu_query: Option<oneshot::Receiver<TransportQueryResponse>>,
active_offer_generation: Option<u64>,
generation_exhausted: bool,
terminal_result: Option<PeerSyncTerminalResult>,
identify_retried: bool,
pending_transport: VecDeque<TransportMessage>,
preserve_pending_on_cleanup: bool,
offered_count: u64,
@@ -180,6 +217,8 @@ pub struct PropagationSyncTask {
transfer_wire_size: u64,
transfer_started: Option<Instant>,
link_establishment_rate: Option<f64>,
path_query: Option<oneshot::Receiver<TransportQueryResponse>>,
path_requested_at: Option<Instant>,
}
impl PropagationSyncTask {
@@ -220,12 +259,17 @@ impl PropagationSyncTask {
offer_preparation_rx: None,
ready_prepared_offer: None,
handled_updates: Vec::new(),
dropped_unhandled_updates: Vec::new(),
runtime_handle: tokio::runtime::Handle::try_current().ok(),
identity_pub: None,
identity_key: None,
link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()),
prepared_link_keys: None,
mtu_query: None,
active_offer_generation: None,
generation_exhausted: false,
terminal_result: None,
identify_retried: false,
pending_transport: VecDeque::new(),
preserve_pending_on_cleanup: false,
offered_count: 0,
@@ -234,6 +278,8 @@ impl PropagationSyncTask {
transfer_wire_size: 0,
transfer_started: None,
link_establishment_rate: None,
path_query: None,
path_requested_at: None,
}
}
@@ -282,12 +328,17 @@ impl PropagationSyncTask {
offer_preparation_rx: None,
ready_prepared_offer: None,
handled_updates: Vec::new(),
dropped_unhandled_updates: Vec::new(),
runtime_handle: tokio::runtime::Handle::try_current().ok(),
identity_pub: None,
identity_key: None,
link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()),
prepared_link_keys: None,
mtu_query: None,
active_offer_generation: None,
generation_exhausted: false,
terminal_result: None,
identify_retried: false,
pending_transport: VecDeque::new(),
preserve_pending_on_cleanup: false,
offered_count: 0,
@@ -296,6 +347,8 @@ impl PropagationSyncTask {
transfer_wire_size: 0,
transfer_started: None,
link_establishment_rate: None,
path_query: None,
path_requested_at: None,
})
}
@@ -338,12 +391,17 @@ impl PropagationSyncTask {
offer_preparation_rx: None,
ready_prepared_offer: None,
handled_updates: Vec::new(),
dropped_unhandled_updates: Vec::new(),
runtime_handle: tokio::runtime::Handle::try_current().ok(),
identity_pub: None,
identity_key: None,
link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()),
prepared_link_keys: None,
mtu_query: None,
active_offer_generation: None,
generation_exhausted: false,
terminal_result: None,
identify_retried: false,
pending_transport: VecDeque::new(),
preserve_pending_on_cleanup: false,
offered_count: 0,
@@ -352,6 +410,8 @@ impl PropagationSyncTask {
transfer_wire_size: 0,
transfer_started: None,
link_establishment_rate: None,
path_query: None,
path_requested_at: None,
}
}
@@ -375,7 +435,7 @@ impl PropagationSyncTask {
}
self.node_dest_hash = Some(dest_hash);
self.offer_policy = None;
if !self.start_sync(dest_hash) {
if !self.begin_attempt(dest_hash) {
return false;
}
self.last_sync = Instant::now();
@@ -392,13 +452,25 @@ impl PropagationSyncTask {
let dest_hash = policy.peer_hash;
self.node_dest_hash = Some(dest_hash);
self.offer_policy = Some(policy);
if !self.start_sync(dest_hash) {
if !self.begin_attempt(dest_hash) {
return false;
}
self.last_sync = Instant::now();
true
}
/// Stamp new link requests with this stamper's policy and announced costs.
/// The default stamps only when `always_stamp_lrs` is set.
pub fn set_link_request_stamper(&mut self, stamper: LinkRequestStamper) {
self.link_stamper = stamper;
}
/// Open the next Link to `node` with `keys`, such as stamped keys
/// generated off the caller's task, instead of the stamper's.
pub fn provide_link_request_keys(&mut self, node: [u8; 16], keys: EphemeralKeys) {
self.prepared_link_keys = Some((node, keys));
}
/// Configure the local identity used for Link identification. Production
/// peer sync must set this before requesting a sync; compatibility callers
/// without identity material retain the historical unidentified behavior.
@@ -414,6 +486,12 @@ impl PropagationSyncTask {
std::mem::take(&mut self.handled_updates)
}
/// Drain IDs that offer preparation dropped from the peer's unhandled set
/// for an insufficient stamp value. They are not handled by the peer.
pub fn take_dropped_unhandled_updates(&mut self) -> Vec<PropagationTransientId> {
std::mem::take(&mut self.dropped_unhandled_updates)
}
pub fn take_terminal_peer_result(&mut self) -> Option<PeerSyncTerminalResult> {
self.terminal_result.take()
}
@@ -452,6 +530,7 @@ impl PropagationSyncTask {
self.active_offer_generation = None;
self.generation_exhausted = false;
self.handled_updates.clear();
self.dropped_unhandled_updates.clear();
self.terminal_result = None;
self.reset_attempt_accounting();
self.state = SyncTaskState::Idle;
@@ -629,8 +708,10 @@ impl PropagationSyncTask {
self.state = SyncTaskState::Failed;
return;
}
let establishment_rate =
self.link.as_ref().and_then(|link| link.establishment_rate);
let establishment_rate = self
.link
.as_ref()
.and_then(|link| link.get_establishment_rate());
self.link_establishment_rate = establishment_rate;
if let (Some(peer), Some(link_id)) = (self.peer.as_mut(), self.link_id) {
peer.link_established(link_id, establishment_rate);
@@ -662,6 +743,7 @@ impl PropagationSyncTask {
self.transfer_wire_size = 0;
self.transfer_started = None;
self.link_establishment_rate = None;
self.identify_retried = false;
}
/// Drain inbound events from transport.
@@ -777,7 +859,7 @@ impl PropagationSyncTask {
}
rns_wire::context::PacketContext::ResourcePrf => {
// Python Packet.pack() sends PROOF+RESOURCE_PRF as
// plaintext (Packet.py:195-197) on PacketType::Proof.
// plaintext (Packet.py) on PacketType::Proof.
// Body = resource_hash(32) || proof(32).
let completed = self
.active_transfer
@@ -886,7 +968,8 @@ impl PropagationSyncTask {
TransferAction::None
| TransferAction::SendAdvertisement(_)
| TransferAction::SendProof(_)
| TransferAction::SendRequest(_) => {}
| TransferAction::SendRequest(_)
| TransferAction::QueryProofCache(_) => {}
}
}
}
@@ -1018,7 +1101,7 @@ impl PropagationSyncTask {
}
}
/// Python reference: LXMPeer.py:396-439 (offer_response).
/// Python reference: LXMPeer.py (offer_response).
fn handle_offer_response(&mut self, response: OfferResponse) {
let node_hash = match self.node_dest_hash {
Some(h) => h,
@@ -1067,6 +1150,17 @@ impl PropagationSyncTask {
self.record_handled_updates(&already_handled);
self.prepare_transfer_for_ids(&wanted_ids);
}
// Python identifies again and resends the offer without a bound; retry once per attempt.
OfferResponse::ErrorNoIdentity if !self.identify_retried && self.link.is_some() => {
self.identify_retried = true;
self.state = if self.send_identify() {
SyncTaskState::Offering
} else {
SyncTaskState::Failed
};
}
OfferResponse::ErrorThrottled => self.state = SyncTaskState::Throttled,
OfferResponse::ErrorNoAccess => self.state = SyncTaskState::NoAccess,
_ => {
self.state = SyncTaskState::Failed;
}
@@ -1148,14 +1242,27 @@ impl PropagationSyncTask {
}
if !self.pending_transport.is_empty()
&& !matches!(self.state, SyncTaskState::Complete | SyncTaskState::Failed)
&& !matches!(
self.state,
SyncTaskState::Complete
| SyncTaskState::NoPath
| SyncTaskState::Throttled
| SyncTaskState::NoAccess
| SyncTaskState::Failed
)
{
return;
}
if !matches!(
self.state,
SyncTaskState::Idle | SyncTaskState::Complete | SyncTaskState::Failed
SyncTaskState::Idle
| SyncTaskState::PathRequested
| SyncTaskState::Complete
| SyncTaskState::NoPath
| SyncTaskState::Throttled
| SyncTaskState::NoAccess
| SyncTaskState::Failed
) {
self.drive_link_watchdog();
}
@@ -1168,12 +1275,13 @@ impl PropagationSyncTask {
&& let Some(node_hash) = self.node_dest_hash
{
if self.message_count() > 0 {
let _ = self.start_sync(node_hash);
let _ = self.begin_attempt(node_hash);
} else {
self.last_sync = Instant::now();
}
}
}
SyncTaskState::PathRequested => self.poll_path_wait(),
SyncTaskState::Establishing | SyncTaskState::AwaitingResponse => {}
SyncTaskState::Offering => {
self.send_offer_request();
@@ -1181,17 +1289,23 @@ impl PropagationSyncTask {
SyncTaskState::Transferring => {
self.drive_transfers();
}
SyncTaskState::Complete | SyncTaskState::Failed => {
SyncTaskState::Complete
| SyncTaskState::NoPath
| SyncTaskState::Throttled
| SyncTaskState::NoAccess
| SyncTaskState::Failed => {
if self.terminal_result.is_none()
&& let Some(peer_hash) = self.node_dest_hash
{
let complete = self.state == SyncTaskState::Complete;
self.terminal_result = Some(PeerSyncTerminalResult {
peer_hash,
state: if complete {
PeerSyncTerminalState::Complete
} else {
PeerSyncTerminalState::Failed
state: match self.state {
SyncTaskState::Complete => PeerSyncTerminalState::Complete,
SyncTaskState::NoPath => PeerSyncTerminalState::NoPath,
SyncTaskState::Throttled => PeerSyncTerminalState::Throttled,
SyncTaskState::NoAccess => PeerSyncTerminalState::NoAccess,
_ => PeerSyncTerminalState::Failed,
},
offer_generation: complete
.then_some(self.active_offer_generation)
@@ -1253,7 +1367,7 @@ impl PropagationSyncTask {
}
}
/// Python reference: LXMPeer.py:381-386.
/// Python reference: LXMPeer.py.
fn send_offer_request(&mut self) {
let node_hash = match self.node_dest_hash {
Some(h) => h,
@@ -1342,11 +1456,20 @@ impl PropagationSyncTask {
offer,
generation,
terminal_handled_ids,
dropped_unhandled_ids,
generation_exhausted,
} => {
self.active_offer_generation = Some(generation);
self.generation_exhausted = generation_exhausted;
self.record_handled_updates(&terminal_handled_ids);
for transient_id in dropped_unhandled_ids {
if !self.dropped_unhandled_updates.contains(&transient_id) {
self.dropped_unhandled_updates.push(transient_id);
}
if let Some(peer) = self.peer.as_mut() {
peer.remove_unhandled_message(&transient_id);
}
}
if offer.transient_ids.is_empty()
&& let Ok(mut node) = self.propagation_node.lock()
{
@@ -1423,6 +1546,88 @@ impl PropagationSyncTask {
}
}
/// LXMPeer.sync: link only once a path is known.
fn begin_attempt(&mut self, node_hash: [u8; 16]) -> bool {
self.path_requested_at = None;
if !self.query_path(node_hash) {
self.state = SyncTaskState::Failed;
return false;
}
self.state = SyncTaskState::PathRequested;
true
}
fn query_path(&mut self, node_hash: [u8; 16]) -> bool {
// Asked ahead of HasPath, so Transport has answered it once the path is known.
let (mtu_tx, mtu_rx) = oneshot::channel();
self.mtu_query = self
.queue_transport(TransportMessage::Rpc {
query: TransportQuery::GetNextHopHardwareMtu { dest: node_hash },
response_tx: mtu_tx,
})
.then_some(mtu_rx);
let (response_tx, response_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::Rpc {
query: TransportQuery::HasPath { dest: node_hash },
response_tx,
}) {
return false;
}
self.path_query = Some(response_rx);
true
}
/// Without a path, request one, check again after `PATH_REQUEST_GRACE`,
/// and end in `NoPath` if it is still missing.
fn poll_path_wait(&mut self) {
let Some(node_hash) = self.node_dest_hash else {
self.state = SyncTaskState::Failed;
return;
};
if let Some(receiver) = self.path_query.as_mut() {
let has_path = match receiver.try_recv() {
Ok(TransportQueryResponse::BoolResult(has_path)) => has_path,
Err(oneshot::error::TryRecvError::Empty) => return,
Ok(_) | Err(oneshot::error::TryRecvError::Closed) => {
self.path_query = None;
self.state = SyncTaskState::Failed;
return;
}
};
self.path_query = None;
if has_path {
self.path_requested_at = None;
let _ = self.start_sync(node_hash);
return;
}
if self.path_requested_at.is_some() {
tracing::debug!(
peer = %hex_encode(&node_hash),
"path request was not answered, retrying sync with peer later"
);
self.path_requested_at = None;
self.state = SyncTaskState::NoPath;
return;
}
tracing::debug!(peer = %hex_encode(&node_hash), "no path to peer exists, requesting");
if !self.queue_transport(TransportMessage::RequestPath {
destination_hash: node_hash,
}) {
self.state = SyncTaskState::Failed;
return;
}
self.path_requested_at = Some(Instant::now());
return;
}
if self
.path_requested_at
.is_some_and(|requested| requested.elapsed().as_secs_f64() >= PATH_REQUEST_GRACE)
&& !self.query_path(node_hash)
{
self.state = SyncTaskState::Failed;
}
}
fn start_sync(&mut self, node_hash: [u8; 16]) -> bool {
self.pending_transport.clear();
self.preserve_pending_on_cleanup = false;
@@ -1437,7 +1642,22 @@ impl PropagationSyncTask {
self.active_transfer_ids.clear();
self.active_offer_generation = None;
self.generation_exhausted = false;
let (link, request_data) = Link::new_initiator(node_hash, 1);
let next_hop_mtu = self
.mtu_query
.take()
.and_then(|mut receiver| crate::link_delivery::answered_hardware_mtu(&mut receiver));
let mtu = crate::link_delivery::signalled_link_mtu(&self.link_stamper, next_hop_mtu);
let initiator = match self.prepared_link_keys.take() {
Some((node, keys)) if node == node_hash => {
Ok(Link::new_initiator_with_keys(node_hash, 1, keys, mtu))
}
_ => self.link_stamper.new_initiator(node_hash, 1, mtu),
};
let Ok((link, request_data)) = initiator else {
tracing::warn!("propagation sync link request stamp generation failed");
self.state = SyncTaskState::Failed;
return false;
};
let link_id = link.link_id;
self.link = Some(link);
@@ -1541,9 +1761,14 @@ impl PropagationSyncTask {
return;
};
let data_size = batch.payload.len() as u64;
let Ok(mut transfers) =
prepare_outbound_resource_transfers(batch.payload, true, rtt, link_keys)
else {
let Ok(mut transfers) = prepare_outbound_resource_transfers(
batch.payload,
true,
rtt,
link_keys,
link.resource_sdu(),
link.mdu,
) else {
self.state = SyncTaskState::Failed;
return;
};
@@ -1615,6 +1840,35 @@ impl PropagationSyncTask {
self.fail_active_transfer();
break;
}
TransferAction::QueryProofCache(proof_data) => {
let Some(link_id) = self.link_id else {
break;
};
let packet_hash =
rns_protocol::resource::resource_proof_packet_hash(&link_id, &proof_data);
if !self.queue_transport(TransportMessage::CacheRequest {
packet_hash,
destination_hash: link_id,
}) {
self.fail_active_transfer();
}
break;
}
TransferAction::SendCancel(_, resource_hash) => {
// Resource.cancel() sends ICL only on an active Link (Resource.py).
if self
.link
.as_ref()
.is_some_and(|link| link.state == LinkState::Active)
{
let _ = self.send_resource_packet(
&resource_hash,
rns_wire::context::PacketContext::ResourceIcl,
);
}
self.fail_active_transfer();
break;
}
TransferAction::None => break,
_ => break,
}
@@ -1768,9 +2022,11 @@ impl PropagationSyncTask {
})
}
/// Python LXMPeer.py:540-542.
/// Python LXMPeer.py.
fn cleanup_sync(&mut self) {
self.link_request_result = None;
self.path_query = None;
self.path_requested_at = None;
self.pending_transport
.retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. }));
// No transfer packet should survive the attempt it belongs to. The
@@ -1946,6 +2202,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator_keys,
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
assert_eq!(transfers.len(), 1);
@@ -2058,6 +2316,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
@@ -2122,6 +2382,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
@@ -2170,6 +2432,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
@@ -2223,6 +2487,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
@@ -2264,6 +2530,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator_keys,
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
assert_eq!(transfers.len(), 2);
@@ -2341,6 +2609,78 @@ mod tests {
task.last_sync = Instant::now();
}
/// Answer queued path queries, then tick; returns whether a path was requested.
fn answer_sync_path(
task: &mut PropagationSyncTask,
rx: &mut mpsc::Receiver<TransportMessage>,
has_path: bool,
) -> bool {
let mut requested_path = false;
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::Rpc {
query: TransportQuery::HasPath { .. },
response_tx,
} => {
let _ = response_tx.send(TransportQueryResponse::BoolResult(has_path));
}
TransportMessage::Rpc {
query: TransportQuery::GetNextHopHardwareMtu { .. },
response_tx,
} => {
let _ = response_tx.send(TransportQueryResponse::IntResult(-1));
}
TransportMessage::RequestPath { .. } => requested_path = true,
TransportMessage::SendLinkRequest { .. } => panic!("link request without a path"),
_ => {}
}
}
task.tick();
requested_path
}
#[test]
fn peer_sync_waits_for_a_peer_path_before_linking() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = test_task(tx, [0xAA; 16]);
assert!(task.request_sync_now([0xB6; 16]));
assert_eq!(task.state, SyncTaskState::PathRequested);
assert!(!answer_sync_path(&mut task, &mut rx, false));
assert!(
answer_sync_path(&mut task, &mut rx, false),
"missing path is requested"
);
assert_eq!(task.state, SyncTaskState::PathRequested);
task.path_requested_at = Some(ago_or_skip!(Duration::from_secs_f64(PATH_REQUEST_GRACE)));
task.tick();
assert!(
!answer_sync_path(&mut task, &mut rx, true),
"path is requested once"
);
assert_eq!(task.state, SyncTaskState::Establishing);
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::RegisterDestination { .. }
));
let (tx, mut rx) = mpsc::channel(64);
let mut task = test_task(tx, [0xAA; 16]);
assert!(task.request_sync_now([0xB7; 16]));
answer_sync_path(&mut task, &mut rx, false);
assert!(answer_sync_path(&mut task, &mut rx, false));
task.path_requested_at = Some(ago_or_skip!(Duration::from_secs_f64(PATH_REQUEST_GRACE)));
task.tick();
answer_sync_path(&mut task, &mut rx, false);
assert_eq!(task.state, SyncTaskState::NoPath);
task.tick();
assert_eq!(task.state, SyncTaskState::Idle);
assert!(task.link_id.is_none());
assert_eq!(
task.take_terminal_peer_result().unwrap().state,
PeerSyncTerminalState::NoPath
);
}
#[test]
fn test_sync_task_creation() {
let (tx, _rx) = mpsc::channel(16);
@@ -2405,6 +2745,7 @@ mod tests {
assert_eq!(task.message_count(), 1);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
assert_eq!(task.state, SyncTaskState::Establishing);
assert!(matches!(
rx.try_recv().unwrap(),
@@ -2449,6 +2790,7 @@ mod tests {
task.accept_fixture(&msg);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
assert_eq!(task.state, SyncTaskState::Establishing);
assert!(task.link_id.is_some());
@@ -2466,7 +2808,7 @@ mod tests {
#[test]
fn test_sync_timeout() {
let (tx, _rx) = mpsc::channel(64);
let (tx, mut rx) = mpsc::channel(64);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
@@ -2483,6 +2825,7 @@ mod tests {
task.accept_fixture(&msg);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
assert_eq!(task.state, SyncTaskState::Establishing);
task.sync_timeout = Duration::ZERO;
@@ -2571,10 +2914,12 @@ mod tests {
let mut task = test_task(tx, [0xAA; 16]);
assert!(task.request_sync_now([0xBB; 16]));
assert_eq!(task.pending_transport.len(), 2);
assert_eq!(task.pending_transport.len(), 2, "MTU and path queries");
let _blocker = rx.try_recv().unwrap();
task.tick();
answer_sync_path(&mut task, &mut rx, true);
answer_sync_path(&mut task, &mut rx, true);
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::RegisterDestination { .. }
@@ -2660,6 +3005,8 @@ mod tests {
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
rns_protocol::resource::SDU,
rns_wire::constants::LINK_MDU,
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
@@ -2709,6 +3056,7 @@ mod tests {
task.accept_fixture(&msg);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
while let Ok(message) = rx.try_recv() {
if let TransportMessage::SendLinkRequest { result_tx, .. } = message {
let _ = result_tx.send(Ok(()));
@@ -2934,7 +3282,7 @@ mod tests {
.accept_blob_fixture(&oversized, 2)
);
let mut policy = OutboundOfferPolicy::unrestricted(node_hash);
policy.minimum_stamp_cost = 1;
policy.minimum_stamp_cost = 1.0;
policy.propagation_transfer_limit = Some(0.5);
let mut task = PropagationSyncTask::with_shared_node(tx, shared_node);
task.set_node(node_hash);
@@ -2943,14 +3291,14 @@ mod tests {
task.send_offer_request();
let mut updates = task.take_handled_updates();
updates.sort();
let mut expected = vec![
rns_crypto::sha::full_hash(&low),
rns_crypto::sha::full_hash(&oversized),
];
expected.sort();
assert_eq!(updates, expected);
assert_eq!(
task.take_handled_updates(),
vec![rns_crypto::sha::full_hash(&oversized)]
);
assert_eq!(
task.take_dropped_unhandled_updates(),
vec![rns_crypto::sha::full_hash(&low)]
);
assert_eq!(task.state, SyncTaskState::Complete);
assert!(task.generation_exhausted);
assert!(rx.try_recv().is_err());
@@ -3056,14 +3404,38 @@ mod tests {
}
#[test]
fn test_handle_offer_response_error() {
let (tx, _rx) = mpsc::channel(16);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
task.handle_offer_response(OfferResponse::ErrorNoAccess);
assert_eq!(task.state, SyncTaskState::Failed);
fn offer_error_responses_reach_the_peer_as_distinct_outcomes() {
for (response, expected) in [
(
OfferResponse::ErrorThrottled,
PeerSyncTerminalState::Throttled,
),
(
OfferResponse::ErrorNoAccess,
PeerSyncTerminalState::NoAccess,
),
(
OfferResponse::ErrorInvalidKey,
PeerSyncTerminalState::Failed,
),
// Without a live link there is nothing to identify on.
(
OfferResponse::ErrorNoIdentity,
PeerSyncTerminalState::Failed,
),
] {
let (tx, _rx) = mpsc::channel(16);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
task.handle_offer_response(response.clone());
task.tick();
assert_eq!(
task.take_terminal_peer_result().map(|r| r.state),
Some(expected),
"{response:?}"
);
}
}
#[test]
@@ -3254,7 +3626,7 @@ mod tests {
#[test]
fn test_peer_created_on_sync_start() {
let (tx, _rx) = mpsc::channel(64);
let (tx, mut rx) = mpsc::channel(64);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
@@ -3273,6 +3645,7 @@ mod tests {
task.accept_fixture(&msg);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
assert_eq!(task.state, SyncTaskState::Establishing);
let peer = task.peer().expect("peer should exist after sync start");
@@ -3282,10 +3655,11 @@ mod tests {
#[test]
fn request_sync_now_starts_without_waiting_for_interval() {
let (tx, _rx) = mpsc::channel(64);
let (tx, mut rx) = mpsc::channel(64);
let mut task = test_task(tx, [0xAA; 16]);
task.request_sync_now([0xBB; 16]);
answer_sync_path(&mut task, &mut rx, true);
assert_eq!(task.node_dest_hash(), Some([0xBB; 16]));
assert_eq!(task.state, SyncTaskState::Establishing);
@@ -3439,6 +3813,11 @@ mod tests {
};
result_tx.send(LinkEndpointBindResult::Bound).unwrap();
task.poll_endpoint_control();
// Python stores Link.get_establishment_rate(), in bits per second.
let bits = task.link.as_ref().unwrap().get_establishment_rate();
assert!(bits.is_some_and(|rate| rate > 0.0));
assert_eq!(task.link_establishment_rate, bits);
assert_eq!(task.peer().unwrap().link_establishment_rate, bits.unwrap());
task.send_offer_request();
let mut contexts = Vec::new();
@@ -3456,6 +3835,29 @@ mod tests {
rns_wire::context::PacketContext::Request,
]
);
// ERROR_NO_IDENTITY: identify again and resend the offer, once per attempt.
task.state = SyncTaskState::AwaitingResponse;
task.handle_offer_response(OfferResponse::ErrorNoIdentity);
assert_eq!(task.state, SyncTaskState::Offering);
task.send_offer_request();
let mut contexts = Vec::new();
while let Ok(message) = rx.try_recv() {
if let TransportMessage::SendLinkEndpoint { request, .. } = message {
let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
contexts.push(header.context);
}
}
assert_eq!(
contexts,
vec![
rns_wire::context::PacketContext::LinkIdentify,
rns_wire::context::PacketContext::Request,
]
);
task.state = SyncTaskState::AwaitingResponse;
task.handle_offer_response(OfferResponse::ErrorNoIdentity);
assert_eq!(task.state, SyncTaskState::Failed);
}
#[test]
@@ -3477,6 +3879,7 @@ mod tests {
task.accept_fixture(&msg);
task.tick();
answer_sync_path(&mut task, &mut rx, true);
while rx.try_recv().is_ok() {}
assert!(task.peer().is_some());
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,
}
}
+240 -494
View File
@@ -1,227 +1,115 @@
//! 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).
//!
//! Rust validation requires at least `cost` leading zero bits in
//! `SHA-256(workblock || stamp)`. Python uses an inclusive numeric threshold,
//! `result <= 1 << (256 - cost)`; the exact equality boundary differs for
//! nonzero 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
}
/// Attempt budget for [`generate_stamp`] and [`generate_stamp_cancellable`]:
/// `64 * 2^cost`. Returns `None` for costs at least 58 because the budget would
/// overflow `u64`. This limits attempts, not elapsed time. Deferred stamp
/// workers use explicit cancellation and do not use this budget.
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
/// requested cost has no supported iteration budget.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
}
/// Synchronous search with the [`stamp_iteration_cap`] attempt budget.
/// Checks cancellation before workblock construction and every 1,000 attempts;
/// workblock construction itself is not interrupted. Run on a blocking worker
/// when called from async code.
pub fn generate_stamp_cancellable(
/// 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,
cancel: &AtomicBool,
) -> Option<([u8; 32], u32)> {
if cancel.load(Ordering::Acquire) {
return None;
}
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 iteration in 0..max_iterations {
if iteration % 1000 == 0 && cancel.load(Ordering::Acquire) {
return None;
}
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
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)
}))
}
/// Stamp search with a configurable iteration limit (for tests).
pub fn generate_stamp_limited(
/// 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],
cost: u8,
stamp: &[u8],
cost: f64,
expand_rounds: usize,
max_iterations: u64,
) -> Option<[u8; 32]> {
if cost == 0 {
return Some([0u8; 32]);
) -> Option<f64> {
if stamp_valid(stamp, cost, material) {
return Some(stamp_value(material, stamp));
}
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
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.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(
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.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))
}
@@ -230,31 +118,32 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
/// 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.
/// The search has no iteration cap; see [`spawn_deferred_stamp_on`] for its
/// cancellation contract.
///
/// # Panics
/// Panics when called outside a Tokio runtime.
#[tracing::instrument(
@@ -269,7 +158,7 @@ pub enum DeferredStampResult {
)]
pub fn spawn_deferred_stamp(
message_id: [u8; 32],
cost: u8,
cost: f64,
expand_rounds: usize,
) -> (
DeferredStampHandle,
@@ -279,372 +168,229 @@ pub fn spawn_deferred_stamp(
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
}
/// Spawn on an explicit runtime handle, without requiring a current runtime
/// context on the calling thread.
///
/// After workblock construction, a nonzero-cost search checks cancellation
/// between batches of 1,000 attempts and runs until success or cancellation.
/// It does not apply [`stamp_iteration_cap`]. Keep the cancellation handle and
/// call `cancel()` when abandoning the result.
/// 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
+1 -1
View File
@@ -376,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],
+9 -4
View File
@@ -162,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());
}
+59 -153
View File
@@ -241,21 +241,22 @@ fn processing_admission_fails_promptly_without_partial_credit_deadlock() {
#[test]
fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
let msg = message(None);
let mut envelope = PropagationEnvelope::new(msg, [6; 32], 0, |p| Ok(p.to_vec())).unwrap();
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,
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;
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);
assert!(envelope.stamp_value() >= 4.0);
assert_eq!(
propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
@@ -263,28 +264,23 @@ fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok());
}
#[test]
fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
#[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;
let intent = router.prepare_outbound(&mut draft).unwrap();
assert!(intent.requires_persistence());
assert!(
draft
.clone()
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.is_err()
);
let mut other =
LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap();
other.include_ticket = true;
assert!(matches!(
router.prepare_outbound(&mut other),
Err(lxmf_core::router::TicketPreparationError::PendingPersistence)
));
intent.persist(temp.path(), &mut draft).unwrap();
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()
@@ -295,9 +291,25 @@ fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
.get(lxmf_core::constants::FIELD_TICKET)
.is_some()
);
let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap();
assert!(!loaded.0.inbound.is_empty());
assert!(router.prepare_outbound(&mut other).is_ok());
// 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]
@@ -357,6 +369,23 @@ fn adapter_processing_memory_shares_peak_budget_without_second_worker() {
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>,
) {
@@ -395,6 +424,8 @@ fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeo
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!(
@@ -404,6 +435,8 @@ fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeo
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!(
@@ -417,6 +450,8 @@ fn canceled_download_closes_exact_request_admission_reply() {
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() {
@@ -429,132 +464,3 @@ fn canceled_download_closes_exact_request_admission_reply() {
}
assert!(found);
}
#[test]
fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() {
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
let stale = router.state_snapshot();
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
let intent = router.prepare_outbound(&mut draft).unwrap();
intent.persist(temp.path(), &mut draft).unwrap();
let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0;
assert_eq!(committed.inbound.len(), 1);
stale.save_state(temp.path()).unwrap();
assert_eq!(
lxmf_core::persist::load_tickets(temp.path()).unwrap().0,
committed
);
// A newer checkpoint can commit while a draft is waiting for its exact
// intent. The old intent verifies that its ticket is still present.
drop(draft);
let mut next =
LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap();
next.include_ticket = true;
let intent = router.prepare_outbound(&mut next).unwrap();
router.state_snapshot().save_state(temp.path()).unwrap();
intent.persist(temp.path(), &mut next).unwrap();
assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok());
assert_eq!(
lxmf_core::persist::load_tickets(temp.path())
.unwrap()
.0
.inbound
.len(),
2
);
}
#[test]
fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() {
let temp = tempfile::tempdir().unwrap();
let mut ledger = SuppressionLedger::default();
ledger
.record_failure(
scope(1),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap();
assert_eq!(
lxmf_core::persist::load_suppression(temp.path())
.unwrap()
.records()
.count(),
1
);
let path = temp.path().join("propagation_suppression_v1");
let bytes = std::fs::read(&path).unwrap();
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
let rmpv::Value::Array(fields) = &mut value else {
panic!("ledger wrapper")
};
let rmpv::Value::Map(rows) = &mut fields[0] else {
panic!("ledger records")
};
rows.push(rows[0].clone());
let mut duplicate = Vec::new();
rmpv::encode::write_value(&mut duplicate, &value).unwrap();
std::fs::write(&path, duplicate).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
}
#[test]
fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() {
use rns_identity::{
announce_state::RatchetControlState,
identity::Identity,
ratchet::{RatchetRing, ReceivedRatchet},
};
let temp = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut ring = RatchetRing::new();
let public = ring.rotate_at(100.);
let ring_path = temp.path().join("ring");
ring.save_verified_durable(&ring_path, &identity).unwrap();
assert_eq!(
RatchetRing::load_verified(&ring_path, &identity)
.unwrap()
.ring()
.current_public_key(),
Some(public)
);
let control = RatchetControlState::new(identity.hash, [2; 16])
.prepare_announce(100)
.unwrap()
.unwrap();
let control_path = temp.path().join("control");
control
.save_verified_durable(&control_path, &identity)
.unwrap();
assert_eq!(
RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(),
control
);
let received = ReceivedRatchet::new_at(public, 100.);
let received_path = temp.path().join("received");
received.save_durable(&received_path).unwrap();
assert_eq!(
ReceivedRatchet::load(&received_path).unwrap().ratchet_pub,
public
);
let blocker = temp.path().join("not-a-directory");
std::fs::write(&blocker, b"preserve").unwrap();
assert!(
ring.save_verified_durable(&blocker.join("ring"), &identity)
.is_err()
);
assert!(
control
.save_verified_durable(&blocker.join("control"), &identity)
.is_err()
);
assert!(received.save_durable(&blocker.join("received")).is_err());
assert_eq!(std::fs::read(blocker).unwrap(), b"preserve");
}
+9 -11
View File
@@ -12,7 +12,7 @@ fn payload(destination: [u8; 16]) -> Bytes {
bytes.into()
}
fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob {
ValidatedOpaquePropagationBlob::validate(bytes, 0).unwrap()
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]>>| {
@@ -182,7 +182,7 @@ fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() {
assert!(!reopened.contains(&tid));
}
#[test]
fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() {
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];
@@ -199,19 +199,17 @@ fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() {
assert_eq!(purge.into_response(), encode(&Value::Array(vec![])));
assert!(!node.contains(&tid));
assert!(!old_path.exists());
let replacement = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(replacement.persist().unwrap()));
let new_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
assert_ne!(old_path, new_path);
// The old plan fails or sees an already completed retirement; it cannot
// gain authority over the distinct new admission path.
// 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));
assert_eq!(std::fs::read(&new_path).unwrap(), bytes);
assert!(!node.contains(&tid));
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap();
assert!(reopened.contains(&tid));
assert!(!reopened.contains(&tid));
}
#[test]
fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() {
+2 -1
View File
@@ -15,15 +15,16 @@ 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]
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
+41 -76
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.
@@ -79,8 +84,11 @@ pub struct Args {
#[arg(long)]
pub exampleconfig: bool,
/// Default to warning-level logging for service use; -v/-q override this.
/// The process remains in the foreground.
/// 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,
@@ -112,8 +120,9 @@ pub struct Args {
#[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.
@@ -182,78 +191,16 @@ 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
# Threshold for new inbound propagation sync offers. Already accepted offers
# and static-peer bypass can exceed this value.
# 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.
@@ -325,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
+46 -25
View File
@@ -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"
);
}