Compare commits

..
215 Commits
Author SHA1 Message Date
DeFiDude 5c18a5f8e6 ci: pin rsReticulum f6d0d69 2026-11-20 12:57:54 -07:00
DeFiDude 483bf7f970 propagation: the delivery limit bounds only a message download, not the ID list 2026-11-20 11:47:18 -07:00
DeFiDude 094c49bd83 ci: pin rsReticulum 54c8525 2026-11-19 20:51:38 -07:00
DeFiDude 3d606ca703 message: a signed message lends out its attachment bytes 2026-11-19 20:47:47 -07:00
DeFiDude 419711b0ee propagation: the Offline Inbox client refuses a response larger than its delivery limit allows 2026-11-19 20:28:05 -07:00
DeFiDude 9436d052c5 message: media fields encode once at their size, and signing builds the wire in place 2026-11-19 20:28:05 -07:00
DeFiDude 70fa224211 ci: pin rsReticulum 5e35c9f 2026-11-19 09:33:10 -07:00
DeFiDude 2d04201bff ci: pin rsReticulum 0ce5a12 2026-11-19 08:55:25 -07:00
DeFiDude 7cbb87cd47 test: lxmd's ratchet test re-announces a second later, past Reticulum's same-second prefilter 2026-11-19 08:52:27 -07:00
DeFiDude b92923e2ec ci: pin rsReticulum 3d53958 2026-11-19 07:54:34 -07:00
DeFiDude bc04e75c4b lxmd: deregister destination types once at exit, through runtime shutdown 2026-11-18 20:11:17 -07:00
DeFiDude 2e057f6172 readme: 1.5.1 follows LXMF 1.3.1 and Reticulum 1.6.1 2026-11-18 17:14:39 -07:00
DeFiDude e2719fbe07 release: version 1.5.1 2026-11-18 17:08:58 -07:00
DeFiDude f65ffa6295 stamps: fractional PN stamp test uses a stamp only the expanded form accepts 2026-11-18 16:54:38 -07:00
DeFiDude 932d59ab74 lxmf: report LXMF 1.3.1 2026-11-18 16:54:38 -07:00
DeFiDude eae4fd50a4 stamps: accept both LXMF workblock forms 2026-11-18 12:59:15 -07:00
DeFiDude bc07d04396 discovery: delegate both-form stamp validation 2026-11-18 12:54:32 -07:00
DeFiDude eee86a37c2 build: lock rsReticulum 1.5.1 2026-11-18 11:36:52 -07:00
DeFiDude b21732352b lxmd: startup logs the full identity, delivery, and propagation hashes as lxmd does 2026-11-15 19:46:27 -07:00
DeFiDude 2520ee1594 ci: pin rsReticulum 184bbfe 2026-11-15 10:08:18 -07:00
DeFiDude 65d43b19a8 ci: pin rsReticulum 81e6188 2026-11-15 08:51:42 -07:00
DeFiDude cf56eb3f1f ci: pin rsReticulum 0680941 2026-11-15 07:20:50 -07:00
DeFiDude 8380416ad5 lxmd: the ctrl-c test kills and reaps its daemon on every path 2026-11-15 04:38:40 -07:00
DeFiDude fa02487ef8 ci: pin rsReticulum cce85ec 2026-11-15 00:26:45 -07:00
DeFiDude 8f0bda8653 ci: pin rsReticulum 1.5.0 2026-11-14 19:38:57 -07:00
DeFiDude d946da1b2a lxmd: drop the hand-over of earlier releases' received ratchets 2026-11-14 01:18:58 -07:00
DeFiDude 9209d9f888 docs: README and changelog for 1.5.0 2026-11-14 00:02:11 -07:00
DeFiDude 91da3bf6df api: version 1.5.0 with refreshed baselines and the 1.5 migration guide 2026-11-13 23:06:43 -07:00
DeFiDude 1b6002e162 build: take rns-tools without the rnodeconf firmware feature 2026-11-13 21:56:43 -07:00
DeFiDude caeb3ffd1b propagation: a node announces the LXMF version it follows 2026-11-13 18:28:52 -07:00
DeFiDude 49728b0f4a build: lxmf-core builds without SQLite when default features are off 2026-11-13 18:08:48 -07:00
DeFiDude 3be3248b58 propagation: turn a node's announce into its policy in one place 2026-11-13 17:53:58 -07:00
DeFiDude 3110cf1a0e lxmd: use Reticulum's ratchet store; unknown announce facts stay unknown
Ratchet files from earlier releases are handed to Reticulum's import
once.
2026-11-13 16:54:34 -07:00
DeFiDude 146ade134c router: keep delivered ids, stamp costs, and tickets in LXMF's state.db
Cache files from earlier versions are imported once. A file that cannot
be used never stops the router.
2026-11-13 14:43:36 -07:00
DeFiDude c90b371c3d lxmd: accept the released -c and -V spellings with a warning 2026-11-13 13:59:58 -07:00
DeFiDude c6fd9e488b lxmd: print the LXMF and Reticulum versions it follows; drop -c and -V 2026-11-13 13:03:30 -07:00
DeFiDude ec3924a812 build: lock file gains the SQLite dependencies 2026-11-13 11:25:03 -07:00
DeFiDude 747aa966f6 api: make config structs non-exhaustive and the outbound module private 2026-11-13 11:25:03 -07:00
DeFiDude d508f19b77 api: type router limits as PnLimit and hide the delivery-claim helpers 2026-11-13 10:12:42 -07:00
DeFiDude 68fe75d34e delivery: a link that fails or closes leaves settled messages alone 2026-11-12 07:42:34 -07:00
DeFiDude cdc8df4b01 lxmf: cite upstream files without line numbers in comments 2026-11-12 06:58:08 -07:00
DeFiDude db559f282d api: update the baselines and draft the next release's migration guide 2026-11-12 05:26:29 -07:00
DeFiDude aa728fde06 lxmf: drop an older upstream version name from comments 2026-11-11 22:29:29 -07:00
DeFiDude ba4202a18a lxmd: keep one processed store and bound the announce backlog 2026-11-11 09:25:42 -07:00
DeFiDude a5ad58e999 lxmf: receive Resources without a segment cap and carry the window over 2026-11-11 09:21:10 -07:00
DeFiDude 01da92ecd4 lxmf: signal the next-hop MTU on delivery, download, and peer sync links 2026-11-11 04:05:31 -07:00
DeFiDude 455e0b1476 propagation: match upstream in the client's requests, purges, and errors 2026-11-11 00:52:26 -07:00
DeFiDude 1f5a51b8b2 lxmf: links can open with prepared request keys 2026-11-10 22:48:47 -07:00
DeFiDude 5939c7b124 propagation: follow upstream store limits, unpeering, and identify retry 2026-11-10 22:22:09 -07:00
DeFiDude 2ae0610272 tests: pass the link SDU through the propagation client test 2026-11-10 21:51:16 -07:00
DeFiDude 1a7d5aaa90 lxmf: send and honour Resource cancels in delivery and propagation 2026-11-10 20:57:10 -07:00
DeFiDude 747c7e98ab lxmd: control commands wait for a path to the control destination 2026-11-10 19:45:15 -07:00
DeFiDude ff3bf1031c propagation: add a configurable stamp throttle and drop ignored sources 2026-11-10 19:19:20 -07:00
DeFiDude ed3ec7070c router: journal delivery claims and keep upstream's delivery metadata 2026-11-10 19:12:40 -07:00
DeFiDude 186ffb48e3 lxmf: check the proof cache after a Resource proof times out 2026-11-10 15:36:52 -07:00
DeFiDude 1a9830008c lxmf: stamp link requests, wait for paths, and pick peers like upstream 2026-11-10 13:37:20 -07:00
DeFiDude 052128bf4e delivery: count inbound link data toward link liveness 2026-11-10 12:45:02 -07:00
DeFiDude 5d9320d7da propagation: follow the Resource reassembly limit API 2026-11-10 12:35:45 -07:00
DeFiDude ea5c61aa6f router: rework outbound delivery to follow upstream's process_outbound 2026-11-10 12:23:55 -07:00
DeFiDude f855bcfbe5 router: follow upstream on paper messages, PLAIN sends, and compression 2026-11-10 10:17:56 -07:00
DeFiDude d486ae85d7 lxmd: follow upstream config, exit codes, and logging; close idle links 2026-11-10 09:56:26 -07:00
DeFiDude 3e9341ad66 lxmd: announce through the stamped announce builder 2026-11-10 08:41:04 -07:00
DeFiDude b6db122563 lxmd: send no stats reply when it is not a propagation node 2026-11-10 08:14:57 -07:00
DeFiDude d3ad54a457 delivery: send link packet proofs with upstream's context 2026-11-10 07:16:18 -07:00
DeFiDude 4f04bcac4e lxmd: keep node announces out of the delivery stamp cost cache 2026-11-10 06:35:05 -07:00
DeFiDude 7edeff229e lxmd: take the log level from its own config and flags, as upstream does 2026-11-10 05:18:02 -07:00
DeFiDude 05ab881975 lxmd: match upstream control requests, announces, and peering config 2026-11-10 05:08:58 -07:00
DeFiDude 01764f3238 lxmd: register its destination types with the shared instance 2026-11-10 04:14:12 -07:00
DeFiDude c65f9ef960 lxmf: support fractional stamp costs and announce them as upstream does 2026-11-10 03:28:42 -07:00
DeFiDude c8a793b0d5 lxmd: answer control requests with a packed value reply 2026-11-10 02:16:22 -07:00
DeFiDude 718419b9d0 lxmf: build the discovery stamper on Reticulum's stamp code 2026-11-10 01:43:29 -07:00
DeFiDude 408d088e56 lxmf: hash messages canonically and match upstream names and paper URIs 2026-11-10 00:00:36 -07:00
DeFiDude 00f439df7e Release 1.4.0 2026-11-08 11:54:07 -07:00
DeFiDude 5a6a0cbbdb Replace invalid AGPL license with Reticulum License
This repository is a port of LXMF, which is licensed under the Reticulum
License. The AGPL-3.0-or-later grant previously in LICENSE was never
effective, because there was no right to place the derived code under AGPL
terms. The Reticulum License now in LICENSE governs every revision in this
repository's history, not only revisions from this commit forward. Additions
and modifications by Ratspeak LLC remain its copyright and are licensed under
the same terms.
2026-11-07 20:49:18 -07:00
DeFiDude 18b99b8932 docs: refresh guides and reference help 2026-11-02 11:13:50 -07:00
DeFiDude b5c3365b57 build: pin rsReticulum to the commit the lockfiles match 2026-10-26 09:04:26 -06:00
DeFiDude 7922c5d7b0 router: retain delivered destinations in Reticulum, as Python LXMF does 2026-10-25 21:26:31 -06:00
DeFiDude bc25696fda router: generate deferred stamps in submission order 2026-10-25 21:13:04 -06:00
DeFiDude e674b3f24b router: resume a stored signed message under its own id 2026-10-25 21:06:21 -06:00
DeFiDude 9bb80d754b build: lock the AES zeroize dependencies 2026-10-25 10:14:00 -06:00
DeFiDude f45abdc335 build: lock rns-link's clock dependencies in the API fixture 2026-10-25 09:34:28 -06:00
DeFiDude 0da6a73b5d build: lock rns-link's new clock dependencies 2026-10-25 06:35:40 -06:00
DeFiDude cfd9a9e82d lxmd: learn the identities Reticulum validated before it subscribed, and recall missing ones 2026-10-25 06:04:18 -06:00
DeFiDude ea09b0e105 router: fall back to direct delivery above Python's 287-byte opportunistic limit 2026-10-25 02:51:46 -06:00
DeFiDude 769d0eb0a3 lxmd: space propagation node announces like Python lxmd 2026-10-21 14:45:25 -06:00
DeFiDude bf348ae810 tests: skip long backdated timeouts on freshly booted Windows clocks 2026-10-20 23:30:56 -06:00
DeFiDude 32084c24a1 docs: accept network and RAM-backed relay storage with a warning 2026-10-20 20:27:13 -06:00
DeFiDude f6a402363f ci: pin Rust 1.96.0 instead of floating stable 2026-10-20 20:08:40 -06:00
DeFiDude ecfb115027 propagation: start without rereading and re-flushing every stored message 2026-10-20 19:53:20 -06:00
DeFiDude 580fe1deab lxmf: harden relay replies and crypto storage initialization 2026-10-13 17:47:25 -06:00
DeFiDude 652dc3cd46 daemon: restore direct receipts and authenticated ticket learning 2026-10-13 00:56:16 -06:00
DeFiDude 66e22cb41f lxmf: require durable propagation acceptance and immutable messages 2026-10-13 00:32:49 -06:00
DeFiDude 74dc13f687 release: keep archive documentation identical across platforms 2026-10-12 16:09:54 -06:00
DeFiDude f8753b5f33 release: prepare LXMF 1.3.0 and archive qualification 2026-10-12 15:59:34 -06:00
DeFiDude 628162a41c release: adopt Reticulum 1.3 and plain version titles 2026-10-12 15:25:44 -06:00
DeFiDude 5fe094c83e propagation: transfer oversized requests as bounded Resources 2026-10-12 14:12:29 -06:00
DeFiDude 4917620b21 api: simplify compatibility metadata 2026-10-10 17:39:31 -06:00
DeFiDude 8bad5e2f1f ci: include final BLE disconnect ownership correction 2026-10-08 23:17:54 -06:00
DeFiDude a40fda5ccf ci: qualify against finalized Rust 1.89 protocol candidate 2026-10-08 23:11:08 -06:00
DeFiDude e38d30e02a build: raise LXMF host minimum to Rust 1.89 2026-10-08 22:59:46 -06:00
DeFiDude 284d56fee3 build: qualify delivery against corrected toolchain-compatible core 2026-10-08 16:21:43 -06:00
DeFiDude df3a500c4f docs: organize pending delivery and compatibility changes 2026-09-25 00:24:56 -06:00
DeFiDude 8a22f7e951 api: record pending Direct compression hook 2026-09-24 17:56:29 -06:00
DeFiDude 98aa927e1d delivery: refresh pending Direct compression policy 2026-09-24 17:51:21 -06:00
DeFiDude 7caacbb382 delivery: weight split Resource progress by payload bytes 2026-09-24 13:23:10 -06:00
DeFiDude f959b200d8 delivery: keep active Resource links alive 2026-09-24 12:44:55 -06:00
DeFiDude 49a1f2a182 api: record event-driven delivery readiness contract 2026-09-24 10:21:59 -06:00
DeFiDude a48ee9c6a3 delivery: wake link transfers on input and local receipts 2026-09-24 10:20:13 -06:00
DeFiDude 4a0abec3b4 lxmd: preserve binary peer hashes in control requests 2026-09-20 00:47:32 -06:00
DeFiDude 534abbb95b build: align API fixture lock and qualified core metadata 2026-09-17 14:43:35 -06:00
DeFiDude 86d5e10230 build: pin corrected Windows socket dependency 2026-09-17 14:21:55 -06:00
DeFiDude 09948bf81c ci: pin bounded RPC fixture checkpoint 2026-09-17 13:51:01 -06:00
DeFiDude 7a851cc204 ci: qualify final core shutdown-test checkpoint 2026-09-17 12:41:36 -06:00
DeFiDude 85e725a064 build: adopt the bounded Reticulum 1.3 dependency line 2026-09-10 12:05:59 -06:00
DeFiDude 0a34047342 propagation: preserve legacy opaque blobs across reload 2026-09-09 00:52:43 -06:00
DeFiDude bb628ba8ef delivery: reject idle cancellation owners and cover Link reuse 2026-09-08 21:50:21 -06:00
DeFiDude fd69ab4fbc api: record reviewed delivery coordination additions 2026-09-08 20:03:36 -06:00
DeFiDude 8db95825c5 daemon: preserve ordered delivery receipts and exact cleanup 2026-09-08 20:00:35 -06:00
DeFiDude 7cf129f76c delivery: retain bounded protocol and cancellation ownership 2026-09-08 20:00:35 -06:00
DeFiDude d7da7f34aa ci: qualify LXMF against the current protocol source graph 2026-09-05 22:48:21 -06:00
DeFiDude e609864d88 build: synchronize existing runtime zeroize dependency in lockfile 2026-09-05 19:29:00 -06:00
DeFiDude e210e0c244 lxmd: exit cleanly during early shutdown 2026-08-26 20:55:38 -06:00
DeFiDude fc1c99d3ff docs: promote RNS 1.4.2 release baseline 2026-08-26 20:48:14 -06:00
DeFiDude e49a8b3d88 api: review link timing additions 2026-08-21 03:03:52 -06:00
DeFiDude 2ab8fdf22b link: align establishment timing with first hop 2026-08-21 00:31:18 -06:00
DeFiDude eac0feaced router: add owned persistence snapshots 2026-08-20 17:56:21 -06:00
DeFiDude a446ee21b6 release: keep maintainer policy internal 2026-08-17 17:08:36 -06:00
DeFiDude b2aab6940d api: organize compatibility evidence 2026-08-17 16:48:42 -06:00
DeFiDude d58ea18011 ci: qualify release source with full history 2026-08-17 15:54:17 -06:00
DeFiDude c0053734f5 release: prepare rsLXMF 1.2.0 2026-08-17 15:00:05 -06:00
DeFiDude 1aee9dc1ed ci: follow clean Reticulum API source 2026-08-17 12:53:34 -06:00
DeFiDude 7da6df836c api: require clean snapshot source 2026-08-17 12:52:42 -06:00
DeFiDude 84c59c87b4 ci: follow reviewed Reticulum API source 2026-08-17 12:37:03 -06:00
DeFiDude 7d0285f46d api: bind snapshots to reviewed source 2026-08-17 12:36:12 -06:00
DeFiDude c934ccc5fe api: add canonical message facade 2026-08-17 11:50:43 -06:00
DeFiDude a8f74d2aed api: enforce manifest and additive compatibility 2026-08-17 11:43:25 -06:00
DeFiDude 133b9e2f60 ci: pin qualified Reticulum API source 2026-08-17 11:42:11 -06:00
DeFiDude 80bb96f799 api: record public compatibility baseline 2026-08-17 10:23:02 -06:00
DeFiDude b8d7afce73 ci: run source contract from workspace 2026-08-17 04:06:39 -06:00
DeFiDude ca9f119cbb release: pin qualified Reticulum source 2026-08-17 02:20:13 -06:00
DeFiDude 8101523fb9 lint: adopt Rust 1.87 integer divisibility 2026-08-17 02:20:13 -06:00
DeFiDude 92ea14b485 release: raise unified MSRV to Rust 1.87 2026-08-17 01:42:44 -06:00
DeFiDude 8b641971d9 ci: pin source qualification actions 2026-08-17 00:38:58 -06:00
DeFiDude c787312b48 release: pin compatible Reticulum source 2026-08-17 00:14:20 -06:00
DeFiDude 00de17cf26 release: enforce source qualification contract 2026-08-17 00:10:25 -06:00
DeFiDude 8a6316c635 lxmd: own announce discovery subscriptions 2026-08-16 20:18:31 -06:00
DeFiDude 0bd4220db6 docs: distinguish LXMF reference baselines 2026-08-16 18:41:23 -06:00
DeFiDude 44af77dc98 lxmd: follow current Python resource policy 2026-08-16 18:34:25 -06:00
DeFiDude 42355b4f46 lxmd: restore Python resource limit default 2026-08-16 17:32:26 -06:00
DeFiDude d100e3eae5 docs: explain established Link binding 2026-08-16 15:39:49 -06:00
DeFiDude 502795c70d link: observe typed endpoint send results 2026-08-16 15:37:13 -06:00
DeFiDude a530ad77c0 tools: map Link identity send errors 2026-08-16 15:19:59 -06:00
DeFiDude f91747b1d8 docs: record Link delivery hardening 2026-08-16 15:17:11 -06:00
DeFiDude 29804534ce propagation: pin Link sessions to proof interfaces 2026-08-16 15:17:08 -06:00
DeFiDude f89b6a2811 direct: bind Links and retain reverse proofs 2026-08-16 15:17:04 -06:00
DeFiDude 094bc95662 core: add native LXMF audio fields 2026-08-15 12:48:04 -06:00
DeFiDude b40dcd37f2 delivery: reconcile backchannel outcomes and reverse resources 2026-08-14 13:49:48 -06:00
DeFiDude 681c0f5961 delivery: reduce large message allocation 2026-08-13 12:42:35 -06:00
DeFiDude f9ed81e3ae docs: clarify Opportunistic proof lifecycle 2026-08-13 02:10:40 -06:00
DeFiDude 326022cae8 runtime: complete tickets and durable propagation 2026-08-12 23:58:24 -06:00
DeFiDude 27a49aed00 runtime: harden LXMF daemon parity 2026-08-12 20:15:30 -06:00
DeFiDude 2e124b1006 ci: enforce strict Clippy across supported targets 2026-08-06 18:49:06 -06:00
DeFiDude c0bd1ef82f core, lxmd: make inbound link delivery lossless 2026-07-27 00:07:19 -06:00
dude.eth a1c3a29603 Merge pull request #5 from ratspeak/feature/api-parity
propagation: harden delivery and complete parity APIs
2026-07-26 13:41:20 -06:00
DeFiDude 830db46735 presentation: avoid trailing separator truncation 2026-07-26 13:38:34 -06:00
DeFiDude b4c2e09ca6 tests: await bounded offer preparation 2026-07-26 13:35:35 -06:00
DeFiDude 7dfe9c18bd release: prepare v1.1.0 2026-07-26 13:24:34 -06:00
DeFiDude 4350dd1a88 ci: gate public API documentation 2026-07-26 06:57:59 -06:00
DeFiDude e38bab9d16 docs: keep public API rustdoc clean 2026-07-26 06:55:49 -06:00
DeFiDude 115c9dd17c lxmd: restore Python delivery limit default 2026-07-26 02:56:51 -06:00
DeFiDude 3070484a5f propagation: guard transfer restarts 2026-07-26 02:01:04 -06:00
DeFiDude c52c0a254f presentation: unify safe transfer status 2026-07-26 01:57:08 -06:00
DeFiDude 42e3907835 router: make inbound state durable 2026-07-26 01:39:48 -06:00
DeFiDude 5c37690bd6 router: expose inbound Resource control 2026-07-26 01:29:38 -06:00
DeFiDude 703942ecf5 lxmd: align delivery defaults and limits 2026-07-25 23:24:07 -06:00
DeFiDude d22fa362fa propagation: complete live peer offer sync 2026-07-25 23:18:26 -06:00
DeFiDude b47a2d29b9 propagation: integrate bounded inbound runtime 2026-07-25 22:14:07 -06:00
DeFiDude bd9d51b6b7 propagation: harden inbound throttle policy 2026-07-25 21:39:51 -06:00
DeFiDude 356ba6a305 propagation: isolate bounded offer evaluation 2026-07-25 21:28:37 -06:00
DeFiDude 3a17ca6845 lxmd: parse inbound sync policy 2026-07-25 20:21:57 -06:00
DeFiDude e55074595c propagation: model inbound admission 2026-07-25 19:55:14 -06:00
DeFiDude e0257d6fd6 build: refresh Reticulum dependency lock 2026-07-25 19:47:33 -06:00
DeFiDude 663bfb6066 tests: include inbound packet metrics 2026-07-25 19:36:08 -06:00
DeFiDude 68f84ce0a6 lxmd: bind receipts to destination identity 2026-07-24 03:50:02 -06:00
DeFiDude 93f4257068 deps: refresh Reticulum lock 2026-07-20 21:23:14 -06:00
DeFiDude 90606fdb3f lxmd: make delivery ratchets crash-safe 2026-07-20 17:28:39 -06:00
DeFiDude 393478019b style: rustfmt 2026-07-18 22:35:11 -06:00
DeFiDude 3e048eda1a lxmf: drop dead enforce_stamps router mirror; stamp-gate propagation downloads 2026-07-18 19:58:02 -06:00
DeFiDude b99c177f01 lxmf: drop inert enforce_ratchets knob for Python lxmd parity 2026-07-18 19:01:18 -06:00
DeFiDude b08de427a9 docs: retarget README to LXMF 1.0.1 2026-07-17 08:37:47 -06:00
DeFiDude 22b1907d4c parity: LXMF 1.0.1 — reply/reaction/comment field standards, compression signalling in announces, blackholed-source drop, atomic message persist 2026-07-15 14:24:04 -06:00
DeFiDude 20ef834281 lxmf: check every valid ticket in stamp validation, cull state at load, use announced stamp flexibility 2026-07-10 18:10:17 -05:00
DeFiDude 68ad7c8351 lxmf: expose delivery compression capability state 2026-06-26 16:01:15 -06:00
DeFiDude 90e44916a4 release: bump rsLXMF to 1.0.1 2026-06-13 23:43:19 -06:00
DeFiDude 134a17c704 release: point LXMF builds at Reticulum 1.0.0 2026-06-13 21:52:06 -06:00
DeFiDude 89689fbdb4 release: align crates at 1.0.0 2026-06-13 21:40:26 -06:00
DeFiDude c4f4a04dbb core, lxmd: wire router jobloop and node maintenance; 300s route_hops re-baseline 2026-06-12 11:50:23 -06:00
DeFiDude 68d9d5541f core: prune peer handled sets against store; weight-cap the node store in tick 2026-06-12 11:50:23 -06:00
DeFiDude 1a2acd32f6 router: drive deferred stamp PoW via stored runtime handle; defer delivery-time stamps 2026-06-10 14:39:31 -06:00
DeFiDude 62f30baa0f propagation: stage store file reads outside the node lock; drop lxmd per-tick map clones 2026-06-10 03:46:57 -06:00
DeFiDude 167e571a3a lxmf-core: drop dead max_message_size config and stamp-validation branch 2026-06-10 03:28:42 -06:00
DeFiDude 06015ae181 lxmd: clean startup errors instead of panics; quarantine corrupt store files on load 2026-06-10 00:37:26 -06:00
DeFiDude 9e44e8a407 propagation: age-based dedup cache retention with persisted timestamps 2026-06-10 00:33:43 -06:00
DeFiDude 2fc60703ea message: bound propagation wrapper decode against transfer limits 2026-06-10 00:26:49 -06:00
DeFiDude b61724d1f1 router: enforce max peering cost at announce ingest and bound stamp searches 2026-06-10 00:21:41 -06:00
DeFiDude c7736b9d24 propagation: gate client get and purge on entry ownership 2026-06-10 00:16:00 -06:00
DeFiDude 19187146c8 lint: rustfmt and clippy cleanup 2026-06-09 18:21:54 -06:00
DeFiDude b41c7ac263 lxmd: incremental ratchet persistence and identity cache cap 2026-06-09 17:45:15 -06:00
DeFiDude 8f59b66854 stamper: unify message stamps on the Python HKDF workblock 2026-06-09 17:45:15 -06:00
Oleg Belousov 5ea513bb95 lxmd: drop full crypto-state save from announce processing 2026-06-09 17:17:52 -06:00
DeFiDude 6ac04f0311 deps: refresh rns runtime lockfile 2026-05-30 22:59:31 -06:00
DeFiDude b790ca91d3 lxmd: exit promptly during startup shutdown 2026-05-30 00:06:50 -06:00
DeFiDude 511e0a77f1 lxmd: note hardware signing gap 2026-05-29 23:45:35 -06:00
DeFiDude fedba0bdfa deps: bump bzip2 to 0.6.1 (pure-Rust libbz2-rs-sys) 2026-05-29 02:21:43 -06:00
DeFiDude c0bf58eb52 lxmd: pass Option to LinkManager::with_destination
Adapts to the optional link signing key in rns-runtime; lxmd identities always have one.
2026-05-28 23:41:03 -06:00
81 changed files with 56190 additions and 9869 deletions

No files matched your search

+94 -12
View File
@@ -9,7 +9,47 @@ on:
permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
api-compat:
name: Public API baseline
runs-on: macos-15
timeout-minutes: 45
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: nightly-2026-08-01
targets: aarch64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: true
- name: Install API snapshot tool
run: cargo install cargo-public-api --version 0.52.0 --locked
- name: Check reviewed public API baseline
run: python3 tools/check-api-baseline.py
working-directory: rsLXMF
- name: Check manifest and feature contract
run: python3 tools/check-api-manifest.py
working-directory: rsLXMF
- name: Check additions-only compatibility floor
run: python3 tools/check-api-compatibility.py
working-directory: rsLXMF
- name: Check canonical and legacy external consumer
run: cargo check --manifest-path api/fixtures/Cargo.toml --locked
working-directory: rsLXMF
test:
name: Test (${{ matrix.os }})
timeout-minutes: 30
@@ -19,22 +59,27 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.96.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace
- run: cargo test --workspace --locked
working-directory: rsLXMF
- name: Build embedding examples
run: cargo build -p lxmf-core --examples --locked
working-directory: rsLXMF
lint:
@@ -42,23 +87,60 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.96.0
components: clippy, rustfmt
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Check source-release contract
run: python3 scripts/ci/check_source_release_contract.py
working-directory: rsLXMF
- run: cargo fmt --all -- --check
working-directory: rsLXMF
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps --locked
working-directory: rsLXMF
msrv:
name: Rust 1.89 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
components: clippy
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
+96 -18
View File
@@ -7,21 +7,65 @@ on:
workflow_dispatch:
inputs:
tag_name:
description: "Release tag to create or update"
description: "Version tag (also used for untagged qualification)"
required: true
qualify_only:
description: "Build and verify archives without publishing or creating a tag"
type: boolean
default: true
required: true
permissions:
contents: read
actions: read
env:
SOURCE_REF: ${{ github.sha }}
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_REF: v0.9.4
RSLXMF_RSRETICULUM_VERSION: 1.5.1
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
verify:
name: Verify release source
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.SOURCE_REF }}
path: rsLXMF
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
- name: Verify release source and dependency
working-directory: rsLXMF
shell: bash
env:
GH_TOKEN: ${{ github.token }}
QUALIFY_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.qualify_only }}
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "${SOURCE_REF}"
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SOURCE_REF}&event=push&per_page=100" \
--jq '.workflow_runs | any(.head_sha == env.SOURCE_REF and .conclusion == "success")' | grep -qx true
if [[ "${QUALIFY_ONLY}" == "true" ]]; then
python3 scripts/ci/check_source_release_contract.py --candidate-tag "${RELEASE_TAG}"
else
python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
fi
build:
name: Build ${{ matrix.artifact_suffix }}
needs: verify
timeout-minutes: 30
strategy:
fail-fast: false
@@ -40,17 +84,19 @@ jobs:
env:
ARCHIVE_NAME: rsLXMF-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.RELEASE_TAG }}
ref: ${{ env.SOURCE_REF }}
path: rsLXMF
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_REF }}
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps (Linux)
@@ -58,12 +104,17 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Build release binaries
working-directory: rsLXMF
run: cargo build -p lxmf-tools --release --bins
run: cargo build -p lxmf-tools --release --bins --locked
- name: Stage archive contents
shell: bash
working-directory: rsLXMF
run: |
set -euo pipefail
for bin in ${LXMF_BINS}; do
suffix=""
if [[ "${RUNNER_OS}" == "Windows" ]]; then suffix=".exe"; fi
"target/release/${bin}${suffix}" --version
done
mkdir -p "dist/${PACKAGE_ROOT}/bin"
for bin in ${LXMF_BINS}; do
if [[ "${RUNNER_OS}" == "Windows" ]]; then
@@ -72,7 +123,10 @@ jobs:
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
fi
done
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
# Read blobs directly so Windows checkout line endings cannot alter the package.
for doc in README.md LICENSE CHANGELOG.md; do
git show "HEAD:${doc}" > "dist/${PACKAGE_ROOT}/${doc}"
done
- name: Create tar archive
if: runner.os != 'Windows'
shell: bash
@@ -83,7 +137,7 @@ jobs:
shell: pwsh
working-directory: rsLXMF
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
- uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
@@ -91,22 +145,46 @@ jobs:
rsLXMF/*.zip
if-no-files-found: error
package:
name: Verify release archives
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.SOURCE_REF }}
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
pattern: rsLXMF-*
path: release-assets
merge-multiple: true
- name: Verify archive inventory and generate checksums
run: python3 scripts/ci/check_release_archives.py --tag "${RELEASE_TAG}" --directory release-assets
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: verified-release-assets
path: release-assets/*
if-no-files-found: error
publish:
name: Publish GitHub release
needs: build
if: github.event_name == 'push' || !inputs.qualify_only
needs: package
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@v7
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
name: verified-release-assets
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v3
- uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
with:
tag_name: ${{ env.RELEASE_TAG }}
name: ${{ env.RELEASE_TAG }}
body: ""
generate_release_notes: false
append_body: false
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
files: release-assets/*
+3
View File
@@ -1,4 +1,7 @@
/target/
/api/fixtures/target/
*.swp
.DS_Store
__pycache__/
*.pyc
proptest-regressions/
+132
View File
@@ -0,0 +1,132 @@
# Changelog
## Unreleased
## 1.5.1 - 2026-11-18
- **Follows Python LXMF 1.3.1** with Reticulum 1.6.1 (rsReticulum 1.5.1), and reports LXMF 1.3.1, propagation-node announces included.
- Message, propagation-node, and peering stamps are accepted in both workblock forms: the non-expanded one LXMF senders are moving to, tried first, then the expanded one. A stamp's value comes from the form that passed. Generation stays expanded until senders switch.
- Discovery stamps are validated in both forms through rsReticulum's discovery stamper.
## 1.5.0 - 2026-11-13
### Added
- **Fractional stamp costs**: stamp costs can be fractional, as in LXMF 1.3.0, and announces carry them where LXMF 1.3.0 reads them.
- **Stamped links**: delivery, propagation downloads, and peer sync stamp their link requests when the destination asks for it, following Reticulum's `[stamps]` settings. With stamping on, `lxmd-rs` also stamps its own announces.
### Fixed and improved
- `lxmd-rs` reads its config as Python's `lxmd` does: a malformed value, or a stamp cost of 100 or more, now stops it instead of being replaced by a default. It writes a default config on first run and, as a service, logs to `logfile` in its config directory.
- `lxmd-rs --version` prints `lxmd-rs 1.5.0 (LXMF 1.3.0, Reticulum 1.6.0)`, and it logs at Notice by default.
- Control commands (`--status`, `--peers`, `--sync`, `--break`) wait for a path to the node within `--timeout`.
- Propagation nodes follow LXMF 1.3.0 in storage limits, peering, and sync, throttle peers that send invalid stamps, and announce LXMF 1.3.0 as their version.
- The propagation client waits for a path, reuses an open link, and reports a missing path, refused access, and a missing identity as separate failures.
- Outgoing messages reuse an open link to the same destination, and a link that closes no longer fails messages it already delivered.
- Paper messages are checked for duplicates, and messages are compressed only when the recipient says it supports it.
- Message ids and signatures match Python LXMF for messages packed by any encoder. Display names in announces are passed through unchanged; use `presentation::sanitize_name` before showing one.
### Build and compatibility
- Delivered message ids, stamp costs, and tickets are stored in `lxmf/state.db`, the same SQLite store LXMF 1.3.0 uses, and ratchets and identities are left to Reticulum. The old cache files are imported on first start, and `lxmd-rs`'s old ratchet and identity files are removed: each contact's ratchet returns with its next announce. Going back to an older release starts without them.
- Breaking API changes are listed in the [1.5 migration guide](api/migrations/1.5.md); use the `~1.5.0` line with rsReticulum `~1.5.0`. The default `sqlite-store` feature builds a bundled SQLite, so builds need a C compiler.
## 1.4.0 - 2026-11-08
- Start a propagation node without rereading and flushing every stored message, so restarts with large stores no longer delay announces and hosting. Each message is still verified when it is served.
- Space `lxmd` announces like Python lxmd: the propagation and control announces follow their trigger by 20 seconds instead of going out together with the delivery announce, so Python transport nodes no longer hold the control announce after a restart. A node set not to announce at start now waits a full interval before its first periodic announce.
- Fall back from opportunistic to direct delivery whenever a message's content does not fit one encrypted packet, over 287 bytes, as in Python LXMF 1.2.0.
- `lxmd` learns the identities Reticulum validated before it subscribed to announces, and asks Reticulum for a missing identity before a propagation download, a delivery or a peer sync, as Python LXMF recalls them.
- Store a signed message so its delivery can resume after a restart under the same id. A message that is already queued is no longer queued twice.
- Generate deferred stamps in the order messages were sent, as Python LXMF does, so a reply no longer overtakes the message it answers.
- Keep a destination's identity in Reticulum once a message to it is delivered, as Python LXMF does. `lxmd` asks the shared instance when attached to one.
- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions.
- Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry.
- Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available.
- Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext.
- Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods.
- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. Use the `~1.4.0` compatibility line for these source-breaking APIs.
## 1.3.0 - 2026-10-12
### Added
- Added delivery readiness hooks so applications can react promptly to incoming Link traffic and local send completion.
- Added support for updating pending Direct-message compression as peer capabilities become known.
### Fixed and improved
- Send oversized propagation `/get` and purge requests as request Resources,
with sequential bounded chunks for larger inboxes. Match responses and
Resource completion to the owning request, preserve partial downloads on
failure, and keep healthy transfers alive beyond the former whole-phase
timeout. Resource receipt alone is not successful purge completion.
- Kept active attachment transfers alive while data is moving and reduced delays between delivery steps.
- Corrected progress reporting for transfers split across multiple Resources by weighting each part by its payload size.
- Fixed intermittent propagation-node sync and unpeer failures caused by incorrectly encoded peer addresses.
### Build and compatibility
- Raised the host source-build minimum to Rust 1.89 and qualified the corresponding protocol dependency update.
- Migrated rsReticulum compatibility to the explicit `~1.3.0` line, including
nullable interface discovery and bounded RNode announce admission.
- Updated the Python interoperability baseline to Reticulum 1.4.2 and LXMF 1.0.1, with separate LXMF 1.1.0 checks.
## 1.2.0 - 2026-08-17
- Added the exact-reexport `lxmf_core::message_api` facade, a compiled message
example, and canonical/legacy external-consumer coverage while retaining all
existing module paths and leaving router, delivery, propagation, wire, and
persistence behavior unchanged.
- Classified `lxmf-core` as candidate stable and `lxmf-tools` as tool internal,
with pinned CI-enforced public API snapshots and no visibility or signature
change.
- Made source releases reproducible from an existing immutable component tag:
packages are non-publishable by default and expose Rust 1.87 metadata,
release builds use the committed lockfile and exact dependency commits,
actions are commit-pinned, and CI verifies the release-source contract.
- Replaced temporary aspect-wide announce handlers in remote-control lookup
with bounded validated destination recall, and made lxmd's delivery and
propagation observers exact owned subscriptions with deterministic cleanup.
- Matched current Python LXMF 1.1.0's fresh `lxmd` direct-delivery Resource
admission default of 1 decimal KB, while keeping the reusable router's
separate 1000 KB library default and preserving explicit configured limits.
- Bound Direct-delivery, propagation-download, and propagation-sync Link
initiators to the authenticated LRPROOF ingress interface before LRRTT,
routed all established-Link traffic through ordered typed endpoints, and
made reverse delivery proofs durable before plaintext publication.
- Bounded propagation-sync transport staging, scoped Link endpoint failures
to their owning operation, and prevented Resource responses from becoming
visible when their delivery proof cannot be retained.
- Made typed Link sends fail closed on rejected transport admission, delayed
reverse plaintext and propagation responses until their proofs are reliably
admitted, and made failed graceful closes unbind before deregistration.
- Added automatic pre-sign reply-ticket issue, signature-gated inbound
learning, directional migration-safe persistence, and proof-gated delivery
accounting, with live Python restart/reply interoperability.
- Made Opportunistic one-shot delivery wait for an authenticated Reticulum
proof, with atomic receipt-first dispatch and bounded retries.
- Moved propagation-store persistence off the daemon loop through
reserve/write/commit transactions so visibility, handled IDs and counters
advance only after durable writes.
- Added coalescing announce handoff, live allow-list rotation and split
peer-Resource convergence coverage.
- Made one-shot remote control commands wait for a real online Reticulum
interface before opening their Link, avoiding stale-path startup loss.
- This source line targets the rsReticulum 1.2 dependency line and includes
API evolution since the alpha-stage 1.1.0 source release.
## 1.1.0 - 2026-07-26
- Added bounded propagation-node admission, exact inbound Resource ownership,
asynchronous validation, and peer-specific throttling.
- Completed live peer offer preparation, encrypted Resource synchronization,
cancellation, and proof-gated convergence.
- Added public inbound Resource tracking and cancellation plus restart-safe
persistence and packet/Resource deduplication.
- Unified safe name presentation and authoritative propagation transfer
status, including restart protection.
- Aligned `lxmd-rs` delivery and stamp defaults with the proven Python LXMF
compatibility target.
Generated
+295 -59
View File
@@ -11,6 +11,19 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
@@ -132,15 +145,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block2"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2",
]
[[package]]
name = "bytes"
version = "1.11.1"
@@ -149,21 +153,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bzip2"
version = "0.5.2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"bzip2-sys",
]
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
dependencies = [
"cc",
"pkg-config",
"libbz2-rs-sys",
]
[[package]]
@@ -177,9 +171,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.2.58"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -211,6 +205,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -344,6 +339,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"pem-rfc7468",
"zeroize",
]
@@ -354,6 +350,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
@@ -399,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"
@@ -413,9 +422,9 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "fnv"
@@ -475,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"
@@ -490,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"
@@ -627,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"
@@ -634,12 +664,35 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
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"
@@ -663,13 +716,16 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "0.9.2"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2",
"proptest",
"rand 0.8.5",
"rmp",
"rmp-serde",
"rmpv",
"rns-crypto",
@@ -678,17 +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 = "0.9.2"
version = "1.5.1"
dependencies = [
"base64",
"bytes",
@@ -699,12 +758,15 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-runtime",
"rns-tools",
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tracing",
"tracing-subscriber",
"zeroize",
]
[[package]]
@@ -716,6 +778,16 @@ dependencies = [
"libc",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.0"
@@ -724,9 +796,9 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"wasi",
@@ -765,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"
@@ -772,31 +879,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
name = "objc-sys"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.5.2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc-sys",
"objc2-encode",
]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2-foundation",
]
@@ -809,13 +909,11 @@ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
]
@@ -854,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"
@@ -872,9 +990,9 @@ dependencies = [
[[package]]
name = "pkg-config"
version = "0.3.32"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "ppv-lite86"
@@ -1065,7 +1183,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"aes",
"cbc",
@@ -1083,34 +1201,41 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-interface"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
"if-addrs",
"jni",
"libc",
"md-5",
"mio",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-transport",
"rns-wire",
"serde",
@@ -1125,9 +1250,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmpv",
"rns-crypto",
@@ -1135,12 +1261,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"bzip2",
"hex",
@@ -1149,6 +1276,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -1156,11 +1284,12 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "0.9.4"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1174,14 +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 = "0.9.4"
version = "1.5.1"
dependencies = [
"bytes",
"hex",
@@ -1191,6 +1349,7 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"rusqlite",
"serde",
"subtle",
"thiserror 2.0.18",
@@ -1200,13 +1359,47 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.4"
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"
@@ -1355,9 +1548,9 @@ dependencies = [
[[package]]
name = "shlex"
version = "1.3.0"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
@@ -1375,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",
]
@@ -1404,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"
@@ -1499,6 +1699,21 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.50.0"
@@ -1605,12 +1820,27 @@ 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"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-xid"
version = "0.2.6"
@@ -1629,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"
+20 -13
View File
@@ -6,30 +6,32 @@ members = [
]
[workspace.package]
version = "0.9.2"
version = "1.5.1"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
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" }
rns-wire = { path = "../rsReticulum/crates/rns-wire" }
rns-identity = { path = "../rsReticulum/crates/rns-identity" }
rns-link = { path = "../rsReticulum/crates/rns-link" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol" }
rns-transport = { path = "../rsReticulum/crates/rns-transport" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime" }
rns-interface = { path = "../rsReticulum/crates/rns-interface" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.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" }
lxmf-tools = { path = "crates/lxmf-tools" }
lxmf-core = { path = "crates/lxmf-core", version = "~1.5.1" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.5.1" }
# Encoding
base64 = "0.22"
# Serialization
rmp = "0.8"
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
@@ -53,9 +55,14 @@ tracing-subscriber = "0.3"
# Error handling
thiserror = "2"
# SQLite (router state, LXMF 1.3.0 state.db)
rusqlite = { version = "0.32", features = ["bundled"] }
# Misc
hex = "0.4"
tempfile = "3"
unicode-normalization = "0.1"
unicode-general-category = "0.6"
# Testing
proptest = "1"
+26 -653
View File
@@ -1,661 +1,34 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Reticulum License
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Derived from the reference implementation at
https://github.com/markqvist/LXMF
Preamble
Copyright (c) 2020-2026 Mark Qvist, unless otherwise noted
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Additions and modifications Copyright (c) 2026 Ratspeak LLC
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- The Software shall not be used in any kind of system which includes amongst
its functions the ability to purposefully do harm to human beings.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
- The Software shall not be used, directly or indirectly, in the creation of
an artificial intelligence, machine learning or language model training
dataset, including but not limited to any use that contributes to the
training or development of such a model or algorithm.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+95 -57
View File
@@ -4,9 +4,10 @@
**Rust LXMF messaging and propagation for Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![LXMF 0.9.8](https://img.shields.io/badge/target-LXMF%200.9.8-success.svg)](https://github.com/markqvist/LXMF)
[![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)
[![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) |
@@ -18,24 +19,26 @@
---
rsLXMF is a Rust implementation of LXMF, the Reticulum messaging layer. This is not a fork of LXMF, this is LXMF written in a different language focused on staying interoperable. This is not a source of truth implementation, do not use it as such.
Commands are intentionally namespaced for Rust with the Rust-specific `lxmd-rs` command, so rsLXMF can live beside other
LXMF daemons on `PATH` without worry.
rsLXMF is a Rust port of [LXMF](https://github.com/markqvist/LXMF), the
Reticulum messaging layer, from the reference implementation by Mark Qvist. It
was written from the reference source, not from a specification, and tracks the
reference's wire behavior release by release.
## Contents
- [Build It](#build-it)
- [Rust API](api/README.md)
- [Operating lxmd-rs](#operating-lxmd-rs)
- [Configuration](#configuration)
- [Delivery Model](#delivery-model)
- [Feature Status](#feature-status)
- [Compatibility Notes](#compatibility-notes)
- [Contributing](#contributing)
- [License](#license)
## Build It
This guide describes the 1.5.1 release, [v1.5.1](https://github.com/ratspeak/rsLXMF/releases/tag/v1.5.1), built with rsReticulum [v1.5.1](https://github.com/ratspeak/rsReticulum/releases/tag/v1.5.1), the source line Ratspeak builds from.
The current development layout for rsLXMF requires
rsReticulum as a sibling directory/repo next to it, such as:
@@ -50,9 +53,13 @@ mkdir ratspeak-src
cd ratspeak-src
git clone https://github.com/ratspeak/rsReticulum
git clone https://github.com/ratspeak/rsLXMF
git -C rsReticulum checkout --detach v1.5.1
git -C rsLXMF checkout --detach v1.5.1
cd rsLXMF
```
Run the build commands below from that `rsLXMF` directory. The host crates require Rust 1.89 or newer. The default build compiles a bundled SQLite, so it also needs a C compiler; the build tools below provide one.
### macOS
Install Rust with `rustup`, then install Apple's build tools:
@@ -64,8 +71,7 @@ xcode-select --install
Build from the sibling checkout:
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Linux / Raspberry Pi
@@ -76,26 +82,25 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
sudo apt install -y build-essential pkg-config
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
sudo dnf install gcc make pkgconf-pkg-config
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
sudo pacman -S --needed base-devel pkgconf
```
#### Build the daemon:
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Windows
@@ -106,8 +111,7 @@ Build Tools, install the "Desktop development with C++" workload.
Build from PowerShell:
```powershell
cd rsLXMF
cargo build --release
cargo build --release --locked
```
After the build, use the commands below with `./target/release/lxmd-rs` on
@@ -123,7 +127,7 @@ macOS/Linux or `.\target\release\lxmd-rs.exe` on Windows.
Generate the example config:
Print the example configuration to standard output:
```bash
lxmd-rs --exampleconfig
@@ -141,11 +145,11 @@ Run a propagation node:
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --propagation-node
```
Send a message and exit:
Send a message and exit. Replace uppercase hash placeholders with the appropriate 32-character hexadecimal destination hash:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> "message body"
--send "DELIVERY_DESTINATION_HASH" "message body"
```
The `--send` flag is an rsLXMF convenience. Normal
@@ -155,7 +159,7 @@ Send UTF-8 file content or select a delivery method:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> --send-file ./message.txt --send-method direct
--send "DELIVERY_DESTINATION_HASH" --send-file ./message.txt --send-method direct
```
Supported `--send-method` values are `opportunistic`, `direct`, and
@@ -165,20 +169,23 @@ Attach custom LXMF fields from scripts:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--send <destination_hash> "with fields" \
--send-fields-json '{"1":"aGVsbG8=","42":"AAECAw=="}'
--send "DELIVERY_DESTINATION_HASH" "with fields" \
--send-fields-json '{"200":"aGVsbG8=","201":"AAECAw=="}'
```
The JSON object maps field IDs to base64-encoded bytes. It is only a shell
convenience; LXMF fields remain MessagePack field maps on the wire.
The CLI JSON object maps IDs from 0 to 255 to base64-encoded binary values.
Choose IDs and schemas agreed with the receiving application. This option
does not construct structured MessagePack fields such as an LRGP envelope;
use the library’s typed field API for those. The library supports a wider
integer ID range than this CLI convenience.
Control a propagation node:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --status
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --peers
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync <peer_hash>
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break <peer_hash>
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --sync "PEER_PROPAGATION_HASH"
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum --break "PEER_PROPAGATION_HASH"
```
These commands query an `lxmf.propagation.control` endpoint over Reticulum.
@@ -190,7 +197,7 @@ For a remote propagation node, pass the node's propagation destination hash:
```bash
lxmd-rs --config ~/.rsLXMF --rnsconfig ~/.rsReticulum \
--status --peers --remote <propagation_destination_hash> --timeout 5
--status --peers --remote "PROPAGATION_DESTINATION_HASH" --timeout 5
```
Control queries use `<config-dir>/identity` by default. Use `--identity PATH`
@@ -216,6 +223,8 @@ If no LXMF config directory is supplied, the default is:
| Linux/macOS | `/etc/rsLXMF/config`, then `~/.config/rsLXMF/config`, then `~/.rsLXMF/config` |
| Windows | `%APPDATA%\rsLXMF\config` |
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
If `--rnsconfig` is omitted, Reticulum config resolution follows
rsReticulum-specific defaults.
@@ -230,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:
@@ -238,8 +247,8 @@ Minimal config:
[lxmf]
display_name = Rat
announce_at_start = no
delivery_transfer_max_accepted_size = 1000
# stamp_cost = 8
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
[propagation]
@@ -249,8 +258,8 @@ autopeer = yes
autopeer_maxdepth = 6
auth_required = no
# node_name = Rat Nest
# static_peers = e17f833c4ddf8890dd3a79a6fea8161d
# outbound_node = e17f833c4ddf8890dd3a79a6fea8161d
# static_peers = 0123456789abcdef0123456789abcdef
# outbound_node = 0123456789abcdef0123456789abcdef
# max_peers = 20
# propagation_stamp_cost_target = 16
# propagation_stamp_cost_flexibility = 3
@@ -259,12 +268,16 @@ auth_required = no
loglevel = 4
```
Supported sections:
`delivery_transfer_max_accepted_size` limits incoming Direct Resource data
in decimal KB and defaults to 1 when omitted. The reusable router library has a separate 1000 KB default. Applications that accept
larger incoming messages should set their own explicit policy.
Common sections and supported keys (see `--exampleconfig` for annotated defaults):
| Section | Keys |
| --- | --- |
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_ratchets`, `enforce_stamps` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `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` |
@@ -272,10 +285,17 @@ Optional hash-list files live next to `<config-dir>/config`:
| File | Meaning |
| --- | --- |
| `ignored` | Hashes loaded into the router ignored list. |
| `allowed` | Hashes loaded into the router delivery allow-list. Empty means no allow-list restriction. |
| `ignored` | LXMF destination hashes to ignore. |
| `allowed` | Reticulum **identity hashes** permitted to retrieve messages when propagation `auth_required = yes`. An empty list then admits no clients. |
Hash-list files accept one raw 32-character hex destination hash per line.
Each file accepts one raw 32-character hex hash per line. The two files use different hash types. Propagation administration is separate: `control_allowed` contains authorized control identity hashes; the daemon’s own identity is also authorized. Client retrieval authorization does not make the node’s stored messages readable to other clients.
Router state (delivered and processed transient IDs, stamp costs, and tickets)
is kept in `<config-dir>/storage/lxmf/state.db`, the SQLite file LXMF 1.3.1 uses.
Received ratchets are kept
by Reticulum in its own storage. These stores come from the default
`sqlite-store` feature of `lxmf-core`; without it, router state lasts only for
the session.
## Delivery Model
@@ -284,11 +304,18 @@ and, where network-backed, through `lxmd-rs --send-method`.
| Method | Behavior |
| --- | --- |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Oversized opportunistic messages are downgraded to Direct by the router. |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. The router switches oversized opportunistic messages to Direct. |
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. |
| Propagated | Store-and-forward delivery through a propagation node, including deposit, retrieve, peer sync, stamps, and tickets. |
| Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
Direct and propagation Links use ordinary Reticulum path discovery only for
their initial LINKREQUEST. After a valid LRPROOF, rsLXMF pins the Link to that
proof's ingress interface and all later packets, Resources, proofs, keepalives,
and teardown use the same interface. A lost interface closes the Link instead
of silently rerouting it. Reverse Direct delivery is published only after its
role-correct proof has been admitted to that bound endpoint.
An ordinary direct or opportunistic LXMF message is a signed Reticulum payload:
```text
@@ -298,39 +325,50 @@ signature 64 bytes
payload MessagePack([timestamp, title, content, fields, optional_stamp])
```
`title` and `content` are bytes on the wire. `fields` is a `map<u8, bytes>` for
application-defined data such as tickets, attachments, location data, or
application envelopes.
`title` and `content` are bytes on the wire. `fields` maps integer IDs to
MessagePack values, which can be binary, text, arrays, maps or other supported
values. Standard fields have defined schemas. The library preserves signed
and unsigned integer IDs beyond the CLI’s 0–255 range and rejects duplicate
outer IDs. Encoding a structured field as a binary blob changes its meaning.
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
| Area | Current behavior |
| --- | --- |
| Message format | Signed LXMF envelopes, custom field maps, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, and opportunistic-to-direct downgrade. |
| Propagation | Disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, propagation tickets, and restart-safe ticket persistence. |
| 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, 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`.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
and Reticulum remain the reference implementations.
PRs are closed for now until I have time to catch up on everything. I'm tired.
rsLXMF 1.5.1 follows Python LXMF 1.3.1 with Reticulum 1.6.1, and
`lxmd-rs --version` names both.
## License
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
rsLXMF is licensed under the [Reticulum License](LICENSE), the license of the
reference implementation it is ported from. Copyright (c) 2020-2026 Mark Qvist,
unless otherwise noted; additions and modifications Copyright (c) 2026 Ratspeak
LLC.
The license is permissive with two conditions: no use in systems built to
purposefully harm people, and no use in or contribution to AI or language-model
training. The copyright and permission notice must stay in every copy.
[LICENSE](LICENSE) is the binding text.
+121
View File
@@ -0,0 +1,121 @@
# Rust API
This guide describes the 1.5.0 API, published as v1.5.0. Application code should use `lxmf_core::message_api`, which
re-exports the message types without wrappers. The equivalent module-qualified
paths remain available. The [1.5 migration guide](migrations/1.5.md) covers
the changes since 1.4.0.
The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path.
## Stability
The 1.5 line follows LXMF 1.3.0. It makes stamp costs and values `f64`, keeps
the router's delivered ids, stamp costs, and tickets in LXMF's SQLite state
store, and marks the router and daemon configuration structs
`#[non_exhaustive]`. See the [1.5 migration guide](migrations/1.5.md).
`lxmf-core` is candidate stable, but that classification does not make every
public implementation detail a permanent API. The message facade is the
recommended application path. Router ownership, delivery orchestration,
propagation clients and nodes, handlers, persistence representations,
admission machinery, Link-delivery state, and raw Reticulum channels remain
provisional module-qualified APIs.
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library
integration target.
Choosing the facade instead of the equivalent module-qualified path does not
change behavior. Upgrading from 1.3 to 1.4, and from 1.4 to 1.5, does change
message and persistence APIs; follow the migration guides. Further reductions
to the broader module tree require a reviewed API diff, downstream migration,
and an explicit version decision.
## Delivery-owner integration
`LinkDeliveryManager::poll_ready` lets one embedding task wait for inbound
delivery packets, local admission acknowledgements, endpoint lifecycle changes,
and staged-transport capacity. On readiness, call `drain_events` and `tick`.
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, 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
handle from the same runtime that owns the manager's transport channel.
Local FIFO residence and the subsequent measured-RTT proof wait are different
phases; neither is a recipient delivery confirmation.
Applications using responder-owned backchannels should forward the ordered
`LinkManagerAccountingEvent` packet and Resource wait observations through
`observe_backchannel_packet_wait` and `observe_backchannel_resource_wait`,
retaining the exact packet/resource identity and original timestamps.
Forward the optional exact packet-cancellation capability with its original
wait observation as well. A separate application owner can then cancel a
packet still awaiting local admission without closing the shared Link. This
cannot retract driver-admitted bytes. When a command receipt cannot be
published to its message owner, retain its exact identity for bounded cleanup;
close and drain a oneshot receiver before discarding it to fence concurrent
publication.
Adapters implementing that close-and-drain protocol can install their sender
with `set_cancellation_aware_backchannel_sender`, allowing cancellation before
the command receipt arrives to notify the adapter immediately. The existing
`set_backchannel_sender` retains legacy receipt-after-cancellation behavior.
Each pending send captures its adapter policy; replacing a sender does not
retroactively change cancellation semantics for older sends.
`message_timeout_window` exposes the finite current owner window for an outer
orphan watchdog. Externally observed Resource windows include a bounded
180-second notification allowance measured from the original protocol deadline;
this does not alter the Resource engine's timeout or delay explicit terminal
events. It is not renewed by receiving the same observation or by keepalives.
Queued messages without an active protocol owner receive no
blanket timeout exemption. Explicit rejection and cancellation are not evidence
of a failed route.
When an authenticated recipient announcement rules out compression, call
`LinkDeliveryManager::disable_pending_direct_compression` before advancing
ready delivery events. It updates unconstructed Direct Resources and queued
messages, including Link setup waits. Constructed Resources and split plans
remain immutable, and propagation envelopes keep their independent policy.
The call only disables compression; new submissions still carry their policy.
This additive API remains provisional delivery-owner integration.
Applications that reserve inbound attachment memory can opt into
`set_inbound_resource_completion_handler`. It receives one owned completed
payload before the ordinary conclusion callback, so an application can move
its exact Link/Resource reservation into a queued payload and retain it through
processing. This synchronous callback must not block. It replaces the legacy
inbound packet-channel delivery for that Resource, without cloning the data;
applications that do not install it keep the existing completion behavior.
## Compatibility checks
The `api/` directory contains the evidence used by CI:
- `stability.json` records package tiers, compatibility baselines, and snapshot
hashes;
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
manifest, feature, dependency, target, and MSRV contract; and
- `fixtures/` compiles recommended and retained imports as an external
consumer.
These checks catch accidental changes, but they do not replace platform builds,
wire and persistence tests, Python interoperability, or manual review. The API
snapshot omits auto-derived, auto-trait, and blanket implementations and is not
by itself a complete SemVer verdict.
Run the checks with:
```sh
python3 tools/check-api-baseline.py
python3 tools/check-api-manifest.py
python3 tools/check-api-compatibility.py
cargo check --manifest-path api/fixtures/Cargo.toml --locked
```
After reviewing an API change, run
`python3 tools/check-api-baseline.py --update` and commit the source and snapshot
changes together. CI compares snapshots with the current source; compatibility
checks retain the historical baseline.
+1165
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "lxmf-message-api-fixture"
version = "0.0.0"
edition = "2024"
publish = false
[workspace]
[dependencies]
lxmf-core = { path = "../../crates/lxmf-core" }
+88
View File
@@ -0,0 +1,88 @@
//! External-consumer compile contract for canonical and retained LXMF paths.
pub mod canonical {
use lxmf_core::message_api::{
AudioField, DeliveryMethod, DeliveryRepresentation, DestinationHash, IdentityHash,
LxMessage, MessageError, MessageId, MessageState, UnverifiedReason,
};
pub fn compile_surface() {
let _ = std::mem::size_of::<AudioField<'static>>();
let _ = std::mem::size_of::<DeliveryMethod>();
let _ = std::mem::size_of::<DeliveryRepresentation>();
let _ = std::mem::size_of::<DestinationHash>();
let _ = std::mem::size_of::<IdentityHash>();
let _ = std::mem::size_of::<LxMessage>();
let _ = std::mem::size_of::<MessageError>();
let _ = std::mem::size_of::<MessageId>();
let _ = std::mem::size_of::<MessageState>();
let _ = std::mem::size_of::<UnverifiedReason>();
}
}
pub mod legacy {
use lxmf_core::constants::{
DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason,
};
use lxmf_core::message::{AudioField, LxMessage, MessageError};
use lxmf_core::types::{DestinationHash, IdentityHash, MessageId};
pub fn compile_surface() {
let _ = std::mem::size_of::<AudioField<'static>>();
let _ = std::mem::size_of::<DeliveryMethod>();
let _ = std::mem::size_of::<DeliveryRepresentation>();
let _ = std::mem::size_of::<DestinationHash>();
let _ = std::mem::size_of::<IdentityHash>();
let _ = std::mem::size_of::<LxMessage>();
let _ = std::mem::size_of::<MessageError>();
let _ = std::mem::size_of::<MessageId>();
let _ = std::mem::size_of::<MessageState>();
let _ = std::mem::size_of::<UnverifiedReason>();
}
}
/// Delivery coordination remains a module-qualified opt-in API.
pub mod delivery_ownership {
use lxmf_core::link_delivery::LinkDeliveryManager;
pub fn compile_surface(manager: &mut LinkDeliveryManager) {
let _ = LinkDeliveryManager::set_link_endpoint_dispatch_handle;
let _ = LinkDeliveryManager::set_cancellation_aware_backchannel_sender;
let _ = LinkDeliveryManager::observe_backchannel_packet_wait;
let _ = LinkDeliveryManager::observe_backchannel_resource_wait;
let _ = LinkDeliveryManager::abandon_backchannel_packet;
let _ = LinkDeliveryManager::message_timeout_window;
manager.set_inbound_resource_completion_handler(|link_id, resource_id, data| {
let _: ([u8; 16], [u8; 32], Vec<u8>) = (link_id, resource_id, data);
});
}
}
/// Reviewed immutable construction, full-width keys and source-bound verification.
pub mod immutable_messages {
use lxmf_core::message_api::{
DeliveryMethod, FieldId, LxMessage, LxMessageDraft, MessageError, RecipientStamp,
VerifiedLxMessage,
};
pub fn with_external_signer<F, E>(signer: F) -> Result<LxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct)?;
draft.set_field(FieldId::from(u64::MAX), vec![1, 2])?;
draft.set_msgpack_field(FieldId::from(i64::MIN), vec![0x91, 0x01])?;
let signed = draft.sign_with(signer)?;
let _id = signed.message_id();
signed.finalize(Some(RecipientStamp::Ticket([0; 16])))
}
pub fn inspect<'a>(
message: &'a LxMessage,
public_key: &[u8; 64],
) -> Result<VerifiedLxMessage<'a>, MessageError> {
let _same_owner = message.wire_owned();
let _custom = message.fields().get(u64::MAX);
message.verify(public_key)
}
}
+196
View File
@@ -0,0 +1,196 @@
# Migrating to the 1.4 source API
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
from. These APIs and migration commands require a 1.4 build.
Messages now retain the exact signed bytes received or finalized for sending.
Verification, storage, and delivery metadata cannot change those bytes. The
`message_api` and `message` module paths export the same types.
## Construct, sign, then finalize
This fragment uses `?` to propagate `MessageError` from the enclosing function.
```rust
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
use rns_crypto::ed25519::Ed25519PrivateKey;
let mut draft = LxMessageDraft::new(
[0x11; 16], [0x22; 16], "Hello", "A message", DeliveryMethod::Direct,
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
// When using a router, prepare and durably commit its reply-ticket intent here.
let signed = draft.sign(&Ed25519PrivateKey::generate())?;
let stamp = signed.generate_recipient_stamp()?;
let message = signed.finalize(stamp)?;
let bytes = message.wire_bytes();
```
Use `sign_with` for an external or hardware signer. Both signing methods consume
the draft. Signing refuses a router-prepared ticket whose persistence intent is
still pending. `SignedLxMessage` exposes the stable message ID for recipient
stamp work, but cannot be sent. `finalize(None)` explicitly chooses no recipient
stamp. A finalized message has no content setters, signing method, or assignable
hash/signature/stamp. To change content, construct a new draft and explicitly
copy the desired fields; reply tickets and authentication state are not copied
implicitly. Propagation encryption/stamps belong to their separate send owner.
## Read the immutable message
| Previous access | Replacement |
| --- | --- |
| `message.destination_hash`, `source_hash` | `destination_hash()`, `source_hash()` |
| `message.hash` or `message.message_id` | `message_id()`; always present |
| `message.signature` | `signature()`; always present |
| `message.title`, `content` | `title_text()`, `content_text()` return `Cow<str>`; `*_bytes()` preserve exact bytes |
| `message.timestamp` | `timestamp()` |
| `message.fields`, `msgpack_field_ids` | `fields()` and coherent `FieldValueRef` |
| `message.stamp` | `recipient_stamp()` |
| `message.signature_validated` | successful source-bound `verify` capability |
| `message.wire_payload` | `wire_bytes()` for the complete image |
Mutable delivery metadata remains available through `MessageMetadata` and
field access (`message.method`, `message.progress`, etc.). It cannot alter
content or create authentication authority.
`wire_bytes()` borrows the complete image; `wire_owned()` cheaply shares its
ownership for asynchronous writes. `pack()` explicitly copies it into a Vec.
`pack_payload()` copies the original payload. `unpack_owned(Bytes, limits)`
takes ownership without copying; `unpack(&[u8])` makes a convenience copy.
Container and paper exports preserve these bytes. Repeated verification is pure.
`verify(&full_reticulum_public_key)` checks that the complete 64-byte public key
binds the claimed `lxmf.delivery` source, then verifies the signature. It returns
a private-construction `VerifiedLxMessage` for sender-authorized operations such
as ticket learning. `verify_signature(&ed25519_key)` remains available for
detached diagnostics, but does not establish source identity. Parsing and an
unknown sender are not authenticated-sender status.
## Fields and profiles
`FieldId` preserves integers from `i64::MIN` through `u64::MAX`. Nonnegative IDs
serialize as MessagePack unsigned64; negative IDs as signed64. Equivalent
positive signed and unsigned integer encodings compare equal. Outer duplicate
IDs are rejected, including alternative encodings of the same number. IDs above
255 and negative IDs remain custom keys and never alias a standard field.
`set_field` emits a binary value. `set_msgpack_field` accepts exactly one validated
encoded MessagePack value. `set_field_value` accepts their coherent `FieldValue`
representation. `FieldValueRef::encoded()` exposes exact encoded bytes;
`as_binary()` unwraps only binary. Binary bytes that happen to look like a map
or array do not become structured values. Recognized schema readers can use
`unique_map()` to reject duplicate integer/text keys before acting; unknown
nested values remain opaque. `MessagePayload` is a semantic DTO, not an archive
or signature source.
The host default profile permits 4,096 outer fields and 134,217,727 complete
wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit
`MessageDecodeLimits` when selecting another local policy. Construction checks
count and exact size before signing and finalization, including stamp framing.
These are parser/construction ceilings, not transport promises: Resource segment
limits, metadata, encryption and propagation wrapping impose separate admission
checks. The embedded profile retains 64 fields and depth 8; host-valid custom
messages are not automatically compatible with every device.
Old corrupted files are never silently repaired or re-signed. A hash-shaped
filename that disagrees with its decoded message ID returns a distinct error;
the file is retained. Restore original bytes from a trusted backup when available.
Unknown sender keys cannot establish whether an old signature is valid.
Use the reviewed compatible minor line (for example `~1.4.0`) or an exact source
revision when migrating dependents together. A default caret requirement permits
subsequent minor lines. Do not mix dependent code still using mutable messages
with this API.
## Router, propagation, and asynchronous ownership
`prepare_outbound(&mut draft)` returns an `OutboundTicketIntent`; persist it
through the intended durable state store before signing. A pending intent blocks
the exact draft's signer. `submit_signed` takes a `SignedLxMessage` and handles
recipient-stamp work before finalization; `defer_stamp` and the deferred map also
own signed messages. The former mutable `get_stamp` work belongs to
`SignedLxMessage::generate_recipient_stamp`, while frozen-message stamp checks
are read-only and return a result for the current policy.
`learn_ticket_from_inbound` takes a successful `VerifiedLxMessage`. When a worker
must retain authentication across an asynchronous handoff, use `to_owned()` and
later `OwnedVerifiedLxMessage::as_verified()`. The owned capability shares the
original bytes and does not expose mutable authenticated state.
Replace `pack_propagated_encrypted*` with `PropagationEnvelope` in the
`propagation_send` module. It owns the frozen message, encrypted blob, exact TID
and PN stamp. Reuse that envelope for retries; regenerate only the work whose
policy changed. The old message `transient_id` and `propagation_stamp` fields no
longer exist. `PendingDelivery.message` is a retained delivery owner that can
release payload bytes when an idle Link only needs metadata/receipt state.
Replace `take_received_messages` with `take_downloaded_messages`. Keep each
leased image and admission token until validation and durable local commit;
resolve the token with the explicit disposition and durable receipt. A fetched
message or Resource proof is not permission to purge remote data.
Hosted propagation accepts a validated opaque encrypted/stamped blob through
`ValidatedOpaquePropagationBlob` and `plan_opaque_admission`, followed by the
plan's durable persistence and exact commit. Plain `accept_message`,
`accept_propagated_blob`, their old planning variants and sync plaintext
admission are removed: plaintext signatures are not relay storage authority.
Use a durable node store and follow the [relay store migration](relay-store-v2.md).
A nondurable `PropagationNode::new` cannot acknowledge relay storage.
Hosted `/get` handlers must use the bounded deferred request API in
`rns_runtime::LinkManager`, after installing its exact endpoint dispatch handle.
Check the handler registration result. Retain `DeferredRequestResponder` inside
the actual blocking worker through store planning, durable purge and verified
file reads; cancellation of an async caller must not detach uncharged I/O.
Pass `response_byte_limit()` to both `handle_get_request_bounded` and
`into_response_with_served_count_bounded`, using the configured propagation
transfer ceiling when registering the handler. These methods reject malformed
requests before purge, deduplicate wants, preserve complete-message accounting
and build one bounded response. An absent client limit still obeys the local
ceiling. The runtime fences responses to the original Link generation and keeps
Resource credits until the transfer releases its data. `Sent` acknowledges
queue acceptance or Resource initiation, not remote delivery.
`unpack_propagation_wrapper_owned(Bytes, limit)` returns shared `Bytes` payloads
and checks framing/counts before allocation. The Vec-returning compatibility
helper still copies explicitly. `FieldValueRef::from_encoded` validates exactly
one borrowed value, and `as_text` accepts UTF8 MessagePack text only; binary data
is not silently interpreted. Use `unique_map` before acting on recognized map
keys. Text/media projections borrow where possible; repaired UTF8 allocates only
the exact replacement length.
`constants::ENCRYPTED_PACKET_MAX_CONTENT` is LXMF 1.2.0's single-packet
content limit, 287 bytes, which `LxmRouter::try_send` applies to opportunistic
messages. Applications that choose a delivery method themselves should compare
against it rather than a hard-coded limit.
## Resuming a signed message
`SignedLxMessage::to_resumable()` returns a `ResumableLxMessage` to store before
`submit_signed`; `as_bytes()` and `ResumableLxMessage::from_bytes` move it
through storage. It keeps the signed, unstamped message and the stamp cost it
was signed under. It is not a wire message, and `LxMessage::unpack` rejects it.
After a restart, `LxmRouter::restore_signed(&stored, &active_public_key,
method)` verifies the message as sent by the active identity, so no signing key
is needed. It attaches the current outbound ticket and uses the larger of the
stored and current stamp costs. Set delivery metadata such as `auto_compress`,
then call `submit_signed`. The message keeps its id, so recipients deduplicate a
copy that was already delivered.
`submit_signed` now refuses a message whose id is already queued, awaiting its
stamp or delivery, with `MessageError::AlreadyQueued`. Treat that result as
already queued; it is not evidence of transmission or recipient delivery.
## Retaining delivered destinations
`LxmRouter::take_destination_retains()` returns the destinations whose messages
were delivered since the last call; the router keeps the newest 256. Send each
as `TransportQuery::RetainDestination` through Reticulum's control plane
(`ReticulumHandle::query_control`), which forwards to a shared instance, so the
destination's identity outlives its path, as in Python LXMF.
The API ledger retains its original compatibility floor and lists exact removed
rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary
field access through Deref; duplicate `message_api` snapshot paths describe the
same type migration. No unrelated API removal is waived.
+254
View File
@@ -0,0 +1,254 @@
# Migrating to rsLXMF 1.5
This guide covers source and behaviour changes from the published 1.4.0
release (commit `00f439d`) to 1.5.0. The crates now follow LXMF 1.3.0 on
Reticulum 1.6.0. Upstream references are to LXMF 1.3.0 (`LXMF/...:line`) and
Reticulum 1.6.0 (`RNS/...:line`). `api/stability.json` lists every removed
snapshot line under `approvedBreakingChanges`.
Migrate together with rsReticulum 1.5, whose guide covers `StampControl`, link
request stamps, the transport's SQLite stores, and the runtime changes.
## Stamp costs are fractional
LXMF 1.3.0 takes stamp values from `RNS.Stamps.stamp_value`, which returns a
float (`LXMF/LXStamper.py:12`, `RNS/Stamps.py:104`). Its router costs are
floats too (`PEERING_COST = 18.0`, `PROPAGATION_COST = 16.0`,
`LXMF/LXMRouter.py:63-67`). Every stamp cost, flexibility, peering cost, and
stamp value in the API is now `f64`:
- the `constants::{PROPAGATION_COST, PROPAGATION_COST_MIN, PROPAGATION_COST_FLEX,
PEERING_COST, MAX_PEERING_COST, COST_TICKET}` constants;
- `RouterConfig::{stamp_cost, propagation_stamp_cost, propagation_stamp_flex}`
and `RouterConfigExt::{peering_cost, max_peering_cost, propagation_cost_min}`;
- `LxmRouter::{set_stamp_cost, get_stamp_cost, set_stamp_requirements,
get_outbound_lxm_stamp_cost, get_outbound_lxm_propagation_stamp_cost,
validate_stamp, validate_stamp_with_tickets}`;
- `LxMessageDraft::stamp_cost`, `SignedLxMessage::stamp_cost()`,
`LxMessage::{validate_stamp_with_tickets, validated_stamp_value}`;
- the `LxmPeer`, `OutboundOfferPolicy`, `AutopeerCandidate`, `PeerStats`,
`NodeStats`, `PropagationEntry`, `PropagationNodeConfig`,
`AdvertisedNodePolicy`, and `RecoveryPolicy` cost fields;
- `LxmPeer::{from_announce, from_announce_with_metadata, refresh_from_announce,
refresh_from_announce_with_metadata, minimum_accepted_stamp_cost}`,
`PropagationEntry::{new_stamped, parse_filename}`, and
`PropagationStore::get_stamp_value`;
- `PropagationNode::{min_stamp_cost, set_min_stamp_cost, create_offer,
accept_stamped_propagated_blob, plan_accept_stamped_propagated_blob}`,
`ValidatedOpaquePropagationBlob::{validate, stamp_value}`;
- `handlers::{get_announce_app_data, parse_announce_app_data,
stamp_cost_from_app_data, pn_stamp_cost_from_app_data}`. The announce cost
slot may be an int or a float (`LXMF/LXMF.py:183-195`).
A destination that announces no cost is recorded with no cost, as
`outbound_stamp_costs[dest] = [time, stamp_cost]` stores `None`
(`LXMF/LXMRouter.py:1160`). The costs live in the router's state store (see
"Router state"); read them with `get_outbound_lxm_stamp_cost`.
```rust
// old
router.set_stamp_cost(dest, 8);
// new
router.set_stamp_cost(dest, 8.0);
```
### Stamper
| Old | New |
| --- | --- |
| `stamper::generate_stamp(&[u8], u8, usize) -> Option<([u8; 32], u32)>` | `generate_stamp(&[u8], f64, usize, &StampControl) -> Result<Option<([u8; 32], f64)>, StampError>` |
| `generate_stamp_cancellable(.., &AtomicBool)`, `generate_stamp_limited`, `stamp_iteration_cap` | `generate_stamp` with `StampControl { cancel, deadline, threads }` |
| `stamper::stamp_value(&[u8], &[u8; 32]) -> u32`, `stamper::stamp_workblock` | re-exports of `rns_identity::stamps::{stamp_value, stamp_workblock}`; `stamp_value(&[u8], &[u8]) -> f64` |
| `stamp_valid(&[u8; 32], u8, &[u8])` | `stamp_valid(&[u8], f64, &[u8])` |
| `validate_stamp(&[u8; 32], &[u8; 32], u8, usize)` | `validate_stamp(&[u8; 32], &[u8], f64, usize)` |
| `validate_peering_key(&[u8], &[u8; 32], u8)` | `validate_peering_key(&[u8], &[u8], f64)` (`LXMF/LXStamper.py:26-29`) |
| `validate_pn_stamp(&[u8], u8)`, `PropagationStampParts` with a `u32` value | `f64` value |
| `spawn_deferred_stamp(_on)(.., u8, ..)`, `DeferredStampResult::Success { value: u32 }` | `f64`; new `DeferredStampResult::Failed(StampError)` |
| `PropagationEnvelope::new_cancellable(.., &AtomicBool)`, `pack_for_cancellable(.., &AtomicBool)` | `&StampControl` |
| `PropagationEnvelope::{new, new_cancellable, matches}(.., [u8; 32], ..)` | `EncryptionBinding`, from `EncryptionBinding::for_recipient(&public_key, ratchet)` |
| `LxmPeer::generate_peering_key(&mut self, &[u8; 16], &[u8; 16])` | adds `&StampControl` |
| `LxmfDiscoveryStamper::{generate, valid, value}` | `f64` costs; `generate` takes `&StampControl` |
```rust
let control = rns_identity::stamps::StampControl::default();
let stamp = lxmf_core::stamper::generate_stamp(&material, 8.0, 3000, &control)?;
```
## LXMF delivery (outbound queue)
The router's outbound pass follows `LXMRouter.process_outbound`
(`LXMF/LXMRouter.py:3050`). It returns embedder work instead of per-method
deliveries:
| Old `OutboundAction` | New |
| --- | --- |
| `DeliverOpportunistic { dest_hash, message }` | `SendOpportunistic { message }` |
| `DeliverDirect { dest_hash, message }`, `PlanDirect { dest_hash, message, plan }`, `DeliverPropagated { prop_hash, message }` | `DeliverOverLink { target, message, plan: LinkDeliveryPlan }` (`UseLink` or `StartLink { hops }`), for Direct and Propagated |
| path requests issued inside planning | `RequestPath { destination, drop_existing }` |
| `Expired(message)` | `Failed(message)`: the failure callback has run |
These helpers are removed:
- `DirectDeliveryPlan`, `DirectDeliveryPlanInput`, `DirectRouteSnapshot`,
`plan_direct_delivery`;
- `LxmRouter::process_outbound_with_direct`, `defer_outbound_for_path_request`.
Call `process_outbound_with_inputs(&OutboundInputs, now)` with a snapshot of
known identities, links, and routes (`OutboundInputs::medium: MediumSnapshot`).
Use `await_outbound_path` / `outbound_link_closed` for the path and link
callbacks. `process_outbound()` keeps working with empty inputs.
`MessageMetadata::ratchet_id` is `Option<Vec<u8>>`. It holds the 10-byte
ratchet id or the 16-byte link id the message arrived under, as
`lxmf_delivery(.., ratchet_id=packet.ratchet_id ..)` passes either
(`LXMF/LXMRouter.py:2165-2173`, `RNS/Identity.py:521-522`).
`MessageMetadata` gains upstream's delivery fields (`stamp_checked`,
`stamp_valid`, `sent_on_path`, `awaiting_path`, ...).
**Paper messages.** `LxmRouter::ingest_lxm_uri(&mut self, uri, decrypt)`
becomes `ingest_lxm_uri(uri, allow_duplicate, decrypt) ->
Result<PaperIngest, _>`. `PaperIngest::Delivered(Box<LxMessage>)` or
`Duplicate` replaces upstream's `signal_local_delivery`/`signal_duplicate`
callbacks (`LXMF/LXMRouter.py:2905`).
`DeliveryRatchetState::create_announce` takes a trailing
`Option<&AnnounceStampExt>` for the stamped announce.
## Router state
`RouterConfig` and `RouterConfigExt` are `#[non_exhaustive]`. Start from
`RouterConfig::default()` and set fields:
```rust
let mut config = RouterConfig::default();
config.stamp_cost = Some(8.0);
let router = LxmRouter::new(config);
```
`LxmRouter::load_state(dir)` keeps delivered and processed message ids,
outbound stamp costs, and tickets in `dir/state.db` (`state_store::FILE_NAME`),
the store LXMF 1.3.0 keeps (`LXMFStore`, `LXMF/Storage.py`). The
`state_store` module holds `SqliteStateStore`, the sealed `StateStore` trait,
and `StateStoreError`. Before `load_state`, or when the file cannot be opened,
the state is kept in memory for the session.
| Old | New |
| --- | --- |
| `persist::{load,save}_{local_deliveries, locally_processed, stamp_costs, tickets}`, `LOCAL_DELIVERIES_FILE`, `LOCALLY_PROCESSED_FILE`, `STAMP_COSTS_FILE`, `TICKETS_FILE` | removed; `load_state` imports those files once |
| `LxmRouter::outbound_stamp_costs`, `StampCostEntry`, `RouterStats::stamp_costs_cached` | `get_outbound_lxm_stamp_cost`, `update_stamp_cost`, `cull_stamp_costs` |
| `LxmRouter::ticket_store` | `generate_ticket`, `get_inbound_tickets`, `get_outbound_ticket`, `remember_ticket` |
| `generate_ticket(..) -> [u8; 16]` | `-> Option<Ticket>`; `None` within `TICKET_INTERVAL` of the last ticket delivered there, or when the store could not commit the new one (`LXMRouter.generate_ticket`) |
| `get_inbound_tickets(&self) -> &[Ticket]` | `get_inbound_tickets(&self, &[u8; 16]) -> Option<Vec<[u8; 16]>>`, the unexpired tickets issued to one destination (`LXMRouter.get_inbound_tickets`) |
| `prepare_outbound(..) -> Result<OutboundTicketIntent, _>`, `OutboundTicketIntent::{persist, requires_persistence}`, `TicketPreparationError::PendingPersistence` | `prepare_outbound(..) -> Result<(), _>`; a reply ticket is in the store when it returns |
`lxmf-core` has a default `sqlite-store` feature. It builds SQLite from source
through `rusqlite`'s `bundled` feature, so the build needs a C compiler, and
turns on `rns-transport/sqlite-store`. With `default-features = false` the
router keeps this state in memory only.
## Propagation
- `LxmRouter::sync_peers(&mut self) -> Vec<[u8; 16]>` becomes
`sync_peers(&mut self, now, store_bytes) -> PeerSyncPass { culled, selected }`.
This follows the cull-then-select pass in `LXMF/LXMRouter.py:2468-2516`.
`select_sync_peer` takes the current time.
- `LxmRouter::sync_peer_policies_for_store` is removed.
- `LxmPeer::unhandled_messages` is now a public
`HashSet<PropagationTransientId>` instead of a count method. Use
`unhandled_message_count()`.
- `add_unhandled_message(&mut self)` takes the transient id, as
`add_unhandled_message(transient_id)` does (`LXMF/LXMPeer.py:588-626`).
`set_unhandled_count` is removed.
- `LxmPeer::peering_key` stores `([u8; 32], f64)`, and `peering_key_value()`
returns `Option<f64>`.
- Transfer and sync limits keep Python's number kind: lxmd's defaults are ints
and configured values are floats, and the announce packs whichever it holds
(`LXMF/LXMRouter.py:394-395`). The following fields are now
`handlers::PnLimit` (`Int(u64)` or `Float(f64)`, `From<u64>`/`From<f64>`):
- `PropagationNodeAnnounceData::{transfer_limit, sync_limit}`;
- `DaemonConfig::{propagation_limit_kb, sync_limit_kb}`;
- `PythonLxmdConfig::propagation_{transfer,sync}_max_accepted_size`;
- `RouterConfig::{propagation_limit_kb, sync_limit_kb}`;
- `NodeStats::{propagation_limit, sync_limit}`.
`PropagationNodeAnnounceData::new` and `LxmRouter::set_propagation_limit`
take `impl Into<PnLimit>`.
- `PropagationClientState`, `SyncTaskState`, and `PeerSyncTerminalState` gain
`NoPath`, `PathRequested`, `NoAccess`, `Throttled`, `LinkFailed`,
`TransferFailed`, and `NoIdentityReceived`, where they apply.
`PropagationAdmission` gains `AlreadyProcessed`. Exhaustive matches need the
new arms.
## Tools (lxmd library)
- `DaemonConfig` is `#[non_exhaustive]`; build it with `from_config` or
`DaemonConfig::default()` and set fields.
- `LxmdPaths::received_ratchets_dir` and `known_identities_path` become
`legacy_received_ratchets_dir` and `legacy_known_identities_path`. Reticulum
now keeps received ratchets and known destinations. `LocalStatusView::
stamp_costs_cached` is removed.
- `DaemonConfig::from_config` and `PythonLxmdConfig::from_config` return
`Result<Self, DaemonConfigError>`. lxmd exits when `as_float`/`as_int`/
`as_bool` raise on a malformed key (`LXMF/Utilities/lxmd.py:187-240`):
```rust
let config = lxmf_tools::daemon::DaemonConfig::from_config(&cfg)?;
```
- The `PythonLxmdConfig` cost fields are `f64` instead of `i64`, read with
`as_float` (`LXMF/Utilities/lxmd.py:187-215`). `DaemonConfig` cost fields are
`f64`.
- `lxmd_control::encode_router_control_stats` takes a trailing per-peer lookup
closure. `encode_nil_response` is removed.
- `lxmd_runtime::delivery_announce_app_data` takes `Option<f64>`.
## New fields and variants
`RouterConfig`, `RouterConfigExt` (which gains `pn_stamp_throttle`), and
`DaemonConfig` (likewise) are now `#[non_exhaustive]`; set fields on their
defaults.
Exhaustive literals and matches over these types need updating:
- `MessageMetadata`, `PropagationNodeAnnounceData`, `LxmPeer`,
`OutboundOfferPolicy`;
- `PnInboundAdmissionConfig` (`invalid_stamp_throttle`), `DirectLinkSnapshot`,
and `DeliveryResult::Failed` (`link_activated`);
- `PythonLxmdConfig` (`propagation_stamp_throttle`), `lxmd_cli::Args`
(`version`), `LxmdPaths`;
- `LinkDeliveryStartError::StampFailure`, `SendError::ContentTooLarge`.
## Behaviour and configuration an operator sees
- **Strict lxmd config.** A malformed number or boolean in lxmd's config now
stops lxmd with a `DaemonConfigError`. 1.4.0 fell back to the default.
Costs below their floor are raised to it, as `lxmd.py` does
(`LXMF/Utilities/lxmd.py:187-215`); a cost of 100 or more, which upstream
accepts but no stamp can meet, is rejected at load.
- **Announced node version.** A propagation node announces the LXMF release
it follows (`lxmf_core::constants::LXMF_COMPAT_VERSION`, "1.3.0") as its
version, where it announced the Rust crate version
(`LXMF/LXMRouter.py`, `get_propagation_node_announce_metadata`).
`PropagationNodeAnnounceData::new` sets it. `lxmd-rs --version` still names
both versions.
- **Stored files.**
- Delivered and processed message ids, outbound stamp costs, and tickets
move to `lxmf/state.db`. On first start the caches it replaces
(`local_deliveries`, `locally_processed`, `outbound_stamp_costs`,
`available_tickets`) are imported once and renamed with an `.imported`
suffix (`LXMRouter.__import_legacy_storage`). A file that cannot be opened
never stops the router; the state is kept in memory for the session.
- lxmd moves the received-ratchet files of earlier releases from its
`ratchets/received` directory to Reticulum's `storage/ratchets`, where
Reticulum imports them once, and removes `ratchets/known_identities`.
- Admission bodies move from the messages directory to
`download-admission-bodies` under the router state directory. Bodies still
in the old place are moved on first start.
- lxmd keeps one processed-message store.
- **Log levels.** lxmd starts at Notice (3) without a `loglevel` key and always
applies `-v`/`-q`, as `lxmd.py` does. Control commands log at Notice on
stdout.
- **Link MTU and stamps.** Delivery, the propagation client, and peer sync open
links that signal the next hop's MTU and carry link request stamps at the
cost the destination announced. These follow the Reticulum
`link_mtu_discovery` and `[stamps]` settings.
+137
View File
@@ -0,0 +1,137 @@
# Relay store migration
This guide applies to the 1.4 API and daemon, published as v1.4.0. The 1.3.0
binary does not provide this migration.
Relay nodes now admit only validated opaque propagation data to a durable store.
A packet proof follows complete validation and acknowledged durable admission.
Resource completion still means transport completion; it does not certify the
receiver's application storage. Ordinary message archives are separate from
relay storage and must never be copied into it.
## Startup and recovery
A new store can initialize automatically. An existing legacy directory requires
explicit offline migration. An incomplete migration, invalid committed record,
or unavailable storage prevents hosting. Network shares and RAM disks are
accepted with a logged warning because they cannot guarantee crash safety. Daemons fail
startup when required relay storage is unavailable. Applications retain the
user's hosting preference but show hosting as unavailable until recovery succeeds.
There is no automatic in-memory fallback for a durable host. Startup checks each
committed record's index, provenance, size and destination without rereading
whole message bodies; every read verifies the full body, and a body that fails
is not served.
Stop every process that can write the store, including service supervisors and
scheduled restarts. Then run the 1.4 source-built daemon against the correct config:
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped
```
Check `lxmd-rs --help` for the config-path option supported by your build. The
writer-stopped flag is an explicit assertion that supervisors have been stopped.
The tool also holds the store's OS lock and refuses when it finds another known
Ratspeak/LXMF daemon process, or cannot enumerate processes. Older binaries do not
honor the new lock; manually restarting one while migration runs is unsupported.
The process-name check cannot discover every renamed or custom relay program.
On iOS and Android, use the application's inbox recovery action for its private
store. The app first stops and joins its hosting and sync workers. Recovery
checks native application ownership and takes the same exclusive store lock;
it does not run the desktop process-list command or accept arbitrary external
directories. iOS recovery is restricted to the main app's private data container,
excluding extensions and shared app groups. Android recovery additionally
requires an exclusive app UID, the default app process, and no declared secondary
processes. Shared storage, shared UIDs and unverified ownership remain unavailable
for automatic recovery. Keep the original files and resolve the ownership or
storage error before retrying; do not remove the guard or copy archives into the
live store.
The migrator inventories relative paths, lengths and SHA-256 hashes before
moving anything. Symbolic links, special files, changed inventory and conflicting
unowned destinations stop migration without overwriting originals. It preserves
the legacy directory as `<store>.legacy-quarantine`, writes a regular-file guard
at the old path, and creates `<store>.v2`. The sibling `<store>.migration` journal
records every transition. Interrupted runs resume through the same command;
do not remove journals or guards to force startup. Windows directory publication
uses recorded sibling moves rather than inferring durability from existence.
The completion report gives the number and size of preserved files. Legacy
files are not offered, served, or counted as live relay messages. Their apparent
encryption shape, filename, previous app version, or old directory location does
not establish opaque-ingress provenance. Migration never automatically deletes
or expires the archive.
## Explicitly trusted recovery
Recovery requires independent, per-entry evidence of the original opaque
propagation ingress. A directory-wide assertion is insufficient. An operator
can supply a MessagePack named-map `TrustedRecoveryManifest` with these fields:
| Field | Value |
| --- | --- |
| `version` | `2` |
| `provenance` | Nonempty explanation of the independently checked evidence |
| `entries` | Array of the exact authorized records |
| Entry `archive_relative_path` | Relative path from the committed inventory |
| Entry `content_hash` | SHA-256 of the complete stored bytes, as 32 integer bytes |
| Entry `transient_id` | SHA-256 of destination+ciphertext, excluding a trailing PN stamp |
| Entry `stamped` | Whether the file includes the 32-byte PN stamp |
| Entry `stored_at` | Finite, nonnegative receipt timestamp |
Use the exported Rust structs and `rmp_serde::to_vec_named` to encode the record.
Review the manifest and independently record its SHA-256. Supply that approved
digest separately; merely hashing an unreviewed manifest does not establish trust.
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped \
--recover-propagation-manifest /path/to/recovery.msgpack \
--recovery-manifest-sha256 APPROVED_SHA256_HEX
```
The importer checks the complete archive against its committed inventory, every
selected path/hash/TID, ciphertext framing, positive plaintext rejection, actual
stamp strength, and current size/quota policy before publication. Unstamped
recovery requires both explicit provenance and a zero minimum stamp policy.
Entries without evidence remain quarantined. Repeating the exact approved import
is idempotent; it cannot replace a different first accepted image. A failed IO
can leave a valid subset committed, so retain the manifest and retry.
## Library integration
Use `PropagationNode::with_storage` for a durable host. Keep readiness bound to
the active identity generation and drain the old generation's workers before
opening or migrating its store. `begin_offline_migration` returns the retained
writer-exclusion guard used by both migration and trusted recovery.
Mobile embeddings use `begin_ios_container_migration` or
`begin_android_container_migration` on the corresponding target. The Android
function takes the attached worker's JNI environment and real platform Context;
it obtains package, UID, component and data-directory metadata from the framework.
Neither API accepts a caller-provided container root or a flag to bypass ownership
checks. Hold the identity/session lifecycle guard through the actual blocking
operation and restart, including after the invoking UI task is canceled. An app
that launches additional native relay writers must stop and join those writers
too; the container boundary does not replace ownership of current-process work.
For ingress, validate a complete packet batch before writing anything, then use
`plan_opaque_admission`. Run `Reserved(plan).persist()` on a blocking worker and
commit its returned capability to that same node. Await `Pending` outside the
bounded storage-worker slots. `CommittedDuplicate(check)` is only a plan: call
`check.verify()` on a blocking worker before treating it as durable. Keep the
original typed Link receipt alive through all these operations. A dropped worker
result yields no proof; retry reuses the first complete indexed image.
The private format publishes an immutable object and provenance record, then a
per-TID active index. Unindexed remnants are never served. A durable deletion
intent revokes eligibility before cleanup; restart resumes cleanup. Purge and
maintenance operate on a particular admission path, so a stale plan cannot
delete a later admission of the same TID. Resolve `GetServePlan` and maintenance
plans off the actor; a failed purge intent cannot return an empty success array.
The old-path guard prevents ordinary reopening of that exact legacy directory.
It cannot revoke objects already held in an old process or prevent an old daemon
from using another path or its in-memory fallback. If rolling back software,
keep **both relay hosting and propagation sync disabled**. Preserve the archive,
journal, guard and v2 store; never copy them back to the legacy layout.
File diff suppressed because it is too large. Load diff
+214
View File
@@ -0,0 +1,214 @@
pub mod lxmf_tools
pub mod lxmf_tools::daemon
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
pub lxmf_tools::daemon::DaemonConfig::autopeer: bool
pub lxmf_tools::daemon::DaemonConfig::autopeer_maxdepth: usize
pub lxmf_tools::daemon::DaemonConfig::control_allowed: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::delivery_transfer_max_accepted_size: f64
pub lxmf_tools::daemon::DaemonConfig::display_name: core::option::Option<alloc::string::String>
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: 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
pub lxmf_tools::daemon::DaemonConfig::node_announce_interval: core::option::Option<u64>
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: 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: 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<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: lxmf_core::handlers::PnLimit
impl lxmf_tools::daemon::DaemonConfig
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
pub fn lxmf_tools::daemon::DaemonConfig::default() -> Self
pub struct lxmf_tools::daemon::PythonLxmdConfig
pub lxmf_tools::daemon::PythonLxmdConfig::auth_required: bool
pub lxmf_tools::daemon::PythonLxmdConfig::autopeer: bool
pub lxmf_tools::daemon::PythonLxmdConfig::autopeer_maxdepth: core::option::Option<i64>
pub lxmf_tools::daemon::PythonLxmdConfig::control_allowed_identities: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::delivery_transfer_max_accepted_size: f64
pub lxmf_tools::daemon::PythonLxmdConfig::display_name: alloc::string::String
pub lxmf_tools::daemon::PythonLxmdConfig::enable_propagation_node: bool
pub lxmf_tools::daemon::PythonLxmdConfig::from_static_only: bool
pub lxmf_tools::daemon::PythonLxmdConfig::max_inbound_syncs: i64
pub lxmf_tools::daemon::PythonLxmdConfig::max_peers: core::option::Option<i64>
pub lxmf_tools::daemon::PythonLxmdConfig::message_storage_limit: f64
pub lxmf_tools::daemon::PythonLxmdConfig::node_announce_at_start: bool
pub lxmf_tools::daemon::PythonLxmdConfig::node_announce_interval: core::option::Option<i64>
pub lxmf_tools::daemon::PythonLxmdConfig::node_name: core::option::Option<alloc::string::String>
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: 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: 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) -> core::result::Result<Self, lxmf_tools::daemon::DaemonConfigError>
pub fn lxmf_tools::daemon::create_router(&lxmf_tools::daemon::DaemonConfig) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::create_router_with_transport(&lxmf_tools::daemon::DaemonConfig, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::execute_on_inbound(&str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::execute_on_inbound_with_event(&str, &str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::persist_inbound_and_execute(&std::path::Path, &[u8], core::option::Option<&str>) -> core::io::error::Result<()>
pub mod lxmf_tools::lxmd_cli
pub enum lxmf_tools::lxmd_cli::SendMethod
pub lxmf_tools::lxmd_cli::SendMethod::Direct
pub lxmf_tools::lxmd_cli::SendMethod::Opportunistic
pub lxmf_tools::lxmd_cli::SendMethod::Propagated
impl lxmf_tools::lxmd_cli::SendMethod
pub fn lxmf_tools::lxmd_cli::SendMethod::delivery_method(self) -> lxmf_core::constants::DeliveryMethod
pub struct lxmf_tools::lxmd_cli::Args
pub lxmf_tools::lxmd_cli::Args::config: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::exampleconfig: bool
pub lxmf_tools::lxmd_cli::Args::identity: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::migrate_propagation_store: bool
pub lxmf_tools::lxmd_cli::Args::on_inbound: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::peers: bool
pub lxmf_tools::lxmd_cli::Args::propagation_node: bool
pub lxmf_tools::lxmd_cli::Args::quiet: u8
pub lxmf_tools::lxmd_cli::Args::recover_propagation_manifest: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::recovery_manifest_sha256: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::relay_writers_stopped: bool
pub lxmf_tools::lxmd_cli::Args::remote: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::rnsconfig: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::send: core::option::Option<alloc::vec::Vec<alloc::string::String>>
pub lxmf_tools::lxmd_cli::Args::send_fields_json: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::send_file: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::send_method: lxmf_tools::lxmd_cli::SendMethod
pub lxmf_tools::lxmd_cli::Args::send_timeout_secs: u64
pub lxmf_tools::lxmd_cli::Args::service: bool
pub lxmf_tools::lxmd_cli::Args::status: bool
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
pub fn lxmf_tools::lxmd_cli::parse_destination_hash(&str) -> core::result::Result<[u8; 16], alloc::string::String>
pub fn lxmf_tools::lxmd_cli::parse_send_fields_json(&str) -> core::result::Result<alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>, alloc::string::String>
pub mod lxmf_tools::lxmd_control
pub enum lxmf_tools::lxmd_control::ControlCommandKind
pub lxmf_tools::lxmd_control::ControlCommandKind::Status
pub lxmf_tools::lxmd_control::ControlCommandKind::Sync
pub lxmf_tools::lxmd_control::ControlCommandKind::Unpeer
impl lxmf_tools::lxmd_control::ControlCommandKind
pub fn lxmf_tools::lxmd_control::ControlCommandKind::timeout_message(self) -> &'static str
pub enum lxmf_tools::lxmd_control::ControlResponse
pub lxmf_tools::lxmd_control::ControlResponse::Empty
pub lxmf_tools::lxmd_control::ControlResponse::Error(lxmf_core::constants::PeerError)
pub lxmf_tools::lxmd_control::ControlResponse::Stats(rmpv::Value)
pub lxmf_tools::lxmd_control::ControlResponse::Success
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_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, 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>
pub fn lxmf_tools::lxmd_control::print_control_link_error(lxmf_tools::lxmd_control::ControlCommandKind, &rns_runtime::link_client::LinkClientError) -> never
pub async fn lxmf_tools::lxmd_control::query_control(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, rns_identity::identity::Identity, [u8; 16], &str, alloc::vec::Vec<u8>, f64) -> core::result::Result<alloc::vec::Vec<u8>, rns_runtime::link_client::LinkClientError>
pub async fn lxmf_tools::lxmd_control::resolve_remote_identity_hash(tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, [u8; 16], f64) -> core::result::Result<[u8; 16], rns_runtime::link_client::LinkClientError>
pub mod lxmf_tools::lxmd_runtime
pub struct lxmf_tools::lxmd_runtime::ControlPreflight
pub lxmf_tools::lxmd_runtime::ControlPreflight::identity_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::ControlPreflight::peer_hash: core::option::Option<[u8; 16]>
pub lxmf_tools::lxmd_runtime::ControlPreflight::remote_hash: core::option::Option<[u8; 16]>
pub struct lxmf_tools::lxmd_runtime::ControlPreflightError
pub lxmf_tools::lxmd_runtime::ControlPreflightError::exit_code: i32
pub lxmf_tools::lxmd_runtime::ControlPreflightError::message: alloc::string::String
pub struct lxmf_tools::lxmd_runtime::LocalPeerView
pub lxmf_tools::lxmd_runtime::LocalPeerView::alive: bool
pub lxmf_tools::lxmd_runtime::LocalPeerView::hash: [u8; 16]
pub lxmf_tools::lxmd_runtime::LocalPeerView::last_heard: f64
pub lxmf_tools::lxmd_runtime::LocalPeerView::state: u8
pub lxmf_tools::lxmd_runtime::LocalPeerView::unhandled: u32
pub struct lxmf_tools::lxmd_runtime::LocalStatusView
pub lxmf_tools::lxmd_runtime::LocalStatusView::lxmf_dest_hash: [u8; 16]
pub lxmf_tools::lxmd_runtime::LocalStatusView::peers: usize
pub lxmf_tools::lxmd_runtime::LocalStatusView::pending_deferred_stamps: usize
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
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::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::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<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>
pub fn lxmf_tools::lxmd_runtime::propagation_announce_app_data(&lxmf_core::handlers::PropagationNodeAnnounceData) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_runtime::resolve_config_dirs(core::option::Option<&str>, core::option::Option<&str>) -> (std::path::PathBuf, std::path::PathBuf)
+510
View File
@@ -0,0 +1,510 @@
{
"schemaVersion": 1,
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
"packages": [
{
"name": "lxmf-core",
"version": "1.5.1",
"rustVersion": "1.89",
"edition": "2024",
"features": {
"default": [
"sqlite-store"
],
"sqlite-store": [
"dep:rusqlite",
"rns-transport/sqlite-store"
]
},
"targets": [
{
"name": "lxmf_core",
"kind": [
"lib"
],
"crateTypes": [
"lib"
],
"requiredFeatures": []
}
],
"dependencies": [
{
"name": "base64",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.22",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "bytes",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "hex",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.4",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "rand",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "rmp",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.8",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "rmp-serde",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "rmpv",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"with-serde"
],
"sourceKind": "registry"
},
{
"name": "rns-crypto",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-link",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-protocol",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"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,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"derive"
],
"sourceKind": "registry"
},
{
"name": "sha2",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.10",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
"kind": null,
"target": null,
"requirement": "^2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "tokio",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"full"
],
"sourceKind": "registry"
},
{
"name": "tracing",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.1",
"optional": false,
"defaultFeatures": true,
"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,
"kind": null,
"target": null,
"requirement": "^0.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "jni",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"android\")",
"requirement": "^0.19",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "objc2",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"ios\")",
"requirement": "^0.6",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
},
{
"name": "lxmf-tools",
"version": "1.5.1",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
"targets": [
{
"name": "lxmf_tools",
"kind": [
"lib"
],
"crateTypes": [
"lib"
],
"requiredFeatures": []
}
],
"dependencies": [
{
"name": "base64",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.22",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "bytes",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "clap",
"rename": null,
"kind": null,
"target": null,
"requirement": "^4",
"optional": false,
"defaultFeatures": true,
"features": [
"derive"
],
"sourceKind": "registry"
},
{
"name": "hex",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.4",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "lxmf-core",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rmpv",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "rns-crypto",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-runtime",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [
"serial"
],
"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.5.1",
"optional": false,
"defaultFeatures": false,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.5.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "serde_json",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "thiserror",
"rename": null,
"kind": null,
"target": null,
"requirement": "^2",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "tokio",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [
"full"
],
"sourceKind": "registry"
},
{
"name": "tracing",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "zeroize",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
}
]
}
+249
View File
@@ -0,0 +1,249 @@
{
"schemaVersion": 2,
"tool": {
"name": "cargo-public-api",
"version": "0.52.0",
"rustdocToolchain": "nightly-2026-08-01",
"target": "aarch64-apple-darwin",
"arguments": [
"--all-features",
"-sss"
]
},
"baseline": {
"commit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"compatibilityFloor": {
"evidenceCommit": "00f439df7e6d14d29e5ca75efc7c694ab4990b3d",
"sourceCommit": "00f439df7e6d14d29e5ca75efc7c694ab4990b3d"
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 2458,
"sha256": "93bd001beb46ae13e2ece84d355e9fd4ffc8198029233de3a397b1a645b77651"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 214,
"sha256": "61656c05c28423f95c71f716998a834e0e9bc8855d0ddd29617aed1a0ee3045b"
}
],
"approvedBreakingChanges": {
"releaseLine": "1.5",
"migrationGuide": "api/migrations/1.5.md",
"removed": {
"lxmf-core": [
"impl lxmf_core::router::DirectRouteSnapshot",
"impl lxmf_core::router::OutboundTicketIntent",
"pub const lxmf_core::constants::COST_TICKET: u16",
"pub const lxmf_core::constants::MAX_PEERING_COST: u8",
"pub const lxmf_core::constants::PEERING_COST: u8",
"pub const lxmf_core::constants::PROPAGATION_COST: u8",
"pub const lxmf_core::constants::PROPAGATION_COST_FLEX: u8",
"pub const lxmf_core::constants::PROPAGATION_COST_MIN: u8",
"pub const lxmf_core::persist::LOCALLY_PROCESSED_FILE: &str",
"pub const lxmf_core::persist::LOCAL_DELIVERIES_FILE: &str",
"pub const lxmf_core::persist::STAMP_COSTS_FILE: &str",
"pub const lxmf_core::persist::TICKETS_FILE: &str",
"pub enum lxmf_core::router::DirectDeliveryPlan",
"pub fn lxmf_core::delivery_ratchet::DeliveryRatchetState::create_announce(&mut self, &rns_identity::identity::Identity, &[u8], u64, f64, lxmf_core::delivery_ratchet::DeliveryAnnounceKind<'_>) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::delivery_ratchet::DeliveryRatchetError>",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::generate(&self, &[u8; 32], u8) -> core::option::Option<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
"pub fn lxmf_core::discovery_stamper::LxmfDiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> u8",
"pub fn lxmf_core::handlers::PropagationNodeAnnounceData::new(bool, u64, u64, u8, u8, u8) -> Self",
"pub fn lxmf_core::handlers::get_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>",
"pub fn lxmf_core::handlers::parse_announce_app_data(&[u8]) -> core::option::Option<(core::option::Option<alloc::string::String>, core::option::Option<u8>)>",
"pub fn lxmf_core::handlers::pn_stamp_cost_from_app_data(&[u8]) -> core::option::Option<u8>",
"pub fn lxmf_core::handlers::stamp_cost_from_app_data(&[u8]) -> core::option::Option<u8>",
"pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> bool",
"pub fn lxmf_core::message::LxMessage::validated_stamp_value(&self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> core::option::Option<u16>",
"pub fn lxmf_core::message::SignedLxMessage::stamp_cost(&self) -> core::option::Option<u8>",
"pub fn lxmf_core::peer::LxmPeer::add_unhandled_message(&mut self)",
"pub fn lxmf_core::peer::LxmPeer::from_announce([u8; 16], f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>) -> Self",
"pub fn lxmf_core::peer::LxmPeer::from_announce_with_metadata([u8; 16], f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<std::collections::hash::map::HashMap<u8, alloc::vec::Vec<u8>>>) -> Self",
"pub fn lxmf_core::peer::LxmPeer::generate_peering_key(&mut self, &[u8; 16], &[u8; 16]) -> bool",
"pub fn lxmf_core::peer::LxmPeer::minimum_accepted_stamp_cost(&self) -> u8",
"pub fn lxmf_core::peer::LxmPeer::peering_key_value(&self) -> core::option::Option<u32>",
"pub fn lxmf_core::peer::LxmPeer::refresh_from_announce(&mut self, f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>) -> bool",
"pub fn lxmf_core::peer::LxmPeer::refresh_from_announce_with_metadata(&mut self, f64, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<u8>, core::option::Option<std::collections::hash::map::HashMap<u8, alloc::vec::Vec<u8>>>) -> bool",
"pub fn lxmf_core::peer::LxmPeer::set_unhandled_count(&mut self, u32)",
"pub fn lxmf_core::peer::LxmPeer::unhandled_messages(&self) -> u32",
"pub fn lxmf_core::peer::select_sync_peer(&[&lxmf_core::peer::LxmPeer]) -> core::option::Option<usize>",
"pub fn lxmf_core::persist::load_local_deliveries(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>>",
"pub fn lxmf_core::persist::load_locally_processed(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>>",
"pub fn lxmf_core::persist::load_stamp_costs(&std::path::Path) -> core::io::error::Result<std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>>",
"pub fn lxmf_core::persist::load_tickets(&std::path::Path) -> core::io::error::Result<(lxmf_core::ticket::TicketStoreSnapshot, core::option::Option<alloc::vec::Vec<lxmf_core::ticket::Ticket>>)>",
"pub fn lxmf_core::persist::save_local_deliveries(&std::path::Path, &std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_locally_processed(&std::path::Path, &std::collections::hash::map::HashMap<lxmf_core::types::PropagationTransientId, f64>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_stamp_costs(&std::path::Path, &std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>) -> core::io::error::Result<()>",
"pub fn lxmf_core::persist::save_tickets(&std::path::Path, &lxmf_core::ticket::TicketStoreSnapshot) -> core::io::error::Result<()>",
"pub fn lxmf_core::propagation::PropagationEntry::new(lxmf_core::types::PropagationTransientId, [u8; 32], [u8; 16], usize, u8) -> Self",
"pub fn lxmf_core::propagation::PropagationEntry::new_stamped(lxmf_core::types::PropagationTransientId, [u8; 32], [u8; 16], usize, u8) -> Self",
"pub fn lxmf_core::propagation::PropagationEntry::parse_filename(&str) -> core::option::Option<(lxmf_core::types::PropagationTransientId, f64, u8)>",
"pub fn lxmf_core::propagation::PropagationStore::get_stamp_value(&self, &lxmf_core::types::PropagationTransientId) -> core::option::Option<u8>",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::create_offer(&self, [u8; 16], core::option::Option<u8>) -> alloc::vec::Vec<lxmf_core::types::PropagationTransientId>",
"pub fn lxmf_core::propagation_node::PropagationNode::min_stamp_cost(&self) -> u8",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_stamped_propagated_blob(&mut self, &[u8], &[u8; 32], u8) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_node::PropagationNode::set_min_stamp_cost(&mut self, u8)",
"pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::stamp_value(&self) -> u8",
"pub fn lxmf_core::propagation_node::ValidatedOpaquePropagationBlob::validate(bytes::bytes::Bytes, u8) -> core::option::Option<Self>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::matches(&self, &lxmf_core::message::LxMessage, &[u8; 32]) -> bool",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::new<F>(lxmf_core::message::LxMessage, [u8; 32], u8, F) -> core::result::Result<Self, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::new_cancellable<F>(lxmf_core::message::LxMessage, [u8; 32], u8, F, &core::sync::atomic::AtomicBool) -> core::result::Result<Self, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::pack_for_cancellable(&mut self, lxmf_core::propagation_send::PreparedNode, f64, &core::sync::atomic::AtomicBool) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::propagation_send::PropagationEnvelope::stamp_value(&self) -> u32",
"pub fn lxmf_core::router::DirectRouteSnapshot::new([u8; 16], u8) -> Self",
"pub fn lxmf_core::router::LxmRouter::defer_outbound_for_path_request(&mut self, &[u8; 32], f64) -> bool",
"pub fn lxmf_core::router::LxmRouter::generate_ticket(&mut self, [u8; 16], core::option::Option<u64>) -> [u8; 16]",
"pub fn lxmf_core::router::LxmRouter::get_inbound_tickets(&self) -> &[lxmf_core::ticket::Ticket]",
"pub fn lxmf_core::router::LxmRouter::get_outbound_lxm_propagation_stamp_cost(&self, &[u8; 32]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::get_outbound_lxm_stamp_cost(&self, &[u8; 16]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::get_stamp_cost(&self, &[u8; 16]) -> core::option::Option<u8>",
"pub fn lxmf_core::router::LxmRouter::ingest_lxm_uri<F>(&mut self, &str, F) -> core::result::Result<lxmf_core::message::LxMessage, lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessageDraft) -> core::result::Result<lxmf_core::router::OutboundTicketIntent, lxmf_core::router::TicketPreparationError>",
"pub fn lxmf_core::router::LxmRouter::process_outbound_with_direct<F>(&mut self, F) -> alloc::vec::Vec<lxmf_core::router::OutboundAction> where F: core::ops::function::FnMut(&lxmf_core::message::LxMessage, f64) -> lxmf_core::router::DirectDeliveryPlanInput",
"pub fn lxmf_core::router::LxmRouter::set_propagation_limit(&mut self, usize)",
"pub fn lxmf_core::router::LxmRouter::set_stamp_cost(&mut self, [u8; 16], u8)",
"pub fn lxmf_core::router::LxmRouter::set_stamp_requirements(&mut self, u8, u8)",
"pub fn lxmf_core::router::LxmRouter::sync_peer_policies_for_store(&self, u64) -> alloc::vec::Vec<lxmf_core::peer::OutboundOfferPolicy>",
"pub fn lxmf_core::router::LxmRouter::sync_peers(&mut self) -> alloc::vec::Vec<[u8; 16]>",
"pub fn lxmf_core::router::LxmRouter::validate_stamp(&self, &[u8; 32], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::router::LxmRouter::validate_stamp_with_tickets(&self, &[u8; 32], &[u8], u8, &[u8; 16]) -> bool",
"pub fn lxmf_core::router::OutboundTicketIntent::persist(self, &std::path::Path, &mut lxmf_core::message::LxMessageDraft) -> core::io::error::Result<()>",
"pub fn lxmf_core::router::OutboundTicketIntent::requires_persistence(&self) -> bool",
"pub fn lxmf_core::router::plan_direct_delivery(&mut lxmf_core::message::LxMessage, lxmf_core::router::DirectDeliveryPlanInput, f64) -> lxmf_core::router::DirectDeliveryPlan",
"pub fn lxmf_core::stamper::generate_stamp(&[u8], u8, usize) -> core::option::Option<([u8; 32], u32)>",
"pub fn lxmf_core::stamper::generate_stamp_cancellable(&[u8], u8, usize, &core::sync::atomic::AtomicBool) -> core::option::Option<([u8; 32], u32)>",
"pub fn lxmf_core::stamper::generate_stamp_limited(&[u8], u8, usize, u64) -> core::option::Option<[u8; 32]>",
"pub fn lxmf_core::stamper::spawn_deferred_stamp([u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver<lxmf_core::stamper::DeferredStampResult>)",
"pub fn lxmf_core::stamper::spawn_deferred_stamp_on(&tokio::runtime::handle::Handle, [u8; 32], u8, usize) -> (lxmf_core::stamper::DeferredStampHandle, tokio::sync::oneshot::Receiver<lxmf_core::stamper::DeferredStampResult>)",
"pub fn lxmf_core::stamper::stamp_iteration_cap(u8) -> core::option::Option<u64>",
"pub fn lxmf_core::stamper::stamp_valid(&[u8; 32], u8, &[u8]) -> bool",
"pub fn lxmf_core::stamper::stamp_value(&[u8], &[u8; 32]) -> u32",
"pub fn lxmf_core::stamper::stamp_workblock(&[u8], usize) -> alloc::vec::Vec<u8>",
"pub fn lxmf_core::stamper::validate_peering_key(&[u8], &[u8; 32], u8) -> bool",
"pub fn lxmf_core::stamper::validate_pn_stamp(&[u8], u8) -> core::option::Option<lxmf_core::stamper::PropagationStampParts>",
"pub fn lxmf_core::stamper::validate_stamp(&[u8; 32], &[u8; 32], u8, usize) -> bool",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::peering_cost: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::stamp_cost: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::stamp_flex: u8",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::sync_limit: u64",
"pub lxmf_core::handlers::PropagationNodeAnnounceData::transfer_limit: u64",
"pub lxmf_core::message::LxMessageDraft::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message_api::LxMessageDraft::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message_api::MessageMetadata::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::peer::LxmPeer::peering_cost: u8",
"pub lxmf_core::peer::LxmPeer::peering_key: core::option::Option<([u8; 32], u32)>",
"pub lxmf_core::peer::LxmPeer::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::peer::LxmPeer::stamp_cost_flexibility: core::option::Option<u8>",
"pub lxmf_core::peer::OutboundOfferPolicy::minimum_stamp_cost: u8",
"pub lxmf_core::peer::OutboundOfferPolicy::peering_cost: u8",
"pub lxmf_core::peer::OutboundOfferPolicy::peering_key_value: core::option::Option<u32>",
"pub lxmf_core::peer::OutboundOfferPolicy::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::peer::OutboundOfferPolicy::stamp_cost_flexibility: core::option::Option<u8>",
"pub lxmf_core::propagation::PropagationEntry::stamp_value: u8",
"pub lxmf_core::propagation_node::PropagationNodeConfig::min_stamp_cost: u8",
"pub lxmf_core::propagation_node::PropagationNodeConfig::peering_cost: u8",
"pub lxmf_core::propagation_send::AdvertisedNodePolicy::stamp_cost: u8",
"pub lxmf_core::propagation_store_v2::RecoveryPolicy::minimum_stamp_cost: u8",
"pub lxmf_core::router::AutopeerCandidate::peering_cost: core::option::Option<u8>",
"pub lxmf_core::router::AutopeerCandidate::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::AutopeerCandidate::stamp_flexibility: core::option::Option<u8>",
"pub lxmf_core::router::DirectDeliveryPlan::DeferTerminalFailure",
"pub lxmf_core::router::DirectDeliveryPlan::Fail",
"pub lxmf_core::router::DirectDeliveryPlan::RequestPath",
"pub lxmf_core::router::DirectDeliveryPlan::RequestPath::drop_existing: bool",
"pub lxmf_core::router::DirectDeliveryPlan::StartNewLink",
"pub lxmf_core::router::DirectDeliveryPlan::StartNewLink::hops: u8",
"pub lxmf_core::router::DirectDeliveryPlan::UseReusableLink",
"pub lxmf_core::router::DirectDeliveryPlan::WaitForReusableLink",
"pub lxmf_core::router::DirectDeliveryPlanInput::identity_known: bool",
"pub lxmf_core::router::DirectDeliveryPlanInput::reusable_link: lxmf_core::router::DirectReusableLinkState",
"pub lxmf_core::router::DirectDeliveryPlanInput::route: core::option::Option<lxmf_core::router::DirectRouteSnapshot>",
"pub lxmf_core::router::DirectRouteSnapshot::destination_hash: [u8; 16]",
"pub lxmf_core::router::DirectRouteSnapshot::expires_at: core::option::Option<f64>",
"pub lxmf_core::router::DirectRouteSnapshot::hops: u8",
"pub lxmf_core::router::DirectRouteSnapshot::interface_name: core::option::Option<alloc::string::String>",
"pub lxmf_core::router::DirectRouteSnapshot::learned_at: core::option::Option<f64>",
"pub lxmf_core::router::LxmRouter::outbound_stamp_costs: std::collections::hash::map::HashMap<[u8; 16], lxmf_core::router::StampCostEntry>",
"pub lxmf_core::router::LxmRouter::ticket_store: lxmf_core::ticket::TicketStore",
"pub lxmf_core::router::NodeStats::peering_cost: u8",
"pub lxmf_core::router::NodeStats::propagation_limit: usize",
"pub lxmf_core::router::NodeStats::stamp_cost: u8",
"pub lxmf_core::router::NodeStats::stamp_flex: u8",
"pub lxmf_core::router::NodeStats::sync_limit: usize",
"pub lxmf_core::router::OutboundAction::DeliverDirect",
"pub lxmf_core::router::OutboundAction::DeliverDirect::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::DeliverDirect::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::DeliverOpportunistic::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverPropagated",
"pub lxmf_core::router::OutboundAction::DeliverPropagated::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::DeliverPropagated::prop_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::Expired(lxmf_core::message::LxMessage)",
"pub lxmf_core::router::OutboundAction::PlanDirect",
"pub lxmf_core::router::OutboundAction::PlanDirect::dest_hash: [u8; 16]",
"pub lxmf_core::router::OutboundAction::PlanDirect::message: lxmf_core::message::LxMessage",
"pub lxmf_core::router::OutboundAction::PlanDirect::plan: lxmf_core::router::DirectDeliveryPlan",
"pub lxmf_core::router::PeerStats::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::RouterConfig::propagation_limit_kb: usize",
"pub lxmf_core::router::RouterConfig::propagation_stamp_cost: u8",
"pub lxmf_core::router::RouterConfig::propagation_stamp_flex: u8",
"pub lxmf_core::router::RouterConfig::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::router::RouterConfig::sync_limit_kb: usize",
"pub lxmf_core::router::RouterConfigExt::max_peering_cost: u8",
"pub lxmf_core::router::RouterConfigExt::peering_cost: u8",
"pub lxmf_core::router::RouterConfigExt::propagation_cost_min: u8",
"pub lxmf_core::router::RouterStats::stamp_costs_cached: usize",
"pub lxmf_core::router::StampCostEntry::cost: u8",
"pub lxmf_core::router::StampCostEntry::recorded_at: f64",
"pub lxmf_core::router::TicketPreparationError::PendingPersistence",
"pub lxmf_core::stamper::DeferredStampResult::Success::value: u32",
"pub struct lxmf_core::router::DirectDeliveryPlanInput",
"pub struct lxmf_core::router::DirectRouteSnapshot",
"pub struct lxmf_core::router::OutboundTicketIntent",
"pub struct lxmf_core::router::RouterConfig",
"pub struct lxmf_core::router::RouterConfigExt",
"pub struct lxmf_core::router::StampCostEntry",
"pub type lxmf_core::stamper::PropagationStampParts = ([u8; 32], alloc::vec::Vec<u8>, u32, [u8; 32])"
],
"lxmf-tools": [
"pub fn lxmf_tools::daemon::DaemonConfig::from_config(&rns_runtime::config::Config) -> Self",
"pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::Config) -> Self",
"pub fn lxmf_tools::lxmd_control::encode_nil_response() -> alloc::vec::Vec<u8>",
"pub fn lxmf_tools::lxmd_control::encode_router_control_stats(&lxmf_core::router::LxmRouter, [u8; 16], [u8; 16], core::option::Option<&lxmf_core::propagation_node::PropagationNode>, f64) -> alloc::vec::Vec<u8>",
"pub fn lxmf_tools::lxmd_runtime::delivery_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>",
"pub lxmf_tools::daemon::DaemonConfig::max_peering_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::peering_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::propagation_limit_kb: usize",
"pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_cost: u8",
"pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_flex: u8",
"pub lxmf_tools::daemon::DaemonConfig::stamp_cost: core::option::Option<u8>",
"pub lxmf_tools::daemon::DaemonConfig::sync_limit_kb: usize",
"pub lxmf_tools::daemon::PythonLxmdConfig::peer_stamp_cost: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::peering_cost: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_flexibility: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_target: i64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_sync_max_accepted_size: f64",
"pub lxmf_tools::daemon::PythonLxmdConfig::propagation_transfer_max_accepted_size: f64",
"pub lxmf_tools::daemon::PythonLxmdConfig::remote_peering_cost_max: i64",
"pub lxmf_tools::lxmd_runtime::LocalStatusView::stamp_costs_cached: usize",
"pub lxmf_tools::lxmd_runtime::LxmdPaths::known_identities_path: std::path::PathBuf",
"pub lxmf_tools::lxmd_runtime::LxmdPaths::received_ratchets_dir: std::path::PathBuf",
"pub struct lxmf_tools::daemon::DaemonConfig"
]
}
}
}
+2
View File
@@ -0,0 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.89"
+20 -2
View File
@@ -1,9 +1,17 @@
[package]
name = "lxmf-core"
description = "LXMF messaging protocol implementation for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.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 }
@@ -17,12 +25,22 @@ thiserror = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
rmp = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
serde = { workspace = true }
sha2 = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
unicode-normalization = { workspace = true }
unicode-general-category = { workspace = true }
rusqlite = { workspace = true, optional = true }
[target.'cfg(target_os = "ios")'.dependencies]
objc2 = "0.6"
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
[dev-dependencies]
tempfile = { workspace = true }
+23
View File
@@ -0,0 +1,23 @@
//! Construct, sign, freeze, and inspect a message through the canonical API.
//! The hashes below are placeholders: this local packing example does not
//! authenticate a sender or transmit a message. Real source hashes must bind
//! the signing identity to its lxmf.delivery destination.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState};
use rns_crypto::ed25519::Ed25519PrivateKey;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut draft = LxMessageDraft::new(
[0x11; 16],
[0x22; 16],
"Hello",
"LXMF from Rust",
DeliveryMethod::Direct,
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
let message = draft.sign(&Ed25519PrivateKey::generate())?.finalize(None)?;
let unpacked = LxMessage::unpack(message.wire_bytes())?;
assert_eq!(unpacked.title_text(), "Hello");
assert_eq!(unpacked.state, MessageState::Generating);
assert_eq!(unpacked.wire_bytes(), message.wire_bytes());
Ok(())
}
+630
View File
@@ -0,0 +1,630 @@
//! Durable propagation-download admission and non-purging retry policy.
//!
//! A transport Resource proof is not an application receipt. The trusted local
//! adapter implements [`DurableAdmissionBackend`] and commits its body/effects
//! and receipt together before a download token can authorize remote deletion.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
pub const MAX_DOWNLOAD_ITEMS: usize = 4096;
pub const MAX_RETAINED_DOWNLOAD_BYTES: usize = 134_217_727;
pub const MAX_PROCESSING_BYTES: usize = 256 * 1024 * 1024;
pub const MAX_PROCESSORS: usize = 4;
pub const POLICY_RECEIPT_LIFETIME: u64 = 90 * 86400;
/// Exact remote and local ownership of a ciphertext transient ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AdmissionScope {
pub identity: [u8; 16],
pub node: [u8; 16],
pub transient_id: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DurableDisposition {
Committed,
Duplicate,
PolicyDiscard,
UserDeleted,
}
/// Persisted effect identity. A duplicate need not have the same complete wire
/// hash: the optional recipient stamp is excluded from the signed message ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionRecord {
pub scope: AdmissionScope,
pub message_id: [u8; 32],
pub received_wire_hash: [u8; 32],
pub stored_message_wire_hash: Option<[u8; 32]>,
pub disposition: DurableDisposition,
pub committed_at: u64,
}
/// Local purge authority with an optional expiry. Policy-discard and user-deleted
/// receipts expire after [`POLICY_RECEIPT_LIFETIME`]; committed/duplicate receipts
/// have no time expiry. Adapters must check the referenced durable effect before
/// supplying this value; constructing it does not perform that verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DurableHave {
pub transient_id: [u8; 32],
pub expires_at: Option<u64>,
}
impl DurableHave {
pub fn from_record(record: &AdmissionRecord) -> Self {
Self {
transient_id: record.scope.transient_id,
expires_at: matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
)
.then(|| record.committed_at.saturating_add(POLICY_RECEIPT_LIFETIME)),
}
}
pub fn active(self, now: u64) -> bool {
self.expires_at.is_none_or(|expiry| now < expiry)
}
}
#[derive(Debug, thiserror::Error)]
pub enum AdmissionError {
#[error("admission was not committed: {0}")]
NotCommitted(String),
#[error("admission publication is uncertain; reconcile all durability barriers: {0}")]
CommitUncertain(String),
#[error("durable disposition ledger is full")]
DispositionLedgerFull,
#[error("admission scope does not match the downloaded ciphertext")]
WrongScope,
}
/// Trusted persistence adapter boundary. Implementations must atomically commit
/// the receipt with the message/effect, or reference a previously durable effect.
/// In particular, returning a record after a failed/uncertain filesystem or SQL
/// commit violates this contract. SQL adapters must establish their transaction
/// and durability guarantees. [`crate::admission_store::FileAdmissionStore`]
/// uses an intent/body/commit journal.
pub trait DurableAdmissionBackend {
fn commit(self) -> Result<AdmissionRecord, AdmissionError>;
}
#[derive(Debug)]
pub struct DurableAdmissionReceipt {
record: AdmissionRecord,
}
impl DurableAdmissionReceipt {
pub fn commit(backend: impl DurableAdmissionBackend) -> Result<Self, AdmissionError> {
Ok(Self {
record: backend.commit()?,
})
}
pub fn record(&self) -> &AdmissionRecord {
&self.record
}
}
/// Persisted, deterministic epochs; never reset these to a process generation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionEpochs {
pub policy: [u8; 32],
pub keys: [u8; 32],
pub budget: [u8; 32],
pub storage_health: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SuppressionReason {
Malformed,
WrongDestination,
InvalidSignature,
InvalidStamp,
DecryptionFailed,
TooLarge,
MissingKey,
StorageUnavailable,
StorageBusy,
Quota,
WorkerUnavailable,
DispositionLedgerFull,
Cancelled,
}
impl SuppressionReason {
pub fn is_transient(self) -> bool {
matches!(
self,
Self::MissingKey
| Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::WorkerUnavailable
| Self::DispositionLedgerFull
| Self::Cancelled
)
}
fn epoch_matches(self, before: AdmissionEpochs, now: AdmissionEpochs) -> bool {
match self {
Self::DecryptionFailed | Self::MissingKey => before.keys == now.keys,
Self::InvalidSignature => before.keys == now.keys && before.policy == now.policy,
Self::TooLarge => before.budget == now.budget,
Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::DispositionLedgerFull => before.storage_health == now.storage_health,
_ => before.policy == now.policy,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionRecord {
pub scope: AdmissionScope,
pub reason: SuppressionReason,
pub epochs: AdmissionEpochs,
pub attempts: u16,
pub last_failure: u64,
pub next_retry: u64,
pub expires_at: u64,
}
impl SuppressionRecord {
pub fn active(&self, now: u64, epochs: AdmissionEpochs) -> bool {
now < self.expires_at
&& now < self.next_retry
&& self.reason.epoch_matches(self.epochs, epochs)
}
}
/// Quotas bound metadata independently of message bytes. Full ledgers preserve
/// existing entries and pause new wants, rather than evicting into a retry loop.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppressionLedger {
records: HashMap<AdmissionScope, SuppressionRecord>,
}
impl SuppressionLedger {
pub const PER_NODE: usize = 4096;
pub const PER_IDENTITY: usize = 16384;
pub const GLOBAL: usize = 65536;
/// Restore typed rows only after duplicate and quota validation. Never
/// silently overwrite persisted scope decisions during hydration.
pub fn from_records(
records: impl IntoIterator<Item = SuppressionRecord>,
) -> Result<Self, AdmissionError> {
let mut ledger = Self::default();
let mut identities = HashMap::<[u8; 16], usize>::new();
let mut nodes = HashMap::<([u8; 16], [u8; 16]), usize>::new();
for record in records {
if ledger.records.contains_key(&record.scope) {
return Err(AdmissionError::NotCommitted(
"duplicate suppression scope".into(),
));
}
if record.attempts == 0
|| record.next_retry < record.last_failure
|| record.expires_at <= record.last_failure
|| record.expires_at > record.last_failure.saturating_add(30 * 86400)
{
return Err(AdmissionError::NotCommitted(
"invalid suppression interval".into(),
));
}
let identity = identities.entry(record.scope.identity).or_default();
let node = nodes
.entry((record.scope.identity, record.scope.node))
.or_default();
if ledger.records.len() >= Self::GLOBAL
|| *identity >= Self::PER_IDENTITY
|| *node >= Self::PER_NODE
{
return Err(AdmissionError::DispositionLedgerFull);
}
*identity += 1;
*node += 1;
ledger.records.insert(record.scope, record);
}
Ok(ledger)
}
pub fn records(&self) -> impl Iterator<Item = &SuppressionRecord> {
self.records.values()
}
pub fn get(&self, scope: &AdmissionScope) -> Option<&SuppressionRecord> {
self.records.get(scope)
}
pub fn remove(&mut self, scope: &AdmissionScope) {
self.records.remove(scope);
}
pub fn prune(&mut self, now: u64, epochs: AdmissionEpochs) {
self.records.retain(|_, record| {
now < record.expires_at && record.reason.epoch_matches(record.epochs, epochs)
});
}
pub fn saturated(&self, identity: [u8; 16], node: [u8; 16]) -> bool {
self.records.len() >= Self::GLOBAL
|| self
.records
.keys()
.filter(|k| k.identity == identity)
.count()
>= Self::PER_IDENTITY
|| self
.records
.keys()
.filter(|k| k.identity == identity && k.node == node)
.count()
>= Self::PER_NODE
}
pub fn record_failure(
&mut self,
scope: AdmissionScope,
reason: SuppressionReason,
epochs: AdmissionEpochs,
now: u64,
) -> Result<&SuppressionRecord, AdmissionError> {
self.prune(now, epochs);
if !self.records.contains_key(&scope) && self.saturated(scope.identity, scope.node) {
return Err(AdmissionError::DispositionLedgerFull);
}
let attempts = self
.records
.get(&scope)
.filter(|r| r.reason == reason)
.map_or(1, |r| r.attempts.saturating_add(1));
let (next_retry, expires_at) = if reason.is_transient() {
let base = (60u64 << attempts.saturating_sub(1).min(6)).min(3600);
// Stable +/-10% jitter avoids synchronized retries after restart.
let jitter =
u16::from_be_bytes([scope.transient_id[0], scope.transient_id[1]]) as u64 % 21;
(
now.saturating_add(base * (90 + jitter) / 100),
now.saturating_add(86400),
)
} else {
(
now.saturating_add(30 * 86400),
now.saturating_add(30 * 86400),
)
};
self.records.insert(
scope,
SuppressionRecord {
scope,
reason,
epochs,
attempts,
last_failure: now,
next_retry,
expires_at,
},
);
Ok(&self.records[&scope])
}
}
#[derive(Debug)]
pub enum DownloadAdmissionOutcome {
Accepted(DurableAdmissionReceipt),
Rejected(SuppressionReason),
}
pub(crate) struct AdmissionResolution {
pub generation: u64,
pub scope: AdmissionScope,
pub outcome: DownloadAdmissionOutcome,
}
/// Single-use, generation-bound authority. Dropping an unresolved token attempts
/// to send a Cancelled rejection to its consumer. Cancelling the client generation
/// cannot cancel a blocking commit.
pub struct DownloadAdmissionToken {
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: Option<mpsc::UnboundedSender<AdmissionResolution>>,
}
impl std::fmt::Debug for DownloadAdmissionToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DownloadAdmissionToken")
.field("scope", &self.scope)
.field("generation", &self.generation)
.finish_non_exhaustive()
}
}
impl DownloadAdmissionToken {
pub(crate) fn new(
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: mpsc::UnboundedSender<AdmissionResolution>,
) -> Self {
Self {
scope,
generation,
current_generation,
tx: Some(tx),
}
}
pub fn scope(&self) -> AdmissionScope {
self.scope
}
/// Read whether this token still belongs to the current client generation.
///
/// This is a snapshot, not a lock: the generation can change immediately.
/// Check after durable commit and use the adapter's lifecycle gate around
/// current-generation UI effects. Cancellation cannot stop an in-flight
/// commit or release its memory lease.
pub fn is_current(&self) -> bool {
self.current_generation.load(Ordering::Acquire) == self.generation
}
/// Enqueue one outcome for this token's scope and current generation.
/// Success reports enqueueing, not remote deletion or an atomic lifecycle
/// transition; the consumer rechecks the generation before applying it.
/// A mismatched scope, revoked generation or closed consumer returns an error.
pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> {
if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome
&& receipt.record.scope != self.scope
{
return Err(AdmissionError::WrongScope);
}
if !self.is_current() {
self.tx.take();
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
let tx = self.tx.take().ok_or_else(|| {
AdmissionError::NotCommitted("download authority already consumed".into())
})?;
tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome,
})
.map_err(|_| AdmissionError::NotCommitted("download consumer is closed".into()))?;
// The client rechecks the exact generation while consuming. This result
// reports enqueue only; adapters need their lifecycle gate around any
// current-generation UI effects, not an atomic-cancellation promise.
if !self.is_current() {
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
Ok(())
}
}
impl Drop for DownloadAdmissionToken {
fn drop(&mut self) {
if let Some(tx) = self.tx.take() {
let _ = tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome: DownloadAdmissionOutcome::Rejected(SuppressionReason::Cancelled),
});
}
}
}
#[derive(Debug)]
pub struct DownloadedPropagationMessage {
data: Bytes,
token: DownloadAdmissionToken,
}
impl DownloadedPropagationMessage {
pub(crate) fn new(data: Bytes, token: DownloadAdmissionToken) -> Self {
Self { data, token }
}
pub fn data(&self) -> &Bytes {
&self.data
}
pub fn scope(&self) -> AdmissionScope {
self.token.scope
}
pub fn into_parts(self) -> (Bytes, DownloadAdmissionToken) {
(self.data, self.token)
}
}
fn raw_budget() -> &'static Arc<Semaphore> {
static BUDGET: OnceLock<Arc<Semaphore>> = OnceLock::new();
BUDGET.get_or_init(|| Arc::new(Semaphore::new(MAX_RETAINED_DOWNLOAD_BYTES)))
}
struct RetainedResponse {
bytes: Bytes,
_credit: OwnedSemaphorePermit,
}
impl AsRef<[u8]> for RetainedResponse {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
/// Credit follows every Bytes clone/slice, including payloads in cancelled
/// blocking workers. Moving a response out of the client never releases it.
pub(crate) fn retain_response(
bytes: Bytes,
local_limit: usize,
) -> Result<Bytes, SuppressionReason> {
if bytes.len() > local_limit.min(MAX_RETAINED_DOWNLOAD_BYTES) {
return Err(SuppressionReason::TooLarge);
}
let credit = raw_budget()
.clone()
.try_acquire_many_owned(bytes.len() as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Bytes::from_owner(RetainedResponse {
bytes,
_credit: credit,
}))
}
/// Full peak reservation is obtained before decrypting while raw ciphertext is
/// retained separately. Never wait for a partial reservation while holding the
/// parent response. This bounds Rust-owned buffers, not SQLite's native heap.
fn processing_budget() -> &'static Arc<Semaphore> {
static BYTES: OnceLock<Arc<Semaphore>> = OnceLock::new();
BYTES.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSING_BYTES)))
}
/// Additional explicitly bounded adapter state, sharing the processing byte
/// budget without taking a second worker slot. Admission is always nonblocking.
pub struct ProcessingMemoryLease {
_bytes: OwnedSemaphorePermit,
}
impl ProcessingMemoryLease {
pub fn try_acquire(amount: usize) -> Result<Self, SuppressionReason> {
if amount > MAX_PROCESSING_BYTES {
return Err(SuppressionReason::TooLarge);
}
Ok(Self {
_bytes: processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?,
})
}
}
pub struct ProcessingLease {
_bytes: OwnedSemaphorePermit,
_worker: OwnedSemaphorePermit,
}
impl ProcessingLease {
pub fn try_acquire(cipher_len: usize) -> Result<Self, SuppressionReason> {
static WORKERS: OnceLock<Arc<Semaphore>> = OnceLock::new();
let amount = cipher_len
.checked_mul(4)
.and_then(|v| v.checked_add(128 * 1024 + 256))
.filter(|v| *v <= MAX_PROCESSING_BYTES)
.ok_or(SuppressionReason::TooLarge)?;
let bytes = processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
let worker = WORKERS
.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSORS)))
.clone()
.try_acquire_owned()
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Self {
_bytes: bytes,
_worker: worker,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [n; 32],
}
}
#[test]
fn resolution_rejects_revoked_generation_and_closed_consumer() {
let generation = Arc::new(AtomicU64::new(1));
let (tx, mut rx) = mpsc::unbounded_channel();
let token = DownloadAdmissionToken::new(scope(1), 1, generation.clone(), tx.clone());
generation.store(2, Ordering::Release);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
assert!(rx.try_recv().is_err());
let token = DownloadAdmissionToken::new(scope(2), 2, generation, tx);
drop(rx);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
}
#[test]
fn permanent_failures_revalidate_on_epoch_change_or_expiry() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
let r = ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(r.active(101, epoch));
let mut changed = epoch;
changed.keys[0] = 1;
assert!(!r.active(101, changed));
assert!(!r.active(100 + 30 * 86400, epoch));
assert!(rmp_serde::to_vec(r).unwrap().len() <= 512);
}
#[test]
fn temporary_storage_failure_is_retryable_and_bounded() {
let mut ledger = SuppressionLedger::default();
for _ in 0..20 {
ledger
.record_failure(
scope(1),
SuppressionReason::StorageBusy,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
let r = ledger.get(&scope(1)).unwrap();
assert!((3340..=4060).contains(&r.next_retry));
assert_eq!(r.expires_at, 86500);
}
#[test]
fn full_node_ledger_does_not_evict_existing_suppression() {
let mut ledger = SuppressionLedger::default();
for n in 0..SuppressionLedger::PER_NODE {
let mut s = scope(0);
s.transient_id[..8].copy_from_slice(&(n as u64).to_be_bytes());
ledger
.record_failure(
s,
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
assert!(
ledger
.record_failure(
scope(255),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100
)
.is_err()
);
assert_eq!(ledger.records().count(), SuppressionLedger::PER_NODE);
}
#[test]
fn impossible_processing_size_rejects_without_partial_wait() {
assert!(matches!(
ProcessingLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::TooLarge)
));
}
}
+714
View File
@@ -0,0 +1,714 @@
//! File adapter for lxmd's durable download receipts and hook outbox.
//! The original ciphertext TID is journaled before publishing decrypted bytes.
//! Keep exclusive ownership of the journal and body paths while the store is
//! open; its mutex coordinates clones of one store, not independent open calls
//! or external file writers.
use crate::admission::*;
use bytes::Bytes;
use rns_identity::persistence::{
DurableCommitPhase, DurableWriteError, durable_create_dir_all, durable_reconcile,
durable_remove, durable_write,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionIntent {
version: u8,
admission_id: [u8; 32],
record: AdmissionRecord,
body_path: Option<PathBuf>,
hook_event: Option<[u8; 32]>,
}
/// One atomic logical commit publishes both the receipt and pending hook event.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionCommit {
intent: AdmissionIntent,
hook_completed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserDeletedMessage {
version: u8,
identity: [u8; 16],
message_id: [u8; 32],
deleted_at: u64,
}
struct Inner {
journal: PathBuf,
bodies: PathBuf,
/// The only directory journaled bodies may be moved in from.
legacy_bodies: Option<PathBuf>,
committed: HashMap<AdmissionScope, AdmissionCommit>,
deleted: HashMap<([u8; 16], [u8; 32]), UserDeletedMessage>,
}
#[derive(Clone)]
pub struct FileAdmissionStore {
inner: Arc<Mutex<Inner>>,
}
fn error(e: DurableWriteError) -> AdmissionError {
match e.phase {
DurableCommitPhase::NotCommitted => AdmissionError::NotCommitted(e.to_string()),
_ => AdmissionError::CommitUncertain(e.to_string()),
}
}
fn other(e: impl std::fmt::Display) -> AdmissionError {
AdmissionError::NotCommitted(e.to_string())
}
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, AdmissionError> {
rmp_serde::to_vec_named(value).map_err(other)
}
fn read_bounded(path: &Path, limit: usize) -> Result<Vec<u8>, AdmissionError> {
use std::io::Read;
let mut bytes = Vec::new();
std::fs::File::open(path)
.map_err(other)?
.take(limit as u64 + 1)
.read_to_end(&mut bytes)
.map_err(other)?;
if bytes.len() > limit {
return Err(other("admission artifact exceeds limit"));
}
Ok(bytes)
}
fn admission_id(scope: &AdmissionScope) -> Result<[u8; 32], AdmissionError> {
Ok(rns_crypto::sha::full_hash(&encode(scope)?))
}
impl FileAdmissionStore {
/// Parent is the daemon's already configured state directory. A strict
/// outside bootstrap receipt witnesses creation of journal/body directories.
pub fn open(state_dir: &Path, bodies: &Path) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, None)
}
/// [`Self::open`] for a store whose bodies used to live in `legacy_bodies`:
/// a journaled body still there is moved into `bodies`.
pub fn open_moving_bodies_from(
state_dir: &Path,
bodies: &Path,
legacy_bodies: &Path,
) -> Result<Self, AdmissionError> {
Self::open_inner(state_dir, bodies, Some(legacy_bodies))
}
fn open_inner(
state_dir: &Path,
bodies: &Path,
legacy_bodies: Option<&Path>,
) -> Result<Self, AdmissionError> {
let journal = state_dir.join("download-admission-v1");
let parent = state_dir
.ancestors()
.find(|parent| {
bodies.starts_with(parent) && *parent != bodies && parent.parent().is_some()
})
.ok_or_else(|| other("admission state and bodies need a private common ancestor"))?;
let scope = encode(&(1u8, state_dir, bodies))?;
let bootstrap_path = parent.join(format!(
"download-admission-{}.bootstrap",
hex::encode(rns_crypto::sha::full_hash(&scope))
));
let bootstrap = durable_write(&bootstrap_path, &scope).map_err(error)?;
durable_create_dir_all(&journal, &bootstrap).map_err(error)?;
durable_create_dir_all(bodies, &bootstrap).map_err(error)?;
let mut inner = Inner {
journal,
bodies: bodies.to_owned(),
legacy_bodies: legacy_bodies.map(Path::to_owned),
committed: HashMap::new(),
deleted: HashMap::new(),
};
inner.recover()?;
Ok(Self {
inner: Arc::new(Mutex::new(inner)),
})
}
/// Prepare a persistence operation for an already authenticated message and
/// caller-selected disposition. The scope must retain the original ciphertext
/// TID; this method recomputes only the received plaintext wire hash.
/// Neither preparation nor commit authenticates the sender. Preparation writes
/// no files; commit performs persistence.
pub fn prepare(
&self,
mut record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
) -> FileAdmissionCommit {
// The caller cannot mislabel the incoming image even for a duplicate.
record.received_wire_hash = rns_crypto::sha::full_hash(&wire);
FileAdmissionCommit {
store: self.clone(),
record,
wire,
run_hook,
}
}
/// Return live receipts from committed or recovered state for this identity/node.
/// Visible receipts have no time expiry; invisible policy/TID receipts expire
/// after 90 days. This query does not re-read archive files. Use the store's
/// deletion API to revoke visible receipts when deleting a message.
pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec<Vec<u8>> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| c.intent.record.scope.transient_id.to_vec())
.collect()
}
pub fn durable_haves(
&self,
identity: [u8; 16],
node: [u8; 16],
now: u64,
) -> Vec<super::admission::DurableHave> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| super::admission::DurableHave::from_record(&c.intent.record))
.collect()
}
/// Explicit user deletion is a permanent message-ID decision, separate
/// from expiring per-node TID accelerators. No filesystem absence is treated
/// as user authorization. Removing this tombstone requires explicit reset.
pub fn mark_user_deleted(
&self,
identity: [u8; 16],
message_id: [u8; 32],
now: u64,
) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let tombstone = UserDeletedMessage {
version: 1,
identity,
message_id,
deleted_at: now,
};
let path = inner.journal.join(format!(
"{}-{}.deleted",
hex::encode(identity),
hex::encode(message_id)
));
let witness = durable_write(&path, &encode(&tombstone)?).map_err(error)?;
inner.deleted.insert((identity, message_id), tombstone);
let targets = inner
.committed
.iter()
.filter(|(_, c)| {
c.intent.record.scope.identity == identity
&& c.intent.record.message_id == message_id
})
.map(|(scope, c)| (*scope, c.clone()))
.collect::<Vec<_>>();
for (scope, mut commit) in targets {
commit.intent.body_path = None;
commit.intent.hook_event = None;
commit.hook_completed = true;
commit.intent.record.disposition = DurableDisposition::UserDeleted;
commit.intent.record.stored_message_wire_hash = None;
commit.intent.record.committed_at = now;
durable_write(
&inner.intent_path(&commit.intent.admission_id),
&encode(&commit.intent)?,
)
.map_err(error)?;
durable_write(
&inner.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
inner.committed.insert(scope, commit);
}
durable_remove(
&inner
.bodies
.join(format!("{}.lxm", hex::encode(message_id))),
&witness,
)
.map_err(error)?;
Ok(())
}
/// Prune only expired invisible TID receipts. Visible archive authority and
/// permanent UserDeleted message decisions are retained independently.
pub fn maintain(&self, now: u64) -> Result<usize, AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let expired = inner
.committed
.iter()
.filter(|(_, c)| !live(&c.intent.record, now))
.map(|(scope, c)| (*scope, c.intent.admission_id))
.collect::<Vec<_>>();
if expired.is_empty() {
return Ok(0);
}
let witness = durable_write(
&inner.journal.join("receipt-pruning-v1"),
&encode(&(1u8, &expired))?,
)
.map_err(error)?;
let mut removed = 0;
for (scope, id) in expired {
durable_remove(&inner.intent_path(&id), &witness).map_err(error)?;
durable_remove(&inner.commit_path(&id), &witness).map_err(error)?;
inner.committed.remove(&scope);
removed += 1;
}
Ok(removed)
}
pub fn pending_hooks(&self) -> Vec<([u8; 32], PathBuf)> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| !c.hook_completed)
.filter_map(|c| {
c.intent.body_path.as_ref()?;
Some((
c.intent.hook_event?,
inner.body_path(&c.intent.record.message_id),
))
})
.collect()
}
pub fn complete_hook(&self, event: [u8; 32]) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let Some(scope) = inner
.committed
.iter()
.find_map(|(s, c)| (c.intent.hook_event == Some(event)).then_some(*s))
else {
return Ok(());
};
let mut updated = inner.committed[&scope].clone();
updated.hook_completed = true;
durable_write(
&inner.commit_path(&updated.intent.admission_id),
&encode(&updated)?,
)
.map_err(error)?;
inner.committed.insert(scope, updated);
Ok(())
}
}
fn live(record: &AdmissionRecord, now: u64) -> bool {
!matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) || now.saturating_sub(record.committed_at) < POLICY_RECEIPT_LIFETIME
}
pub struct FileAdmissionCommit {
store: FileAdmissionStore,
record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
}
impl DurableAdmissionBackend for FileAdmissionCommit {
fn commit(self) -> Result<AdmissionRecord, AdmissionError> {
let mut inner = self.store.inner.lock().unwrap_or_else(|p| p.into_inner());
let parsed = crate::message::LxMessage::unpack_owned(self.wire.clone(), Default::default())
.map_err(other)?;
if parsed.message_id() != self.record.message_id {
return Err(other("admission message identity mismatch"));
}
if let Some(existing) = inner.committed.get(&self.record.scope) {
if existing.intent.record.received_wire_hash != self.record.received_wire_hash {
return Err(other("ciphertext TID receipt wire mismatch"));
}
if !inner
.deleted
.contains_key(&(self.record.scope.identity, self.record.message_id))
&& live(&existing.intent.record, self.record.committed_at)
&& matches!(
existing.intent.record.disposition,
DurableDisposition::Committed | DurableDisposition::Duplicate
)
&& self.record.disposition == DurableDisposition::Committed
{
inner.validate_body(&existing.intent)?;
let mut duplicate = existing.intent.record.clone();
duplicate.disposition = DurableDisposition::Duplicate;
return Ok(duplicate);
}
}
let mut record = self.record;
if inner
.deleted
.contains_key(&(record.scope.identity, record.message_id))
{
record.disposition = DurableDisposition::UserDeleted;
}
let invisible = matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
);
if invisible {
let existing = inner.committed.values().filter(|c| {
matches!(
c.intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) && live(&c.intent.record, record.committed_at)
});
let global = existing.clone().count();
let identity = existing
.filter(|c| c.intent.record.scope.identity == record.scope.identity)
.count();
if global >= 65536 || identity >= 16384 {
return Err(AdmissionError::DispositionLedgerFull);
}
}
let body_path = (!invisible).then(|| {
inner
.bodies
.join(format!("{}.lxm", hex::encode(record.message_id)))
});
let mut body = None;
let mut newly_visible = false;
if let Some(path) = &body_path {
match std::fs::metadata(path) {
Ok(_) => {
let existing = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
// Keep the first immutable archive. Same message ID can have
// a different fifth-stamp image; record both hashes.
let parsed = crate::message::LxMessage::unpack(&existing).map_err(other)?;
if parsed.message_id() != record.message_id {
return Err(other("existing archive has a different message ID"));
}
record.stored_message_wire_hash = Some(rns_crypto::sha::full_hash(&existing));
record.disposition = DurableDisposition::Duplicate;
body = Some(Bytes::from(existing));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
record.stored_message_wire_hash = Some(record.received_wire_hash);
newly_visible = true;
body = Some(self.wire.clone());
}
Err(e) => return Err(other(e)),
}
}
let admission_id = admission_id(&record.scope)?;
let intent = AdmissionIntent {
version: 1,
admission_id,
record: record.clone(),
body_path,
hook_event: (self.run_hook && newly_visible).then_some(admission_id),
};
durable_write(&inner.intent_path(&admission_id), &encode(&intent)?).map_err(error)?;
if let (Some(path), Some(body)) = (&intent.body_path, body) {
if newly_visible {
durable_write(path, &body).map_err(error)?;
} else {
durable_reconcile(path, &body).map_err(error)?;
}
}
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(&inner.commit_path(&admission_id), &encode(&commit)?).map_err(error)?;
inner.committed.insert(record.scope, commit);
Ok(record)
}
}
impl Inner {
fn body_path(&self, message_id: &[u8; 32]) -> PathBuf {
self.bodies.join(format!("{}.lxm", hex::encode(message_id)))
}
fn intent_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.intent", hex::encode(id)))
}
fn commit_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.commit", hex::encode(id)))
}
fn validate_body(&self, intent: &AdmissionIntent) -> Result<(), AdmissionError> {
if intent.version != 1 || admission_id(&intent.record.scope)? != intent.admission_id {
return Err(other("unknown admission journal version or identity"));
}
if self
.deleted
.contains_key(&(intent.record.scope.identity, intent.record.message_id))
&& intent.record.disposition != DurableDisposition::UserDeleted
{
return Err(other("message was explicitly deleted"));
}
if let Some(path) = &intent.body_path {
if path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
{
return Err(other("admission archive path escapes configured inbox"));
}
// A journal written before the bodies moved names the old directory.
let journaled = path;
let path = &self.body_path(&intent.record.message_id);
if !path.exists()
&& self.legacy_bodies.is_some()
&& journaled.parent() == self.legacy_bodies.as_deref()
&& journaled.exists()
{
std::fs::rename(journaled, path).map_err(other)?;
}
let body = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
if Some(rns_crypto::sha::full_hash(&body)) != intent.record.stored_message_wire_hash {
return Err(other("admission archive content mismatch"));
}
// A previous CommitUncertain becomes authoritative only after all
// native barriers succeed again, never merely after readback.
durable_reconcile(path, &body).map_err(error)?;
} else if !matches!(
intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) {
return Err(other("visible admission is missing its archive"));
}
Ok(())
}
fn recover(&mut self) -> Result<(), AdmissionError> {
// Stream directory passes: directory size must not itself allocate an
// unbounded vector. Malformed artifacts remain private and unavailable.
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("deleted") {
continue;
}
let data = read_bounded(&path, 2048)?;
let tombstone: UserDeletedMessage = rmp_serde::from_slice(&data).map_err(other)?;
if tombstone.version != 1
|| path.file_name().and_then(|s| s.to_str())
!= Some(
format!(
"{}-{}.deleted",
hex::encode(tombstone.identity),
hex::encode(tombstone.message_id)
)
.as_str(),
)
{
return Err(other("invalid user deletion tombstone"));
}
let witness = durable_reconcile(&path, &data).map_err(error)?;
durable_remove(
&self
.bodies
.join(format!("{}.lxm", hex::encode(tombstone.message_id))),
&witness,
)
.map_err(error)?;
self.deleted
.insert((tombstone.identity, tombstone.message_id), tombstone);
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("commit") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let commit: AdmissionCommit = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.commit_path(&commit.intent.admission_id) {
return Err(other("commit filename mismatch"));
}
self.validate_body(&commit.intent)?;
durable_reconcile(&path, &data).map_err(error)?;
Ok(commit)
})();
match result {
Ok(commit) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"unavailable admission preserved without purge authority")
}
}
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("intent") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let intent: AdmissionIntent = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.intent_path(&intent.admission_id) {
return Err(other("intent filename mismatch"));
}
if self
.committed
.get(&intent.record.scope)
.is_some_and(|c| c.intent.record == intent.record)
{
return Ok(None);
}
self.validate_body(&intent)?;
durable_reconcile(&path, &data).map_err(error)?;
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(
&self.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
Ok(Some(commit))
})();
match result {
Ok(Some(commit)) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Ok(None) => {}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"uncommitted admission preserved without purge authority")
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn committed_receipt_survives_reopen_and_hook_is_in_same_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
let receipt = DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
assert_eq!(
receipt.record().received_wire_hash,
rns_crypto::sha::full_hash(message.wire_bytes())
);
drop(store);
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
recovered
.complete_hook(recovered.pending_hooks()[0].0)
.unwrap();
assert!(recovered.pending_hooks().is_empty());
}
/// A store whose one committed body sits in `<temp>/messages`.
fn store_with_body_in_inbox() -> (tempfile::TempDir, PathBuf, String, AdmissionScope, Vec<u8>) {
let temp = tempfile::tempdir().unwrap();
let inbox = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &inbox).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
drop(store);
let name = format!("{}.lxm", hex::encode(message.message_id()));
assert!(inbox.join(&name).exists());
(temp, inbox, name, scope, message.wire_bytes().to_vec())
}
#[test]
fn bodies_journaled_in_the_inbox_move_to_a_new_bodies_directory_on_open() {
let (temp, inbox, name, scope, wire) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let reopened =
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &inbox).unwrap();
assert!(!inbox.join(&name).exists());
assert_eq!(std::fs::read(bodies.join(&name)).unwrap(), wire);
assert_eq!(
reopened.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(reopened.pending_hooks()[0].1, bodies.join(&name));
}
#[test]
fn bodies_are_moved_in_only_from_the_named_legacy_directory() {
let (temp, inbox, name, _, _) = store_with_body_in_inbox();
let bodies = temp.path().join("bodies");
let elsewhere = temp.path().join("elsewhere");
for _ in [
FileAdmissionStore::open(temp.path(), &bodies),
FileAdmissionStore::open_moving_bodies_from(temp.path(), &bodies, &elsewhere),
] {
assert!(inbox.join(&name).exists());
assert!(!bodies.join(&name).exists());
}
}
}
+103 -20
View File
@@ -9,6 +9,7 @@ pub const FIELD_ICON_APPEARANCE: u8 = 0x04;
pub const FIELD_FILE_ATTACHMENTS: u8 = 0x05;
pub const FIELD_IMAGE: u8 = 0x06;
pub const FIELD_AUDIO: u8 = 0x07;
/// Bytes, full thread ID hash.
pub const FIELD_THREAD: u8 = 0x08;
pub const FIELD_COMMANDS: u8 = 0x09;
pub const FIELD_RESULTS: u8 = 0x0A;
@@ -17,6 +18,22 @@ pub const FIELD_TICKET: u8 = 0x0C;
pub const FIELD_EVENT: u8 = 0x0D;
pub const FIELD_RNR_REFS: u8 = 0x0E;
pub const FIELD_RENDERER: u8 = 0x0F;
/// Bytes, full `LXMessage` hash. Python reference: LXMF.py.
pub const FIELD_REPLY_TO: u8 = 0x30;
/// 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.
pub const FIELD_REACTION: u8 = 0x40;
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py.
pub const FIELD_COMMENT: u8 = 0x41;
/// 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.
pub const FIELD_CUSTOM_TYPE: u8 = 0xFB;
pub const FIELD_CUSTOM_DATA: u8 = 0xFC;
pub const FIELD_CUSTOM_META: u8 = 0xFD;
@@ -49,12 +66,40 @@ pub const RENDERER_MICRON: u8 = 0x01;
pub const RENDERER_MARKDOWN: u8 = 0x02;
pub const RENDERER_BBCODE: u8 = 0x03;
// Clients choose how to handle reaction content, if at all. While reactions
// are typically a single unicode emoji or similar, the exact implementation
// and sanitization is left up to the client. FIELD_REACTION dict keys —
// Python reference: LXMF.py.
/// Bytes, full `LXMessage` hash.
pub const REACTION_TO: u8 = 0x00;
/// Bytes, the reaction content in UTF-8 encoding.
pub const REACTION_CONTENT: u8 = 0x01;
// Comment content is carried as the normal LXM content, so clients that do
// not support comments display them as normal messages. FIELD_COMMENT dict
// key — Python reference: LXMF.py.
/// 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.
/// 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;
@@ -114,6 +159,14 @@ pub const STRUCT_OVERHEAD: usize = 8;
/// 2 * dest(16) + sig(64) + timestamp(8) + struct(8) = 112.
pub const LXMF_OVERHEAD: usize =
2 * DESTINATION_LENGTH + SIGNATURE_LENGTH + TIMESTAMP_SIZE + STRUCT_OVERHEAD;
/// Largest content an opportunistic message carries in one encrypted packet;
/// the packet's destination supplies the destination hash. 383 - 112 + 16 = 287.
pub const ENCRYPTED_PACKET_MAX_CONTENT: usize =
rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH;
/// Largest content of an unencrypted single packet to a PLAIN destination.
/// 464 - 112 + 16 = 368.
pub const PLAIN_PACKET_MAX_CONTENT: usize =
rns_wire::constants::PLAIN_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH;
pub const PAPER_MDU: usize = 2210;
pub const TICKET_EXPIRY: u64 = 21 * 24 * 60 * 60;
@@ -121,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).
@@ -131,27 +184,34 @@ pub const PATH_REQUEST_WAIT: u64 = 7;
pub const MAX_PATHLESS_TRIES: u32 = 1;
/// Maximum link inactivity before teardown (seconds).
pub const LINK_MAX_INACTIVITY: u64 = 10 * 60;
/// Maximum propagation link inactivity (seconds).
/// Inbound propagation links with no data for this long are torn down (seconds).
pub const P_LINK_MAX_INACTIVITY: u64 = 3 * 60;
pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
/// Delay before announcing propagation node (seconds).
pub const NODE_ANNOUNCE_DELAY: u64 = 20;
/// LXMF configuration and announce values use decimal kilobytes, matching
/// Python's `limit_kb * 1000` accounting.
pub const BYTES_PER_KILOBYTE: usize = 1000;
pub const PROPAGATION_LIMIT: usize = 256;
pub const DELIVERY_LIMIT: usize = 1000;
/// PROPAGATION_LIMIT * 40, in KB.
pub const SYNC_LIMIT: usize = 10240;
pub const PROPAGATION_COST_MIN: u8 = 13;
pub const PROPAGATION_COST: u8 = 16;
pub const PROPAGATION_COST_FLEX: u8 = 3;
pub const PEERING_COST: u8 = 18;
pub const MAX_PEERING_COST: u8 = 26;
/// Link-request stamp cost announced by delivery destinations (LXMRouter.py).
pub const DELIVERY_LINK_COST: f64 = 3.25;
/// Link-request stamp cost announced by propagation destinations (LXMRouter.py).
pub const PROPAGATION_LINK_COST: f64 = 3.25;
pub const PROPAGATION_COST_MIN: f64 = 13.0;
pub const PROPAGATION_COST: f64 = 16.0;
pub const PROPAGATION_COST_FLEX: f64 = 3.0;
pub const PEERING_COST: f64 = 18.0;
pub const MAX_PEERING_COST: f64 = 26.0;
pub const MAX_PEERS: usize = 20;
pub const PN_STAMP_THROTTLE: u64 = 180;
pub const PN_STAMP_THROTTLE: u64 = 300;
pub const AUTOPEER: bool = true;
pub const AUTOPEER_MAXDEPTH: usize = 4;
/// When selecting peers for sync, pick from the N fastest.
/// Size of the fastest-peer pool considered alongside unknown-speed peers.
pub const FASTEST_N_RANDOM_POOL: usize = 2;
/// Percentage of max_peers kept as headroom for rotation.
pub const ROTATION_HEADROOM_PCT: usize = 10;
@@ -168,12 +228,12 @@ pub const DUPLICATE_SIGNAL: &str = "lxmf_duplicate";
pub const OFFER_REQUEST_PATH: &str = "/offer";
pub const MESSAGE_GET_PATH: &str = "/get";
/// Maximum time a peer can be unreachable before removal (14 days).
/// Age since last contact after which `mark_unreachable` marks a peer not alive (14 days).
pub const MAX_UNREACHABLE: u64 = 14 * 24 * 60 * 60;
/// Sync backoff step per consecutive failure (12 minutes).
pub const SYNC_BACKOFF_STEP: u64 = 12 * 60;
pub const PATH_REQUEST_GRACE: f64 = 7.5;
/// Maximum time a peer can be stale before rotation (14 days).
/// Age since last contact used by the peer staleness check (14 days).
pub const PEER_STALE_TIME: u64 = 14 * 24 * 60 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -218,22 +278,25 @@ pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PN: usize = 1000;
pub const STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING: usize = 25;
/// SHA-256 output length.
pub const STAMP_SIZE: usize = 32;
/// Minimum batch size before using parallel validation pool.
/// Python propagation-validation pool threshold, retained as a reference constant.
pub const PN_VALIDATION_POOL_MIN_SIZE: usize = 256;
/// Interval (in ticks) for processing outbound messages.
/// Python outbound-processing cadence in ticks; retained as a reference constant.
pub const JOB_OUTBOUND_INTERVAL: u64 = 1;
/// Interval (in ticks) for processing deferred stamps.
/// Python deferred-stamp cadence in ticks; retained as a reference constant.
pub const JOB_STAMPS_INTERVAL: u64 = 1;
/// Interval (in ticks) for cleaning inactive links.
/// Python inactive-link cleanup cadence in ticks; retained as a reference constant.
pub const JOB_LINKS_INTERVAL: u64 = 1;
/// Interval (in ticks) for cleaning transient ID caches.
pub const JOB_TRANSIENT_INTERVAL: u64 = 60;
/// Interval (in ticks) for cleaning the message store.
pub const JOB_STORE_INTERVAL: u64 = 120;
/// Interval (in ticks) for syncing peers.
/// Interval (in ticks) for culling stamp costs and expired tickets.
pub const JOB_STAMPCOST_INTERVAL: u64 = 120;
/// Tick interval for cleaning throttled-peer entries, named for Python
/// peer-sync cadence. Peer synchronization is driven by the embedding runtime.
pub const JOB_PEERSYNC_INTERVAL: u64 = 6;
/// Interval (in ticks) for ingesting peer distribution queues.
/// Python peer-distribution ingestion cadence in ticks; retained as a reference constant.
pub const JOB_PEERINGEST_INTERVAL: u64 = 6;
/// 56 * JOB_PEERINGEST_INTERVAL.
pub const JOB_ROTATE_INTERVAL: u64 = 56 * 6;
@@ -251,6 +314,12 @@ mod tests {
assert_eq!(LXMF_OVERHEAD, 112);
}
/// LXMF 1.2.0 `ENCRYPTED_PACKET_MAX_CONTENT` (LXMessage.pyfc60af).
#[test]
fn encrypted_packet_max_content_is_lxmf_1_2_0s() {
assert_eq!(ENCRYPTED_PACKET_MAX_CONTENT, 287);
}
#[test]
fn test_message_states_distinct() {
assert_ne!(MessageState::Generating as u8, MessageState::Outbound as u8);
@@ -283,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]
@@ -322,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);
}
@@ -341,4 +410,18 @@ mod tests {
assert_eq!(MAX_UNREACHABLE, 14 * 24 * 60 * 60);
assert_eq!(SYNC_BACKOFF_STEP, 12 * 60);
}
#[test]
fn test_field_standards_match_python_101() {
// LXMF.py 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);
assert_eq!(FIELD_COMMENT, 0x41);
assert_eq!(FIELD_CONTINUATION, 0x42);
assert_eq!(REACTION_TO, 0x00);
assert_eq!(REACTION_CONTENT, 0x01);
assert_eq!(COMMENT_FOR, 0x00);
assert_eq!(CONTINUATION_OF, 0x00);
}
}
+608
View File
@@ -0,0 +1,608 @@
//! Crash-safe ratchet ownership for an LXMF delivery destination.
//!
//! A delivery announce is returned only after any candidate private ratchet
//! and the associated announce-ordering state are durably committed. The
//! propagation destination intentionally does not use this type.
use std::path::{Path, PathBuf};
use rns_identity::announce::AnnounceStampExt;
use rns_identity::announce_state::RatchetControlState;
use rns_identity::destination::{AnnounceTime, DestType, Destination, Direction};
use rns_identity::identity::Identity;
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
use thiserror::Error;
/// Reticulum aspect used by an LXMF delivery destination.
pub const DELIVERY_APP_NAME: &str = "lxmf.delivery";
/// Whether a delivery announce is a normal broadcast or a tagged path reply.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryAnnounceKind<'a> {
Broadcast,
PathResponse { tag: Option<&'a [u8]> },
}
#[derive(Debug, Error)]
pub enum DeliveryRatchetError {
#[error("LXMF delivery destination does not match the supplied identity")]
DestinationMismatch,
#[error("ratchet control state at {path} is untrusted; refusing to overwrite it")]
UntrustedControl { path: PathBuf },
#[error("announce coalesced until wall time advances")]
Coalesced,
#[error("failed to plan announce time: {0}")]
Plan(#[source] std::io::Error),
#[error("failed to persist announce ordering state at {path}: {source}")]
PersistControl {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error(transparent)]
Destination(#[from] rns_identity::destination::DestinationError),
#[error("internal ratchet invariant failed: {0}")]
Invariant(&'static str),
}
/// Owns the private-key ring, signed control sidecar, and exact tagged-response
/// cache for one `lxmf.delivery` destination.
pub struct DeliveryRatchetState {
destination: Destination,
ring: RatchetRing,
control: RatchetControlState,
ring_path: PathBuf,
control_path: PathBuf,
ring_file_trusted: bool,
control_file_trusted: bool,
}
impl DeliveryRatchetState {
/// Load canonical or legacy Rust state, preserving rejected files in place.
/// Canonical signatures cover the packed key list. Accepted legacy signatures
/// cover only the current public key, not retained old keys; canonical rewrite
/// is best-effort and does not establish their historical authenticity.
/// A failed rewrite does not prevent use of the accepted legacy ring.
///
/// A missing ring is generated and persisted before it becomes live. A
/// ring that cannot be stored leaves delivery available but unratcheted.
/// An invalid control sidecar defers new announces because their ordering
/// cannot be proven safely.
pub fn load_or_initialize(
identity: &Identity,
destination_hash: [u8; 16],
ring_path: PathBuf,
control_path: PathBuf,
wall_now: u64,
) -> Result<Self, DeliveryRatchetError> {
let mut destination = Destination::new(
Some(identity),
Direction::In,
DestType::Single,
DELIVERY_APP_NAME,
)?;
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 {
match RatchetRing::load_verified(&ring_path, identity) {
Ok(loaded) => {
let format = loaded.format();
let ring = loaded.into_ring();
if format == RatchetRingFormat::LegacyRust {
match ring.save_verified_durable(&ring_path, identity) {
Ok(()) => tracing::info!(
path = %ring_path.display(),
"migrated legacy Rust ratchet ring to canonical format"
),
Err(error) => tracing::warn!(
path = %ring_path.display(),
%error,
"legacy ratchet ring is valid but canonical rewrite failed"
),
}
}
(ring, true)
}
Err(error) => {
tracing::error!(
path = %ring_path.display(),
%error,
"ratchet ring is untrusted; preserving it and announcing without a ratchet"
);
(RatchetRing::new(), false)
}
}
} else {
(RatchetRing::new(), true)
};
let control_existed = control_path.exists();
let (mut control, control_file_trusted) = if control_existed {
match RatchetControlState::load_verified(&control_path, identity, destination_hash) {
Ok(state) => (state, true),
Err(error) => {
tracing::error!(
path = %control_path.display(),
%error,
"ratchet control state is untrusted; preserving it and deferring new announces"
);
(
RatchetControlState::new(identity.hash, destination_hash),
false,
)
}
}
} else {
(
RatchetControlState::new(identity.hash, destination_hash),
true,
)
};
let mut control_changed = false;
if control_file_trusted && control.last_rotation_wall().is_none() {
control.anchor_rotation_if_unknown(wall_now);
control_changed = true;
}
if ring.is_empty() && ring_file_trusted && control_file_trusted {
let prepared = ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified_durable(&ring_path, identity) {
Ok(()) => {
ring.commit_prepared_rotation(prepared);
control = control.with_rotation_at(wall_now);
control_changed = true;
}
Err(error) => tracing::error!(
path = %ring_path.display(),
%error,
"could not durably initialise ratchet ring; delivery announces will be unratcheted"
),
}
}
if control_file_trusted
&& (!control_existed || control_changed)
&& let Err(error) = control.save_verified_durable(&control_path, identity)
{
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
}
Ok(Self {
destination,
ring,
control,
ring_path,
control_path,
ring_file_trusted,
control_file_trusted,
})
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination.hash
}
/// 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
}
pub fn control(&self) -> &RatchetControlState {
&self.control
}
/// Build an announce after committing all state that its wire bytes claim.
///
/// `wall_now` supplies both rotation age and the 40-bit wire ordering
/// value. `cache_now` is a separate local elapsed-time domain used only for
/// tagged path-response expiry. `stamp_ext` is appended to the app data
/// when the stamp policy stamps destinations.
pub fn create_announce(
&mut self,
identity: &Identity,
app_data: &[u8],
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);
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
&& let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
}
if !self.control_file_trusted {
return Err(DeliveryRatchetError::UntrustedControl {
path: self.control_path.clone(),
});
}
let Some(mut candidate_control) = self
.control
.prepare_announce(wall_now)
.map_err(DeliveryRatchetError::Plan)?
else {
return Err(DeliveryRatchetError::Coalesced);
};
let rotation_due = self.ring.is_empty()
|| self
.control
.rotation_due(wall_now, self.ring.ratchet_interval());
let mut prepared_rotation = None;
let mut ratchet_public = self.ring.current_public_key();
if rotation_due && self.ring_file_trusted {
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
match prepared
.ring()
.save_verified_durable(&self.ring_path, identity)
{
Ok(()) => {
ratchet_public = Some(prepared.public_key());
candidate_control = candidate_control.with_rotation_at(wall_now);
prepared_rotation = Some(prepared);
}
Err(error) => tracing::error!(
path = %self.ring_path.display(),
%error,
"ratchet rotation was not persisted; reusing the last durable ratchet"
),
}
}
candidate_control
.save_verified_durable(&self.control_path, identity)
.map_err(|source| DeliveryRatchetError::PersistControl {
path: self.control_path.clone(),
source,
})?;
let wire_now =
candidate_control
.last_announce_wire()
.ok_or(DeliveryRatchetError::Invariant(
"prepared announce has no wire-order value",
))?;
if let Some(prepared) = prepared_rotation {
self.ring.commit_prepared_rotation(prepared);
}
self.control = candidate_control;
let (path_response, tag) = match kind {
DeliveryAnnounceKind::Broadcast => (false, None),
DeliveryAnnounceKind::PathResponse { tag } => (true, tag),
};
self.destination
.announce_packet_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)
}
/// Best-effort shutdown checkpoint. Invalid files detected during load are
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted
&& let Err(error) = self.ring.save_verified_durable(&self.ring_path, identity)
{
tracing::warn!(%error, "failed to save ratchet ring");
}
if self.control_file_trusted
&& let Err(error) = self
.control
.save_verified_durable(&self.control_path, identity)
{
tracing::warn!(%error, "failed to save ratchet control state");
}
}
/// Checked strict checkpoint. Invalid files discovered during load remain
/// untouched and prevent a successful checkpoint claim.
pub fn save_durable(&self, identity: &Identity) -> std::io::Result<()> {
if !self.ring_file_trusted || !self.control_file_trusted {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"ratchet checkpoint contains untrusted state",
));
}
self.ring.save_verified_durable(&self.ring_path, identity)?;
self.control
.save_verified_durable(&self.control_path, identity)
}
pub fn ring_path(&self) -> &Path {
&self.ring_path
}
pub fn control_path(&self) -> &Path {
&self.control_path
}
}
#[cfg(test)]
mod tests {
use super::*;
use rns_identity::ratchet::ratchet_public_bytes;
fn unpack_announce(
raw: &[u8],
) -> (
rns_wire::header::PacketHeader,
rns_identity::announce::AnnounceData,
) {
let (header, header_len) = rns_wire::header::PacketHeader::unpack(raw).unwrap();
let announce = rns_identity::announce::AnnounceData::unpack(
&raw[header_len..],
header.flags.context_flag,
)
.unwrap();
(header, announce)
}
fn state_at(dir: &Path, identity: &Identity, wall_now: u64) -> DeliveryRatchetState {
let destination_hash =
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
DeliveryRatchetState::load_or_initialize(
identity,
destination_hash,
dir.join("ring"),
dir.join("ring.control"),
wall_now,
)
.unwrap()
}
#[test]
fn survives_restart_rotates_and_retains_the_previous_private_key() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let initial_public = state.ring.current_public_key().unwrap();
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
assert!(header.flags.context_flag);
assert_eq!(announce.ratchet, Some(initial_public));
let committed_wire_time = state.control.last_announce_wire();
assert!(matches!(
state.create_announce(
&identity,
b"changed",
101,
101.5,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Coalesced)
));
assert_eq!(state.control.last_announce_wire(), committed_wire_time);
let mut restarted = state_at(dir.path(), &identity, 102);
assert_eq!(restarted.ring.current_public_key(), Some(initial_public));
let raw = restarted
.create_announce(
&identity,
b"app",
102,
102.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert_eq!(unpack_announce(&raw).1.ratchet, Some(initial_public));
let rotate_at = 100 + restarted.ring.ratchet_interval();
let raw = restarted
.create_announce(
&identity,
b"app",
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let rotated_public = unpack_announce(&raw).1.ratchet.unwrap();
assert_ne!(rotated_public, initial_public);
assert_eq!(restarted.ring.len(), 2);
assert!(
restarted
.ring
.private_keys()
.iter()
.any(|private| ratchet_public_bytes(private) == initial_public)
);
}
#[test]
fn unavailable_ring_storage_can_only_emit_an_unratcheted_announce() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let destination =
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
let mut state = DeliveryRatchetState::load_or_initialize(
&identity,
destination,
dir.path().join("missing/ring"),
dir.path().join("ring.control"),
100,
)
.unwrap();
assert!(state.ring.is_empty());
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
assert!(!header.flags.context_flag);
assert_eq!(announce.ratchet, None);
assert!(state.ring.is_empty());
}
#[test]
fn corrupt_ring_is_preserved_and_never_advertised() {
let dir = tempfile::tempdir().unwrap();
let ring_path = dir.path().join("ring");
let corrupt = b"not-a-ratchet-ring";
std::fs::write(&ring_path, corrupt).unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
assert!(!unpack_announce(&raw).0.flags.context_flag);
assert_eq!(std::fs::read(ring_path).unwrap(), corrupt);
}
#[test]
fn failed_control_commit_cannot_publish_or_commit_a_prepared_rotation() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
None,
)
.unwrap();
let live_public = state.ring.current_public_key();
let live_wire_time = state.control.last_announce_wire();
state.control_path = dir.path().join("missing/ring.control");
let rotate_at = 100 + state.ring.ratchet_interval();
assert!(matches!(
state.create_announce(
&identity,
b"app",
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::PersistControl { .. })
));
assert_eq!(state.ring.current_public_key(), live_public);
assert_eq!(state.control.last_announce_wire(), live_wire_time);
}
#[test]
fn same_tag_replays_exact_packet_without_consuming_announce_time() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let tag = b"path-request-tag";
let first = state
.create_announce(
&identity,
b"first",
101,
101.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
let committed_wire = state.control.last_announce_wire();
let replay = state
.create_announce(
&identity,
b"changed",
101,
102.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
None,
)
.unwrap();
assert_eq!(
replay, first,
"removing the cache lookup changes signed bytes"
);
assert_eq!(state.control.last_announce_wire(), committed_wire);
assert_eq!(
unpack_announce(&replay).0.context,
rns_wire::context::PacketContext::PathResponse
);
}
#[test]
fn invalid_cache_clock_cannot_commit_announce_state() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let live_wire = state.control.last_announce_wire();
let live_public = state.ring.current_public_key();
assert!(matches!(
state.create_announce(
&identity,
b"app",
101,
f64::NAN,
DeliveryAnnounceKind::Broadcast,
None,
),
Err(DeliveryRatchetError::Destination(_))
));
assert_eq!(state.control.last_announce_wire(), live_wire);
assert_eq!(state.ring.current_public_key(), live_public);
}
}
+89 -147
View File
@@ -1,27 +1,19 @@
//! LXMF-backed stamper for Reticulum interface discovery.
//!
//! # Layering
//!
//! Python `RNS/Discovery.py:41` imports `LXMF.LXStamper` directly; the
//! discovery subsystem cannot work without LXMF installed. Rust keeps
//! Reticulum below LXMF, so `rns-transport` depends on a trait object and
//! the concrete implementation lives here.
//!
//! # Workblock: Python parity
//!
//! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)`
//! (RNS/Discovery.py:220), where `stamp_workblock` is the
//! HKDF-expanded construction: one HKDF expand per round, each round
//! producing 256 bytes, total `expand_rounds * 256` bytes.
//!
//! The matching Rust primitive is [`crate::stamper::stamp_workblock_raw`]
//! (the plain `stamp_workblock` in `lxmf-core` uses an iterative
//! SHA-256 workblock for a *different* path and is **not** wire
//! compatible with Python's discovery stamps).
//! 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_raw, stamp_value_raw, stamp_workblock_raw};
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.
@@ -30,103 +22,64 @@ use crate::stamper::{stamp_valid_raw, stamp_value_raw, stamp_workblock_raw};
/// interface, so this path has to stay cheap enough for periodic announces.
pub const DISCOVERY_WORKBLOCK_EXPAND_ROUNDS: usize = 20;
/// Upper bound on the random-stamp search before we give up on a given
/// tick. If the cap is hit, the announcer skips this cycle and tries again
/// rather than pinning a blocking worker indefinitely.
///
/// Python has no equivalent cap (it blocks until success); we cap so
/// `spawn_blocking` threads cannot be stuck forever if the user
/// misconfigures `discover_interfaces_required_value` to something
/// unreasonable.
/// Attempt budget for [`generate_discovery_stamp`] callers. The
/// [`LxmfDiscoveryStamper`] trait implementation has no cap.
pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000;
/// PoW stamper for on-network discovery announces. Thin wrapper around
/// [`lxmf_core::stamper`](crate::stamper) that binds the exact Python
/// discovery construction (HKDF workblock with 20 expand rounds).
///
/// Clonable and `Send + Sync`; the default instance is fine for most
/// users.
/// Discovery stamper; delegates to
/// [`rns_transport::discovery::RnsDiscoveryStamper`], which has no attempt cap.
#[derive(Debug, Clone, Default)]
pub struct LxmfDiscoveryStamper {
/// Override the iteration cap; defaults to [`DISCOVERY_MAX_ITERATIONS`].
/// Zero means "use the default".
max_iterations: u64,
_private: (),
}
impl LxmfDiscoveryStamper {
/// Build a stamper with a custom iteration cap. Most callers want
/// [`LxmfDiscoveryStamper::default`].
pub fn with_max_iterations(max_iterations: u64) -> Self {
Self { max_iterations }
}
fn effective_max_iterations(&self) -> u64 {
if self.max_iterations == 0 {
DISCOVERY_MAX_ITERATIONS
} else {
self.max_iterations
}
/// Discovery generation has no attempt cap upstream; the argument is ignored.
#[deprecated(note = "discovery stamp generation has no attempt cap; use `default()`")]
pub fn with_max_iterations(_max_iterations: u64) -> Self {
Self::default()
}
}
impl DiscoveryStamper for LxmfDiscoveryStamper {
fn generate(&self, infohash: &[u8; 32], target_value: u8) -> Option<Vec<u8>> {
if target_value == 0 {
return Some(vec![0u8; 32]);
}
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..self.effective_max_iterations() {
let candidate = crate::stamper::rand_bytes();
if stamp_valid_raw(&candidate, target_value, &workblock) {
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_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let v = stamp_value_raw(&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_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
stamp_valid_raw(&stamp_arr, required_value, &workblock)
fn valid(&self, infohash: &[u8; 32], stamp: &[u8], required_value: f64) -> bool {
rns_transport::discovery::RnsDiscoveryStamper.valid(infohash, stamp, required_value)
}
fn validate(&self, infohash: &[u8; 32], stamp: &[u8], required_value: f64) -> Option<f64> {
rns_transport::discovery::RnsDiscoveryStamper.validate(infohash, stamp, required_value)
}
}
/// Validation helper: synchronous wrapper mirroring
/// [`crate::stamper::generate_stamp_limited`] but using the HKDF
/// workblock construction. Public so interop tests and downstream validation
/// can exercise discovery stamping without a transport runtime.
/// Synchronous discovery stamp search with 20 HKDF workblock rounds and an
/// explicit attempt limit. Uses the same construction as
/// [`crate::stamper::generate_stamp`], without a transport runtime.
/// For nonzero cost, a zero iteration limit returns `None`.
pub fn generate_discovery_stamp(
infohash: &[u8; 32],
target_value: u8,
max_iterations: u64,
) -> Option<[u8; 32]> {
if target_value == 0 {
return Some([0u8; 32]);
return Some(random_stamp());
}
let workblock = stamp_workblock_raw(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
let workblock = stamp_workblock(infohash, DISCOVERY_WORKBLOCK_EXPAND_ROUNDS);
for _ in 0..max_iterations {
let candidate = crate::stamper::rand_bytes();
if stamp_valid_raw(&candidate, target_value, &workblock) {
let candidate = random_stamp();
if stamp_valid(&candidate, f64::from(target_value), &workblock) {
return Some(candidate);
}
}
@@ -137,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]
@@ -223,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
+545
View File
@@ -0,0 +1,545 @@
//! Actor-owned tracking for inbound LXMF delivery Resources.
//!
//! The Reticulum runtime owns the actual transfers. Embedders project its
//! lifecycle notifications into [`InboundResourceEvent`] and forward bounded
//! [`InboundResourceCancelRequest`] values back to that owner. This keeps the
//! public LXMF API independent of a concrete Reticulum runtime while retaining
//! exact `(link_id, logical_resource_id)` cancellation authority.
use std::collections::HashMap;
use tokio::sync::{mpsc, watch};
/// Exact owner key for one logical inbound Resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct InboundResourceKey {
pub link_id: [u8; 16],
pub resource_id: [u8; 32],
}
impl InboundResourceKey {
pub const fn new(link_id: [u8; 16], resource_id: [u8; 32]) -> Self {
Self {
link_id,
resource_id,
}
}
}
/// Terminal result of an inbound Resource transfer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InboundResourceConclusion {
Complete,
Cancelled,
Rejected,
Failed,
}
/// Current public state of an inbound Resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InboundResourceStatus {
Receiving,
Complete,
Cancelled,
Rejected,
Failed,
}
impl InboundResourceStatus {
pub const fn is_closed(self) -> bool {
!matches!(self, Self::Receiving)
}
}
impl From<InboundResourceConclusion> for InboundResourceStatus {
fn from(value: InboundResourceConclusion) -> Self {
match value {
InboundResourceConclusion::Complete => Self::Complete,
InboundResourceConclusion::Cancelled => Self::Cancelled,
InboundResourceConclusion::Rejected => Self::Rejected,
InboundResourceConclusion::Failed => Self::Failed,
}
}
}
/// Owned snapshot containing link/Resource IDs, sizes, progress and status.
/// It contains no transferred payload bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InboundResourceSnapshot {
pub key: InboundResourceKey,
pub data_size: usize,
pub transferred: usize,
pub total_segments: usize,
pub status: InboundResourceStatus,
}
impl InboundResourceSnapshot {
pub const fn is_closed(&self) -> bool {
self.status.is_closed()
}
}
/// Transport-neutral lifecycle input consumed by [`InboundResourceTracker`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InboundResourceEvent {
Started {
key: InboundResourceKey,
data_size: usize,
total_segments: usize,
},
Progress {
key: InboundResourceKey,
transferred: usize,
total: usize,
},
Concluded {
key: InboundResourceKey,
conclusion: InboundResourceConclusion,
},
LinkClosed {
link_id: [u8; 16],
},
}
/// Exact cancellation request for the embedding runtime's Resource owner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InboundResourceCancelRequest {
key: InboundResourceKey,
}
impl InboundResourceCancelRequest {
pub const fn new(key: InboundResourceKey) -> Self {
Self { key }
}
pub const fn key(self) -> InboundResourceKey {
self.key
}
}
/// Cloneable live handle retained by a caller after the active list changes.
#[derive(Debug, Clone)]
pub struct InboundResourceHandle {
key: InboundResourceKey,
snapshot_rx: watch::Receiver<InboundResourceSnapshot>,
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
}
impl InboundResourceHandle {
pub const fn key(&self) -> InboundResourceKey {
self.key
}
pub fn snapshot(&self) -> InboundResourceSnapshot {
self.snapshot_rx.borrow().clone()
}
/// Wait for an unseen lifecycle/progress state. Intermediate updates may
/// be coalesced by the watch channel.
///
/// Returns `None` once the sender is gone and its latest value has been seen.
/// Dropping the tracker can close the channel without publishing a terminal
/// state; terminal states require the corresponding lifecycle event.
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
if self.snapshot_rx.changed().await.is_err() {
return None;
}
Some(self.snapshot())
}
/// Queue exact inbound cancellation without blocking the actor owner.
///
/// `false` means the transfer is already closed, cancellation is not
/// wired by the embedder, or the bounded command channel cannot accept the
/// request. Authoritative closure arrives through the lifecycle stream.
pub fn cancel(&self) -> bool {
if self.snapshot().is_closed() {
return false;
}
self.cancel_tx.as_ref().is_some_and(|tx| {
tx.try_send(InboundResourceCancelRequest::new(self.key))
.is_ok()
})
}
/// 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 {
snapshot_tx: watch::Sender<InboundResourceSnapshot>,
}
/// Single-owner active Resource registry.
///
/// Concluded and LinkClosed events remove records immediately. The embedder
/// must forward those events to keep the registry limited to active transfers;
/// the tracker has no independent entry cap or timeout. Previously returned
/// handles retain their latest snapshot without keeping tracker state alive.
#[derive(Default)]
pub struct InboundResourceTracker {
active: HashMap<InboundResourceKey, ActiveInboundResource>,
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
}
impl InboundResourceTracker {
pub fn new(cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) -> Self {
Self {
active: HashMap::new(),
cancel_tx: Some(cancel_tx),
}
}
pub fn set_cancel_sender(&mut self, cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) {
self.cancel_tx = Some(cancel_tx);
}
/// Number of currently active inbound Resources.
pub fn inbound_count(&self) -> usize {
self.active.len()
}
/// Deterministic snapshot of all active Resource handles.
pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> {
let mut keys = self.active.keys().copied().collect::<Vec<_>>();
keys.sort_unstable();
keys.into_iter()
.filter_map(|key| self.handle_for(key))
.collect()
}
/// Return the active Resource matching `resource_id`.
///
/// If the same Resource ID is active on more than one Link, returns `None`.
/// Use [`Self::inbound_resource_exact`] with the full key to disambiguate.
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
let mut matches = self
.active
.keys()
.filter(|key| &key.resource_id == resource_id)
.copied();
let key = matches.next()?;
if matches.next().is_some() {
return None;
}
self.handle_for(key)
}
/// Return one exact active Resource.
pub fn inbound_resource_exact(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
self.handle_for(key)
}
/// Queue cancellation for one unique active logical Resource.
pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool {
self.inbound_resource(resource_id)
.is_some_and(|handle| handle.cancel())
}
/// Queue cancellation for one exact active Resource.
pub fn cancel_inbound_exact(&self, key: InboundResourceKey) -> bool {
self.handle_for(key).is_some_and(|handle| handle.cancel())
}
/// Queue cancellation for a stable snapshot of every active Resource.
///
/// The returned count is the number accepted by the bounded command
/// channel, not the number of completed cancellations. Closure is reported
/// by subsequent lifecycle events.
pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resources()
.into_iter()
.filter(InboundResourceHandle::cancel)
.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 {
InboundResourceEvent::Started {
key,
data_size,
total_segments,
} => self.started(key, data_size, total_segments),
InboundResourceEvent::Progress {
key,
transferred,
total,
} => self.progress(key, transferred, total),
InboundResourceEvent::Concluded { key, conclusion } => self.concluded(key, conclusion),
InboundResourceEvent::LinkClosed { link_id } => self.link_closed(link_id),
}
}
fn handle_for(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
let active = self.active.get(&key)?;
Some(InboundResourceHandle {
key,
snapshot_rx: active.snapshot_tx.subscribe(),
cancel_tx: self.cancel_tx.clone(),
})
}
fn started(&mut self, key: InboundResourceKey, data_size: usize, total_segments: usize) {
if let Some(active) = self.active.get(&key) {
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.data_size = snapshot.data_size.max(data_size);
snapshot.total_segments = snapshot.total_segments.max(total_segments.max(1));
active.snapshot_tx.send_replace(snapshot);
return;
}
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,
transferred: 0,
total_segments: total_segments.max(1),
status: InboundResourceStatus::Receiving,
};
let (snapshot_tx, _snapshot_rx) = watch::channel(snapshot);
self.active
.insert(key, ActiveInboundResource { snapshot_tx });
}
fn progress(&mut self, key: InboundResourceKey, transferred: usize, total: usize) {
let Some(active) = self.active.get(&key) else {
return;
};
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.data_size = snapshot.data_size.max(total);
snapshot.transferred = transferred.min(snapshot.data_size);
active.snapshot_tx.send_replace(snapshot);
}
fn concluded(&mut self, key: InboundResourceKey, conclusion: InboundResourceConclusion) {
let Some(active) = self.active.remove(&key) else {
return;
};
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.status = conclusion.into();
if conclusion == InboundResourceConclusion::Complete {
snapshot.transferred = snapshot.data_size;
}
active.snapshot_tx.send_replace(snapshot);
}
fn link_closed(&mut self, link_id: [u8; 16]) {
let keys = self
.active
.keys()
.filter(|key| key.link_id == link_id)
.copied()
.collect::<Vec<_>>();
for key in keys {
self.concluded(key, InboundResourceConclusion::Failed);
}
}
}
/// 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::*;
fn key(link: u8, resource: u8) -> InboundResourceKey {
InboundResourceKey::new([link; 16], [resource; 32])
}
fn started(key: InboundResourceKey, size: usize) -> InboundResourceEvent {
InboundResourceEvent::Started {
key,
data_size: size,
total_segments: 1,
}
}
#[tokio::test]
async fn active_handle_tracks_progress_and_terminal_snapshot() {
let (cancel_tx, _cancel_rx) = mpsc::channel(4);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let resource = key(1, 2);
tracker.handle_event(started(resource, 100));
let mut handle = tracker.inbound_resource(&resource.resource_id).unwrap();
assert_eq!(tracker.inbound_count(), 1);
assert_eq!(handle.snapshot().transferred, 0);
tracker.handle_event(InboundResourceEvent::Progress {
key: resource,
transferred: 40,
total: 100,
});
assert_eq!(handle.changed().await.unwrap().transferred, 40);
tracker.handle_event(InboundResourceEvent::Concluded {
key: resource,
conclusion: InboundResourceConclusion::Complete,
});
let terminal = handle.changed().await.unwrap();
assert_eq!(terminal.status, InboundResourceStatus::Complete);
assert_eq!(terminal.transferred, 100);
assert!(terminal.is_closed());
assert_eq!(tracker.inbound_count(), 0);
assert!(!handle.cancel());
assert!(handle.changed().await.is_none());
}
#[test]
fn cancellation_is_exact_bounded_and_snapshot_based() {
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let first = key(1, 3);
let second = key(2, 4);
tracker.handle_event(started(first, 10));
tracker.handle_event(started(second, 20));
assert!(tracker.cancel_inbound(&first.resource_id));
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
assert_eq!(tracker.cancel_all_inbound(), 2);
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
assert_eq!(cancel_rx.try_recv().unwrap().key(), second);
assert!(!tracker.cancel_inbound(&[9; 32]));
}
#[test]
fn full_cancel_channel_fails_without_removing_active_state() {
let (cancel_tx, _cancel_rx) = mpsc::channel(1);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let first = key(1, 5);
let second = key(1, 6);
tracker.handle_event(started(first, 10));
tracker.handle_event(started(second, 10));
assert!(tracker.cancel_inbound_exact(first));
assert!(!tracker.cancel_inbound_exact(second));
assert_eq!(tracker.inbound_count(), 2);
}
#[test]
fn duplicate_start_preserves_one_logical_handle() {
let (cancel_tx, _cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let split = key(3, 7);
tracker.handle_event(InboundResourceEvent::Started {
key: split,
data_size: 100,
total_segments: 3,
});
tracker.handle_event(InboundResourceEvent::Started {
key: split,
data_size: 100,
total_segments: 3,
});
assert_eq!(tracker.inbound_count(), 1);
let snapshot = tracker.inbound_resource_exact(split).unwrap().snapshot();
assert_eq!(snapshot.total_segments, 3);
}
#[test]
fn rejected_or_unknown_resources_never_become_visible() {
let mut tracker = InboundResourceTracker::default();
let unknown = key(4, 8);
tracker.handle_event(InboundResourceEvent::Progress {
key: unknown,
transferred: 5,
total: 10,
});
tracker.handle_event(InboundResourceEvent::Concluded {
key: unknown,
conclusion: InboundResourceConclusion::Rejected,
});
assert_eq!(tracker.inbound_count(), 0);
}
#[tokio::test]
async fn link_close_fails_only_resources_owned_by_that_link() {
let mut tracker = InboundResourceTracker::default();
let closed = key(5, 9);
let retained = key(6, 10);
tracker.handle_event(started(closed, 10));
tracker.handle_event(started(retained, 20));
let mut closed_handle = tracker.inbound_resource_exact(closed).unwrap();
tracker.handle_event(InboundResourceEvent::LinkClosed {
link_id: closed.link_id,
});
assert_eq!(
closed_handle.changed().await.unwrap().status,
InboundResourceStatus::Failed
);
assert!(tracker.inbound_resource_exact(closed).is_none());
assert!(tracker.inbound_resource_exact(retained).is_some());
}
#[test]
fn cancel_then_complete_is_terminal_and_not_requeued() {
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let resource = key(7, 11);
tracker.handle_event(started(resource, 10));
let handle = tracker.inbound_resource_exact(resource).unwrap();
assert!(handle.cancel());
assert_eq!(cancel_rx.try_recv().unwrap().key(), resource);
tracker.handle_event(InboundResourceEvent::Concluded {
key: resource,
conclusion: InboundResourceConclusion::Complete,
});
assert_eq!(handle.snapshot().status, InboundResourceStatus::Complete);
assert!(!handle.cancel());
assert_eq!(tracker.inbound_count(), 0);
}
}
+65 -7
View File
@@ -4,17 +4,20 @@
//!
//! This crate implements the LXMF wire model and is the core LXMF building
//! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications.
//! Its Reticulum dependency is `rns-transport` from rsReticulum; LXMF sits one
//! layer above the Reticulum stack.
//! It uses rsReticulum for transport, links, identities and Resources; LXMF
//! sits one layer above the Reticulum stack.
//!
//! # Module map
//!
//! | Module | What it does |
//! | --------------------- | -------------------------------------------------- |
//! | [`message`] | Message object: fields, packing, stamp, encryption |
//! | [`router`] | Actor-driven routing and delivery state machine |
//! | [`message`] | Message types, packing, verification and encryption hooks |
//! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction |
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
//! | [`presentation`] | Safe bounded presentation of untrusted names |
//! | [`router`] | Caller-driven routing and delivery state machine |
//! | [`peer`] | Propagation-peer state and sync bookkeeping |
//! | [`propagation`] | On-disk store-and-forward message pool |
//! | [`propagation`] | In-memory propagation message index and selection |
//! | [`propagation_node`] | Propagation-node role logic |
//! | [`propagation_client`]| Client side of propagation sync |
//! | [`propagation_sync`] | Wire-level peer sync exchange |
@@ -22,9 +25,16 @@
//! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery |
//! | [`sync`] | Shared peer-to-peer sync primitives |
//! | [`link_delivery`] | Reticulum-link-based delivery path |
//! | [`handlers`] | Callback trait surface for delivery events |
//! | [`ticket`] | Small typed identifier for propagation workflows |
//! | [`handlers`] | Announce parsing and propagation control handlers |
//! | [`ticket`] | Directional tickets for bypassing recipient stamp work |
//! | [`persist`] | MessagePack-based on-disk state |
//! | [`admission`] | Durable inbox admission and receipt state |
//! | [`admission_store`] | Admission-store interface and file-backed adapter |
//! | [`propagation_admission`] | Inbound propagation offer and transfer states |
//! | [`propagation_offer`] | Propagation-offer evaluation outcomes |
//! | [`propagation_send`] | Outbound propagation payload preparation |
//! | [`propagation_store_v2`] | Durable propagation store and recovery |
//! | [`types`] | Message, destination and identity hash aliases |
//! | [`constants`] | Wire constants: STATE, METHOD, field IDs, etc. |
//!
//! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum`
@@ -32,23 +42,71 @@
//!
//! [`DiscoveryStamper`]: rns_transport::discovery::DiscoveryStamper
/// Unix time as f64 seconds — Python `time.time()` equivalent.
pub(crate) fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
#[cfg(test)]
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
pub mod admission;
pub mod admission_store;
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
pub mod handlers;
pub mod inbound_resource;
pub mod link_delivery;
pub mod message;
pub mod peer;
pub mod persist;
pub mod presentation;
pub mod propagation;
pub mod propagation_admission;
pub mod propagation_client;
pub mod propagation_node;
pub mod propagation_offer;
pub mod propagation_send;
pub mod propagation_store_v2;
pub mod propagation_sync;
pub mod router;
pub mod stamper;
pub mod state_store;
pub mod sync;
pub mod ticket;
pub mod types;
/// Canonical message construction and inspection identities for applications.
///
/// These are exact re-exports of the existing module-qualified types. The
/// original paths remain supported. Router, delivery, propagation, handler,
/// and persistence ownership intentionally remain outside this first facade.
pub mod message_api {
pub use crate::constants::{
DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason,
};
pub use crate::message::{
AudioField, EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields,
LxMessage, LxMessageDraft, MessageDecodeLimits, MessageError, MessageMetadata,
OwnedVerifiedLxMessage, RecipientStamp, ResumableLxMessage, SignedLxMessage,
UniqueFieldMap, VerifiedLxMessage,
};
pub use crate::types::{DestinationHash, IdentityHash, MessageId};
}
/// Encode an `rmpv::Value` into a byte buffer.
///
/// `Write` into a `Vec<u8>` is infallible, so the inner `expect` is unreachable.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+509
View File
@@ -0,0 +1,509 @@
//! MessagePack decoding with the acceptance rules of the umsgpack decoder used
//! by Python LXMF, and its canonical re-encoding (`umsgpack.packb(unpackb(x))`).
use super::MessageError;
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
const MAX_DEPTH: usize = 64;
// datetime.min / datetime.max relative to the Unix epoch, in microseconds.
const MIN_TIMESTAMP_MICROS: i128 = -62_135_596_800 * 1_000_000;
const MAX_TIMESTAMP_MICROS: i128 = 253_402_300_799 * 1_000_000 + 999_999;
/// Python value identity of a decoded map key.
#[derive(Debug)]
enum Key {
Nil,
Number(i128),
Float(u64),
NaN,
Str(Vec<u8>),
Bin(Vec<u8>),
Ext(i8, Vec<u8>),
Time(i128),
Tuple(Vec<Key>),
Unhashable,
}
impl Key {
fn same(&self, other: &Key) -> bool {
match (self, other) {
(Key::Nil, Key::Nil) => true,
(Key::Number(a), Key::Number(b)) => a == b,
(Key::Float(a), Key::Float(b)) => a == b,
(Key::Str(a), Key::Str(b)) | (Key::Bin(a), Key::Bin(b)) => a == b,
(Key::Ext(t, a), Key::Ext(u, b)) => t == u && a == b,
(Key::Time(a), Key::Time(b)) => a == b,
(Key::Tuple(a), Key::Tuple(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.same(y))
}
_ => false,
}
}
fn hashable(&self) -> bool {
match self {
Key::Unhashable => false,
Key::Tuple(items) => items.iter().all(Key::hashable),
_ => true,
}
}
fn contains_nan(&self) -> bool {
match self {
Key::NaN => true,
Key::Tuple(items) => items.iter().any(Key::contains_nan),
_ => false,
}
}
fn from_float(value: f64) -> Key {
if value.is_nan() {
Key::NaN
} else if value.fract() == 0.0 && value.abs() < 1.0e38 {
Key::Number(value as i128)
} else {
Key::Float(value.to_bits())
}
}
}
// Equality is reflexive for every key that reaches the index (NaN keys never do).
impl PartialEq for Key {
fn eq(&self, other: &Key) -> bool {
self.same(other)
}
}
impl Eq for Key {}
impl Hash for Key {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Key::Nil => 0u8.hash(state),
Key::Number(n) => (1u8, n).hash(state),
Key::Float(bits) => (2u8, bits).hash(state),
Key::NaN => 3u8.hash(state),
Key::Str(v) => (4u8, v).hash(state),
Key::Bin(v) => (5u8, v).hash(state),
Key::Ext(t, v) => (6u8, t, v).hash(state),
Key::Time(t) => (7u8, t).hash(state),
Key::Tuple(items) => {
8u8.hash(state);
items.len().hash(state);
for item in items {
item.hash(state);
}
}
Key::Unhashable => 9u8.hash(state),
}
}
}
fn fail(reason: &str) -> MessageError {
MessageError::UnpackFailed(reason.to_string())
}
fn take<'a>(input: &mut &'a [u8], length: usize) -> Result<&'a [u8], MessageError> {
if input.len() < length {
return Err(fail("truncated MessagePack value"));
}
let (value, rest) = input.split_at(length);
*input = rest;
Ok(value)
}
fn be(input: &mut &[u8], width: usize) -> Result<u64, MessageError> {
Ok(take(input, width)?
.iter()
.fold(0u64, |acc, byte| (acc << 8) | u64::from(*byte)))
}
fn emit(out: &mut Option<&mut Vec<u8>>, bytes: &[u8]) {
if let Some(out) = out.as_deref_mut() {
out.extend_from_slice(bytes);
}
}
fn write_int(out: &mut Vec<u8>, value: i128) {
if value < 0 {
if value >= -32 {
out.push(value as i8 as u8);
} else if value >= i128::from(i8::MIN) {
out.push(0xd0);
out.push(value as i8 as u8);
} else if value >= i128::from(i16::MIN) {
out.push(0xd1);
out.extend_from_slice(&(value as i16).to_be_bytes());
} else if value >= i128::from(i32::MIN) {
out.push(0xd2);
out.extend_from_slice(&(value as i32).to_be_bytes());
} else {
out.push(0xd3);
out.extend_from_slice(&(value as i64).to_be_bytes());
}
} else if value < 128 {
out.push(value as u8);
} else if value <= i128::from(u8::MAX) {
out.push(0xcc);
out.push(value as u8);
} else if value <= i128::from(u16::MAX) {
out.push(0xcd);
out.extend_from_slice(&(value as u16).to_be_bytes());
} else if value <= i128::from(u32::MAX) {
out.push(0xce);
out.extend_from_slice(&(value as u32).to_be_bytes());
} else {
out.push(0xcf);
out.extend_from_slice(&(value as u64).to_be_bytes());
}
}
fn write_sized(out: &mut Vec<u8>, length: usize, fix: Option<(u8, usize)>, wide: [u8; 3]) {
match fix {
Some((base, limit)) if length < limit => out.push(base | length as u8),
_ if length <= usize::from(u8::MAX) && wide[0] != 0 => {
out.push(wide[0]);
out.push(length as u8);
}
_ if length <= usize::from(u16::MAX) => {
out.push(wide[1]);
out.extend_from_slice(&(length as u16).to_be_bytes());
}
_ => {
out.push(wide[2]);
out.extend_from_slice(&(length as u32).to_be_bytes());
}
}
}
fn write_ext(out: &mut Vec<u8>, ext_type: i8, data: &[u8]) {
match data.len() {
1 => out.push(0xd4),
2 => out.push(0xd5),
4 => out.push(0xd6),
8 => out.push(0xd7),
16 => out.push(0xd8),
length => write_sized(out, length, None, [0xc7, 0xc8, 0xc9]),
}
out.push(ext_type as u8);
out.extend_from_slice(data);
}
fn timestamp_micros(data: &[u8]) -> Result<i128, MessageError> {
let (seconds, micros) = match data.len() {
4 => (
i128::from(u32::from_be_bytes(data.try_into().expect("length"))),
0,
),
8 => {
let value = u64::from_be_bytes(data.try_into().expect("length"));
(
i128::from(value & 0x3_ffff_ffff),
i128::from(value >> 34) / 1000,
)
}
12 => (
i128::from(i64::from_be_bytes(data[4..12].try_into().expect("length"))),
i128::from(u32::from_be_bytes(data[0..4].try_into().expect("length"))) / 1000,
),
_ => return Err(fail("unsupported MessagePack timestamp")),
};
let total = seconds * 1_000_000 + micros;
if !(MIN_TIMESTAMP_MICROS..=MAX_TIMESTAMP_MICROS).contains(&total) {
return Err(fail("MessagePack timestamp out of range"));
}
Ok(total)
}
fn write_timestamp(out: &mut Vec<u8>, total: i128) {
let seconds = total.div_euclid(1_000_000);
let micros = total.rem_euclid(1_000_000);
if micros == 0 && (0..=i128::from(u32::MAX)).contains(&seconds) {
out.extend_from_slice(&[0xd6, 0xff]);
out.extend_from_slice(&(seconds as u32).to_be_bytes());
} else if (0..(1i128 << 34)).contains(&seconds) {
let value = ((micros as u64 * 1000) << 34) | seconds as u64;
out.extend_from_slice(&[0xd7, 0xff]);
out.extend_from_slice(&value.to_be_bytes());
} else {
out.extend_from_slice(&[0xc7, 0x0c, 0xff]);
out.extend_from_slice(&((micros * 1000) as u32).to_be_bytes());
out.extend_from_slice(&(seconds as i64).to_be_bytes());
}
}
/// Decode one value, writing its canonical encoding to `out` when present.
/// Returns the value's key identity when `want_key` is set.
fn walk(
input: &mut &[u8],
mut out: Option<&mut Vec<u8>>,
want_key: bool,
depth: usize,
) -> Result<Option<Key>, MessageError> {
if depth >= MAX_DEPTH {
return Err(fail("MessagePack nesting exceeds limit"));
}
let marker = take(input, 1)?[0];
let number = |value: i128, out: Option<&mut Vec<u8>>| {
if let Some(out) = out {
write_int(out, value);
}
Ok(want_key.then_some(Key::Number(value)))
};
match marker {
0x00..=0x7f => number(i128::from(marker), out),
0xe0..=0xff => number(i128::from(marker as i8), out),
0xcc => number(i128::from(be(input, 1)?), out),
0xcd => number(i128::from(be(input, 2)?), out),
0xce => number(i128::from(be(input, 4)?), out),
0xcf => number(i128::from(be(input, 8)?), out),
0xd0 => number(i128::from(be(input, 1)? as u8 as i8), out),
0xd1 => number(i128::from(be(input, 2)? as u16 as i16), out),
0xd2 => number(i128::from(be(input, 4)? as u32 as i32), out),
0xd3 => number(i128::from(be(input, 8)? as i64), out),
0xc0 => {
emit(&mut out, &[0xc0]);
Ok(want_key.then_some(Key::Nil))
}
0xc1 => Err(fail("reserved MessagePack marker")),
0xc2 | 0xc3 => {
emit(&mut out, &[marker]);
Ok(want_key.then_some(Key::Number(i128::from(marker == 0xc3))))
}
0xca | 0xcb => {
let value = if marker == 0xca {
f64::from(f32::from_bits(be(input, 4)? as u32))
} else {
f64::from_bits(be(input, 8)?)
};
if let Some(out) = out {
out.push(0xcb);
out.extend_from_slice(&value.to_bits().to_be_bytes());
}
Ok(want_key.then(|| Key::from_float(value)))
}
0xa0..=0xbf | 0xd9..=0xdb => {
let length = match marker {
0xd9 => be(input, 1)?,
0xda => be(input, 2)?,
0xdb => be(input, 4)?,
_ => u64::from(marker & 0x1f),
} as usize;
let data = take(input, length)?;
if std::str::from_utf8(data).is_err() {
return Err(fail("MessagePack string is invalid UTF-8"));
}
if let Some(out) = out {
write_sized(out, length, Some((0xa0, 32)), [0xd9, 0xda, 0xdb]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Str(data.to_vec())))
}
0xc4..=0xc6 => {
let length = be(input, 1 << (marker - 0xc4))? as usize;
let data = take(input, length)?;
if let Some(out) = out {
write_sized(out, length, None, [0xc4, 0xc5, 0xc6]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Bin(data.to_vec())))
}
0xc7..=0xc9 | 0xd4..=0xd8 => {
let length = match marker {
0xc7 => be(input, 1)? as usize,
0xc8 => be(input, 2)? as usize,
0xc9 => be(input, 4)? as usize,
_ => 1 << (marker - 0xd4),
};
let ext_type = take(input, 1)?[0] as i8;
let data = take(input, length)?;
if ext_type == -1 {
let total = timestamp_micros(data)?;
if let Some(out) = out {
write_timestamp(out, total);
}
return Ok(want_key.then_some(Key::Time(total)));
}
if let Some(out) = out {
write_ext(out, ext_type, data);
}
Ok(want_key.then(|| Key::Ext(ext_type, data.to_vec())))
}
0x90..=0x9f | 0xdc | 0xdd => {
let count = match marker {
0xdc => be(input, 2)?,
0xdd => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
if let Some(out) = out.as_deref_mut() {
write_sized(out, count as usize, Some((0x90, 16)), [0, 0xdc, 0xdd]);
}
let mut items = Vec::new();
for _ in 0..count {
let item = walk(input, out.as_deref_mut(), want_key, depth + 1)?;
if let Some(item) = item {
items.push(item);
}
}
Ok(want_key.then_some(Key::Tuple(items)))
}
0x80..=0x8f | 0xde | 0xdf => {
let count = match marker {
0xde => be(input, 2)?,
0xdf => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
walk_map(input, out, count, depth)?;
Ok(want_key.then_some(Key::Unhashable))
}
}
}
struct Entry {
encoded_key: Vec<u8>,
encoded_value: Vec<u8>,
}
fn walk_map(
input: &mut &[u8],
out: Option<&mut Vec<u8>>,
count: u64,
depth: usize,
) -> Result<(), MessageError> {
let writing = out.is_some();
let mut entries: Vec<Entry> = Vec::new();
let mut index: HashMap<Key, usize> = HashMap::new();
for _ in 0..count {
let is_list = matches!(input.first(), Some(0x90..=0x9f | 0xdc | 0xdd));
let mut encoded_key = Vec::new();
let key = walk(input, writing.then_some(&mut encoded_key), true, depth + 1)?
.expect("key requested");
// Lists become tuples and bypass the duplicate check; later ones overwrite.
if !is_list {
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
if index.contains_key(&key) {
return Err(fail("duplicate MessagePack map key"));
}
}
let mut encoded_value = Vec::new();
walk(
input,
writing.then_some(&mut encoded_value),
false,
depth + 1,
)?;
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
let existing = if key.contains_nan() {
None
} else {
index.get(&key).copied()
};
match existing {
Some(position) => entries[position].encoded_value = encoded_value,
None => {
if !key.contains_nan() {
index.insert(key, entries.len());
}
entries.push(Entry {
encoded_key,
encoded_value,
});
}
}
}
if let Some(out) = out {
write_sized(out, entries.len(), Some((0x80, 16)), [0, 0xde, 0xdf]);
for entry in entries {
out.extend_from_slice(&entry.encoded_key);
out.extend_from_slice(&entry.encoded_value);
}
}
Ok(())
}
/// Check that the leading value decodes under the umsgpack rules; trailing bytes are ignored.
pub(crate) fn validate_leading(bytes: &[u8]) -> Result<(), MessageError> {
let mut input = bytes;
walk(&mut input, None, false, 0).map(|_| ())
}
/// Canonical re-encoding of exactly one value.
pub(crate) fn canonicalize(bytes: &[u8]) -> Result<Vec<u8>, MessageError> {
let mut input = bytes;
let mut out = Vec::with_capacity(bytes.len());
walk(&mut input, Some(&mut out), false, 0)?;
if !input.is_empty() {
return Err(fail("trailing MessagePack bytes"));
}
Ok(out)
}
/// The payload bytes Python hashes: the received bytes, or the canonical
/// re-encoding of the first four elements when a stamp is present.
pub(crate) fn hashed_payload(payload: &[u8]) -> Result<Cow<'_, [u8]>, MessageError> {
let mut input = payload;
let count = match take(&mut input, 1)?[0] {
marker @ 0x90..=0x9f => u64::from(marker & 0x0f),
0xdc => be(&mut input, 2)?,
0xdd => be(&mut input, 4)?,
_ => return Err(fail("expected MessagePack array")),
};
if count <= 4 {
return Ok(Cow::Borrowed(payload));
}
let mut out = vec![0x94];
for _ in 0..4 {
walk(&mut input, Some(&mut out), false, 1)?;
}
Ok(Cow::Owned(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn canon(hex_in: &str) -> Result<String, MessageError> {
canonicalize(&hex::decode(hex_in).unwrap()).map(hex::encode)
}
#[test]
fn reencodes_minimally_and_widens_floats() {
assert_eq!(canon("91ca3fc00000").unwrap(), "91cb3ff8000000000000");
assert_eq!(canon("cd0005").unwrap(), "05");
assert_eq!(canon("d9026869").unwrap(), "a26869");
assert_eq!(canon("de00010102").unwrap(), "810102");
assert_eq!(canon("c50001aa").unwrap(), "c401aa");
assert_eq!(canon("c701050a").unwrap(), "d4050a");
assert_eq!(canon("d0ff").unwrap(), "ff");
}
#[test]
fn rejects_duplicates_by_python_equality() {
assert!(canon("820101 0102".replace(' ', "").as_str()).is_err());
assert!(canon("8201 01cb3ff0000000000000 02".replace(' ', "").as_str()).is_err());
assert!(canon("82c301 0102".replace(' ', "").as_str()).is_err());
assert!(canon("82a1610 1c4016102".replace(' ', "").as_str()).is_ok());
assert!(
canon(
"82cb7ff8000000000000 01cb7ff8000000000000 02"
.replace(' ', "")
.as_str()
)
.is_ok()
);
}
#[test]
fn list_keys_overwrite_instead_of_failing() {
assert_eq!(canon("82910101910102").unwrap(), "81910102");
assert!(canon("81918001 01".replace(' ', "").as_str()).is_err());
assert!(canon("818001 01".replace(' ', "").as_str()).is_err());
}
#[test]
fn rejects_invalid_text_and_reserved_marker() {
assert!(canon("a1ff").is_err());
assert!(canon("c1").is_err());
assert!(canon("c7").is_err());
}
}
+461
View File
@@ -0,0 +1,461 @@
//! Checked mutable construction followed by consuming signature/finalization.
use super::*;
use rns_crypto::ed25519::Ed25519PrivateKey;
/// Mutable outbound semantics. This type cannot be submitted as a wire message.
/// ```compile_fail
/// use lxmf_core::message::LxMessageDraft;
/// fn send_unsigned(draft: LxMessageDraft) { let _ = draft.wire_bytes(); }
/// ```
#[derive(Debug, Clone)]
pub struct LxMessageDraft {
destination: [u8; 16],
source: [u8; 16],
title: Bytes,
content: Bytes,
timestamp: f64,
fields: BTreeMap<FieldId, FieldValue>,
limits: MessageDecodeLimits,
pub metadata: MessageMetadata,
pub include_ticket: bool,
pub outbound_ticket: Option<[u8; 16]>,
pub stamp_cost: Option<f64>,
}
impl Deref for LxMessageDraft {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.metadata
}
}
impl DerefMut for LxMessageDraft {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.metadata
}
}
/// Frozen signed body awaiting its optional recipient stamp. Not a sendable type.
#[derive(Debug)]
pub struct SignedLxMessage {
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<f64>,
}
impl Deref for SignedLxMessage {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.message.metadata
}
}
impl DerefMut for SignedLxMessage {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.message.metadata
}
}
impl LxMessageDraft {
pub fn new(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
) -> Result<Self, MessageError> {
Self::new_with_limits(
destination,
source,
title,
content,
method,
MessageDecodeLimits::default(),
)
}
pub fn new_with_limits(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
limits: MessageDecodeLimits,
) -> Result<Self, MessageError> {
limits.check_wire(
title
.len()
.checked_add(content.len())
.and_then(|n| n.checked_add(110))
.ok_or_else(|| MessageError::PackFailed("length overflow".into()))?,
)?;
let draft = Self {
destination,
source,
title: Bytes::copy_from_slice(title.as_bytes()),
content: Bytes::copy_from_slice(content.as_bytes()),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64(),
fields: BTreeMap::new(),
limits,
metadata: MessageMetadata {
method,
..MessageMetadata::default()
},
include_ticket: false,
outbound_ticket: None,
stamp_cost: None,
};
draft.checked_wire_len()?;
Ok(draft)
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination
}
pub fn source_hash(&self) -> [u8; 16] {
self.source
}
pub fn timestamp(&self) -> f64 {
self.timestamp
}
pub fn title_bytes(&self) -> &[u8] {
&self.title
}
pub fn content_bytes(&self) -> &[u8] {
&self.content
}
pub fn fields(&self) -> &BTreeMap<FieldId, FieldValue> {
&self.fields
}
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
self.fields.get(&id.into())
}
pub fn set_timestamp(&mut self, value: f64) -> Result<(), MessageError> {
if !value.is_finite() {
return Err(MessageError::PackFailed(
"nonfinite outbound timestamp".into(),
));
}
self.timestamp = value;
Ok(())
}
pub fn set_title(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, true)
}
pub fn set_content(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, false)
}
fn set_text(&mut self, value: &str, title: bool) -> Result<(), MessageError> {
self.limits.check_wire(value.len())?;
let next = Bytes::copy_from_slice(value.as_bytes());
let old = if title {
std::mem::replace(&mut self.title, next)
} else {
std::mem::replace(&mut self.content, next)
};
if let Err(e) = self.checked_wire_len() {
if title {
self.title = old
} else {
self.content = old
};
return Err(e);
}
Ok(())
}
pub fn set_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(id, FieldValue::Binary(bytes.into()))
}
pub fn set_msgpack_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
let value = EncodedFieldValue::canonical(bytes.into())?;
self.insert_field(id.into(), FieldValue::MessagePack(value))
}
pub fn set_field_value(
&mut self,
id: impl Into<FieldId>,
value: FieldValue,
) -> Result<(), MessageError> {
let value = match value {
FieldValue::MessagePack(v) => {
FieldValue::MessagePack(EncodedFieldValue::canonical(v.into_bytes())?)
}
binary => binary,
};
self.insert_field(id.into(), value)
}
/// Encode one of this crate's media fields at its exact size, once.
fn set_media_field<T: serde::Serialize>(
&mut self,
id: FieldId,
value: &T,
bytes: usize,
name: usize,
) -> Result<(), MessageError> {
self.limits.check_wire(bytes)?;
// Two array headers, a str header and a bin header: at most 12 bytes.
let mut encoded = Vec::with_capacity(bytes + name + 12);
rmp_serde::encode::write(&mut encoded, value).map_err(packed)?;
let value = EncodedFieldValue::trusted(encoded.into());
self.insert_field(id, FieldValue::MessagePack(value))
}
fn insert_field(&mut self, id: FieldId, value: FieldValue) -> Result<(), MessageError> {
if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let old = self.fields.insert(id, value);
if let Err(e) = self.checked_wire_len() {
match old {
Some(v) => {
self.fields.insert(id, v);
}
None => {
self.fields.remove(&id);
}
};
return Err(e);
}
Ok(())
}
pub fn remove_field(&mut self, id: impl Into<FieldId>) -> Option<FieldValue> {
self.fields.remove(&id.into())
}
pub fn set_image_field(&mut self, format: &str, bytes: &[u8]) -> Result<(), MessageError> {
let value = ImageFieldRef { format, bytes };
self.set_media_field(FIELD_IMAGE.into(), &value, bytes.len(), format.len())
}
pub fn set_audio_field(&mut self, mode: u8, bytes: &[u8]) -> Result<(), MessageError> {
let value = AudioFieldRef { mode, bytes };
self.set_media_field(FIELD_AUDIO.into(), &value, bytes.len(), 0)
}
pub fn set_file_attachment_field(
&mut self,
file_name: &str,
bytes: &[u8],
) -> Result<(), MessageError> {
let value = FileAttachmentsFieldRef { file_name, bytes };
self.set_media_field(
FIELD_FILE_ATTACHMENTS.into(),
&value,
bytes.len(),
file_name.len(),
)
}
/// Exact unsigned payload, for diagnostics; it is not a transmittable message.
pub fn pack_payload(&self) -> Result<Vec<u8>, MessageError> {
let size = self.checked_wire_len()?;
let mut out = Vec::with_capacity(size - 96);
self.write_payload(&mut out)?;
Ok(out)
}
pub fn checked_wire_len(&self) -> Result<usize, MessageError> {
if self.fields.len() > self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let mut counter = CountingWriter::default();
self.write_payload(&mut counter)?;
let len = counter
.bytes
.checked_add(96)
.ok_or_else(|| packed("length overflow"))?;
self.limits.check_wire(len)?;
Ok(len)
}
fn write_payload<W: Write>(&self, out: &mut W) -> Result<(), MessageError> {
rmp::encode::write_array_len(out, 4).map_err(packed)?;
rmp::encode::write_f64(out, self.timestamp).map_err(packed)?;
write_bin(out, &self.title)?;
write_bin(out, &self.content)?;
rmp::encode::write_map_len(out, length(self.fields.len())?).map_err(packed)?;
for (id, value) in &self.fields {
if id.as_i128() >= 0 {
rmp::encode::write_uint(out, u64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
} else {
rmp::encode::write_sint(out, i64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
}
match value {
FieldValue::Binary(b) => write_bin(out, b)?,
FieldValue::MessagePack(v) => out.write_all(v.encoded()).map_err(packed)?,
}
}
Ok(())
}
pub fn sign(self, key: &Ed25519PrivateKey) -> Result<SignedLxMessage, MessageError> {
self.sign_with(|bytes| Ok::<_, std::convert::Infallible>(key.sign(bytes)))
}
pub fn sign_with<F, E>(mut self, sign: F) -> Result<SignedLxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
let size = self.checked_wire_len()?;
let mut signed = Vec::with_capacity(size);
signed.extend_from_slice(&self.destination);
signed.extend_from_slice(&self.source);
self.write_payload(&mut signed)?;
// The payload now lives in `signed` alone.
self.fields.clear();
let id = sha256(&signed);
signed.extend_from_slice(&id);
let signature = sign(&signed).map_err(packed)?;
// The wire in place: drop the id and open the signature after the
// two hashes. `size` is exactly the wire length, so nothing moves.
let payload_end = signed.len() - 32;
signed.truncate(payload_end);
signed.resize(size, 0);
signed.copy_within(32..payload_end, 96);
signed[32..96].copy_from_slice(&signature);
let mut message = LxMessage::unpack_owned(signed.into(), self.limits)?;
message.metadata = self.metadata;
message.incoming = false;
message.state = MessageState::Outbound;
Ok(SignedLxMessage {
message,
outbound_ticket: self.outbound_ticket,
stamp_cost: self.stamp_cost,
})
}
}
impl SignedLxMessage {
pub(crate) fn restored(
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<f64>,
) -> Self {
Self {
message,
outbound_ticket,
stamp_cost,
}
}
/// Create a representation the caller can persist to resume delivery after
/// a restart under the same ID. It retains the signing stamp cost as a floor;
/// this method performs no file or database write.
pub fn to_resumable(&self) -> ResumableLxMessage {
ResumableLxMessage::new(&self.message.wire, self.stamp_cost)
}
pub fn timestamp(&self) -> f64 {
self.message.timestamp()
}
/// Complete no-stamp wire length; finalization can add a recipient stamp.
pub fn packed_len(&self) -> Result<usize, MessageError> {
self.message.packed_len()
}
/// Signed payload length, without exposing sendable bytes before finalization.
pub fn payload_len(&self) -> usize {
self.message.wire_bytes().len() - 96
}
pub fn title_bytes(&self) -> &[u8] {
self.message.title_bytes()
}
pub fn content_bytes(&self) -> &[u8] {
self.message.content_bytes()
}
pub fn title_text(&self) -> std::borrow::Cow<'_, str> {
self.message.title_text()
}
pub fn content_text(&self) -> std::borrow::Cow<'_, str> {
self.message.content_text()
}
pub fn message_id(&self) -> [u8; 32] {
self.message.message_id()
}
pub fn destination_hash(&self) -> [u8; 16] {
self.message.destination_hash()
}
pub fn source_hash(&self) -> [u8; 16] {
self.message.source_hash()
}
pub fn fields(&self) -> Fields<'_> {
self.message.fields()
}
/// The first file attachment's name and bytes, borrowed from the wire.
pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.first_file_attachment()
}
/// The image field's format and bytes, borrowed from the wire.
pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.image_attachment()
}
/// The signed, unstamped message, for failing it without a stamp.
pub fn into_unstamped(self) -> LxMessage {
self.message
}
pub fn stamp_cost(&self) -> Option<f64> {
self.stamp_cost
}
pub fn outbound_ticket(&self) -> Option<[u8; 16]> {
self.outbound_ticket
}
/// Compute the optional recipient stamp without changing the signed body.
/// Runs synchronously until the proof of work is found; a cost Python
/// cannot generate is an error.
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
self.generate_recipient_stamp_with(&crate::stamper::StampControl::default())
}
/// [`Self::generate_recipient_stamp`], stopped by `ctl`'s cancel flag or deadline.
pub fn generate_recipient_stamp_with(
&self,
ctl: &crate::stamper::StampControl,
) -> Result<Option<RecipientStamp>, MessageError> {
if let Some(ticket) = self.outbound_ticket {
let mut material = [0u8; 48];
material[..16].copy_from_slice(&ticket);
material[16..].copy_from_slice(&self.message_id());
return Ok(Some(RecipientStamp::Ticket(truncated_hash(&material))));
}
let Some(cost) = self.stamp_cost else {
return Ok(None);
};
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS, ctl)
.map_err(packed)?
.map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp)))
.ok_or_else(|| packed("recipient stamp generation stopped"))
}
pub fn finalize(self, stamp: Option<RecipientStamp>) -> Result<LxMessage, MessageError> {
self.try_finalize(stamp).map_err(|failed| failed.0)
}
/// [`Self::finalize`], returning the unstamped message with the error so
/// the caller can still fail it.
pub fn try_finalize(
self,
stamp: Option<RecipientStamp>,
) -> Result<LxMessage, Box<(MessageError, LxMessage)>> {
let Some(stamp) = stamp else {
return Ok(self.message);
};
match Self::stamped(&self.message, &stamp) {
Ok(message) => Ok(message),
Err(error) => Err(Box::new((error, self.message))),
}
}
fn stamped(message: &LxMessage, stamp: &RecipientStamp) -> Result<LxMessage, MessageError> {
let size = message
.wire
.len()
.checked_add(2 + stamp.as_bytes().len())
.ok_or_else(|| packed("length overflow"))?;
message.limits.check_wire(size)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&message.wire);
wire[96] = 0x95;
write_bin(&mut wire, stamp.as_bytes())?;
let mut stamped = LxMessage::unpack_owned(wire.into(), message.limits)?;
debug_assert_eq!(stamped.message_id, message.message_id);
stamped.metadata = message.metadata.clone();
Ok(stamped)
}
}
fn packed(error: impl std::fmt::Display) -> MessageError {
MessageError::PackFailed(error.to_string())
}
fn length(value: usize) -> Result<u32, MessageError> {
u32::try_from(value).map_err(packed)
}
fn write_bin<W: Write>(out: &mut W, bytes: &[u8]) -> Result<(), MessageError> {
rmp::encode::write_bin_len(out, length(bytes.len())?).map_err(packed)?;
out.write_all(bytes).map_err(packed)
}
+356
View File
@@ -0,0 +1,356 @@
//! Full-width LXMF field keys and coherent binary/structured values.
use super::{MessageError, read_msgpack_binary, skip_msgpack_value};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::{fmt, ops::Range};
/// A MessagePack integer field key, preserving the complete signed/unsigned domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FieldId(i128);
impl FieldId {
pub const fn as_i128(self) -> i128 {
self.0
}
pub fn as_standard(self) -> Option<u8> {
u8::try_from(self.0).ok()
}
}
macro_rules! field_from { ($($t:ty),*) => { $(impl From<$t> for FieldId { fn from(v:$t)->Self { Self(i128::from(v)) } })* }; }
field_from!(u8, u16, u32, u64, i8, i16, i32, i64);
impl TryFrom<i128> for FieldId {
type Error = MessageError;
fn try_from(v: i128) -> Result<Self, Self::Error> {
if v < i128::from(i64::MIN) || v > i128::from(u64::MAX) {
return Err(MessageError::InvalidFieldId);
}
Ok(Self(v))
}
}
impl Serialize for FieldId {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if self.0 >= 0 {
s.serialize_u64(u64::try_from(self.0).map_err(serde::ser::Error::custom)?)
} else {
s.serialize_i64(i64::try_from(self.0).map_err(serde::ser::Error::custom)?)
}
}
}
impl<'de> Deserialize<'de> for FieldId {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = FieldId;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a signed or unsigned 64-bit integer")
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<FieldId, E> {
FieldId::try_from(v).map_err(E::custom)
}
fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<FieldId, E> {
u64::try_from(v).map(FieldId::from).map_err(E::custom)
}
}
d.deserialize_any(V)
}
}
/// One structurally valid encoded MessagePack value. Storage cannot be mutated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedFieldValue(Bytes);
impl EncodedFieldValue {
pub fn new(bytes: Bytes) -> Result<Self, MessageError> {
let mut remaining = bytes.as_ref();
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self(bytes))
}
/// The value as Python LXMF decodes and re-encodes it; fails where
/// Python's decoder fails (duplicate or unhashable map keys, invalid UTF-8).
pub fn canonical(bytes: Bytes) -> Result<Self, MessageError> {
let canonical = super::canonical::canonicalize(&bytes)?;
if canonical == bytes.as_ref() {
return Ok(Self(bytes));
}
Ok(Self(canonical.into()))
}
pub fn encoded(&self) -> &[u8] {
&self.0
}
/// For this crate's encoders, whose output is canonical by construction.
pub(crate) fn trusted(bytes: Bytes) -> Self {
Self(bytes)
}
pub(crate) fn into_bytes(self) -> Bytes {
self.0
}
}
/// A binary byte string or a native structured MessagePack value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldValue {
Binary(Bytes),
MessagePack(EncodedFieldValue),
}
impl Serialize for FieldValue {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Self::Binary(b) => s.serialize_bytes(b),
Self::MessagePack(v) => {
let value = rmpv::decode::read_value(&mut v.encoded())
.map_err(serde::ser::Error::custom)?;
value.serialize(s)
}
}
}
}
impl<'de> Deserialize<'de> for FieldValue {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let value = rmpv::Value::deserialize(d)?;
if let rmpv::Value::Binary(b) = value {
return Ok(Self::Binary(b.into()));
}
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?;
EncodedFieldValue::canonical(bytes.into())
.map(Self::MessagePack)
.map_err(serde::de::Error::custom)
}
}
/// Borrowed exact encoded field value. Binary is never inferred to be structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldValueRef<'a> {
pub(super) encoded: &'a [u8],
}
impl<'a> FieldValueRef<'a> {
/// Borrow exactly one structurally valid value without decoding or copying it.
/// Binary payloads are never interpreted implicitly.
pub fn from_encoded(encoded: &'a [u8]) -> Result<Self, MessageError> {
let mut remaining = encoded;
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self { encoded })
}
/// Exact UTF-8 MessagePack text, without accepting a binary value as text.
pub fn as_text(self) -> Option<&'a str> {
if !matches!(self.encoded.first(), Some(0xa0..=0xbf | 0xd9..=0xdb)) {
return None;
}
let mut input = self.encoded;
let bytes = super::read_msgpack_string_or_binary(&mut input).ok()?;
if !input.is_empty() {
return None;
}
std::str::from_utf8(bytes).ok()
}
pub fn encoded(self) -> &'a [u8] {
self.encoded
}
pub fn as_binary(self) -> Option<&'a [u8]> {
let mut value = self.encoded;
let bytes = read_msgpack_binary(&mut value).ok()?;
value.is_empty().then_some(bytes)
}
/// Owned explicit copy, for constructing a new message deliberately.
pub fn to_owned(self) -> FieldValue {
match self.as_binary() {
Some(b) => FieldValue::Binary(Bytes::copy_from_slice(b)),
None => {
FieldValue::MessagePack(EncodedFieldValue(Bytes::copy_from_slice(self.encoded)))
}
}
}
}
#[derive(Debug, Clone)]
pub(super) struct FieldIndex {
pub id: FieldId,
pub range: Range<usize>,
}
const _: () = assert!(std::mem::size_of::<FieldIndex>() <= 32);
/// Numeric-key ordered view; original field wire order stays in the message.
#[derive(Debug, Clone, Copy)]
pub struct Fields<'a> {
pub(super) wire: &'a [u8],
pub(super) indexes: &'a [FieldIndex],
}
impl<'a> Fields<'a> {
pub fn get(self, id: impl Into<FieldId>) -> Option<FieldValueRef<'a>> {
let id = id.into();
self.indexes
.binary_search_by_key(&id, |entry| entry.id)
.ok()
.map(|i| FieldValueRef {
encoded: &self.wire[self.indexes[i].range.clone()],
})
}
pub fn contains(self, id: impl Into<FieldId>) -> bool {
self.get(id).is_some()
}
pub fn len(self) -> usize {
self.indexes.len()
}
pub fn is_empty(self) -> bool {
self.indexes.is_empty()
}
pub fn iter(self) -> impl ExactSizeIterator<Item = (FieldId, FieldValueRef<'a>)> {
self.indexes.iter().map(move |entry| {
(
entry.id,
FieldValueRef {
encoded: &self.wire[entry.range.clone()],
},
)
})
}
}
pub(super) mod map_serde {
use super::*;
use std::collections::BTreeMap;
pub fn serialize<S: serde::Serializer>(
map: &BTreeMap<FieldId, FieldValue>,
s: S,
) -> Result<S::Ok, S::Error> {
map.serialize(s)
}
pub fn deserialize<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<BTreeMap<FieldId, FieldValue>, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = BTreeMap<FieldId, FieldValue>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("unique integer fields")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut access: A,
) -> Result<Self::Value, A::Error> {
let mut map = BTreeMap::new();
while let Some(key) = access.next_key::<FieldId>()? {
if map.len()
>= super::super::MessageDecodeLimits::default().max_top_level_fields
{
return Err(serde::de::Error::custom("too many fields"));
}
if map.contains_key(&key) {
return Err(serde::de::Error::custom("duplicate field ID"));
}
let value = access.next_value()?;
map.insert(key, value);
}
Ok(map)
}
}
d.deserialize_map(V)
}
}
/// Validated schema-map keys. Integer encodings normalize; text is exact UTF-8.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FieldMapKey<'a> {
Integer(FieldId),
Text(&'a str),
}
/// Borrowed map values with a compact sorted key-offset index.
///
/// Intended for recognized reaction/chat/game schemas. Unknown structured fields
/// remain opaque and need not request this semantic validation. The index uses
/// four bytes per entry (at most twice the encoded field size), with no value copies.
#[derive(Debug)]
pub struct UniqueFieldMap<'a> {
encoded: &'a [u8],
offsets: Vec<u32>,
}
impl<'a> FieldValueRef<'a> {
pub fn unique_map(self) -> Result<UniqueFieldMap<'a>, MessageError> {
let mut input = self.encoded;
let count = super::read_msgpack_map_len(&mut input)? as usize;
if count > input.len() / 2 {
return Err(MessageError::UnpackFailed(
"impossible nested map count".into(),
));
}
let mut offsets = Vec::new();
offsets
.try_reserve_exact(count)
.map_err(|_| MessageError::UnpackFailed("nested map index allocation".into()))?;
for _ in 0..count {
offsets.push(
u32::try_from(self.encoded.len() - input.len())
.map_err(|_| MessageError::InvalidFieldId)?,
);
read_map_key(&mut input)?;
skip_msgpack_value(&mut input, 0)?;
}
if !input.is_empty() {
return Err(MessageError::UnpackFailed(
"trailing nested map bytes".into(),
));
}
let key_at = |offset: &u32| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated immutable map key")
};
offsets.sort_unstable_by(|a, b| key_at(a).cmp(&key_at(b)));
if offsets
.windows(2)
.any(|pair| key_at(&pair[0]) == key_at(&pair[1]))
{
return Err(MessageError::DuplicateField);
}
Ok(UniqueFieldMap {
encoded: self.encoded,
offsets,
})
}
}
impl<'a> UniqueFieldMap<'a> {
pub fn len(&self) -> usize {
self.offsets.len()
}
pub fn is_empty(&self) -> bool {
self.offsets.is_empty()
}
pub fn get(&self, key: FieldMapKey<'_>) -> Option<FieldValueRef<'a>> {
let index = self
.offsets
.binary_search_by(|offset| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated map key")
.cmp(&key)
})
.ok()?;
let mut input = &self.encoded[self.offsets[index] as usize..];
read_map_key(&mut input).ok()?;
let value = input;
skip_msgpack_value(&mut input, 0).ok()?;
Some(FieldValueRef {
encoded: &value[..value.len() - input.len()],
})
}
}
fn read_map_key<'a>(input: &mut &'a [u8]) -> Result<FieldMapKey<'a>, MessageError> {
if input
.first()
.is_some_and(|marker| matches!(*marker,0xa0..=0xbf|0xd9..=0xdb))
{
let text = super::read_msgpack_string_or_binary(input)?;
Ok(FieldMapKey::Text(std::str::from_utf8(text).map_err(
|_| MessageError::UnpackFailed("map key is not UTF-8".into()),
)?))
} else {
Ok(FieldMapKey::Integer(FieldId::try_from(
super::read_msgpack_integer(input)?,
)?))
}
}
@@ -0,0 +1,16 @@
# Expected outputs of upstream's decode step in LXMRouter.ingest_lxm_uri@1.3.0:
# base64.urlsafe_b64decode(uri.replace("lxm://","").replace("/","")+"==")
import base64, json, random, sys
import RNS, LXMF
assert RNS.__version__ == "1.6.0" and LXMF.__version__ == "1.3.0"
random.seed(1517)
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+/= .:!\n"
cases = ["", "QUJD", "QUI", "QU", "Q", "QUJD=QUJD", "QU=JD", "=QUJD", "QUJD==", "Q+-_", "QU JD", "QUJD====", "Q=U=J=D"]
for _ in range(400):
cases.append("".join(random.choice(alpha) for _ in range(random.randint(0, 14))))
# One line per case: hex(input) TAB hex(decoded) or "error".
with open(sys.argv[1], "w") as f:
for c in cases:
try: r = base64.urlsafe_b64decode(c + "==").hex()
except Exception: r = "error"
f.write(c.encode().hex() + "\t" + r + "\n")
@@ -0,0 +1 @@
/�äxîÒÝfPpVJך�*uÁ”qPp÷_I#D‰H®8
@@ -0,0 +1,413 @@
51554a44 414243
515549 4142
5155 41
51 error
51554a443d51554a44 414243414243
51553d4a44 414243
3d51554a44 414243
51554a443d3d 414243
512b2d5f 43efbf
5155204a44 414243
51554a443d3d3d3d 414243
513d553d4a3d44 414243
2d436e590a45 error
517662595f4249632d3145495a44 42f6d8fc121cfb510864
42694d472b6c463a 062306fa51
6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
2d error
7620506247426135733d58597764 bcf6c605ae6c5d8c1d
30426974344a68763574203d41 d018ade0986fe6d0
5931455f324b5f2038736a3d 63513fd8affcb2
78653053 c5ed12
78456466743a68 c4475fb6
576e4f482d635f52616873443d77 error
34704f77746d4873316b2e3939 e293b0b661ecd64f7d
3657393d213a e96f
3d4469366e7142622167616230 0e2ea7a816e069bd
79737352 cacb11
734673 b05b
356f43 e680
736665 b1f7
5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
53484b 4872
63 error
424b 04
75685f48695155354f36704431 error
713468526c6c ab885196
2e6d3d49593452547358376f6867 988638453b17ee8860
2f2047312b2f78613355 error
4c42 2c
392e41426a450a333a f4006313
655374574a5776745f error
205635452b356a2f44 57913ee63fc3
4d536b664c2b6753 31291f2fe812
71554c5a765a7449 a942d9bd9b48
31586946722e4c46725968395f d57885acb16b621f7f
4e6d6b662135 error
4244 04
31536f43796f d52a02ca
735065433754 b0f782ed
2e615f33326635696d3162 6bfdf67f98a6d5
2f5f49362e586c664e546a42 fff23a5e57cd4e30
7441454c61426144 b4010b681683
3d484f6b 1ce9
50724f2f51536c39585962214651 error
683669545a316a59 87a8936758d8
62 error
4159512e4a5a64 01840965
6f3821595a794f6b792b33394731 error
6c2e4777763a 946c2f
69383a77476c544a3d43512f20 8bcc0695324243
4169 02
485a6557626441692177325a 1d97966dd022c366
4e35697578642d526465634a78 error
3146752f393965 d45bbff7d7
394321356378 error
57575632 596576
72592d4b4a303470673a38 ad8f8a274e2983
4b6775457758776751525a754e error
58437a50623643316438 5c2ccf6fa0b577
64380a20320a3859644e6a 77cdbc61d363
0a7777706b2d error
384c65426a7334692f555345 f0b7818ece22fd4484
3a65 error
6e3a7035727863712b4d6874666d error
78784f32627455386c error
6f error
7076794b55513a494471 error
2e0a476d344f4b3a630a4a7239 error
6a error
653163627068680a2f435474 7b571ba6187f093b
52787467454c77553a 471b6010bc14
6f694130737a4d3164 error
426a4c6f45635f79 0632e811cff2
514a4b63336b 40929cde
2b6e fa
7321506547217030746a b0f786a74b63
796564494d47504334316567 c9e7483063c2e357a0
76 error
20786374453379674a473048 c5cb44df28091b41
35714c7743 error
59794620756947 63216e88
784f2162 c4e6
213d4545 10
327a5453310a4b db34d2d4
50534b395071424f6a56213659 3d22bd3ea04e8d5e98
48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
45666c7471685a2f7375 11f96daa167fb2
76 error
73 error
7331714c34577a2d b35a8be16cfe
5353425a6c6453 49205995d4
2e4764663a3a35 19d7f9
4a2f51762d37334a3521 error
2d49 f8
4c4b6575 2ca7ae
743848485277 b7c1c747
6d69546d6f38312e6d7a error
6675617876364769577471 7ee6b1bfa1a25ada
205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
38652e706137715437777a f1ea5aeea4fbc3
48562d6a20714445 1d5fa3a831
6947 88
4462526121 0db45a
56464c39586475396d error
2b757953683638722148213858 faec9287af2b1fc5
7a64356b4a306e cdde642749
3d6d7a 9b
32205632634a31746f70 error
6e37684a52 error
5a0a6b 66
56722f582e2030485f48536775 56bfd7d07fc74a0b
6d64363368516b75 99deb785092e
7a error
786d5f4351 error
6133 6b
4156 01
3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
677945667865526c36632f386c2d 83211fc5e465e9cffc97
383051775a3a764e6d67500a4475 f3443066f36680f0ee
676c5277564269725851 8254705418ab5d
473d68376f54 error
3a382d4431576f6d3d684f error
415021 00
21532e3331460a 4b7d45
782e642e63513754514c4a4563 c5d710ed340b2447
385a6e21307821 error
7864686958 error
62374457 6fb0d6
704666694835 a457e21f
2152576f322b error
566d306b473d69576b3d51554e 566d241a25a44143
6258304634336a654a2d516774 error
52 error
736346346b6343493961 b1c17891c088f5
3a4143202b46333d43 002f85dc
346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
3a206a582b2e4f356b6d 8d7f8ee649
5336652b5051574354466367 4ba7be3d05824c5720
74626d2e733d513058 b5b9ac4345
55422173784f456b206231583448 501b3138491bd57e07
5a4b314252364d620a216e2e6659 64ad4147a31b9df6
58646b3a464953366c 5dd905212ea5
7566656c302b32 b9f7a5d3ed
774b c0
59304471 6340ea
5a error
5357357472736c205a2e6b54 496e6daec95991
470a error
7271 ae
2033795268393668 df2461f7a8
733453640a74696b2b7a3d723161 b3849db6293ecebd5a
5739 5b
6c2e713359544f6775 96add84ce82e
533843612d error
53742f2b6872516161657055 4adffe86b41a69ea54
5a48312b4e6c426f206e696652 647d7e3650689e27d1
3a4a error
34447950 e03c8f
772b535a76486f4350743a3141 c3e499bc7a023edd40
52 error
77414f c003
794d53787a426750687552434b64 c8c4b1cc180f86e44229
4d6b2f37496b 324ffb22
2b3131793132203334 fb5d72d76df8
75214852683a2f470a5463 b87461fc64dc
6735526b 839464
6e error
484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
6771537969742f3964303756542e error
46745a5f75563a65 16d67fb957
50 error
313549 d792
6e4b79364955664a 9cacba2147c9
572f31785521 error
33513031537a55354856707773 error
4334452b5663662d4e5a4a5a 0b813e55c7fe359259
36727a eabc
696c4d526b4a4433792d533d59 8a53119090f7cbe498
7653416e56 error
0a7978692b cb18be
6f796e35473149315635 a329f91b523557
4435532d3a6c5f5255725042 0f94be97f454acf0
5f39 ff
6f747331674d674c3932 a2db3580c80bf7
5f66562b74393672483064 fdf57eb7deab1f47
30363d6950 d3a88f
35505934446643650a e4f6380df09e
4b6d372f34546358 2a6effe13717
2f3277 ff6c
217021454c544b5276723a50 error
69357a6664774b4d 8b9cdf77028c
5a58 65
53663671616f2149 49feaa6a82
4c205175300a6c77346b7665 2d0bb4970e24bd
735137543a59552164376c7556 b10ed361477b96e5
703744 a7b0
614579595547785a63764c 684c98506c5972f2
3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
5855 5d
50514f2b5a58 3d03be65
623242 6f60
46316947526d414a4a47355a65 error
3877444c56576b440a4a error
4f4f456f 38e128
4c586e734746425a5521 error
535959 4986
2b764e0a5249660a58 faf35121f5
3630543936 error
6672473d55 7eb194
41686a5372213879682d79384f63 error
5667422d667131750a44 error
705744534d702b a560d2329f
687577 86ec
2164386f2e696b584f725348 77ca229173ab48
65326e75756b2f6b7849 7b69eeba4fe4c4
6c657374 95eb2d
3a744f b4
375267 ed18
6f4c214668 a0b161
795278456b2d5f69 c91c4493efe2
3d372e error
6a397434516530673239 8fdb7841ed20db
38206b44372034576a46 f240fbe168c5
3554393a55433231412d3770 e53f540b6d40fbba
3a6b46 90
6c63 95
4e48496758366d715a53597659 error
21566556 55e5
495442684a3d747a 21306126dc
0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
734d3d62414a2b4534723a7949 b0c6c027e138af22
6b66534c655759445220535f 91f48b796603452f
4d6a4659795277424943 323158c91c0120
46433a662e4943 error
2d614e713864 f9a36af1
7a4277713777454c4f4a cc1c2aef010b38
4730 1b
66744a412d517347446c3462 7ed240f90b060e5e1b
77 error
6621 error
6f643a4e4f7366 a1d34eb1
50374b73756e495537374a347631 3fb2acba7214efb278bf
32720a da
534137334d642f4e44516f61 480ef731dfcd0d0a1a
636664734a0a4a38656b4f2b354a error
4449706d 0c8a66
705a2b345248204671517a322b63 error
6e305220427a787a 9f4441cf1c
6170363a587774334b34783074 6a9e97c2ddcae31d2d
4376317a34 error
79 error
2d640a49593669596b f9d218ea2624
6968446b0a344447595841317766 error
754221467743552e2b b81170094f
65434d37 78233b
6379354a2b696b41455f453337 error
2e363a740a346432 error
4a error
445075 0cfb
6b694247 922046
4b656b397370520a31456f6651 29e93db294751287d0
6e7165375461645750564c3274 error
5f77437a2b78542145312e6f57 ff00b3fb14c4d685
43652b7121 09efaa
436e3569547056 0a7e624e95
342b2f736e70646f0a765744554b error
692b6b306b743731 8be93492def5
50647478715f68322166 error
333953375258 dfd4bb45
70576474342b3730590a error
37 error
35 error
312078336f2f4d5144657978 d71de8fcc4037b2c
5a484c504d366a384b346c483a 6472cf33a8fc2b8947
2d563d2d616c352f6977 error
5f4375434579 fc2b8213
75753951644176 baef50740b
7430 b7
33476857 dc6856
2d6b706355633443634f fa4a5c51ce0270
544237215f703d516776745253 4c1effa5082fb514
51764e6b46 error
6236624c 6fa6cb
7678 bf
4a2b4f5554 error
4a6d 26
4a66394f304668763a79304f3658 error
313645 d7a1
66707944706942 7e9c83a620
3452532f532f3454 e114bf4bfe13
754d627951382b50 b8c6f243cf8f
4e7650424c52 36f3c12d
742d5f214453675544 b7efc34a0503
50547932625572 3d3cb66d4a
71586e34 a979f8
49456b514f36214a2f465a577547 error
722f af
5248 44
324a3079596b d89d3262
314f6d79666a487973622171 d4e9b27e31f2b1ba
2b375332445f77 fbb4b60ffc
385f30 f3fd
2177574e7266652b622b error
6c2f682d316a2e776f79 error
2e6f4837746b error
3059 d1
5a7739343561626b4f3330 670f78e5a6e43b7d
536e4479 4a70f2
716249 a9b2
2b46345a4a34 f85e1927
33384f57 dfc396
5a58636430 error
496e20765f484876644c5847 227bff1c7bdd2d71
732f747147547a2e b3fb6a193c
307173585320662f436c6945 d2ab1749ffc29621
57656745376f72 59e804ee8a
554f526843335954 50e4610b7613
6e38 9f
6c5a79506c644a6473426e52 959c8f95d25db019d1
2e
4f5973466f78744c337648 398b05a31b4bdef1
77683537524b7355216d354c c21e7b44ab149b92
4d552e4f3637774d6138 error
5275507154573053323d4566 46e3ea4d6d12d847
4850 1c
4d6f33 328d
3a36713a4f662d3162 eaa39ffb56
576d303949634155 5a6d3d21c014
6c4937493d 948ec8
7720394c5a62 error
6b72574455797a622d error
7139574854365343 abd5874fa482
2f304b7055 error
0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
6777343769 error
506b756b6a error
6c7877466b455869552f63552b35 971c059045e253f714fb
55677457692b435a5a54 520b568be09965
30 error
364e72206a32552031 e8dae3d94d
3449203463542e724d750a6d73 e08e1c4eb32e9a
4f21736c6d464544354978 3ac9661440f923
2f397464695230 ffdb5d891d
5f3a error
46 error
5159794c535f5774342f 418c8b4bf5ade3
2b416e7a3957763d463731 f809f3f56bc5ef
76484b585562 bc729751
57 error
617741655a3861396b670a42 6b001e67c6bd9200
3047475f5533656531456e56 d061bf53779ed449d5
4c745a 2ed6
39 error
457579626f7a6a4d 12ec9ba338cc
4b2d5f 2bef
55537a676f68614a4a692d21 512ce0a21689262f
493d3979380a72686e 23dcbcae19
584779596d2d4b484b57693036 error
416668575334 01f8564b
2e6a756e2147 8ee9c6
6b47424d212d594b7a67697a 90604cf982b3822c
397771554b6163 f70a9429a7
4836213a 1f
44474d575a error
7653780a44592f79 bd2c4363fc
50786c6834422d3a6d56503442 3f1961e01fa654fe01
56214b782b686c4951797a2d 54ac7e865210cb3f
53336130596d704c43 error
30 error
2b error
7774 c2
515651762e693a7a2074 41542f8b3b
7049673a7a71724d36756c4f a48833aab33aba53
1
2 51554a44 414243
3 515549 4142
4 5155 41
5 51 error
6 51554a443d51554a44 414243414243
7 51553d4a44 414243
8 3d51554a44 414243
9 51554a443d3d 414243
10 512b2d5f 43efbf
11 5155204a44 414243
12 51554a443d3d3d3d 414243
13 513d553d4a3d44 414243
14 2d436e590a45 error
15 517662595f4249632d3145495a44 42f6d8fc121cfb510864
16 42694d472b6c463a 062306fa51
17 6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
18 2d error
19 7620506247426135733d58597764 bcf6c605ae6c5d8c1d
20
21 30426974344a68763574203d41 d018ade0986fe6d0
22 5931455f324b5f2038736a3d 63513fd8affcb2
23 78653053 c5ed12
24 78456466743a68 c4475fb6
25 576e4f482d635f52616873443d77 error
26 34704f77746d4873316b2e3939 e293b0b661ecd64f7d
27 3657393d213a e96f
28 3d4469366e7142622167616230 0e2ea7a816e069bd
29 79737352 cacb11
30 734673 b05b
31 356f43 e680
32 736665 b1f7
33 5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
34 53484b 4872
35
36 63 error
37 424b 04
38 75685f48695155354f36704431 error
39 713468526c6c ab885196
40 2e6d3d49593452547358376f6867 988638453b17ee8860
41 2f2047312b2f78613355 error
42 4c42 2c
43 392e41426a450a333a f4006313
44
45 655374574a5776745f error
46 205635452b356a2f44 57913ee63fc3
47 4d536b664c2b6753 31291f2fe812
48 71554c5a765a7449 a942d9bd9b48
49 31586946722e4c46725968395f d57885acb16b621f7f
50 4e6d6b662135 error
51 4244 04
52
53 31536f43796f d52a02ca
54 735065433754 b0f782ed
55 2e615f33326635696d3162 6bfdf67f98a6d5
56 2f5f49362e586c664e546a42 fff23a5e57cd4e30
57 7441454c61426144 b4010b681683
58
59 3d484f6b 1ce9
60
61 50724f2f51536c39585962214651 error
62 683669545a316a59 87a8936758d8
63 62 error
64 4159512e4a5a64 01840965
65 6f3821595a794f6b792b33394731 error
66 6c2e4777763a 946c2f
67 69383a77476c544a3d43512f20 8bcc0695324243
68 4169 02
69 485a6557626441692177325a 1d97966dd022c366
70 4e35697578642d526465634a78 error
71 3146752f393965 d45bbff7d7
72 394321356378 error
73 57575632 596576
74 72592d4b4a303470673a38 ad8f8a274e2983
75 4b6775457758776751525a754e error
76 58437a50623643316438 5c2ccf6fa0b577
77 64380a20320a3859644e6a 77cdbc61d363
78 0a7777706b2d error
79 384c65426a7334692f555345 f0b7818ece22fd4484
80
81 3a65 error
82 6e3a7035727863712b4d6874666d error
83 78784f32627455386c error
84 6f error
85 7076794b55513a494471 error
86 2e0a476d344f4b3a630a4a7239 error
87 6a error
88 653163627068680a2f435474 7b571ba6187f093b
89 52787467454c77553a 471b6010bc14
90 6f694130737a4d3164 error
91 426a4c6f45635f79 0632e811cff2
92 514a4b63336b 40929cde
93 2b6e fa
94 7321506547217030746a b0f786a74b63
95 796564494d47504334316567 c9e7483063c2e357a0
96 76 error
97 20786374453379674a473048 c5cb44df28091b41
98 35714c7743 error
99 59794620756947 63216e88
100 784f2162 c4e6
101 213d4545 10
102 327a5453310a4b db34d2d4
103 50534b395071424f6a56213659 3d22bd3ea04e8d5e98
104 48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
105 45666c7471685a2f7375 11f96daa167fb2
106 76 error
107 73 error
108 7331714c34577a2d b35a8be16cfe
109 5353425a6c6453 49205995d4
110 2e4764663a3a35 19d7f9
111 4a2f51762d37334a3521 error
112 2d49 f8
113 4c4b6575 2ca7ae
114 743848485277 b7c1c747
115 6d69546d6f38312e6d7a error
116 6675617876364769577471 7ee6b1bfa1a25ada
117 205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
118 38652e706137715437777a f1ea5aeea4fbc3
119 48562d6a20714445 1d5fa3a831
120 6947 88
121
122
123 4462526121 0db45a
124
125
126 56464c39586475396d error
127
128 2b757953683638722148213858 faec9287af2b1fc5
129 7a64356b4a306e cdde642749
130 3d6d7a 9b
131 32205632634a31746f70 error
132 6e37684a52 error
133 5a0a6b 66
134 56722f582e2030485f48536775 56bfd7d07fc74a0b
135 6d64363368516b75 99deb785092e
136 7a error
137 786d5f4351 error
138 6133 6b
139 4156 01
140 3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
141 677945667865526c36632f386c2d 83211fc5e465e9cffc97
142 383051775a3a764e6d67500a4475 f3443066f36680f0ee
143 676c5277564269725851 8254705418ab5d
144 473d68376f54 error
145 3a382d4431576f6d3d684f error
146
147 415021 00
148 21532e3331460a 4b7d45
149 782e642e63513754514c4a4563 c5d710ed340b2447
150 385a6e21307821 error
151 7864686958 error
152 62374457 6fb0d6
153 704666694835 a457e21f
154 2152576f322b error
155 566d306b473d69576b3d51554e 566d241a25a44143
156 6258304634336a654a2d516774 error
157 52 error
158 736346346b6343493961 b1c17891c088f5
159 3a4143202b46333d43 002f85dc
160 346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
161 3a206a582b2e4f356b6d 8d7f8ee649
162 5336652b5051574354466367 4ba7be3d05824c5720
163 74626d2e733d513058 b5b9ac4345
164 55422173784f456b206231583448 501b3138491bd57e07
165 5a4b314252364d620a216e2e6659 64ad4147a31b9df6
166 58646b3a464953366c 5dd905212ea5
167 7566656c302b32 b9f7a5d3ed
168 774b c0
169
170 59304471 6340ea
171 5a error
172 5357357472736c205a2e6b54 496e6daec95991
173 470a error
174 7271 ae
175 2033795268393668 df2461f7a8
176 733453640a74696b2b7a3d723161 b3849db6293ecebd5a
177 5739 5b
178 6c2e713359544f6775 96add84ce82e
179 533843612d error
180 53742f2b6872516161657055 4adffe86b41a69ea54
181 5a48312b4e6c426f206e696652 647d7e3650689e27d1
182
183
184 3a4a error
185 34447950 e03c8f
186
187 772b535a76486f4350743a3141 c3e499bc7a023edd40
188 52 error
189
190 77414f c003
191 794d53787a426750687552434b64 c8c4b1cc180f86e44229
192 4d6b2f37496b 324ffb22
193 2b3131793132203334 fb5d72d76df8
194 75214852683a2f470a5463 b87461fc64dc
195 6735526b 839464
196 6e error
197
198 484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
199 6771537969742f3964303756542e error
200 46745a5f75563a65 16d67fb957
201 50 error
202 313549 d792
203 6e4b79364955664a 9cacba2147c9
204 572f31785521 error
205 33513031537a55354856707773 error
206 4334452b5663662d4e5a4a5a 0b813e55c7fe359259
207 36727a eabc
208 696c4d526b4a4433792d533d59 8a53119090f7cbe498
209 7653416e56 error
210 0a7978692b cb18be
211 6f796e35473149315635 a329f91b523557
212
213 4435532d3a6c5f5255725042 0f94be97f454acf0
214 5f39 ff
215 6f747331674d674c3932 a2db3580c80bf7
216 5f66562b74393672483064 fdf57eb7deab1f47
217 30363d6950 d3a88f
218 35505934446643650a e4f6380df09e
219 4b6d372f34546358 2a6effe13717
220 2f3277 ff6c
221 217021454c544b5276723a50 error
222 69357a6664774b4d 8b9cdf77028c
223 5a58 65
224 53663671616f2149 49feaa6a82
225 4c205175300a6c77346b7665 2d0bb4970e24bd
226 735137543a59552164376c7556 b10ed361477b96e5
227 703744 a7b0
228 614579595547785a63764c 684c98506c5972f2
229 3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
230 5855 5d
231 50514f2b5a58 3d03be65
232 623242 6f60
233 46316947526d414a4a47355a65 error
234 3877444c56576b440a4a error
235 4f4f456f 38e128
236 4c586e734746425a5521 error
237 535959 4986
238 2b764e0a5249660a58 faf35121f5
239 3630543936 error
240 6672473d55 7eb194
241 41686a5372213879682d79384f63 error
242 5667422d667131750a44 error
243 705744534d702b a560d2329f
244 687577 86ec
245 2164386f2e696b584f725348 77ca229173ab48
246 65326e75756b2f6b7849 7b69eeba4fe4c4
247 6c657374 95eb2d
248 3a744f b4
249 375267 ed18
250 6f4c214668 a0b161
251 795278456b2d5f69 c91c4493efe2
252 3d372e error
253
254 6a397434516530673239 8fdb7841ed20db
255 38206b44372034576a46 f240fbe168c5
256 3554393a55433231412d3770 e53f540b6d40fbba
257 3a6b46 90
258 6c63 95
259 4e48496758366d715a53597659 error
260 21566556 55e5
261 495442684a3d747a 21306126dc
262 0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
263 734d3d62414a2b4534723a7949 b0c6c027e138af22
264 6b66534c655759445220535f 91f48b796603452f
265 4d6a4659795277424943 323158c91c0120
266 46433a662e4943 error
267 2d614e713864 f9a36af1
268 7a4277713777454c4f4a cc1c2aef010b38
269 4730 1b
270 66744a412d517347446c3462 7ed240f90b060e5e1b
271 77 error
272 6621 error
273 6f643a4e4f7366 a1d34eb1
274 50374b73756e495537374a347631 3fb2acba7214efb278bf
275 32720a da
276 534137334d642f4e44516f61 480ef731dfcd0d0a1a
277 636664734a0a4a38656b4f2b354a error
278 4449706d 0c8a66
279 705a2b345248204671517a322b63 error
280 6e305220427a787a 9f4441cf1c
281 6170363a587774334b34783074 6a9e97c2ddcae31d2d
282 4376317a34 error
283 79 error
284 2d640a49593669596b f9d218ea2624
285 6968446b0a344447595841317766 error
286 754221467743552e2b b81170094f
287 65434d37 78233b
288 6379354a2b696b41455f453337 error
289 2e363a740a346432 error
290 4a error
291 445075 0cfb
292 6b694247 922046
293 4b656b397370520a31456f6651 29e93db294751287d0
294 6e7165375461645750564c3274 error
295 5f77437a2b78542145312e6f57 ff00b3fb14c4d685
296 43652b7121 09efaa
297 436e3569547056 0a7e624e95
298 342b2f736e70646f0a765744554b error
299 692b6b306b743731 8be93492def5
300 50647478715f68322166 error
301 333953375258 dfd4bb45
302 70576474342b3730590a error
303 37 error
304 35 error
305 312078336f2f4d5144657978 d71de8fcc4037b2c
306 5a484c504d366a384b346c483a 6472cf33a8fc2b8947
307 2d563d2d616c352f6977 error
308 5f4375434579 fc2b8213
309 75753951644176 baef50740b
310 7430 b7
311 33476857 dc6856
312 2d6b706355633443634f fa4a5c51ce0270
313 544237215f703d516776745253 4c1effa5082fb514
314 51764e6b46 error
315 6236624c 6fa6cb
316 7678 bf
317 4a2b4f5554 error
318 4a6d 26
319 4a66394f304668763a79304f3658 error
320 313645 d7a1
321 66707944706942 7e9c83a620
322 3452532f532f3454 e114bf4bfe13
323 754d627951382b50 b8c6f243cf8f
324 4e7650424c52 36f3c12d
325 742d5f214453675544 b7efc34a0503
326 50547932625572 3d3cb66d4a
327
328 71586e34 a979f8
329 49456b514f36214a2f465a577547 error
330 722f af
331 5248 44
332 324a3079596b d89d3262
333 314f6d79666a487973622171 d4e9b27e31f2b1ba
334 2b375332445f77 fbb4b60ffc
335 385f30 f3fd
336 2177574e7266652b622b error
337 6c2f682d316a2e776f79 error
338 2e6f4837746b error
339 3059 d1
340
341 5a7739343561626b4f3330 670f78e5a6e43b7d
342 536e4479 4a70f2
343 716249 a9b2
344 2b46345a4a34 f85e1927
345
346 33384f57 dfc396
347 5a58636430 error
348 496e20765f484876644c5847 227bff1c7bdd2d71
349 732f747147547a2e b3fb6a193c
350 307173585320662f436c6945 d2ab1749ffc29621
351 57656745376f72 59e804ee8a
352 554f526843335954 50e4610b7613
353 6e38 9f
354
355 6c5a79506c644a6473426e52 959c8f95d25db019d1
356 2e
357 4f5973466f78744c337648 398b05a31b4bdef1
358 77683537524b7355216d354c c21e7b44ab149b92
359 4d552e4f3637774d6138 error
360 5275507154573053323d4566 46e3ea4d6d12d847
361 4850 1c
362 4d6f33 328d
363 3a36713a4f662d3162 eaa39ffb56
364
365 576d303949634155 5a6d3d21c014
366 6c4937493d 948ec8
367 7720394c5a62 error
368 6b72574455797a622d error
369 7139574854365343 abd5874fa482
370 2f304b7055 error
371 0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
372 6777343769 error
373 506b756b6a error
374 6c7877466b455869552f63552b35 971c059045e253f714fb
375 55677457692b435a5a54 520b568be09965
376 30 error
377 364e72206a32552031 e8dae3d94d
378 3449203463542e724d750a6d73 e08e1c4eb32e9a
379 4f21736c6d464544354978 3ac9661440f923
380 2f397464695230 ffdb5d891d
381 5f3a error
382 46 error
383 5159794c535f5774342f 418c8b4bf5ade3
384 2b416e7a3957763d463731 f809f3f56bc5ef
385 76484b585562 bc729751
386 57 error
387 617741655a3861396b670a42 6b001e67c6bd9200
388 3047475f5533656531456e56 d061bf53779ed449d5
389
390 4c745a 2ed6
391 39 error
392 457579626f7a6a4d 12ec9ba338cc
393 4b2d5f 2bef
394 55537a676f68614a4a692d21 512ce0a21689262f
395 493d3979380a72686e 23dcbcae19
396 584779596d2d4b484b57693036 error
397 416668575334 01f8564b
398 2e6a756e2147 8ee9c6
399 6b47424d212d594b7a67697a 90604cf982b3822c
400 397771554b6163 f70a9429a7
401 4836213a 1f
402
403 44474d575a error
404 7653780a44592f79 bd2c4363fc
405 50786c6834422d3a6d56503442 3f1961e01fa654fe01
406
407 56214b782b686c4951797a2d 54ac7e865210cb3f
408 53336130596d704c43 error
409 30 error
410 2b error
411 7774 c2
412 515651762e693a7a2074 41542f8b3b
413 7049673a7a71724d36756c4f a48833aab33aba53
+143
View File
@@ -0,0 +1,143 @@
//! Durable form of a signed message that has not finished delivery.
use super::*;
/// The signed header (destination, source, signature) ends here, and an LXMF
/// payload would begin.
const HEADER_LEN: usize = 96;
/// `0xC1` is never valid MessagePack, so no LXMF parser reads a stored form as
/// a message.
const MAGIC: [u8; 4] = [0xc1, b'L', b'X', b'R'];
const VERSION: u8 = 2;
/// Version 1 stored an integer floor; it is still read.
const VERSION_INTEGER_FLOOR: u8 = 1;
const DIGEST_LEN: usize = 16;
const FLOOR_AT: usize = HEADER_LEN + MAGIC.len() + 1;
const STAMP_AT: usize = FLOOR_AT + 2;
/// A signed, unstamped message stored so delivery can resume after a restart.
///
/// Version 2 holds, in order:
/// - the signed header: destination, source and signature (96 bytes);
/// - the bytes `0xC1`, `L`, `X`, `R`, then the version byte;
/// - the stamp cost the message was signed under, as a big-endian fixed-point
/// cost on the 1/256 grid, 0 meaning none (version 1 held a presence byte
/// and an integer cost);
/// - reserved slots for a finished recipient stamp (a length byte of 0, 16
/// or 32, then the stamp) and a propagation envelope (a big-endian `u32`
/// length, then the envelope). Both are written empty, and a reader of
/// this version ignores filled slots and redoes that work;
/// - the signed payload;
/// - the first 16 bytes of the SHA-256 of everything before them.
///
/// It is not a wire message: [`LxMessage::unpack`] rejects it, because byte
/// 96 is `0xC1`. Restore it with
/// [`LxmRouter::restore_signed`](crate::router::LxmRouter::restore_signed).
#[derive(Clone, PartialEq, Eq)]
pub struct ResumableLxMessage {
bytes: Bytes,
stamp_cost_floor: Option<u16>,
payload_at: usize,
}
impl std::fmt::Debug for ResumableLxMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResumableLxMessage")
.field("len", &self.bytes.len())
.finish_non_exhaustive()
}
}
impl ResumableLxMessage {
pub(super) fn new(wire: &[u8], stamp_cost: Option<f64>) -> Self {
let floor_fp = stamp_cost
.and_then(|cost| crate::stamper::cost_to_fp(cost).ok())
.unwrap_or(0);
let stamp_cost = (floor_fp > 0).then_some(floor_fp);
let mut bytes = Vec::with_capacity(wire.len() + STAMP_AT + 5 + DIGEST_LEN);
bytes.extend_from_slice(&wire[..HEADER_LEN]);
bytes.extend_from_slice(&MAGIC);
bytes.push(VERSION);
bytes.extend_from_slice(&floor_fp.to_be_bytes());
bytes.push(0);
bytes.extend_from_slice(&0u32.to_be_bytes());
let payload_at = bytes.len();
bytes.extend_from_slice(&wire[HEADER_LEN..]);
let digest = sha256(&bytes);
bytes.extend_from_slice(&digest[..DIGEST_LEN]);
Self {
bytes: bytes.into(),
stamp_cost_floor: stamp_cost,
payload_at,
}
}
/// Check a stored form's structure and digest. The signature is checked
/// when the message is restored, against the sender's key.
pub fn from_bytes(bytes: impl Into<Bytes>) -> Result<Self, MessageError> {
let bytes = bytes.into();
let invalid =
|reason: &str| MessageError::UnpackFailed(format!("resumable message: {reason}"));
if bytes.len() < STAMP_AT + 5 + 1 + DIGEST_LEN {
return Err(invalid("too short"));
}
if bytes[HEADER_LEN..HEADER_LEN + MAGIC.len()] != MAGIC {
return Err(invalid("not a stored message"));
}
let version = bytes[HEADER_LEN + MAGIC.len()];
if version != VERSION && version != VERSION_INTEGER_FLOOR {
return Err(invalid("unsupported version"));
}
let digest_at = bytes.len() - DIGEST_LEN;
if sha256(&bytes[..digest_at])[..DIGEST_LEN] != bytes[digest_at..] {
return Err(invalid("damaged"));
}
let floor = [bytes[FLOOR_AT], bytes[FLOOR_AT + 1]];
let stamp_cost_floor = match (version, floor) {
(_, [0, 0]) => None,
(VERSION_INTEGER_FLOOR, [1, cost]) => Some(u16::from(cost.min(100)) * 256),
(VERSION, _) if u16::from_be_bytes(floor) <= crate::stamper::STAMP_COST_CAP_FP => {
Some(u16::from_be_bytes(floor))
}
_ => return Err(invalid("invalid stamp cost")),
};
let stamp_len = usize::from(bytes[STAMP_AT]);
if !matches!(stamp_len, 0 | 16 | 32) {
return Err(invalid("invalid recipient stamp"));
}
let envelope_len_at = STAMP_AT + 1 + stamp_len;
let envelope_len = bytes
.get(envelope_len_at..envelope_len_at + 4)
.map(|len| u32::from_be_bytes(len.try_into().expect("four bytes")) as usize)
.ok_or_else(|| invalid("truncated"))?;
let payload_at = (envelope_len_at + 4)
.checked_add(envelope_len)
.filter(|at| *at < digest_at)
.ok_or_else(|| invalid("truncated"))?;
if bytes[payload_at] != 0x94 {
return Err(invalid("payload is not a signed, unstamped body"));
}
Ok(Self {
bytes,
stamp_cost_floor,
payload_at,
})
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub(crate) fn stamp_cost_floor(&self) -> Option<f64> {
self.stamp_cost_floor
.map(|fp| crate::stamper::cost_from_fp(u32::from(fp)))
}
/// The signed, unstamped message. Its signature is not yet checked.
pub(crate) fn unverified_message(&self) -> Result<LxMessage, MessageError> {
let digest_at = self.bytes.len() - DIGEST_LEN;
let mut wire = Vec::with_capacity(HEADER_LEN + digest_at - self.payload_at);
wire.extend_from_slice(&self.bytes[..HEADER_LEN]);
wire.extend_from_slice(&self.bytes[self.payload_at..digest_at]);
LxMessage::unpack_owned(wire.into(), MessageDecodeLimits::default())
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+308 -102
View File
@@ -1,28 +1,158 @@
//! Persistent router state — matches Python `<storagepath>/lxmf/` layout.
//! Router state files in a caller-supplied directory.
//!
//! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
//! * `available_tickets` — `Vec<Ticket>`
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//! * `node_stats` — propagation-node counters
//! * `propagation_suppression_v1` — bounded download suppression records
//! * `propagation_node_policies_v1` — recorded propagation-node policies
//!
//! All four files are MessagePack-encoded via `rmp-serde`. Missing files are
//! treated as "no prior state" and do not raise errors — a fresh daemon is a
//! valid state.
//! Stamp costs, tickets, and delivered and processed transient IDs live in
//! `state.db` ([`crate::state_store`]). `delivery_claims`, which earlier
//! releases appended to, is only read here so its records can be imported.
//!
//! Missing files yield empty/default state. Other I/O, malformed-data and
//! capacity errors propagate to the caller.
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::Ticket;
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)]
pub struct PersistedNodeStats {
pub client_propagation_messages_received: u64,
pub client_propagation_messages_served: u64,
pub unpeered_propagation_incoming: u64,
pub unpeered_propagation_rx_bytes: u64,
}
/// Publish exact bytes through the strict platform durability boundary.
/// CommitUncertain remains an error: readback alone cannot authorize a receipt.
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
rns_identity::persistence::durable_write(path, data)
.map(|_| ())
.map_err(io::Error::other)
}
/// Suppression state cannot authorize a remote purge. Adapters nevertheless
/// persist it before allowing the next automatic wants selection.
pub fn save_suppression(
dir: &Path,
ledger: &crate::admission::SuppressionLedger,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_suppression_v1"), ledger)
}
pub fn load_suppression(dir: &Path) -> io::Result<crate::admission::SuppressionLedger> {
// Preserve the existing one-field wrapper while rejecting duplicate keys,
// mismatched embedded scope and quota violations before hydration.
#[derive(serde::Deserialize)]
struct Wire {
#[serde(deserialize_with = "suppression_records")]
records: Vec<crate::admission::SuppressionRecord>,
}
let wire: Option<Wire> =
read_mpk_bounded(&dir.join("propagation_suppression_v1"), 65536 * 512 + 4096)?;
crate::admission::SuppressionLedger::from_records(
wire.map_or_else(Vec::new, |wire| wire.records),
)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
fn suppression_records<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Vec<crate::admission::SuppressionRecord>, D::Error> {
struct Records;
impl<'de> serde::de::Visitor<'de> for Records {
type Value = Vec<crate::admission::SuppressionRecord>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("bounded unique suppression map")
}
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut seen = std::collections::HashSet::new();
let mut records = Vec::new();
while let Some((scope,record))=map.next_entry::<crate::admission::AdmissionScope,crate::admission::SuppressionRecord>()? {
if scope!=record.scope || !seen.insert(scope) || records.len()>=crate::admission::SuppressionLedger::GLOBAL {
return Err(serde::de::Error::custom("invalid suppression scope or capacity"));
}
records.push(record);
}
Ok(records)
}
}
deserializer.deserialize_map(Records)
}
pub fn save_node_policies(
dir: &Path,
policies: &HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_node_policies_v1"), policies)
}
pub fn load_node_policies(
dir: &Path,
) -> io::Result<HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>> {
Ok(read_mpk(&dir.join("propagation_node_policies_v1"))?.unwrap_or_default())
}
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
let bytes =
@@ -30,60 +160,48 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let tmp = path.with_extension("tmp");
fs::write(&tmp, &bytes)?;
fs::rename(&tmp, path)?;
Ok(())
write_file_atomic(path, &bytes)
}
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
match fs::read(path) {
Ok(bytes) => {
let value = rmp_serde::from_slice(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(value))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
read_mpk_bounded(path, 64 * 1024 * 1024)
}
fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
path: &Path,
limit: usize,
) -> io::Result<Option<T>> {
use std::io::Read;
let file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut bytes = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > limit {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"router state exceeds bounded capacity",
));
}
// Allocation-free structural walk precedes serde's collection size hints.
// It also rejects trailing roots, deep nesting and truncated huge lengths.
let encoded = crate::message::EncodedFieldValue::new(bytes.into())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
rmp_serde::from_slice(encoded.encoded())
.map(Some)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> {
write_mpk(&dir.join(STAMP_COSTS_FILE), costs)
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
let bytes = rmp_serde::to_vec_named(stats)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
fs::create_dir_all(dir)?;
write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes)
}
pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEntry>> {
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &[Ticket]) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), &tickets)
}
pub fn load_tickets(dir: &Path) -> io::Result<Vec<Ticket>> {
Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default())
}
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 load_node_stats(dir: &Path) -> io::Result<PersistedNodeStats> {
Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default())
}
#[cfg(test)]
@@ -91,50 +209,138 @@ 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 = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
save_tickets(tmp.path(), &tickets).unwrap();
let loaded = load_tickets(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].token, [0x01; 16]);
assert_eq!(loaded[0].destination_hash, [0x02; 16]);
}
#[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());
assert!(load_tickets(tmp.path()).unwrap().is_empty());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
load_node_stats(tmp.path()).unwrap(),
PersistedNodeStats::default()
);
let (delivered, processed) = load_delivery_claims(tmp.path()).unwrap();
assert!(delivered.is_empty() && processed.is_empty());
}
#[test]
fn node_stats_roundtrip_uses_named_python_fields() {
let tmp = TempDir::new().unwrap();
let expected = PersistedNodeStats {
client_propagation_messages_received: 11,
client_propagation_messages_served: 12,
unpeered_propagation_incoming: 13,
unpeered_propagation_rx_bytes: 14,
};
save_node_stats(tmp.path(), &expected).unwrap();
assert_eq!(load_node_stats(tmp.path()).unwrap(), expected);
let encoded = fs::read(tmp.path().join(NODE_STATS_FILE)).unwrap();
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(encoded)).unwrap();
let keys = value
.as_map()
.unwrap()
.iter()
.filter_map(|(key, _)| key.as_str())
.collect::<std::collections::HashSet<_>>();
assert!(keys.contains("client_propagation_messages_received"));
assert!(keys.contains("client_propagation_messages_served"));
assert!(keys.contains("unpeered_propagation_incoming"));
assert!(keys.contains("unpeered_propagation_rx_bytes"));
}
#[test]
fn write_file_atomic_writes_and_replaces_without_leftover_tmp() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("message");
write_file_atomic(&path, b"first").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"first");
// Replaces existing content (os.replace semantics — LXMessage.py).
write_file_atomic(&path, b"second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"second");
// No .tmp.* residue in the directory after successful writes.
let leftovers: Vec<_> = fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn write_file_atomic_cleans_tmp_on_error() {
let tmp = TempDir::new().unwrap();
// Destination is a directory: the final rename fails, and the tmp
// file must be unlinked (LXMessage.py).
let dir_path = tmp.path().join("collide");
fs::create_dir(&dir_path).unwrap();
assert!(write_file_atomic(&dir_path, b"data").is_err());
let leftovers: Vec<_> = fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn serialization_failure_preserves_existing_file_without_temp_residue() {
struct FailsToSerialize;
impl serde::Serialize for FailsToSerialize {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("intentional failure"))
}
}
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("state");
fs::write(&path, b"previous-good-state").unwrap();
assert!(write_mpk(&path, &FailsToSerialize).is_err());
assert_eq!(fs::read(&path).unwrap(), b"previous-good-state");
assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1);
}
#[test]
fn concurrent_atomic_writers_never_publish_torn_data_or_collide_on_temp_names() {
use std::sync::{Arc, Barrier};
let tmp = TempDir::new().unwrap();
let path = Arc::new(tmp.path().join("shared"));
let barrier = Arc::new(Barrier::new(8));
let payloads = (0u8..8)
.map(|value| vec![value; 16 * 1024])
.collect::<Vec<_>>();
let threads = payloads
.iter()
.cloned()
.map(|payload| {
let path = Arc::clone(&path);
let barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
write_file_atomic(path.as_ref(), &payload).unwrap();
})
})
.collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
let published = fs::read(path.as_ref()).unwrap();
assert!(payloads.contains(&published));
let leftovers = fs::read_dir(tmp.path())
.unwrap()
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
.count();
assert_eq!(leftovers, 0);
}
}
+274
View File
@@ -0,0 +1,274 @@
//! Safe presentation helpers for untrusted announce metadata.
use unicode_normalization::UnicodeNormalization;
/// Maximum retained characters for an advertised LXMF display/node name.
pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name 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,
/// and broad emoji/symbol ranges. Tabs and newlines are removed. Remaining
/// whitespace collapses to one ASCII space, with no leading or trailing space.
/// The length limit counts Unicode scalar values, not UTF-8 bytes.
pub fn sanitize_name(input: &str, max_chars: usize) -> String {
let mut output = sanitize_name_pass(input, max_chars);
let rounds = output.nfkd().count().saturating_add(2);
for _ in 0..rounds {
let next = sanitize_name_pass(&output, max_chars);
if next == output {
return output;
}
output = next;
}
debug_assert!(
false,
"name normalization exceeded its derived stabilization bound"
);
String::new()
}
fn sanitize_name_pass(input: &str, max_chars: usize) -> String {
if max_chars == 0 {
return String::new();
}
let mut output = String::new();
let mut pending_space = false;
let mut retained = 0usize;
for character in input.nfkc() {
if is_filtered_name_character(character) {
continue;
}
if character.is_whitespace() {
pending_space = !output.is_empty();
continue;
}
if pending_space {
// A collapsed separator is useful only when the current visible
// character also fits. Never consume the final slot with a
// trailing space that disappears on the next sanitization pass.
if max_chars.saturating_sub(retained) < 2 {
break;
}
output.push(' ');
retained += 1;
pending_space = false;
}
if retained == max_chars {
break;
}
output.push(character);
retained += 1;
}
output
}
fn is_filtered_name_character(character: char) -> bool {
let codepoint = character as u32;
character.is_control()
|| is_bidi_control(codepoint)
|| is_private_use(codepoint)
|| is_zero_width(codepoint)
|| is_variation_selector(codepoint)
|| is_emoji(codepoint)
}
fn is_bidi_control(codepoint: u32) -> bool {
matches!(
codepoint,
0x061C
| 0x200E
| 0x200F
| 0x202A..=0x202E
| 0x2066..=0x2069
| 0x206A..=0x206F
)
}
fn is_private_use(codepoint: u32) -> bool {
matches!(
codepoint,
0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD
)
}
fn is_zero_width(codepoint: u32) -> bool {
matches!(
codepoint,
0x034F | 0x180E | 0x200B..=0x200D | 0x2060 | 0xFEFF
)
}
fn is_variation_selector(codepoint: u32) -> bool {
matches!(codepoint, 0xFE00..=0xFE0F | 0xE0100..=0xE01EF)
}
// Bounded presentation policy, intentionally broader than a font-dependent
// emoji lookup. It covers the Unicode emoji blocks and legacy symbol ranges
// that gain emoji presentation through variation selectors.
fn is_emoji(codepoint: u32) -> bool {
matches!(
codepoint,
0x00A9
| 0x00AE
| 0x203C
| 0x2049
| 0x2122
| 0x2139
| 0x2190..=0x21FF
| 0x2300..=0x23FF
| 0x2460..=0x24FF
| 0x25A0..=0x27BF
| 0x2934..=0x2935
| 0x2B00..=0x2BFF
| 0x3030
| 0x303D
| 0x3297
| 0x3299
| 0x1F000..=0x1FAFF
)
}
/// 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::*;
use proptest::prelude::*;
#[test]
fn normalizes_nfkc_and_collapses_unicode_whitespace() {
assert_eq!(
sanitize_name(" RNS\u{00A0}\tCommunity ", 128),
"RNS Community"
);
}
#[test]
fn removes_controls_bidi_private_use_emoji_variants_and_zero_width() {
let hostile = "safe\n\u{202E}txt\u{E000}\u{1F680}\u{FE0F}\u{200D} name";
assert_eq!(sanitize_name(hostile, 128), "safetxt name");
}
#[test]
fn truncates_multibyte_text_by_characters_without_panicking() {
assert_eq!(sanitize_name("Ångström東京", 8), "Ångström");
assert_eq!(sanitize_name("東京通信", 3), "東京通");
assert_eq!(sanitize_name("anything", 0), "");
}
#[test]
fn truncation_never_retains_a_separator_without_following_text() {
assert_eq!(sanitize_name("¡ A", 2), "¡");
assert_eq!(sanitize_name("A B", 3), "A B");
}
#[test]
fn normalization_reaches_fixed_point_after_filtered_separators() {
for input in [
"A\u{0000}\u{030A}",
"e\u{034f}\u{0301}",
"o\u{200d}\u{0308}",
] {
for limit in 0..8 {
let once = sanitize_name(input, limit);
assert_eq!(sanitize_name(&once, limit), once);
assert_eq!(once.nfkc().collect::<String>(), once);
}
}
assert_eq!(sanitize_name("™", 128), "TM");
}
proptest! {
#[test]
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
let sanitized = sanitize_name(&input, limit);
prop_assert!(sanitized.chars().count() <= limit);
prop_assert_eq!(sanitize_name(&sanitized, limit), sanitized);
}
}
}
+176 -58
View File
@@ -1,6 +1,7 @@
//! Store-and-forward message storage for LXMF propagation nodes.
//! In-memory propagation-entry accounting, deduplication caches and distribution queue.
//!
//! Mirrors propagation entry management in Python LXMRouter.py.
//! The owning router or node handles durable files and admission. Weight-based
//! culling uses the formula from Python `LXMRouter.get_weight`.
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -14,10 +15,11 @@ pub struct PropagationEntry {
pub message_hash: [u8; 32],
pub destination_hash: [u8; 16],
pub stored_at: f64,
pub stamp_value: u8,
/// Quantized stamp value, as Python stores it.
pub stamp_value: f64,
pub size: usize,
pub collected: bool,
/// Stored file contains `lxmf_data || propagation_stamp`.
/// When true, the stored file contains `lxmf_data || propagation_stamp`.
///
/// Client download strips the stamp; peer sync keeps it.
pub stamped: bool,
@@ -29,7 +31,7 @@ impl PropagationEntry {
message_hash: [u8; 32],
destination_hash: [u8; 16],
size: usize,
stamp_value: u8,
stamp_value: f64,
) -> Self {
Self {
transient_id,
@@ -48,7 +50,7 @@ impl PropagationEntry {
message_hash: [u8; 32],
destination_hash: [u8; 16],
size: usize,
stamp_value: u8,
stamp_value: f64,
) -> Self {
let mut entry = Self::new(
transient_id,
@@ -61,50 +63,63 @@ impl PropagationEntry {
entry
}
/// Format: `{hex_transient_id}_{timestamp}_{stamp_value}`.
/// Python's message-store name `{hex_transient_id}_{received}_{stamp_value}`,
/// with both numbers in Python float form and no value part for value 0.
pub fn filename(&self) -> String {
let value = if self.stamp_value > 0.0 {
format!("_{:?}", self.stamp_value)
} else {
String::new()
};
format!(
"{}_{:.0}_{}",
"{}_{:?}{value}",
hex_encode(&self.transient_id),
self.stored_at,
self.stamp_value
self.stored_at
)
}
/// Accepts canonical 64-hex transient IDs in both the 3-component format
/// and the older 2-component `{transient_id}_{timestamp}` form (stamp_value
/// defaults to 0). Pre-fix 32-hex transient IDs are rejected.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
/// defaults to 0). Shortened 32-hex transient IDs are rejected.
///
/// # Panics
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
/// Validate that untrusted filenames are ASCII before calling.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, f64)> {
let parts: Vec<&str> = filename.split('_').collect();
match parts.len() {
3 => {
let tid = hex_decode_32(parts[0])?;
let ts: f64 = parts[1].parse().ok()?;
let sv: u8 = parts[2].parse().ok()?;
Some((tid, ts, sv))
let sv: f64 = parts[2].parse().ok()?;
Some((tid, ts, crate::stamper::quantize_cost(sv).ok()?))
}
2 => {
let tid = hex_decode_32(parts[0])?;
let ts: f64 = parts[1].parse().ok()?;
Some((tid, ts, 0))
Some((tid, ts, 0.0))
}
_ => None,
}
}
}
/// Owned by the router actor; no shared access.
/// In-memory index and accounting state. Mutations require exclusive access;
/// the owner handles synchronization, durable storage and admission policy.
#[derive(Debug, Default)]
pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>,
total_size: usize,
locally_delivered_ids: HashSet<PropagationTransientId>,
locally_processed_ids: HashSet<PropagationTransientId>,
/// Dedup caches: transient ID → first-seen Unix time. Age-based retention
/// (`MESSAGE_EXPIRY * 6`), persisted with their real timestamps.
locally_delivered_ids: HashMap<PropagationTransientId, f64>,
locally_processed_ids: HashMap<PropagationTransientId, f64>,
ignored_destinations: HashSet<[u8; 16]>,
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[u8; 16]>,
peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>,
/// `None` disables the byte-size cap.
/// Optional byte-limit setting. This type does not enforce it automatically;
/// the owner must call culling with its chosen limit.
pub storage_limit: Option<usize>,
}
@@ -114,10 +129,21 @@ impl PropagationStore {
}
/// Returns `false` if the destination is in the ignored list.
///
/// The caller must exclude an existing transient ID before inserting.
/// Replacing one adds the new size without subtracting the previous size.
/// This method performs no persistence, stamp validation or size-limit check.
pub fn insert(&mut self, entry: PropagationEntry) -> bool {
if self.ignored_destinations.contains(&entry.destination_hash) {
return false;
}
self.insert_admitted(entry)
}
/// Account for an entry whose admission policy was checked before its
/// durable publication. Later ignore-list changes affect future admissions,
/// not a write already accepted under the node's reservation authority.
pub(crate) fn insert_admitted(&mut self, entry: PropagationEntry) -> bool {
self.total_size += entry.size;
self.entries.insert(entry.transient_id, entry);
true
@@ -169,11 +195,12 @@ impl PropagationStore {
}
}
/// Cull messages by weighted score until total size is within `limit_bytes`.
/// Remove indexed entries by weighted score until accounted size is within
/// `limit_bytes`, assuming each transient ID was inserted only once.
///
/// Score = priority_weight * age_weight * size. Evicts highest-weight first
/// (oldest + largest + non-prioritised). Matches Python
/// `clean_message_store()` in LXMRouter.py.
/// Score = priority_weight * age_weight * size. Highest scores go first,
/// using Python `LXMRouter.get_weight`'s formula. This updates the in-memory
/// index and byte count; it does not delete message files.
pub fn cull_by_weight(&mut self, limit_bytes: usize) {
if self.total_size <= limit_bytes {
return;
@@ -231,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)
}
@@ -256,45 +283,77 @@ impl PropagationStore {
}
pub fn mark_locally_delivered(&mut self, transient_id: PropagationTransientId) {
self.locally_delivered_ids.insert(transient_id);
self.locally_delivered_ids
.insert(transient_id, crate::now_f64());
}
pub fn is_locally_delivered(&self, transient_id: &PropagationTransientId) -> bool {
self.locally_delivered_ids.contains(transient_id)
self.locally_delivered_ids.contains_key(transient_id)
}
pub fn mark_locally_processed(&mut self, transient_id: PropagationTransientId) {
self.locally_processed_ids.insert(transient_id);
self.locally_processed_ids
.insert(transient_id, crate::now_f64());
}
/// 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(transient_id)
self.locally_processed_ids.contains_key(transient_id)
}
pub fn locally_delivered_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_delivered_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_delivered_ids
}
pub fn locally_processed_ids(&self) -> &HashSet<PropagationTransientId> {
pub fn locally_processed_ids(&self) -> &HashMap<PropagationTransientId, f64> {
&self.locally_processed_ids
}
pub fn replace_locally_delivered(&mut self, ids: HashSet<PropagationTransientId>) {
/// 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;
}
pub fn replace_locally_processed(&mut self, ids: HashSet<PropagationTransientId>) {
pub fn replace_locally_processed(&mut self, ids: HashMap<PropagationTransientId, f64>) {
self.locally_processed_ids = ids;
}
/// Drop cache entries whose transient IDs no longer exist in `entries`
/// (i.e. were culled). Python removes them once older than
/// MESSAGE_EXPIRY * 6; the caller decides the cutoff here.
pub fn clean_transient_caches(&mut self) {
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
/// `LXMRouter.clean_transient_id_caches`). Retention is
/// purely age-based: entries must outlive their store membership so a
/// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
self.locally_delivered_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
self.locally_processed_ids
.retain(|id| self.entries.contains_key(id));
.retain(|_, timestamp| now <= *timestamp + expiry);
}
/// `from_peer` is the peer we received this message from, or `None` if it
@@ -371,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,
@@ -382,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]
@@ -392,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]
@@ -401,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]
@@ -415,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);
@@ -432,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);
@@ -455,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);
@@ -466,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);
@@ -481,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);
}
@@ -515,16 +598,45 @@ mod tests {
assert!(store.is_locally_processed(&transient_id));
}
/// T1-10: dedup caches are age-based (Python MESSAGE_EXPIRY*6), not keyed
/// to store membership — a culled-and-reoffered message must still be
/// recognised; entries expire only once their timestamp ages out.
#[test]
fn test_transient_caches_age_based_retention() {
let expiry = crate::constants::MESSAGE_EXPIRY as f64 * 6.0;
let mut store = PropagationStore::new();
let transient_id = tid(0xAA);
store.mark_locally_delivered(transient_id);
store.mark_locally_processed(transient_id);
let stamped_at = *store.locally_delivered_ids().get(&transient_id).unwrap();
// The entry was never inserted into the store at all — cleaning must
// still retain it while it is young (store-cull independence).
store.clean_transient_caches(stamped_at + 60.0);
assert!(store.is_locally_delivered(&transient_id));
assert!(store.is_locally_processed(&transient_id));
// Still retained just inside the expiry horizon...
store.clean_transient_caches(stamped_at + expiry - 1.0);
assert!(store.is_locally_delivered(&transient_id));
// ...and dropped once aged out.
store.clean_transient_caches(stamped_at + expiry + 1.0);
assert!(!store.is_locally_delivered(&transient_id));
assert!(!store.is_locally_processed(&transient_id));
}
#[test]
fn test_cull_by_weight() {
let mut store = PropagationStore::new();
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;
@@ -568,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,
@@ -591,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);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+346
View File
@@ -0,0 +1,346 @@
//! Typed evaluation of an inbound propagation-node `/offer` request.
//!
//! Admission policy and lifecycle accounting deliberately live in
//! [`crate::propagation_admission`]. Callers must pass that cheap preflight
//! before performing the peering-key work in this module, then commit the
//! returned wanted outcome to the same admission candidate.
use crate::propagation_admission::PnOfferResponse;
use crate::stamper;
use crate::sync::OfferResponse;
use crate::types::PropagationTransientId;
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
/// Offer outcome and the subset absent from local storage. The variants are
/// publicly constructible, so this value alone is not proof of authentication
/// or admission. Obtain it through [`crate::propagation_node::PropagationNode::evaluate_offer_request`]
/// after preflight, then commit it to that same admission candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PnOfferEvaluation {
HaveAll,
WantAll,
WantSome(Vec<PropagationTransientId>),
}
impl PnOfferEvaluation {
/// Lifecycle outcome recorded by [`crate::propagation_admission`].
pub fn admission_response(&self) -> PnOfferResponse {
match self {
Self::HaveAll => PnOfferResponse::HaveAll,
Self::WantAll => PnOfferResponse::WantAll,
Self::WantSome(_) => PnOfferResponse::WantSome,
}
}
/// Python-compatible response value for the `/offer` request.
pub fn into_wire_response(self) -> OfferResponse {
match self {
Self::HaveAll => OfferResponse::HaveAll,
Self::WantAll => OfferResponse::WantAll,
Self::WantSome(ids) => {
OfferResponse::WantSome(ids.into_iter().map(Vec::from).collect())
}
}
}
}
/// Failure before an offer can be committed to admission accounting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PnOfferEvaluationError {
InvalidData,
InvalidKey,
}
impl PnOfferEvaluationError {
pub fn wire_response(self) -> OfferResponse {
match self {
Self::InvalidData => OfferResponse::ErrorInvalidData,
Self::InvalidKey => OfferResponse::ErrorInvalidKey,
}
}
}
enum DecodedPeeringKey {
Empty,
Key([u8; 32]),
InvalidLength,
}
pub(crate) struct DecodedOffer {
peering_key: DecodedPeeringKey,
transient_ids: Vec<PropagationTransientId>,
}
/// Decode, validate, and determine the wanted subset without mutating
/// admission state.
pub(crate) fn evaluate<F>(
request_data: &[u8],
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: f64,
max_offer_size: usize,
contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
where
F: FnMut(&PropagationTransientId) -> bool,
{
let offer = decode(request_data, max_offer_size)?;
evaluate_decoded(
offer,
local_identity_hash,
remote_identity_hash,
peering_cost,
contains,
)
}
pub(crate) fn evaluate_decoded<F>(
offer: DecodedOffer,
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: 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.0,
DecodedPeeringKey::Key(key) => {
let mut peering_id = [0u8; 32];
peering_id[..16].copy_from_slice(local_identity_hash);
peering_id[16..].copy_from_slice(remote_identity_hash);
stamper::validate_peering_key(&peering_id, &key, peering_cost)
}
DecodedPeeringKey::InvalidLength => false,
};
if !peering_key_valid {
return Err(PnOfferEvaluationError::InvalidKey);
}
let wanted: Vec<PropagationTransientId> = offer
.transient_ids
.iter()
.filter(|transient_id| !contains(transient_id))
.copied()
.collect();
if wanted.is_empty() {
Ok(PnOfferEvaluation::HaveAll)
} else if wanted.len() == offer.transient_ids.len() {
Ok(PnOfferEvaluation::WantAll)
} else {
Ok(PnOfferEvaluation::WantSome(wanted))
}
}
pub(crate) fn decode(
data: &[u8],
max_offer_size: usize,
) -> Result<DecodedOffer, PnOfferEvaluationError> {
use std::io::Read;
if data.len() > max_offer_size {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut remaining = data;
let field_count = rmp::decode::read_array_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
if field_count != 2 {
return Err(PnOfferEvaluationError::InvalidData);
}
let peering_key_len = rmp::decode::read_bin_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if peering_key_len > remaining.len() {
return Err(PnOfferEvaluationError::InvalidData);
}
let peering_key = match peering_key_len {
0 => DecodedPeeringKey::Empty,
32 => {
let mut key = [0u8; 32];
key.copy_from_slice(&remaining[..32]);
DecodedPeeringKey::Key(key)
}
_ => DecodedPeeringKey::InvalidLength,
};
remaining = &remaining[peering_key_len..];
let transient_id_count = rmp::decode::read_array_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if transient_id_count > remaining.len() / ENCODED_TRANSIENT_ID_MIN_BYTES {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut transient_ids = Vec::with_capacity(transient_id_count);
for _ in 0..transient_id_count {
let encoded_len = rmp::decode::read_bin_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if encoded_len != 32 {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut transient_id = [0u8; 32];
remaining
.read_exact(&mut transient_id)
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
transient_ids.push(transient_id);
}
if !remaining.is_empty() {
return Err(PnOfferEvaluationError::InvalidData);
}
Ok(DecodedOffer {
peering_key,
transient_ids,
})
}
#[cfg(test)]
mod tests {
use super::*;
use rmpv::Value;
fn encode_offer(key: Value, ids: Value) -> Vec<u8> {
crate::encode_value(&Value::Array(vec![key, ids]))
}
fn id(value: u8) -> PropagationTransientId {
[value; 32]
}
#[test]
fn strict_decode_rejects_malformed_fields_and_trailing_bytes() {
let malformed = [
vec![0xc1],
crate::encode_value(&Value::Array(vec![])),
crate::encode_value(&Value::Array(vec![
Value::Binary(vec![]),
Value::Array(vec![]),
Value::Nil,
])),
encode_offer(Value::Nil, Value::Array(vec![])),
encode_offer(Value::String("key".into()), Value::Array(vec![])),
encode_offer(Value::Binary(vec![]), Value::Nil),
encode_offer(
Value::Binary(vec![]),
Value::Array(vec![Value::Binary(vec![1; 31])]),
),
encode_offer(Value::Binary(vec![]), Value::Array(vec![Value::from(1)])),
encode_offer(
Value::Binary(vec![]),
Value::Array(vec![Value::String(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
)]),
),
];
for request in malformed {
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![]));
trailing.push(0xc0);
assert_eq!(
evaluate(&trailing, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn decode_rejects_requests_over_the_bounded_sync_budget() {
let request = vec![0xc0; 65];
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0.0, 64, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn decode_rejects_declared_id_count_before_allocating_entries() {
let mut request = Vec::new();
rmp::encode::write_array_len(&mut request, 2).unwrap();
rmp::encode::write_bin_len(&mut request, 0).unwrap();
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0.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(
Value::Binary(vec![]),
Value::Array(vec![Value::Binary(id(3).to_vec())]),
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |_| false),
Ok(PnOfferEvaluation::WantAll)
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 1.0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidKey)
);
}
#[test]
fn wanted_evaluation_preserves_offer_order_and_duplicates() {
let request = encode_offer(
Value::Binary(vec![]),
Value::Array(vec![
Value::Binary(id(1).to_vec()),
Value::Binary(id(2).to_vec()),
Value::Binary(id(2).to_vec()),
Value::Binary(id(3).to_vec()),
]),
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0.0, 1024, |id| *id == [1; 32]),
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
);
}
#[test]
fn outcomes_map_to_admission_and_wire_types() {
assert_eq!(
PnOfferEvaluation::HaveAll.admission_response(),
PnOfferResponse::HaveAll
);
assert_eq!(
PnOfferEvaluation::WantAll.admission_response(),
PnOfferResponse::WantAll
);
let some = PnOfferEvaluation::WantSome(vec![id(7)]);
assert_eq!(some.admission_response(), PnOfferResponse::WantSome);
assert_eq!(
some.into_wire_response(),
OfferResponse::WantSome(vec![id(7).to_vec()])
);
}
}
+416
View File
@@ -0,0 +1,416 @@
//! Shared propagation preparation for daemon and embedding applications.
use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN;
use crate::message::{LxMessage, MessageError};
use crate::stamper::StampControl;
use bytes::Bytes;
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct AdvertisedNodePolicy {
/// Announced propagation stamp cost; generation clamps it to `0..=100`.
pub stamp_cost: f64,
pub transfer_limit_kb: f64,
pub recorded_at: f64,
}
impl AdvertisedNodePolicy {
/// The policy in a propagation node's announce `app_data`, heard at Unix
/// time `heard_at`; `None` when Python `pn_announce_data_is_valid` refuses
/// the data. The cost is the one a sender stamps to
/// (`LXMRouter.get_outbound_propagation_cost`): slot 7's when present, else
/// slot 5's as announced. The transfer limit is whole kilobytes, as the
/// announce handler reads it (Handlers.py).
pub fn from_announce(app_data: &[u8], heard_at: f64) -> Option<Self> {
let announced = crate::handlers::parse_pn_announce_data(app_data)?;
Some(Self {
stamp_cost: crate::handlers::pn_stamp_cost_from_app_data(app_data)?,
transfer_limit_kb: announced.transfer_limit.as_f64().trunc(),
recorded_at: heard_at,
})
}
}
/// Which recipient key material an envelope's ciphertext was made for. A
/// sender compares it to learn that the recipient's key or ratchet changed and
/// the message has to be encrypted again.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EncryptionBinding([u8; 32]);
impl EncryptionBinding {
/// The binding for a recipient's 64-byte public key and the ratchet the
/// message is encrypted to, if any.
pub fn for_recipient(public_key: &[u8; 64], ratchet: Option<&[u8; 32]>) -> Self {
let mut material = [0u8; 96];
material[..64].copy_from_slice(public_key);
let len = match ratchet {
Some(ratchet) => {
material[64..].copy_from_slice(ratchet);
96
}
None => 64,
};
Self(rns_crypto::sha::full_hash(&material[..len]))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingPropagationInput {
NodeIdentity,
NodePath,
NodePolicy,
RecipientIdentity,
}
#[derive(Debug, Clone, Copy)]
pub struct PreparedNode {
pub node: [u8; 16],
pub policy: AdvertisedNodePolicy,
}
/// Check the node identity, node path, advertised policy and recipient key.
/// Policy must be younger than [`NODE_METADATA_MAX_AGE`] and have a finite,
/// nonnegative transfer limit. The recipient may be offline: only its key is
/// needed. This function reports missing inputs; it performs no path discovery.
pub fn propagation_readiness(
node: [u8; 16],
node_identity_known: bool,
node_path_known: bool,
policy: Option<AdvertisedNodePolicy>,
recipient_identity_known: bool,
now: f64,
) -> Result<PreparedNode, MissingPropagationInput> {
if !node_identity_known {
return Err(MissingPropagationInput::NodeIdentity);
}
if !node_path_known {
return Err(MissingPropagationInput::NodePath);
}
let policy = policy
.filter(|p| {
p.recorded_at.is_finite()
&& p.recorded_at <= now
&& now - p.recorded_at < NODE_METADATA_MAX_AGE
&& p.transfer_limit_kb.is_finite()
&& p.transfer_limit_kb >= 0.
})
.ok_or(MissingPropagationInput::NodePolicy)?;
if !recipient_identity_known {
return Err(MissingPropagationInput::RecipientIdentity);
}
Ok(PreparedNode { node, policy })
}
/// One send-owned encryption result. Retrying changes the outer timestamp and,
/// if the saved stamp no longer meets the node's cost, regenerates the PN stamp.
/// Ciphertext and transient ID stay fixed.
#[derive(Debug, Clone)]
pub struct PropagationEnvelope {
message: LxMessage,
ciphertext: Bytes,
transient_id: [u8; 32],
encryption_binding: EncryptionBinding,
stamp: [u8; 32],
stamp_value: f64,
required_cost: f64,
}
/// Python `get_outbound_propagation_cost` clamps the node's cost into `0..=100`.
fn outbound_pn_cost(cost: f64) -> f64 {
cost.clamp(0.0, crate::stamper::STAMP_COST_CAP)
}
fn generate_pn_stamp(
transient_id: &[u8; 32],
cost: f64,
ctl: &StampControl,
) -> Result<([u8; 32], f64), MessageError> {
crate::stamper::generate_stamp(
transient_id,
outbound_pn_cost(cost),
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
ctl,
)
.map_err(|e| MessageError::PackFailed(format!("PN stamp generation failed: {e}")))?
.ok_or_else(|| MessageError::PackFailed("PN stamp generation cancelled".into()))
}
impl PropagationEnvelope {
pub fn new<F>(
message: LxMessage,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
Self::new_cancellable(
message,
encryption_binding,
required_cost,
encrypt,
&StampControl::default(),
)
}
pub fn new_cancellable<F>(
message: LxMessage,
encryption_binding: EncryptionBinding,
required_cost: f64,
encrypt: F,
ctl: &StampControl,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
let encrypted = encrypt(&message.wire_bytes()[16..])?;
let mut ciphertext = Vec::with_capacity(16 + encrypted.len());
ciphertext.extend_from_slice(&message.destination_hash());
ciphertext.extend_from_slice(&encrypted);
let transient_id = rns_crypto::sha::full_hash(&ciphertext);
let (stamp, stamp_value) = generate_pn_stamp(&transient_id, required_cost, ctl)?;
Ok(Self {
message,
ciphertext: ciphertext.into(),
transient_id,
encryption_binding,
stamp,
stamp_value,
required_cost,
})
}
pub fn message(&self) -> &LxMessage {
&self.message
}
pub fn transient_id(&self) -> [u8; 32] {
self.transient_id
}
pub fn ciphertext(&self) -> &Bytes {
&self.ciphertext
}
pub fn stamp(&self) -> &[u8; 32] {
&self.stamp
}
pub fn stamp_value(&self) -> f64 {
self.stamp_value
}
/// Whether the saved stamp already meets a node's announced cost.
pub fn meets(&self, cost: f64) -> bool {
crate::stamper::value_meets(self.stamp_value, outbound_pn_cost(cost))
}
pub fn matches(&self, message: &LxMessage, encryption_binding: &EncryptionBinding) -> bool {
self.message.wire_bytes() == message.wire_bytes()
&& &self.encryption_binding == encryption_binding
}
/// Pack immediately before dispatch using policy checked by
/// [`propagation_readiness`]. This does not refresh the policy or send data.
/// It may synchronously regenerate the PN stamp if more work is required.
pub fn pack_for(
&mut self,
node: PreparedNode,
timestamp: f64,
) -> Result<Vec<u8>, MessageError> {
self.pack_for_cancellable(node, timestamp, &StampControl::default())
}
pub fn pack_for_cancellable(
&mut self,
node: PreparedNode,
timestamp: f64,
ctl: &StampControl,
) -> Result<Vec<u8>, MessageError> {
if !timestamp.is_finite() {
return Err(MessageError::PackFailed(
"propagation timestamp must be finite".into(),
));
}
if !self.meets(node.policy.stamp_cost) {
(self.stamp, self.stamp_value) =
generate_pn_stamp(&self.transient_id, node.policy.stamp_cost, ctl)?;
}
self.required_cost = node.policy.stamp_cost;
let blob_len = self
.ciphertext
.len()
.checked_add(32)
.ok_or_else(|| MessageError::PackFailed("PN envelope size overflow".into()))?;
let bin_header = if blob_len < 256 {
2
} else if blob_len < 65536 {
3
} else {
5
};
let packed_len = blob_len
.checked_add(11 + bin_header)
.ok_or_else(|| MessageError::PackFailed("PN wrapper size overflow".into()))?;
let limit = (node.policy.transfer_limit_kb * 1000.).floor();
if packed_len as f64 > limit {
return Err(MessageError::TooLarge {
size: packed_len,
limit: limit as usize,
});
}
let mut out = Vec::with_capacity(packed_len);
rmp::encode::write_array_len(&mut out, 2).expect("Vec writer");
rmp::encode::write_f64(&mut out, timestamp).expect("Vec writer");
rmp::encode::write_array_len(&mut out, 1).expect("Vec writer");
rmp::encode::write_bin_len(
&mut out,
u32::try_from(blob_len)
.map_err(|_| MessageError::PackFailed("PN blob too large".into()))?,
)
.expect("Vec writer");
out.extend_from_slice(&self.ciphertext);
out.extend_from_slice(&self.stamp);
debug_assert_eq!(out.len(), packed_len);
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::DeliveryMethod;
use crate::message::LxMessageDraft;
#[test]
fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() {
let policy = AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
assert!(propagation_readiness([1; 16], true, true, Some(policy), true, 101.).is_ok());
assert_eq!(
propagation_readiness([1; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert_eq!(
propagation_readiness([1; 16], true, true, Some(policy), false, 101.).unwrap_err(),
MissingPropagationInput::RecipientIdentity
);
}
#[test]
fn retry_and_cost_increase_keep_ciphertext_and_transient_id() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[3; 32]);
let msg = LxMessageDraft::new([1; 16], [2; 16], "", "test", DeliveryMethod::Propagated)
.unwrap()
.sign(&key)
.unwrap()
.finalize(None)
.unwrap();
let binding = EncryptionBinding::for_recipient(&[4; 64], None);
let mut envelope = PropagationEnvelope::new(msg, binding, 0.0, |p| Ok(p.to_vec())).unwrap();
let before = envelope.ciphertext.clone();
let tid = envelope.transient_id();
assert_eq!(
envelope.stamp_value(),
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp(),
)
);
let mut prepared = PreparedNode {
node: [5; 16],
policy: AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
},
};
let first = envelope.pack_for(prepared, 101.).unwrap();
prepared.policy.stamp_cost = 4.5;
let next = envelope.pack_for(prepared, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &before);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4.5);
assert_ne!(first, next);
assert!(
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp()
) >= 4.5
);
}
/// A node announce as Python packs it; `fractional` adds the transitional slot 7.
fn announce(
limit: rmpv::Value,
slot5: [rmpv::Value; 3],
fractional: Option<[f64; 3]>,
) -> Vec<u8> {
use rmpv::Value;
let mut slots = vec![
Value::Boolean(false),
Value::from(1_700_000_000i64),
Value::Boolean(true),
limit,
Value::from(10240),
Value::Array(slot5.to_vec()),
Value::Map(Vec::new()),
];
if let Some(costs) = fractional {
slots.push(Value::Array(costs.map(Value::F64).to_vec()));
}
crate::encode_value(&Value::Array(slots))
}
#[test]
fn announce_policy_takes_the_cost_a_sender_stamps_to_and_whole_kilobytes() {
use rmpv::Value;
let ints = [Value::from(14), Value::from(3), Value::from(18)];
// Slot 7 wins over slot 5's rounded-up costs.
let policy = AdvertisedNodePolicy::from_announce(
&announce(Value::from(256), ints.clone(), Some([13.5, 3.0, 18.0])),
100.,
)
.unwrap();
assert_eq!(
(
policy.stamp_cost,
policy.transfer_limit_kb,
policy.recorded_at
),
(13.5, 256., 100.)
);
// Without slot 7, slot 5's cost is taken as announced, not through int().
let floats = [Value::F64(13.5), Value::F64(3.0), Value::F64(18.0)];
let policy =
AdvertisedNodePolicy::from_announce(&announce(Value::F64(256.9), floats, None), 100.)
.unwrap();
assert_eq!((policy.stamp_cost, policy.transfer_limit_kb), (13.5, 256.));
let policy =
AdvertisedNodePolicy::from_announce(&announce(Value::from(256), ints, None), 100.)
.unwrap();
assert_eq!(policy.stamp_cost, 14.);
// What `get_propagation_node_app_data` packs reads back the same way.
let node =
crate::handlers::PropagationNodeAnnounceData::new(true, 1024, 2048, 23.25, 3., 0.);
let policy = AdvertisedNodePolicy::from_announce(
&crate::handlers::get_propagation_node_app_data(&node),
5.,
)
.unwrap();
assert_eq!(
(policy.stamp_cost, policy.transfer_limit_kb),
(23.25, 1024.)
);
assert!(AdvertisedNodePolicy::from_announce(b"not an announce", 100.).is_none());
assert!(AdvertisedNodePolicy::from_announce(&[], 100.).is_none());
}
#[test]
fn encryption_binding_is_the_hash_of_the_key_then_the_ratchet() {
let (key, ratchet) = ([7u8; 64], [9u8; 32]);
assert_eq!(
EncryptionBinding::for_recipient(&key, None).0,
rns_crypto::sha::full_hash(&key)
);
let mut both = key.to_vec();
both.extend_from_slice(&ratchet);
assert_eq!(
EncryptionBinding::for_recipient(&key, Some(&ratchet)).0,
rns_crypto::sha::full_hash(&both)
);
assert_ne!(
EncryptionBinding::for_recipient(&key, None),
EncryptionBinding::for_recipient(&key, Some(&ratchet))
);
}
}
@@ -0,0 +1,479 @@
//! Provenance-gated relay storage and conservative offline migration.
//!
//! Private local manifests record accepted opaque ingress. They are not an
//! encryption oracle, and old files acquire no authority from their names or
//! apparent envelope shape. Callers exclude external writers from these paths.
#[cfg(target_os = "android")]
mod android_container;
mod migration;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod mobile;
#[cfg(target_os = "android")]
pub use mobile::begin_android_container_migration;
#[cfg(target_os = "ios")]
pub use mobile::begin_ios_container_migration;
mod offline;
mod recovery;
pub(crate) use migration::open_locked_store;
pub use migration::{
MigrationReport, QuarantineSummary, migrate_store_offline, open_store, quarantine_summary,
};
pub use offline::{OfflineMigrationGuard, begin_offline_migration};
pub use recovery::{
RecoveryEntry, RecoveryPolicy, RecoveryReport, TrustedRecoveryManifest,
import_trusted_recovery_manifest,
};
use rns_identity::persistence::{durable_reconcile, durable_remove, durable_write};
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
const TOMBSTONE: &[u8] =
b"LXMF relay store moved to v2; legacy hosting and sync must remain disabled.\n";
const FORMAT: &[u8] = b"LXMF opaque relay store v2; objects and per-entry provenance\n";
const MAX_MANIFEST_BYTES: usize = 4096;
static STORE_MUTATION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Debug, thiserror::Error)]
#[error(
"MigrationRequired: stop all legacy relay writers and run explicit offline store migration"
)]
pub struct MigrationRequired;
pub fn is_migration_required(error: &io::Error) -> bool {
error
.get_ref()
.is_some_and(|inner| inner.is::<MigrationRequired>())
}
fn err(error: impl std::fmt::Display) -> io::Error {
io::Error::other(error.to_string())
}
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
fn sibling(path: &Path, suffix: &str) -> io::Result<PathBuf> {
let mut name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?
.to_os_string();
name.push(suffix);
Ok(path.with_file_name(name))
}
fn read_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > maximum as u64 {
return Err(invalid("store record is not a bounded regular file"));
}
let mut data = Vec::new();
File::open(path)?
.take(maximum as u64 + 1)
.read_to_end(&mut data)?;
if data.len() > maximum {
return Err(invalid("store record grew beyond its bound"));
}
Ok(data)
}
fn canonical_legacy(path: &Path) -> io::Result<PathBuf> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let parent = fs::canonicalize(parent)?;
let name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?;
if name == "." || name == ".." {
return Err(invalid("invalid store path"));
}
let path = parent.join(name);
if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(invalid("store root cannot be a symbolic link"));
}
Ok(path)
}
pub(crate) fn manifest_path(path: &Path) -> PathBuf {
sibling(path, ".entry").expect("validated object path")
}
pub(crate) fn deletion_path(path: &Path) -> PathBuf {
sibling(path, ".delete").expect("validated object path")
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum OpaqueIngress {
ValidatedPropagation,
TrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum AdmissionProtocol {
StampedPropagation,
ExplicitTrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum PublicationState {
Committed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EntryManifest {
pub version: u8,
admission_id: [u8; 16],
pub transient_id: [u8; 32],
pub content_hash: [u8; 32],
pub destination: [u8; 16],
pub size: usize,
pub stamp_value: f64,
pub stored_at: f64,
pub stamped: bool,
pub origin: OpaqueIngress,
protocol: AdmissionProtocol,
publication: PublicationState,
}
impl EntryManifest {
pub(crate) fn from_entry(entry: &crate::propagation::PropagationEntry, bytes: &[u8]) -> Self {
Self {
version: 2,
admission_id: rand::random(),
transient_id: entry.transient_id,
content_hash: rns_crypto::sha::full_hash(bytes),
destination: entry.destination_hash,
size: bytes.len(),
stamp_value: entry.stamp_value,
stored_at: entry.stored_at,
stamped: entry.stamped,
origin: OpaqueIngress::ValidatedPropagation,
protocol: AdmissionProtocol::StampedPropagation,
publication: PublicationState::Committed,
}
}
pub(crate) fn validate(&self, data: &[u8]) -> bool {
let tail = if self.stamped { 32 } else { 0 };
self.version == 2
&& self.stored_at.is_finite()
&& self.stored_at >= 0.0
&& self.size <= rns_protocol::resource::MAX_RESOURCE_SIZE
&& data.len() == self.size
&& data.len() > 16 + tail
&& data[..16] == self.destination
&& rns_crypto::sha::full_hash(data) == self.content_hash
&& rns_crypto::sha::full_hash(&data[..data.len() - tail]) == self.transient_id
&& matches!(
(self.origin, self.protocol),
(
OpaqueIngress::ValidatedPropagation,
AdmissionProtocol::StampedPropagation
) | (
OpaqueIngress::TrustedRecovery,
AdmissionProtocol::ExplicitTrustedRecovery
)
)
&& (self.origin == OpaqueIngress::TrustedRecovery || self.stamped)
}
/// Relay object name. Integer values keep the form older stores wrote.
pub(crate) fn filename(&self) -> String {
format!(
"{}_{:.0}_{}_{}",
hex::encode(self.transient_id),
self.stored_at,
self.stamp_value,
hex::encode(self.admission_id)
)
}
pub(crate) fn entry(&self) -> crate::propagation::PropagationEntry {
let mut entry = crate::propagation::PropagationEntry::new(
self.transient_id,
self.transient_id,
self.destination,
self.size,
self.stamp_value,
);
entry.stored_at = self.stored_at;
entry.stamped = self.stamped;
entry
}
}
pub(crate) fn read_manifest(path: &Path) -> io::Result<(EntryManifest, Vec<u8>)> {
let encoded = read_bounded(&manifest_path(path), MAX_MANIFEST_BYTES)?;
let meta: EntryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if meta.filename() != path.file_name().and_then(|s| s.to_str()).unwrap_or("") {
return Err(invalid(
"relay object filename does not match its provenance record",
));
}
Ok((meta, encoded))
}
#[derive(Debug, Serialize, Deserialize)]
struct ActiveIndex {
version: u8,
object: String,
manifest_hash: [u8; 32],
}
fn index_path(object: &Path, id: &[u8; 32]) -> io::Result<PathBuf> {
Ok(object
.parent()
.ok_or_else(|| invalid("object has no parent"))?
.join(format!("{}.active", hex::encode(id))))
}
fn check_index(object: &Path, meta: &EntryManifest, encoded: &[u8]) -> io::Result<()> {
let index: ActiveIndex = rmp_serde::from_slice(&read_bounded(
&index_path(object, &meta.transient_id)?,
MAX_MANIFEST_BYTES,
)?)
.map_err(err)?;
if index.version != 2
|| index.object != meta.filename()
|| index.manifest_hash != rns_crypto::sha::full_hash(encoded)
{
return Err(invalid(
"object is not the active committed relay admission",
));
}
Ok(())
}
pub(crate) fn indexed_object(index_path: &Path) -> io::Result<PathBuf> {
let index: ActiveIndex =
rmp_serde::from_slice(&read_bounded(index_path, MAX_MANIFEST_BYTES)?).map_err(err)?;
if index.version != 2
|| Path::new(&index.object).components().count() != 1
|| !matches!(
Path::new(&index.object).components().next(),
Some(std::path::Component::Normal(_))
)
{
return Err(invalid("invalid relay active index"));
}
let object = index_path
.parent()
.ok_or_else(|| invalid("active index has no parent"))?
.join(index.object);
let (meta, encoded) = read_manifest(&object)?;
if self::index_path(&object, &meta.transient_id)? != index_path {
return Err(invalid("relay index TID mismatch"));
}
check_index(&object, &meta, &encoded)?;
Ok(object)
}
/// Publish object, provenance, then its per-TID commit index. A cancelled
/// in-memory callback cannot cause retry to replace the first committed image.
pub(crate) fn publish_object(
object: &Path,
meta: &EntryManifest,
data: &[u8],
) -> io::Result<(EntryManifest, PathBuf)> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let index = index_path(object, &meta.transient_id)?;
match fs::symlink_metadata(&index) {
Ok(_) => {
let existing = indexed_object(&index)?;
let (first, encoded) = read_manifest(&existing)?;
let retained = read_validated_file(&existing)?;
durable_reconcile(&existing, &retained).map_err(err)?;
durable_reconcile(&manifest_path(&existing), &encoded).map_err(err)?;
let index_bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &index_bytes).map_err(err)?;
return Ok((first, existing));
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if !meta.validate(data)
|| object.file_name().and_then(|s| s.to_str()) != Some(meta.filename().as_str())
{
return Err(invalid("invalid relay publication"));
}
let encoded = rmp_serde::to_vec_named(meta).map_err(err)?;
durable_write(object, data).map_err(err)?;
durable_write(&manifest_path(object), &encoded).map_err(err)?;
let active = ActiveIndex {
version: 2,
object: meta.filename(),
manifest_hash: rns_crypto::sha::full_hash(&encoded),
};
durable_write(&index, &rmp_serde::to_vec_named(&active).map_err(err)?).map_err(err)?;
Ok((meta.clone(), object.to_owned()))
}
/// Verify the complete indexed admission and renew all three publication
/// barriers. Serialize against retirement so successful return has a concrete
/// committed point, even when a purge was prepared concurrently.
pub(crate) fn verify_committed_object(path: &Path) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let (meta, encoded) = read_manifest(path)?;
let data = read_validated_file(path)?;
durable_reconcile(path, &data).map_err(err)?;
durable_reconcile(&manifest_path(path), &encoded).map_err(err)?;
let index = index_path(path, &meta.transient_id)?;
let bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &bytes).map_err(err)?;
check_index(path, &meta, &encoded)
}
/// Startup check for an indexed record: readable, committed size and
/// destination prefix. Publication completed its barriers before any proof,
/// duplicates renew them, and every read revalidates the body, so restart must
/// not reread and re-flush the whole store.
pub(crate) fn check_committed_on_load(path: &Path, meta: &EntryManifest) -> io::Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.len() != meta.size as u64 {
return Err(invalid("relay object does not match its committed size"));
}
let mut destination = [0u8; 16];
File::open(path)?.read_exact(&mut destination)?;
if destination != meta.destination {
return Err(invalid(
"relay object does not match its committed destination",
));
}
Ok(())
}
/// Both the manifest and complete bytes are checked at the final read boundary.
/// An unresolved durable deletion always defeats a previously prepared read.
pub(crate) fn read_validated_file(path: &Path) -> io::Result<Vec<u8>> {
read_validated_file_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)
}
/// Refuse oversized metadata before allocating or opening the payload. The
/// caller can therefore reserve its complete GET response budget first.
pub(crate) fn read_validated_file_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object has a pending durable deletion"));
}
let (meta, encoded) = read_manifest(path)?;
check_index(path, &meta, &encoded)?;
if meta.size > maximum.min(rns_protocol::resource::MAX_RESOURCE_SIZE) {
return Err(invalid("relay object exceeds Resource capacity"));
}
let data = read_bounded(path, meta.size)?;
if !meta.validate(&data) {
return Err(invalid("relay object changed after validated admission"));
}
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object retired while being read"));
}
check_index(path, &meta, &encoded)?;
Ok(data)
}
#[derive(Debug, Serialize, Deserialize)]
struct DeletionRecord {
version: u8,
object: String,
content_hash: [u8; 32],
transient_id: [u8; 32],
}
/// The durable deletion intent is committed before either indexed file is
/// removed. Keep it across every uncertain cleanup; startup resumes cleanup
/// before loading any active objects.
pub(crate) fn retire_object(path: &Path) -> io::Result<()> {
retire_object_inner(path, false)
}
fn retire_object_inner(path: &Path, fail_after_intent: bool) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let marker = deletion_path(path);
let encoded = match read_bounded(&marker, MAX_MANIFEST_BYTES) {
Ok(encoded) => encoded,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (meta, _) = read_manifest(path)?;
let record = DeletionRecord {
version: 2,
object: path
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| invalid("invalid object name"))?
.to_string(),
content_hash: meta.content_hash,
transient_id: meta.transient_id,
};
rmp_serde::to_vec_named(&record).map_err(err)?
}
Err(e) => return Err(e),
};
let record: DeletionRecord = rmp_serde::from_slice(&encoded).map_err(err)?;
if record.version != 2
|| Path::new(&record.object).components().count() != 1
|| path.file_name().and_then(|s| s.to_str()) != Some(&record.object)
{
return Err(invalid("deletion record path mismatch"));
}
let witness = durable_write(&marker, &encoded).map_err(err)?;
if fail_after_intent {
return Err(io::Error::other(
"injected interruption after durable deletion intent",
));
}
let cleanup = (|| -> io::Result<()> {
let index = index_path(path, &record.transient_id)?;
if let Ok(active) = indexed_object(&index)
&& active == path
{
durable_remove(&index, &witness).map_err(err)?;
}
durable_remove(path, &witness).map_err(err)?;
durable_remove(&manifest_path(path), &witness).map_err(err)?;
// A separate, retained FORMAT witness may retire the journal only once both
// removals have acknowledged barriers. Failure leaves the journal reusable.
let root = path
.parent()
.and_then(Path::parent)
.ok_or_else(|| invalid("object outside v2 objects directory"))?;
let format = durable_reconcile(&root.join("FORMAT"), FORMAT).map_err(err)?;
durable_remove(&marker, &format).map_err(err)?;
Ok(())
})();
if let Err(error) = cleanup {
tracing::warn!(%error, "committed relay deletion retains pending cleanup evidence");
}
Ok(())
}
pub(crate) fn reconcile_deletions(root: &Path) -> io::Result<()> {
for entry in fs::read_dir(root.join("objects"))? {
let path = entry?.path();
if path.extension().and_then(|s| s.to_str()) != Some("delete") {
continue;
}
let object = path.with_extension("");
retire_object(&object)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deletion_intent_survives_interruption_and_revokes_all_read_authority() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
let root = open_store(&legacy).unwrap();
let mut data = [2; 16].to_vec();
data.extend_from_slice(
&rns_identity::identity::Identity::new()
.encrypt(b"private payload", None)
.unwrap(),
);
let tid = rns_crypto::sha::full_hash(&data);
data.extend_from_slice(&[0; 32]);
let mut entry =
crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0.0);
entry.stamped = true;
let meta = EntryManifest::from_entry(&entry, &data);
let object = root.join("objects").join(meta.filename());
publish_object(&object, &meta, &data).unwrap();
assert_eq!(read_validated_file(&object).unwrap(), data);
assert!(retire_object_inner(&object, true).is_err());
assert!(object.exists());
assert!(deletion_path(&object).exists());
assert!(read_validated_file(&object).is_err());
assert!(verify_committed_object(&object).is_err());
open_store(&legacy).unwrap();
assert!(!object.exists());
assert!(!index_path(&object, &tid).unwrap().exists());
assert!(!deletion_path(&object).exists());
}
}
@@ -0,0 +1,207 @@
//! Android framework metadata, rather than process-list visibility or guessed
//! /data prefixes, establishes a single-package private-container boundary.
use super::*;
use jni::{
JNIEnv,
objects::{JObject, JString, JValue},
};
use std::os::unix::fs::MetadataExt;
fn take_string(env: &JNIEnv<'_>, value: JObject<'_>) -> io::Result<String> {
if value.is_null() {
return Err(invalid("Android application metadata is missing"));
}
let result: String = env.get_string(JString::from(value)).map_err(err)?.into();
env.delete_local_ref(value).map_err(err)?;
Ok(result)
}
pub(super) fn private_root<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
let result = private_root_inner(env, context);
// Return a Rust failure without leaving an unrelated pending Java exception
// on the embedding application's worker thread.
if result.is_err() && env.exception_check().unwrap_or(true) {
let _ = env.exception_clear();
}
result
}
fn private_root_inner<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
if context.is_null()
|| !env
.is_instance_of(context, "android/content/Context")
.map_err(err)?
{
return Err(invalid(
"an initialized Android application context is required",
));
}
let uid = env
.call_static_method("android/os/Process", "myUid", "()I", &[])
.map_err(err)?
.i()
.map_err(err)?;
if uid < 0 || uid % 100_000 < 10_000 {
return Err(invalid(
"relay recovery requires a private Android application UID",
));
}
let manager = env
.call_method(
context,
"getPackageManager",
"()Landroid/content/pm/PackageManager;",
&[],
)
.map_err(err)?
.l()
.map_err(err)?;
let packages = env
.call_method(
manager,
"getPackagesForUid",
"(I)[Ljava/lang/String;",
&[JValue::Int(uid)],
)
.map_err(err)?
.l()
.map_err(err)?;
if packages.is_null() || env.get_array_length(packages.into_inner()).map_err(err)? != 1 {
return Err(invalid(
"shared or unknown Android UID cannot authorize relay migration",
));
}
let package = take_string(
env,
env.get_object_array_element(packages.into_inner(), 0)
.map_err(err)?,
)?;
let context_package = take_string(
env,
env.call_method(context, "getPackageName", "()Ljava/lang/String;", &[])
.map_err(err)?
.l()
.map_err(err)?,
)?;
if package != context_package {
return Err(invalid("Android context does not own this application UID"));
}
let mut cmdline = Vec::new();
File::open("/proc/self/cmdline")?
.take(4097)
.read_to_end(&mut cmdline)?;
if cmdline.len() > 4096 || cmdline.split(|b| *b == 0).next() != Some(package.as_bytes()) {
return Err(invalid(
"relay migration is restricted to the default Android app process",
));
}
let package_string = env.new_string(&package).map_err(err)?;
// Resolve all four component classes, including disabled declarations. A
// secondary process can own the same private UID even if it is not running.
const FLAGS: i32 = 1 | 2 | 4 | 8 | 512;
let info = env
.call_method(
manager,
"getPackageInfo",
"(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",
&[JValue::Object(package_string.into()), JValue::Int(FLAGS)],
)
.map_err(err)?
.l()
.map_err(err)?;
if !env
.get_field(info, "sharedUserId", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?
.is_null()
{
return Err(invalid(
"sharedUserId applications cannot authorize relay migration",
));
}
let application = env
.get_field(
info,
"applicationInfo",
"Landroid/content/pm/ApplicationInfo;",
)
.map_err(err)?
.l()
.map_err(err)?;
if env
.get_field(application, "uid", "I")
.map_err(err)?
.i()
.map_err(err)?
!= uid
{
return Err(invalid("Android application UID changed"));
}
let process = take_string(
env,
env.get_field(application, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
if process != package {
return Err(invalid(
"custom Android application process is not qualified",
));
}
for (field, signature) in [
("activities", "[Landroid/content/pm/ActivityInfo;"),
("receivers", "[Landroid/content/pm/ActivityInfo;"),
("services", "[Landroid/content/pm/ServiceInfo;"),
("providers", "[Landroid/content/pm/ProviderInfo;"),
] {
let components = env
.get_field(info, field, signature)
.map_err(err)?
.l()
.map_err(err)?;
if components.is_null() {
continue;
}
let count = env.get_array_length(components.into_inner()).map_err(err)?;
if !(0..=4096).contains(&count) {
return Err(invalid(
"Android component inventory exceeds migration bound",
));
}
for index in 0..count {
let component = env
.get_object_array_element(components.into_inner(), index)
.map_err(err)?;
let process = take_string(
env,
env.get_field(component, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
env.delete_local_ref(component).map_err(err)?;
if process != package {
return Err(invalid(
"multi-process Android apps cannot authorize relay migration",
));
}
}
env.delete_local_ref(components).map_err(err)?;
}
let root = fs::canonicalize(take_string(
env,
env.get_field(application, "dataDir", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?)?;
let metadata = fs::metadata(&root)?;
if !metadata.is_dir() || metadata.uid() != uid as u32 || metadata.mode() & 0o022 != 0 {
return Err(invalid(
"Android data directory lacks exclusive application ownership",
));
}
Ok(root)
}
@@ -0,0 +1,470 @@
use super::*;
use rns_identity::persistence::{
DurableFileReceipt, durable_create_dir_all, durable_reconcile_hash, durable_rename_directory,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
const MAX_INVENTORY: usize = 65_536;
const MAX_JOURNAL: usize = 32 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(super) struct InventoryEntry {
pub path: PathBuf,
pub bytes: u64,
pub hash: Option<[u8; 32]>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MigrationJournal {
version: u8,
legacy: PathBuf,
archive: PathBuf,
v2: PathBuf,
inventory: Vec<InventoryEntry>,
had_legacy: bool,
phase: u8,
renewal: Option<PathBuf>,
renewal_sequence: u64,
}
#[derive(Debug, Clone)]
pub struct MigrationReport {
pub store: PathBuf,
pub quarantine: QuarantineSummary,
}
#[derive(Debug, Clone)]
pub struct QuarantineSummary {
pub files: usize,
pub bytes: u64,
pub reason: &'static str,
}
fn summary(j: &MigrationJournal) -> QuarantineSummary {
QuarantineSummary {
files: j.inventory.iter().filter(|e| e.hash.is_some()).count(),
bytes: j
.inventory
.iter()
.fold(0u64, |n, e| n.saturating_add(e.bytes)),
reason: "Preserved legacy files have no trusted per-entry opaque-ingress provenance",
}
}
fn encode(j: &MigrationJournal) -> io::Result<Vec<u8>> {
let encoded = rmp_serde::to_vec_named(j).map_err(err)?;
if encoded.len() > MAX_JOURNAL {
return Err(invalid("migration inventory exceeds journal bound"));
}
Ok(encoded)
}
fn paths(legacy: &Path) -> io::Result<(PathBuf, PathBuf, PathBuf)> {
Ok((
sibling(legacy, ".migration")?,
sibling(legacy, ".legacy-quarantine")?,
sibling(legacy, ".v2")?,
))
}
fn save(j: &MigrationJournal) -> io::Result<DurableFileReceipt> {
durable_write(&paths(&j.legacy)?.0, &encode(j)?).map_err(err)
}
fn read_journal(legacy: &Path) -> io::Result<MigrationJournal> {
let (path, archive, v2) = paths(legacy)?;
let j: MigrationJournal =
rmp_serde::from_slice(&read_bounded(&path, MAX_JOURNAL)?).map_err(err)?;
if j.version != 2
|| j.phase > 4
|| j.legacy != legacy
|| j.archive != archive
|| j.v2 != v2
|| j.inventory.len() > MAX_INVENTORY
{
return Err(invalid("migration journal path/version/phase mismatch"));
}
let mut unique = BTreeSet::new();
for entry in &j.inventory {
if !safe_relative(&entry.path) || !unique.insert(entry.path.clone()) {
return Err(invalid("invalid inventory path"));
}
}
if let Some(path) = &j.renewal
&& *path != sibling(&archive, &format!(".renewal-{}", j.renewal_sequence))?
{
return Err(invalid("directory renewal path mismatch"));
}
Ok(j)
}
pub fn quarantine_summary(legacy: &Path) -> io::Result<QuarantineSummary> {
Ok(summary(&read_journal(&canonical_legacy(legacy)?)?))
}
fn safe_relative(path: &Path) -> bool {
!path.as_os_str().is_empty()
&& path.as_os_str().len() <= 4096
&& path.components().count() <= 32
&& path
.components()
.all(|p| matches!(p, std::path::Component::Normal(_)))
}
fn hash_file(path: &Path) -> io::Result<(u64, [u8; 32])> {
let before = fs::symlink_metadata(path)?;
if !before.is_file() || before.file_type().is_symlink() {
return Err(invalid("legacy inventory contains a nonregular file"));
}
let mut file = File::open(path)?;
let mut hash = Sha256::new();
let mut count = 0u64;
let mut buffer = [0; 8192];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
count = count
.checked_add(n as u64)
.ok_or_else(|| invalid("legacy size overflow"))?;
hash.update(&buffer[..n]);
}
let after = file.metadata()?;
if count != before.len() || after.len() != count || before.modified()? != after.modified()? {
return Err(invalid("legacy file changed during inventory"));
}
Ok((count, hash.finalize().into()))
}
fn inventory(root: &Path) -> io::Result<Vec<InventoryEntry>> {
let metadata = fs::symlink_metadata(root)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(invalid("legacy root is not a real directory"));
}
let mut todo = vec![PathBuf::new()];
let mut result = Vec::new();
while let Some(relative) = todo.pop() {
for entry in fs::read_dir(root.join(&relative))? {
let entry = entry?;
let relative = relative.join(entry.file_name());
if !safe_relative(&relative) || result.len() >= MAX_INVENTORY {
return Err(invalid("legacy inventory exceeds safe path/count bound"));
}
let m = fs::symlink_metadata(entry.path())?;
if m.file_type().is_symlink() {
return Err(invalid(
"legacy symbolic links require explicit operator recovery",
));
}
if m.is_dir() {
result.push(InventoryEntry {
path: relative.clone(),
bytes: 0,
hash: None,
});
todo.push(relative);
} else if m.is_file() {
let (bytes, hash) = hash_file(&entry.path())?;
result.push(InventoryEntry {
path: relative,
bytes,
hash: Some(hash),
});
} else {
return Err(invalid(
"legacy special files require explicit operator recovery",
));
}
}
}
result.sort_by(|a, b| a.path.cmp(&b.path));
Ok(result)
}
fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> {
if inventory(root)? != j.inventory {
return Err(invalid(
"legacy inventory changed; preserve original and investigate before recovery",
));
}
Ok(())
}
/// Initialize a truly absent store or validate a completed v2 store. An
/// incomplete journal or historical directory requires explicit offline migration.
/// The temporary store lock is released before this returns the path; this
/// function does not grant a hosting lease.
pub fn open_store(legacy: &Path) -> io::Result<PathBuf> {
Ok(open_locked_store(legacy)?.0)
}
pub(crate) fn open_locked_store(legacy: &Path) -> io::Result<(PathBuf, File)> {
let legacy = canonical_legacy(legacy)?;
let lock = offline::lock_store(&legacy)?;
let (journal, archive, v2) = paths(&legacy)?;
if journal.exists() {
let j = read_journal(&legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
reconcile_deletions(&v2)?;
return Ok((v2, lock));
}
if fs::symlink_metadata(&legacy).is_ok()
|| fs::symlink_metadata(&archive).is_ok()
|| fs::symlink_metadata(&v2).is_ok()
{
return Err(io::Error::other(MigrationRequired));
}
let j = MigrationJournal {
version: 2,
legacy: legacy.clone(),
archive,
v2,
inventory: Vec::new(),
had_legacy: false,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
let report = run(j, None)?;
Ok((report.store, lock))
}
fn verify_published(j: &MigrationJournal) -> io::Result<()> {
if read_bounded(&j.legacy, 256)? != TOMBSTONE
|| read_bounded(&j.v2.join("FORMAT"), 256)? != FORMAT
{
return Err(invalid("v2 format or old-path guard mismatch"));
}
let objects = fs::symlink_metadata(j.v2.join("objects"))?;
if !objects.is_dir() || objects.file_type().is_symlink() {
return Err(invalid("v2 objects directory invalid"));
}
durable_reconcile(&j.legacy, TOMBSTONE).map_err(err)?;
durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
Ok(())
}
/// Migrate the canonical path protected by the guard. Keep the constructor's
/// writer-exclusion conditions in force throughout this call. Legacy objects
/// remain quarantined; a retry or operator approval does not establish ingress
/// provenance for them.
pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result<MigrationReport> {
migrate(&guard.legacy, None)
}
fn migrate(legacy: &Path, fault: Option<u8>) -> io::Result<MigrationReport> {
let canonical = canonical_legacy(legacy)?;
let legacy = canonical.as_path();
let (journal, archive, v2) = paths(legacy)?;
let j = if journal.exists() {
read_journal(legacy)?
} else {
if archive.exists() || v2.exists() {
return Err(invalid(
"unowned archive/v2 path already exists; refusing overwrite",
));
}
let had_legacy = fs::symlink_metadata(legacy).is_ok();
let inventory = if had_legacy {
inventory(legacy)?
} else {
Vec::new()
};
let j = MigrationJournal {
version: 2,
legacy: legacy.to_owned(),
archive,
v2,
inventory,
had_legacy,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
fail(fault, 0)?;
j
};
run(j, fault)
}
fn fail(fault: Option<u8>, stage: u8) -> io::Result<()> {
if fault == Some(stage) {
Err(io::Error::other(format!(
"injected migration boundary {stage}"
)))
} else {
Ok(())
}
}
/// Re-publish a renamed archive through two fresh sibling transitions. This is
/// valid on Windows WRITE_THROUGH and avoids pretending existing directories
/// can be acknowledged by a generic file flush. Every recovery target is journaled.
fn renew_archive(j: &mut MigrationJournal, fault: Option<u8>) -> io::Result<()> {
if let Some(temporary) = j.renewal.clone() {
match (j.archive.exists(), temporary.exists()) {
(false, true) => {
verify_inventory(&temporary, j)?;
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
return Ok(());
}
(true, false) => {
j.renewal = None;
}
_ => {
return Err(invalid(
"ambiguous archive renewal state; originals preserved",
));
}
}
}
verify_inventory(&j.archive, j)?;
j.renewal_sequence = j
.renewal_sequence
.checked_add(1)
.ok_or_else(|| invalid("renewal generation exhausted"))?;
let temporary = sibling(&j.archive, &format!(".renewal-{}", j.renewal_sequence))?;
if fs::symlink_metadata(&temporary).is_ok() {
return Err(invalid("recovery target already exists"));
}
j.renewal = Some(temporary.clone());
let witness = save(j)?;
durable_rename_directory(&j.archive, &temporary, &witness).map_err(err)?;
fail(fault, 5)?;
// Rewrite the journal after the first acknowledged move; if this write is
// uncertain the existing intent still describes both permitted locations.
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
Ok(())
}
fn run(mut j: MigrationJournal, fault: Option<u8>) -> io::Result<MigrationReport> {
if j.had_legacy {
if j.legacy.is_dir() {
if j.phase != 0 || j.archive.exists() || j.renewal.is_some() {
return Err(invalid("ambiguous legacy archive state"));
}
verify_inventory(&j.legacy, &j)?;
// Renew barriers for every retained file before its directory move.
for entry in j.inventory.iter().filter(|e| e.hash.is_some()) {
let maximum = usize::try_from(entry.bytes).map_err(err)?;
durable_reconcile_hash(&j.legacy.join(&entry.path), entry.hash.unwrap(), maximum)
.map_err(err)?;
}
let witness = save(&j)?;
durable_rename_directory(&j.legacy, &j.archive, &witness).map_err(err)?;
fail(fault, 1)?;
} else {
renew_archive(&mut j, fault)?;
}
verify_inventory(&j.archive, &j)?;
} else if j.archive.exists() || j.renewal.is_some() {
return Err(invalid("unexpected archive for a fresh store"));
}
if j.phase < 1 {
j.phase = 1;
save(&j)?;
}
match fs::symlink_metadata(&j.legacy) {
Ok(_) if read_bounded(&j.legacy, 256)? != TOMBSTONE => {
return Err(invalid("unknown old-path guard"));
}
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
durable_write(&j.legacy, TOMBSTONE).map_err(err)?;
fail(fault, 2)?;
if j.phase < 2 {
j.phase = 2;
save(&j)?;
}
let witness = save(&j)?;
durable_create_dir_all(&j.v2, &witness).map_err(err)?;
durable_create_dir_all(&j.v2.join("objects"), &witness).map_err(err)?;
durable_write(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
fail(fault, 3)?;
if j.phase < 3 {
j.phase = 3;
save(&j)?;
}
verify_published(&j)?;
j.phase = 4;
save(&j)?;
fail(fault, 4)?;
Ok(MigrationReport {
store: j.v2.clone(),
quarantine: summary(&j),
})
}
pub(super) fn verified_archive(
guard: &OfflineMigrationGuard,
) -> io::Result<(PathBuf, PathBuf, Vec<InventoryEntry>)> {
let j = read_journal(&guard.legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
verify_inventory(&j.archive, &j)?;
Ok((j.archive, j.v2, j.inventory))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn migration_preserves_inventory_and_never_promotes_legacy_bytes() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("opaque"), [3; 200]).unwrap();
fs::write(legacy.join("plaintext"), b"private message").unwrap();
assert!(is_migration_required(&open_store(&legacy).unwrap_err()));
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
b"private message"
);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert!(open_store(&legacy).is_ok());
}
#[test]
fn every_migration_and_renewal_boundary_resumes_without_losing_originals() {
for stage in 0..=6 {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"untouched").unwrap();
if stage >= 5 {
assert!(migrate(&legacy, Some(1)).is_err());
}
assert!(migrate(&legacy, Some(stage)).is_err());
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 1);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("message")
)
.unwrap(),
b"untouched"
);
assert!(open_store(&legacy).is_ok());
}
}
#[test]
fn changed_inventory_and_unowned_targets_fail_without_overwrite() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"original").unwrap();
assert!(migrate(&legacy, Some(0)).is_err());
fs::write(legacy.join("message"), b"changed").unwrap();
assert!(migrate(&legacy, None).is_err());
assert!(legacy.is_dir());
let other = temp.path().join("other");
fs::create_dir(sibling(&other, ".v2").unwrap()).unwrap();
assert!(open_store(&other).is_err());
assert!(!other.exists());
}
}
@@ -0,0 +1,167 @@
//! Restricted app-container migration authority. This is not an arbitrary-path
//! alternative to the desktop process probe. All current host workers must be
//! joined by the application before acquisition; the same v2 OS lock additionally
//! rejects live current hosts. iOS's main-app/container lifecycle excludes an
//! older installed bundle from concurrently owning this private data container.
use super::*;
fn contained_store(legacy: &Path, root: &Path) -> io::Result<PathBuf> {
let root = fs::canonicalize(root)?;
let legacy = canonical_legacy(legacy)?;
let parent = legacy
.parent()
.ok_or_else(|| invalid("store has no parent"))?;
if parent == root || !parent.starts_with(&root) {
return Err(invalid(
"relay migration requires a nested private app-container path",
));
}
Ok(legacy)
}
/// Acquire migration authority only inside the current native iOS main app's
/// private data container. App groups, extensions, external directories, and
/// command-line processes are refused. No caller-supplied root or skip flag is
/// accepted. Hold the application's identity/session lifecycle guard, stop all
/// hosted and sync writers, and join their actual workers before calling this.
#[cfg(target_os = "ios")]
pub fn begin_ios_container_migration(legacy: &Path) -> io::Result<offline::OfflineMigrationGuard> {
let root = native_ios_container()?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
/// Acquire migration authority for the platform Context's single-package,
/// single-process private Android data directory. Shared UIDs, declared remote
/// processes, mismatched contexts and external/group-writable roots are refused.
/// The caller must hold its lifecycle guard and join all hosted/sync writers;
/// the returned guard also retains the same OS lock used by current v2 hosts.
#[cfg(target_os = "android")]
pub fn begin_android_container_migration<'a>(
legacy: &Path,
env: &jni::JNIEnv<'a>,
context: jni::objects::JObject<'a>,
) -> io::Result<offline::OfflineMigrationGuard> {
let root = android_container::private_root(env, context)?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
#[cfg(target_os = "ios")]
fn native_ios_container() -> io::Result<PathBuf> {
use objc2::{
msg_send,
rc::autoreleasepool,
runtime::{AnyClass, AnyObject},
};
use std::ffi::CStr;
#[link(name = "Foundation", kind = "framework")]
unsafe extern "C" {
fn NSHomeDirectory() -> *mut AnyObject;
}
// SAFETY: both values are Foundation NSStrings, alive for the surrounding
// autorelease pool; UTF8String is copied before leaving that pool.
unsafe fn string(value: *mut AnyObject) -> io::Result<String> {
if value.is_null() {
return Err(invalid("native app-container metadata unavailable"));
}
let bytes: *const std::ffi::c_char = unsafe { msg_send![value, UTF8String] };
if bytes.is_null() {
return Err(invalid("native app-container path unavailable"));
}
unsafe { CStr::from_ptr(bytes) }
.to_str()
.map(str::to_owned)
.map_err(err)
}
autoreleasepool(|_| {
let class = AnyClass::get(c"NSBundle").ok_or_else(|| invalid("NSBundle unavailable"))?;
// SAFETY: documented synchronous Foundation getters, no ownership transfer.
let bundle: *mut AnyObject = unsafe { msg_send![class, mainBundle] };
if bundle.is_null() {
return Err(invalid("native main app bundle unavailable"));
}
let path: *mut AnyObject = unsafe { msg_send![bundle, bundlePath] };
let identifier: *mut AnyObject = unsafe { msg_send![bundle, bundleIdentifier] };
let bundle_path = PathBuf::from(unsafe { string(path)? });
if bundle_path.extension().and_then(|s| s.to_str()) != Some("app")
|| unsafe { string(identifier)? }.is_empty()
{
return Err(invalid("relay migration requires an iOS main application"));
}
let root = fs::canonicalize(unsafe { string(NSHomeDirectory())? })?;
if !ios_data_container_path(&root) {
return Err(invalid(
"native home is not a private iOS app data container",
));
}
Ok(root)
})
}
// The native home API, not this shape alone, supplies authority. Reject future
// unknown layouts instead of silently certifying a shared or group container.
#[cfg(any(target_os = "ios", test))]
fn ios_data_container_path(root: &Path) -> bool {
let Some(id) = root.file_name().and_then(|s| s.to_str()) else {
return false;
};
let valid_id = id.len() == 36
&& id.bytes().enumerate().all(|(index, byte)| {
if [8, 13, 18, 23].contains(&index) {
byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
valid_id
&& root
.parent()
.is_some_and(|p| p.ends_with("Containers/Data/Application"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_container_policy_rejects_groups_siblings_and_root_store() {
assert!(ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(ios_data_container_path(Path::new(
"/sim/device/data/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Shared/AppGroup/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Bundle/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let nested = root.join("Library/state");
fs::create_dir_all(&nested).unwrap();
assert!(contained_store(&nested.join("relay"), &root).is_ok());
assert!(contained_store(&root.join("relay"), &root).is_err());
assert!(contained_store(&temp.path().join("relay"), &root).is_err());
}
#[cfg(unix)]
#[test]
fn private_container_policy_rejects_symlink_escape() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let outside = temp.path().join("external");
fs::create_dir_all(&root).unwrap();
fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
assert!(contained_store(&root.join("escape/relay"), &root).is_err());
}
}
@@ -0,0 +1,167 @@
use super::*;
use std::process::{Command, Stdio};
/// Hold the OS lock shared with current v2 hosts during offline migration.
/// Legacy binaries ignore it. The desktop constructor also requires the caller
/// to stop supervisors and checks known processes; the iOS/Android constructors
/// use restricted app-container checks and require the caller to join its writers.
pub struct OfflineMigrationGuard {
pub(super) legacy: PathBuf,
pub(super) _lock: File,
}
pub(super) fn lock_store(legacy: &Path) -> io::Result<File> {
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let path = sibling(legacy, ".store-lock")?;
if fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file() || m.file_type().is_symlink()) {
return Err(invalid("invalid relay store lock"));
}
let lock = options.open(path)?;
rns_identity::persistence::try_lock_exclusive(&lock)?;
Ok(lock)
}
/// The adapter must first stop its own hosting workers and service auto-restart.
/// This probes known app/daemon names and refuses if process enumeration fails.
/// Manually launching an old binary during migration remains unsupported.
pub fn begin_offline_migration(
legacy: &Path,
supervisor_writers_stopped: bool,
) -> io::Result<OfflineMigrationGuard> {
if !supervisor_writers_stopped {
return Err(invalid(
"stop relay writers and their service supervisors before migration",
));
}
let legacy = canonical_legacy(legacy)?;
let lock = lock_store(&legacy)?;
refuse_known_relay_processes()?;
Ok(OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
fn known_name(value: &str) -> bool {
let value = value
.trim_matches('"')
.rsplit(['/', '\\'])
.next()
.unwrap_or(value)
.to_ascii_lowercase();
matches!(
value.as_str(),
"ratspeak" | "ratspeak.exe" | "lxmd" | "lxmd.py" | "lxmd-rs" | "lxmd-rs.exe"
)
}
fn refuse_known_relay_processes() -> io::Result<()> {
#[cfg(unix)]
let mut command = {
let mut c = Command::new("ps");
c.args(["-axo", "pid=,comm=,args="]);
c
};
#[cfg(windows)]
let mut command = {
let mut c = Command::new("tasklist");
c.args(["/FO", "CSV", "/NH"]);
c
};
#[cfg(not(any(unix, windows)))]
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"process exclusion cannot be verified on this platform",
));
#[cfg(any(unix, windows))]
{
command.stdout(Stdio::piped()).stderr(Stdio::null());
let mut child = command.spawn()?;
let mut output = Vec::new();
let read = child
.stdout
.take()
.ok_or_else(|| invalid("process probe has no output"))?
.take(4 * 1024 * 1024 + 1)
.read_to_end(&mut output);
if read.is_err() || output.len() > 4 * 1024 * 1024 {
let _ = child.kill();
let _ = child.wait();
return Err(invalid("process inventory exceeds safe bound"));
}
if !child.wait()?.success() {
return Err(invalid(
"process enumeration unavailable; relay writer exclusion unverified",
));
}
let listing = std::str::from_utf8(&output).map_err(err)?;
check_listing(listing, std::process::id(), cfg!(windows))
}
}
fn check_listing(listing: &str, own_pid: u32, windows: bool) -> io::Result<()> {
for line in listing.lines().filter(|l| !l.trim().is_empty()) {
if windows {
let fields: Vec<_> = line.trim_matches('"').split("\",\"").collect();
if fields.len() < 2 {
return Err(invalid("unrecognized process inventory"));
}
let pid: u32 = fields[1].parse().map_err(err)?;
if pid != own_pid && known_name(fields[0]) {
return Err(invalid("a known relay app/daemon is still running"));
}
} else {
let mut fields = line.split_whitespace();
let pid: u32 = fields
.next()
.ok_or_else(|| invalid("missing process ID"))?
.parse()
.map_err(err)?;
let Some(comm) = fields.next() else {
return Err(invalid("missing process name"));
};
if pid == own_pid {
continue;
}
// For interpreted daemons, inspect only the executable/script prefix,
// not arbitrary argument text belonging to shells or other programs.
let python = comm
.rsplit('/')
.next()
.is_some_and(|c| c.starts_with("python"));
if known_name(comm) || (python && fields.take(3).any(known_name)) {
return Err(invalid("a known relay app/daemon is still running"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_process_probe_is_fail_closed_and_excludes_only_own_pid() {
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
8,
false
)
.is_err()
);
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
7,
false
)
.is_ok()
);
assert!(check_listing("9 python3 python3 /usr/bin/lxmd --service\n", 7, false).is_err());
assert!(check_listing("oops", 7, false).is_err());
assert!(check_listing("\"lxmd-rs.exe\",\"9\",\"Console\"", 7, true).is_err());
}
}
@@ -0,0 +1,330 @@
use super::*;
use std::collections::{HashMap, HashSet};
/// A local owner's independently verified ingress record. The approved manifest
/// digest is supplied separately by the recovery UI/CLI; a location or blanket
/// 'recover all' action is never an origin assertion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustedRecoveryManifest {
pub version: u8,
pub provenance: String,
pub entries: Vec<RecoveryEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryEntry {
pub archive_relative_path: PathBuf,
pub content_hash: [u8; 32],
pub transient_id: [u8; 32],
pub stamped: bool,
pub stored_at: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryPolicy {
pub maximum_store_bytes: usize,
pub maximum_message_bytes: usize,
pub minimum_stamp_cost: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryReport {
pub imported: usize,
pub already_present: usize,
}
fn validate(
record: &RecoveryEntry,
bytes: &[u8],
minimum_stamp_cost: f64,
) -> io::Result<EntryManifest> {
let tail = if record.stamped { 32 } else { 0 };
if bytes.len() < 112 + tail
|| !record.stored_at.is_finite()
|| record.stored_at < 0.0
|| rns_crypto::sha::full_hash(bytes) != record.content_hash
{
return Err(invalid("recovery content hash/length/time mismatch"));
}
let opaque = &bytes[..bytes.len() - tail];
if !(opaque.len() - 16 - 32 - rns_crypto::TOKEN_OVERHEAD).is_multiple_of(16)
|| rns_crypto::sha::full_hash(opaque) != record.transient_id
{
return Err(invalid("recovery envelope/TID mismatch"));
}
if crate::message::LxMessage::unpack(opaque).is_ok()
|| crate::message::LxMessage::unpack(bytes).is_ok()
{
return Err(invalid(
"raw plaintext LXMF is never eligible for relay recovery",
));
}
let stamp_value = if record.stamped {
let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().map_err(err)?;
crate::stamper::validated_stamp_value(
&record.transient_id,
stamp,
minimum_stamp_cost,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)
.ok_or_else(|| invalid("recovered stamp does not meet node policy"))?
} else {
if minimum_stamp_cost > 0.0 {
return Err(invalid("unstamped recovery does not meet node policy"));
}
0.0
};
let mut destination = [0; 16];
destination.copy_from_slice(&bytes[..16]);
let mut entry = crate::propagation::PropagationEntry::new(
record.transient_id,
record.transient_id,
destination,
bytes.len(),
stamp_value,
);
entry.stored_at = record.stored_at;
entry.stamped = record.stamped;
let mut manifest = EntryManifest::from_entry(&entry, bytes);
manifest.origin = OpaqueIngress::TrustedRecovery;
manifest.protocol = AdmissionProtocol::ExplicitTrustedRecovery;
Ok(manifest)
}
/// Import exact positively attested archive entries under the same offline
/// guard. Existing deletion journals are reconciled first. All selected entries
/// are checked before any imported object is published, then rechecked at each
/// publication boundary. Retrying after partial completion retains already
/// committed entries and imports only those still absent.
pub fn import_trusted_recovery_manifest(
guard: &OfflineMigrationGuard,
path: &Path,
approved_manifest_sha256: [u8; 32],
policy: RecoveryPolicy,
) -> io::Result<RecoveryReport> {
let encoded = read_bounded(path, 32 * 1024 * 1024)?;
if rns_crypto::sha::full_hash(&encoded) != approved_manifest_sha256 {
return Err(invalid("recovery manifest changed after approval"));
}
let recovery: TrustedRecoveryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if recovery.version != 2
|| recovery.provenance.trim().is_empty()
|| recovery.provenance.len() > 4096
|| recovery.entries.len() > 65_536
{
return Err(invalid("invalid trusted recovery manifest"));
}
let (archive, root, inventory) = migration::verified_archive(guard)?;
let known: HashMap<_, _> = inventory
.into_iter()
.filter_map(|e| e.hash.map(|h| (e.path, (e.bytes, h))))
.collect();
let mut existing = HashMap::new();
let mut total = 0usize;
reconcile_deletions(&root)?;
for file in fs::read_dir(root.join("objects"))? {
let path = file?.path();
if path.extension().and_then(|s| s.to_str()) != Some("active") {
continue;
}
let object = indexed_object(&path)?;
let (meta, _) = read_manifest(&object)?;
let bytes = read_validated_file(&object)?;
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if existing
.insert(meta.transient_id, meta.content_hash)
.is_some()
{
return Err(invalid("duplicate active relay TID"));
}
}
let maximum = policy
.maximum_message_bytes
.min(rns_protocol::resource::MAX_RESOURCE_SIZE);
let mut selected = HashSet::new();
let mut plans = Vec::new();
let mut already_present = 0;
for record in &recovery.entries {
if !selected.insert(record.transient_id) {
return Err(invalid("duplicate recovery TID"));
}
let Some((length, hash)) = known.get(&record.archive_relative_path) else {
return Err(invalid(
"recovery entry is outside the committed legacy inventory",
));
};
if *hash != record.content_hash || *length > maximum as u64 {
return Err(invalid("recovery inventory hash/size mismatch"));
}
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
let meta = validate(record, &bytes, policy.minimum_stamp_cost)?;
if let Some(hash) = existing.get(&record.transient_id) {
if *hash != record.content_hash {
return Err(invalid(
"recovery would replace the first accepted relay image",
));
}
already_present += 1;
continue;
}
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if total > policy.maximum_store_bytes {
return Err(invalid(
"trusted recovery exceeds active relay storage quota",
));
}
plans.push((record, meta));
}
let mut imported = 0;
for (record, meta) in plans {
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
validate(record, &bytes, policy.minimum_stamp_cost)?;
let object = root.join("objects").join(meta.filename());
if object.exists() && read_bounded(&object, maximum)? != bytes {
return Err(invalid("recovery object target contains different bytes"));
}
publish_object(&object, &meta, &bytes)?;
imported += 1;
}
Ok(RecoveryReport {
imported,
already_present,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn guard(legacy: &Path) -> OfflineMigrationGuard {
let legacy = canonical_legacy(legacy).unwrap();
let lock = offline::lock_store(&legacy).unwrap();
OfflineMigrationGuard {
legacy,
_lock: lock,
}
}
fn write_manifest(path: &Path, manifest: &TrustedRecoveryManifest) -> [u8; 32] {
let bytes = rmp_serde::to_vec_named(manifest).unwrap();
fs::write(path, &bytes).unwrap();
rns_crypto::sha::full_hash(&bytes)
}
fn policy() -> RecoveryPolicy {
RecoveryPolicy {
maximum_store_bytes: 8192,
maximum_message_bytes: 4096,
minimum_stamp_cost: 0.0,
}
}
fn record(bytes: &[u8], name: &str) -> RecoveryEntry {
RecoveryEntry {
archive_relative_path: name.into(),
content_hash: rns_crypto::sha::full_hash(bytes),
transient_id: rns_crypto::sha::full_hash(bytes),
stamped: false,
stored_at: 1.0,
}
}
#[test]
fn only_exact_approved_inventory_entries_are_imported_and_retry_is_idempotent() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let recipient = rns_identity::identity::Identity::new();
let mut bytes = [2; 16].to_vec();
bytes.extend_from_slice(
&recipient
.encrypt(b"private recovery payload", None)
.unwrap(),
);
fs::write(legacy.join("opaque"), &bytes).unwrap();
fs::write(legacy.join("unknown"), b"never infer eligibility").unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
let manifest = TrustedRecoveryManifest {
version: 2,
provenance: "operator verified original opaque ingress record #42".into(),
entries: vec![record(&bytes, "opaque")],
};
let path = temp.path().join("recovery.msgpack");
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, [0; 32], policy()).is_err());
let first = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((first.imported, first.already_present), (1, 0));
let retry = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((retry.imported, retry.already_present), (0, 1));
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
3
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("unknown")
)
.unwrap(),
b"never infer eligibility"
);
drop(offline);
let reopened = crate::propagation_node::PropagationNode::with_storage(
crate::propagation_node::PropagationNodeConfig::default(),
[1; 16],
legacy,
)
.unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
fs::read(&reopened.plan_message_reads(&[rns_crypto::sha::full_hash(&bytes)])[0].path)
.unwrap(),
bytes
);
}
#[test]
fn plaintext_or_outside_inventory_recovery_cannot_publish_any_entry() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let message = crate::message::test_message(
[2; 16],
[3; 16],
"Private",
"Do not relay cleartext",
crate::constants::DeliveryMethod::Direct,
);
let bytes = message.wire_bytes();
fs::write(legacy.join("plaintext"), bytes).unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
let path = temp.path().join("recovery.msgpack");
let mut manifest = TrustedRecoveryManifest {
version: 2,
provenance: "inaccurate assertion does not override positive plaintext decode".into(),
entries: vec![record(bytes, "plaintext")],
};
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
manifest.entries[0].archive_relative_path = "../plaintext".into();
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
bytes
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+146
View File
@@ -0,0 +1,146 @@
//! Medium-aware outbound timing: Python `LXMRouter` path and retry model.
//!
//! The embedder supplies a [`MediumSnapshot`] of Reticulum's view (lowest
//! online bitrate, medium path timeout and per-destination routes); the router
//! derives retry waits, attempt limits and receipt timeouts from it.
use std::collections::HashMap;
use std::time::Duration;
use rand::Rng;
use crate::constants::{
DELIVERY_RETRY_WAIT, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, PROCESSING_INTERVAL,
};
use crate::message::LxMessage;
pub const PATH_REQUEST_DEBOUNCE: f64 = 60.0;
pub const SLOW_INTERFACE_BITRATE: u64 = 2000;
pub const AIRTIME_AWARE_MTU_TIME: f64 = 0.5;
const PER_HOP_TIMEOUT: f64 = rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT;
/// Reticulum's current route to a destination.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RouteInfo {
pub hops: u8,
/// `Reticulum.get_first_hop_timeout` for the destination, in seconds.
pub first_hop_timeout: f64,
}
/// Reticulum inputs to outbound planning. A destination without an entry in
/// `routes` has no known path.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MediumSnapshot {
/// `Reticulum.get_lowest_interface_bitrate`.
pub lowest_interface_bitrate: Option<u64>,
/// `Reticulum.get_medium_path_timeout`; 0 when no bitrate is known.
pub medium_path_timeout: f64,
pub routes: HashMap<[u8; 16], RouteInfo>,
}
impl MediumSnapshot {
pub fn has_path(&self, destination: &[u8; 16]) -> bool {
self.routes.contains_key(destination)
}
pub fn route(&self, destination: &[u8; 16]) -> Option<RouteInfo> {
self.routes.get(destination).copied()
}
/// Python `LXMRouter.destination_round_trip`.
pub fn destination_round_trip(&self, destination: &[u8; 16]) -> f64 {
match self.routes.get(destination) {
None => self.medium_path_timeout,
Some(route) => {
2.0 * (route.first_hop_timeout - PER_HOP_TIMEOUT).max(0.0) + PER_HOP_TIMEOUT
}
}
}
/// Python `LXMRouter.path_request_wait`.
pub fn path_request_wait(&self) -> f64 {
(PATH_REQUEST_WAIT as f64).max(self.medium_path_timeout)
}
/// Python `LXMRouter.slow_interface_online`.
pub fn slow_interface_online(&self) -> bool {
self.lowest_interface_bitrate
.is_some_and(|bitrate| bitrate < SLOW_INTERFACE_BITRATE)
}
/// Window within which a repeated path request for one destination is skipped.
pub fn path_request_debounce(&self) -> f64 {
if self.slow_interface_online() {
PATH_REQUEST_DEBOUNCE
} else {
self.path_request_wait()
}
}
}
/// Python `LXMRouter.attempt_limit`.
pub fn attempt_limit(message: &LxMessage) -> u32 {
message
.max_delivery_attempts
.unwrap_or(MAX_DELIVERY_ATTEMPTS)
}
/// Python `LXMRouter.attempt_due`.
pub fn attempt_due(message: &LxMessage, has_path: bool, now: f64) -> bool {
now > message.next_delivery_attempt || (message.awaiting_path && has_path)
}
/// Python `LXMRouter.schedule_attempt`, given the round trip it would use:
/// the medium path timeout for a path request, else the destination round trip.
pub fn schedule_attempt(message: &mut LxMessage, round_trip: f64, path_request: bool, now: f64) {
let wait = if path_request {
message.awaiting_path = true;
(PATH_REQUEST_WAIT as f64).max(round_trip)
} else {
(DELIVERY_RETRY_WAIT as f64).max(round_trip)
};
message.next_delivery_attempt = now + wait;
let limit = if round_trip > DELIVERY_RETRY_WAIT as f64 {
// Python's round() rounds half to even.
let scaled = (MAX_DELIVERY_ATTEMPTS as f64 * DELIVERY_RETRY_WAIT as f64 / round_trip)
.round_ties_even() as u32;
scaled.max(3)
} else {
MAX_DELIVERY_ATTEMPTS
};
message.max_delivery_attempts = Some(limit);
let mtu_time = (round_trip - PER_HOP_TIMEOUT).max(0.0) / 2.0;
if mtu_time > AIRTIME_AWARE_MTU_TIME {
message.next_delivery_attempt += rand::thread_rng().gen_range(0.0..=mtu_time);
let retry_wait = (DELIVERY_RETRY_WAIT as f64).max(round_trip) + mtu_time;
let remaining = (i64::from(limit) - i64::from(message.delivery_attempts) + 1).max(1);
message.receipt_timeout = Some(retry_wait * remaining as f64 + PROCESSING_INTERVAL as f64);
} else {
message.receipt_timeout = None;
}
}
/// Timeout for an opportunistic delivery receipt: the RNS packet receipt
/// timeout (Packet.py), raised to the message's airtime-aware
/// `receipt_timeout` (LXMessage.py). Without a route Reticulum counts
/// `PATHFINDER_M` hops.
pub fn opportunistic_receipt_timeout(
route: Option<RouteInfo>,
receipt_timeout: Option<f64>,
) -> Duration {
let (first_hop, hops) = route
.map(|route| (route.first_hop_timeout, route.hops))
.unwrap_or((PER_HOP_TIMEOUT, rns_transport::constants::PATHFINDER_M));
let base = rns_wire::receipt::receipt_timeout_for_route(
Duration::from_secs_f64(first_hop.max(0.0)),
hops,
);
match receipt_timeout {
Some(timeout) if timeout.is_finite() && timeout > base.as_secs_f64() => {
Duration::from_secs_f64(timeout)
}
_ => base,
}
}
+256 -476
View File
@@ -1,271 +1,151 @@
//! LXMF Stamp system: Proof-of-Work generation and validation.
//! LXMF stamps: proof of work for messages, propagation and peering.
//!
//! Python reference: LXMF/LXStamper.py.
//! Python reference: `LXMF/LXStamper.py`, which takes the workblock, value,
//! validity and generation from `RNS.Stamps`. Only the expand-round counts per
//! stamp kind are LXMF's own (`STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}`
//! in constants.rs). Costs and values are fractional on the 1/256 grid.
//!
//! Two workblock constructions are used:
//! - `stamp_workblock_raw`: HKDF-expand on arbitrary material. Matches Python
//! exactly for peering keys and PN stamps.
//! - `stamp_workblock`: iterative SHA-256 on a 32-byte message_id (simplified
//! construction used internally for message stamps; cheaper and deterministic).
//!
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`.
//! Validation accepts the non-expanded workblock (the material itself) as well
//! as the expanded one, as LXMF 1.3.1 does while senders move to it.
//! Generation stays expanded: LXMF 1.3.0 receivers accept only that form.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::Ordering;
use rand::RngCore;
use rns_crypto::hkdf::hkdf_sha256;
use rns_crypto::sha::sha256;
use sha2::{Digest, Sha256};
/// The same type as `rns_identity::stamps::StampError`, not an LXMF-specific error.
pub use rns_identity::stamps::StampError;
pub use rns_identity::stamps::{
STAMP_COST_CAP, STAMP_COST_CAP_FP, StampControl, cost_from_fp, cost_to_fp, quantize_cost,
stamp_value, stamp_workblock,
};
/// Parsed propagation-node stamp parts: `(stamp, lxm_data, value, workblock)`.
pub type PropagationStampParts = ([u8; 32], Vec<u8>, u32, [u8; 32]);
use crate::constants::{
LXMF_OVERHEAD, STAMP_SIZE, STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
};
/// 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_raw(material: &[u8], expand_rounds: usize) -> Vec<u8> {
let mut workblock = Vec::with_capacity(expand_rounds * 256);
/// Parsed propagation-node stamp parts: `(transient_id, lxm_data, value, stamp)`.
pub type PropagationStampParts = ([u8; 32], Vec<u8>, f64, [u8; 32]);
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)
}
/// `workblock = SHA-256^(expand_rounds)(message_id)`.
///
/// Non-32-byte inputs are first hashed to produce a 32-byte starting point.
pub fn stamp_workblock(message_id: &[u8], expand_rounds: usize) -> [u8; 32] {
let mut current = if message_id.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(message_id);
arr
} else {
sha256(message_id)
};
for _ in 0..expand_rounds {
current = sha256(&current);
}
current
}
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; 32], stamp: &[u8; 32]) -> u32 {
let mut material = [0u8; 64];
material[..32].copy_from_slice(workblock);
material[32..].copy_from_slice(stamp);
let hash = sha256(&material);
leading_zero_bits(&hash)
}
pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8; 32]) -> bool {
if cost == 0 {
return true;
}
stamp_value(workblock, stamp) >= cost as u32
}
/// `stamp_value` counterpart for variable-length (HKDF-expanded) workblocks.
pub fn stamp_value_raw(workblock: &[u8], stamp: &[u8; 32]) -> u32 {
let mut hasher = Sha256::new();
hasher.update(workblock);
raw_stamp_value_from_base(&hasher, stamp)
}
/// `stamp_valid` counterpart for variable-length (HKDF-expanded) workblocks.
pub fn stamp_valid_raw(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
if cost == 0 {
return true;
}
stamp_value_raw(workblock, stamp) >= cost as u32
}
/// Single-threaded brute-force stamp search. Blocks until a valid stamp is found.
/// 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(
message_id: &[u8; 32],
cost: u8,
expand_rounds: usize,
) -> Option<([u8; 32], u32)> {
if cost == 0 {
return Some(([0u8; 32], 0));
}
let workblock = stamp_workblock(message_id, expand_rounds);
let mut rng = rand::thread_rng();
loop {
let stamp = rand_bytes_from(&mut rng);
if stamp_valid(&stamp, cost, &workblock) {
let value = stamp_value(&workblock, &stamp);
return Some((stamp, value));
}
}
}
/// Generate a stamp using the Python-compatible variable-length workblock.
///
/// This is used for propagation-node stamps and peering keys, where the
/// workblock material is arbitrary bytes instead of the regular 32-byte LXMF
/// message id.
pub fn generate_stamp_raw(
material: &[u8],
cost: u8,
cost: f64,
expand_rounds: usize,
) -> Option<([u8; 32], u32)> {
if cost == 0 {
return Some(([0u8; 32], 0));
}
let workblock = stamp_workblock_raw(material, expand_rounds);
let mut base_hasher = Sha256::new();
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
loop {
let stamp = rand_bytes_from(&mut rng);
let value = raw_stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
return Some((stamp, value));
}
}
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(
message_id: &[u8; 32],
cost: u8,
/// The stamp's value when it meets `cost` over the non-expanded workblock,
/// else over `expand_rounds`, from the workblock that passed (LXMF 1.3.1
/// `LXMessage.validate_stamp`, `LXStamper.validate_pn_stamp`). The value can
/// depend on `cost`: below about cost 4 an expanded stamp often passes the
/// non-expanded check too, and at cost 0 it always does.
pub fn validated_stamp_value(
material: &[u8],
stamp: &[u8],
cost: f64,
expand_rounds: usize,
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(message_id, expand_rounds);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
let stamp = rand_bytes_from(&mut rng);
if stamp_valid(&stamp, cost, &workblock) {
return Some(stamp);
}
}
None
let workblock = stamp_workblock(material, expand_rounds);
stamp_valid(stamp, cost, &workblock).then(|| stamp_value(&workblock, stamp))
}
/// Whether `stamp` meets `cost` in either workblock form; see [`validated_stamp_value`].
pub fn validate_stamp(
message_id: &[u8; 32],
stamp: &[u8; 32],
cost: u8,
stamp: &[u8],
cost: f64,
expand_rounds: usize,
) -> bool {
let workblock = stamp_workblock(message_id, expand_rounds);
stamp_valid(stamp, cost, &workblock)
validated_stamp_value(message_id, stamp, cost, expand_rounds).is_some()
}
/// Python reference: LXStamper.py:48-51 (`validate_peering_key`).
///
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_cost: u8) -> bool {
let workblock = stamp_workblock_raw(
/// Python reference: `LXStamper.validate_peering_key`.
pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8], target_cost: f64) -> bool {
validated_stamp_value(
peering_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
);
stamp_valid_raw(peering_key, target_cost, &workblock)
peering_key,
target_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING,
)
.is_some()
}
/// Python reference: LXStamper.py:53-65 (`validate_pn_stamp`).
/// Python reference: `LXStamper.validate_pn_stamp`.
///
/// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes.
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<PropagationStampParts> {
let stamp_size = 32;
let lxmf_overhead = crate::constants::LXMF_OVERHEAD;
if transient_data.len() <= lxmf_overhead + stamp_size {
pub fn validate_pn_stamp(transient_data: &[u8], target_cost: f64) -> Option<PropagationStampParts> {
if transient_data.len() <= LXMF_OVERHEAD + STAMP_SIZE {
return None;
}
let split = transient_data.len() - stamp_size;
let split = transient_data.len() - STAMP_SIZE;
let lxm_data = &transient_data[..split];
let stamp_bytes = &transient_data[split..];
let mut stamp = [0u8; 32];
stamp.copy_from_slice(stamp_bytes);
let stamp: [u8; 32] = transient_data[split..].try_into().ok()?;
let transient_id = rns_crypto::sha::full_hash(lxm_data);
let workblock = stamp_workblock_raw(
let value = validated_stamp_value(
&transient_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = stamp_value_raw(&workblock, &stamp);
if value < target_cost as u32 {
return None;
}
&stamp,
target_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
)?;
Some((transient_id, lxm_data.to_vec(), value, stamp))
}
/// Cancellation handle for a deferred PoW task.
/// Cooperative cancellation handle for a deferred PoW task.
/// Call `cancel()` to request cancellation; dropping this handle or the result
/// receiver does not stop the worker.
#[derive(Clone)]
pub struct DeferredStampHandle {
cancel: Arc<AtomicBool>,
ctl: StampControl,
}
impl DeferredStampHandle {
pub fn cancel(&self) {
self.cancel.store(true, Ordering::Relaxed);
self.ctl.cancel.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed)
self.ctl.cancel.load(Ordering::Relaxed)
}
}
#[derive(Debug)]
pub enum DeferredStampResult {
Success { stamp: [u8; 32], value: u32 },
Success {
stamp: [u8; 32],
value: f64,
},
Cancelled,
/// The cost cannot be generated, as Python's `generate_stamp` raises.
Failed(StampError),
}
/// Spawn a deferred stamp-generation task on a blocking worker.
///
/// Returns a cancellation handle and a oneshot receiver for the result.
/// # Panics
/// Panics when called outside a Tokio runtime.
#[tracing::instrument(
level = "debug",
name = "stamper.compute",
@@ -278,339 +158,239 @@ pub enum DeferredStampResult {
)]
pub fn spawn_deferred_stamp(
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 handle = tokio::runtime::Handle::current();
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
}
/// 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: f64,
expand_rounds: usize,
) -> (
DeferredStampHandle,
tokio::sync::oneshot::Receiver<DeferredStampResult>,
) {
let ctl = StampControl::default();
let (tx, rx) = tokio::sync::oneshot::channel();
let cancel_flag = cancel.clone();
tokio::task::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 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);
if stamp_valid(&stamp, cost, &workblock) {
let value = stamp_value(&workblock, &stamp);
let _ = tx.send(DeferredStampResult::Success { stamp, value });
return;
}
}
}
let worker_ctl = ctl.clone();
runtime.spawn_blocking(move || {
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 raw_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, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let wb2 = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
assert_eq!(wb1, wb2);
// 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));
}
#[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 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 test_stamp_valid_cost_zero() {
let stamp = [0u8; 32];
let workblock = [0u8; 32];
assert!(stamp_valid(&stamp, 0, &workblock));
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 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);
fn workblock_uses_lxmf_expand_rounds() {
let id = sha256(b"size check");
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_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
));
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_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() {
let workblock = [0u8; 32];
let stamp = [0u8; 32];
let _value = stamp_value(&workblock, &stamp);
}
#[test]
fn test_stamp_value_consistency() {
let id = sha256(b"consistency test");
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_handles_short_input() {
let short_input = b"short";
let wb = stamp_workblock(short_input, 10);
assert_ne!(wb, [0u8; 32]);
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_default = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS);
let wb_pn = stamp_workblock(&id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN);
assert_ne!(wb_default, wb_pn);
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_stamp_workblock_raw_deterministic() {
let id = sha256(b"test workblock raw");
let wb1 = stamp_workblock_raw(&id, 10);
let wb2 = stamp_workblock_raw(&id, 10);
assert_eq!(wb1, wb2);
assert_eq!(wb1.len(), 10 * 256);
}
#[test]
fn test_stamp_workblock_raw_arbitrary_length() {
let short_material = b"short";
let wb = stamp_workblock_raw(short_material, 5);
assert_eq!(wb.len(), 5 * 256);
let wb2 = stamp_workblock_raw(short_material, 5);
assert_eq!(wb, wb2);
let wb3 = stamp_workblock_raw(b"other", 5);
assert_ne!(wb, wb3);
}
#[test]
fn test_stamp_workblock_raw_peering_id_length() {
let mut peering_id = Vec::with_capacity(32);
peering_id.extend_from_slice(&[0xAA; 16]);
peering_id.extend_from_slice(&[0xBB; 16]);
let wb = stamp_workblock_raw(
&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_raw_stamp_value_matches_direct_sha256_prefix_hash() {
let material = sha256(b"propagation transient id");
let workblock = stamp_workblock_raw(&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_raw(&workblock, &stamp),
leading_zero_bits(&direct_hash)
);
}
#[test]
fn test_validate_pn_stamp_high_cost_fails() {
let lxm_data = vec![0xCD; crate::constants::LXMF_OVERHEAD + 100];
let stamp = [0xFF; 32];
let mut transient_data = lxm_data.clone();
transient_data.extend_from_slice(&stamp);
let result = validate_pn_stamp(&transient_data, 32);
assert!(result.is_none());
#[tokio::test]
async fn deferred_stamp_zero_cost_completes_with_real_value() {
let id = sha256(b"zero cost");
let (_handle, rx) = spawn_deferred_stamp(id, 0.0, 10);
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx)
.await
.unwrap()
.unwrap();
let DeferredStampResult::Success { stamp, value } = result else {
panic!("{result:?}");
};
assert_eq!(value, stamp_value(&stamp_workblock(&id, 10), &stamp));
}
}
File diff suppressed because it is too large. Load diff
+21 -10
View File
@@ -1,7 +1,9 @@
//! LXMF Propagation Sync Protocol -- Offer/Get between peers.
//! Propagation offer/response values and local sync-session bookkeeping.
//!
//! The network task in [`crate::propagation_sync`] follows this exchange:
//!
//! 1. Peer A opens a Link to Peer B.
//! 2. A sends Offer { transient_ids }.
//! 2. A sends `/offer` with `[peering_key, transient_ids]`.
//! 3. B responds with one of:
//! - `true`: peer wants ALL offered messages.
//! - `false`: peer already has everything.
@@ -9,7 +11,11 @@
//! - integer error code: 0xF0 NoIdentity, 0xF1 NoAccess, 0xF3 InvalidKey,
//! 0xF4 InvalidData, 0xF5 InvalidStamp, 0xF6 Throttled.
//! 4. A sends requested messages via Resource transfer.
//! 5. B stores and sends proof.
//! 5. Resource proof reports transport completion; application admission is a
//! separate responsibility.
//!
//! [`SyncGet`] and [`SyncSession`] are local helpers. They do not implement the
//! authenticated `/offer` admission policy in [`crate::propagation_admission`].
//!
//! Python reference: LXMPeer.py (offer_response).
@@ -23,10 +29,13 @@ use crate::types::PropagationTransientId;
pub const SYNC_MSG_OFFER: u16 = 0x0001;
pub const SYNC_MSG_GET: u16 = 0x0002;
/// Offer message: "I have these messages".
/// Local offer data: a peering stamp and the transient IDs available for sync.
///
/// Python wire: `[peering_key, unhandled_ids]`. `peering_key` is the raw stamp
/// bytes (Python `self.peering_key[0]`), required by the receiver for access control.
/// The `/offer` request uses `[peering_key, unhandled_ids]` with a MessagePack
/// binary key and binary IDs. This type's `MessageBase::pack` uses the default
/// Serde representation, which encodes its byte vectors as integer arrays.
/// [`crate::propagation_sync`] constructs the required binary wire values
/// explicitly when sending the request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncOffer {
pub peering_key: Vec<u8>,
@@ -66,7 +75,8 @@ impl MessageBase for SyncOffer {
}
}
/// Get message: "Send me these messages".
/// Local wanted-ID list used by [`SyncSession`]. This wrapper is not the
/// `/offer` wire response; use [`OfferResponse`] for that response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncGet {
pub wanted_ids: Vec<Vec<u8>>,
@@ -103,7 +113,7 @@ impl MessageBase for SyncGet {
}
}
/// Parsed offer response from a propagation node. Python: LXMPeer.py:396-439.
/// Parsed offer response from a propagation node. See Python `LXMPeer.offer_response`.
#[derive(Debug, Clone, PartialEq)]
pub enum OfferResponse {
WantAll,
@@ -231,7 +241,8 @@ impl SyncSession {
}
}
/// Process a received offer; returns a SyncGet for IDs we don't have.
/// Select 32-byte IDs absent from the local store and enter Receiving state.
/// This helper does not validate the peering key or enforce admission policy.
pub fn process_offer(&mut self, offer: &SyncOffer, our_store: &PropagationStore) -> SyncGet {
let wanted: Vec<Vec<u8>> = offer
.transient_ids
@@ -365,7 +376,7 @@ mod tests {
let mut session = SyncSession::new(peer_hash);
let mut store = PropagationStore::new();
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0));
store.insert(PropagationEntry::new(tid(0x01), [0; 32], [0; 16], 100, 0.0));
let offer = SyncOffer {
peering_key: vec![0xFF; 32],
+245 -85
View File
@@ -1,19 +1,22 @@
//! LXMF Ticket system: bypass PoW with pre-shared 16-byte tokens.
//! LXMF ticket lifecycle and persistence state.
//!
//! Trusted peers may exchange tickets that bypass stamp requirements for a
//! fixed expiry window. Tickets are single-use and renewable before expiry.
//! A ticket issued to a peer is an *inbound* ticket: it validates that peer's
//! future stamps. A ticket learned from a peer is an *outbound* ticket: it is
//! used to stamp future messages to that peer. Keeping those directions
//! separate is required for Python LXMF compatibility.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::constants::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ticket {
pub token: [u8; 16],
pub destination_hash: [u8; 16],
/// Expiry timestamp (Unix epoch seconds).
pub expires: f64,
pub used: bool,
}
impl Ticket {
@@ -22,26 +25,92 @@ impl Ticket {
token,
destination_hash,
expires,
used: false,
}
}
pub fn is_valid(&self, now: f64) -> bool {
!self.used && now < self.expires
now < self.expires
}
pub fn should_renew(&self, now: f64) -> bool {
self.is_valid(now) && (self.expires - now) < TICKET_RENEW as f64
self.is_valid(now) && (self.expires - now) <= TICKET_RENEW as f64
}
pub fn use_ticket(&mut self) {
self.used = true;
/// Encode Python's native MessagePack ticket field `[expires, token]`.
pub fn encode_field(&self) -> Result<Vec<u8>, rmpv::encode::Error> {
let value = rmpv::Value::Array(vec![
rmpv::Value::F64(self.expires),
rmpv::Value::Binary(self.token.to_vec()),
]);
let mut encoded = Vec::new();
rmpv::encode::write_value(&mut encoded, &value)?;
Ok(encoded)
}
/// Decode a Python-compatible ticket field with a finite future expiry and
/// a 16-byte token. The caller must authenticate the containing message and
/// bind `destination_hash` to its sender before storing the learned ticket.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
if cursor.position() != encoded.len() as u64 {
return None;
}
let values = value.as_array()?;
if values.len() != 2 {
return None;
}
let expires = values[0].as_f64()?;
let token = values[1].as_slice()?;
if !expires.is_finite() || expires <= now || token.len() != TICKET_LENGTH {
return None;
}
let mut token_array = [0u8; TICKET_LENGTH];
token_array.copy_from_slice(token);
Some(Self::new(token_array, destination_hash, expires))
}
}
/// Versioned, serializable ticket state.
///
/// Version 1 replaces the former flat `Vec<Ticket>` representation. The flat
/// form could not distinguish tickets issued to peers from tickets learned
/// from peers and therefore could not implement Python's reply semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TicketStoreSnapshot {
#[serde(default = "ticket_store_version")]
pub version: u8,
#[serde(default)]
pub outbound: Vec<Ticket>,
#[serde(default)]
pub inbound: Vec<Ticket>,
#[serde(default)]
pub last_deliveries: HashMap<[u8; 16], f64>,
}
const fn ticket_store_version() -> u8 {
1
}
impl Default for TicketStoreSnapshot {
fn default() -> Self {
Self {
version: ticket_store_version(),
outbound: Vec::new(),
inbound: Vec::new(),
last_deliveries: HashMap::new(),
}
}
}
#[derive(Debug, Default)]
pub struct TicketStore {
tickets: Vec<Ticket>,
/// One learned ticket per destination, matching Python's outbound map.
outbound: HashMap<[u8; 16], Ticket>,
/// Multiple locally issued tickets may overlap during renewal/grace.
inbound: Vec<Ticket>,
/// Last successful delivery of a message containing a ticket.
last_deliveries: HashMap<[u8; 16], f64>,
}
impl TicketStore {
@@ -49,45 +118,135 @@ impl TicketStore {
Self::default()
}
pub fn add(&mut self, ticket: Ticket) {
self.tickets.push(ticket);
}
pub fn find(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.tickets
.iter()
.find(|t| &t.destination_hash == destination_hash && t.is_valid(now))
}
/// Find and mark a ticket as used. Returns the token on success.
pub fn use_for(&mut self, destination_hash: &[u8; 16], now: f64) -> Option<[u8; 16]> {
for ticket in &mut self.tickets {
if &ticket.destination_hash == destination_hash && ticket.is_valid(now) {
ticket.use_ticket();
return Some(ticket.token);
}
/// Store a ticket issued locally for `destination_hash`.
pub fn add_inbound(&mut self, ticket: Ticket) {
if self.inbound.iter().any(|existing| {
existing.destination_hash == ticket.destination_hash && existing.token == ticket.token
}) {
return;
}
None
self.inbound.push(ticket);
}
/// Drop expired and used tickets (past TICKET_GRACE).
/// Store or replace the ticket learned from `destination_hash`.
pub fn remember_outbound(&mut self, ticket: Ticket) {
self.outbound.insert(ticket.destination_hash, ticket);
}
/// Return the valid ticket learned from `destination_hash`.
pub fn find_outbound(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.outbound
.get(destination_hash)
.filter(|ticket| ticket.is_valid(now))
}
/// Return every valid ticket issued locally for `destination_hash`.
pub fn inbound_tokens(&self, destination_hash: &[u8; 16], now: f64) -> Vec<[u8; 16]> {
self.inbound
.iter()
.filter(|ticket| &ticket.destination_hash == destination_hash && ticket.is_valid(now))
.map(|ticket| ticket.token)
.collect()
}
/// Generate or reuse a ticket for a peer, respecting Python's delivery
/// interval and renewal window. `None` means a ticket was delivered too
/// recently and should not be included in this message.
pub fn issue_for(
&mut self,
destination_hash: [u8; 16],
expiry_secs: u64,
now: f64,
) -> Option<Ticket> {
if !self.should_issue_for(&destination_hash, now) {
return None;
}
if let Some(ticket) = self
.inbound
.iter()
.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());
}
let token: [u8; TICKET_LENGTH] = rand::random();
let ticket = Ticket::new(token, destination_hash, now + expiry_secs as f64);
self.inbound.push(ticket.clone());
Some(ticket)
}
pub fn should_issue_for(&self, destination_hash: &[u8; 16], now: f64) -> bool {
!self
.last_deliveries
.get(destination_hash)
.is_some_and(|last| now - *last < TICKET_INTERVAL as f64)
}
pub fn mark_ticket_delivered(&mut self, destination_hash: [u8; 16], delivered_at: f64) {
self.last_deliveries.insert(destination_hash, delivered_at);
}
/// Drop expired outbound tickets and inbound tickets after their grace
/// period. Delivery timestamps need only survive one interval.
pub fn cull(&mut self, now: f64) {
self.tickets
.retain(|t| !t.used && now < t.expires + TICKET_GRACE as f64);
self.outbound.retain(|_, ticket| ticket.is_valid(now));
self.inbound
.retain(|ticket| now < ticket.expires + TICKET_GRACE as f64);
self.last_deliveries
.retain(|_, delivered| now - *delivered < TICKET_INTERVAL as f64);
}
pub fn count_valid(&self, now: f64) -> usize {
self.tickets.iter().filter(|t| t.is_valid(now)).count()
self.outbound
.values()
.filter(|ticket| ticket.is_valid(now))
.count()
+ self
.inbound
.iter()
.filter(|ticket| ticket.is_valid(now))
.count()
}
/// Snapshot of all stored tickets (including expired / used).
pub fn all(&self) -> &[Ticket] {
&self.tickets
pub fn inbound(&self) -> &[Ticket] {
&self.inbound
}
/// Replace the entire ticket set — used when restoring from persisted state.
pub fn replace_all(&mut self, tickets: Vec<Ticket>) {
self.tickets = tickets;
pub fn snapshot(&self) -> TicketStoreSnapshot {
TicketStoreSnapshot {
version: ticket_store_version(),
outbound: self.outbound.values().cloned().collect(),
inbound: self.inbound.clone(),
last_deliveries: self.last_deliveries.clone(),
}
}
pub fn replace_snapshot(&mut self, snapshot: TicketStoreSnapshot) {
self.outbound = snapshot
.outbound
.into_iter()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = snapshot.inbound;
self.last_deliveries = snapshot.last_deliveries;
}
/// Migrate the legacy flat representation conservatively. Old Rust used
/// every entry for both directions, so retaining entries in both stores
/// preserves working stamps while all new state is direction-correct.
pub fn replace_legacy(&mut self, tickets: Vec<Ticket>) {
self.outbound = tickets
.iter()
.cloned()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = tickets;
self.last_deliveries.clear();
}
}
@@ -96,66 +255,67 @@ mod tests {
use super::*;
#[test]
fn test_ticket_validity() {
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(999.0));
assert!(!ticket.is_valid(1001.0));
}
#[test]
fn test_ticket_used() {
let mut ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(500.0));
ticket.use_ticket();
assert!(!ticket.is_valid(500.0));
}
#[test]
fn test_ticket_renew() {
let expires = 2_000_000.0;
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], expires);
// TICKET_RENEW is ~1 week; close to expiry should trigger, far should not.
assert!(ticket.should_renew(expires - 1.0));
assert!(!ticket.should_renew(0.0));
}
#[test]
fn test_ticket_store() {
fn direction_state_is_separate() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
store.add_inbound(Ticket::new([0x01; 16], dest, 2_000.0));
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
assert!(store.find_outbound(&dest, 1_000.0).is_none());
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.add(Ticket::new([0x02; 16], dest, 2000.0));
store.add(Ticket::new([0x03; 16], [0xCC; 16], 1500.0));
assert_eq!(store.count_valid(500.0), 3);
assert_eq!(store.count_valid(1500.0), 1);
let found = store.find(&dest, 500.0);
assert!(found.is_some());
store.remember_outbound(Ticket::new([0x02; 16], dest, 2_000.0));
assert_eq!(
store.find_outbound(&dest, 1_000.0).unwrap().token,
[0x02; 16]
);
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
}
#[test]
fn test_ticket_store_use() {
fn issuance_reuses_then_renews_and_throttles_after_delivery() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
let first = store.issue_for(dest, TICKET_EXPIRY, 1_000.0).unwrap();
let reused = store.issue_for(dest, TICKET_EXPIRY, 2_000.0).unwrap();
assert_eq!(reused.token, first.token);
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.mark_ticket_delivered(dest, 2_000.0);
assert!(store.issue_for(dest, TICKET_EXPIRY, 2_001.0).is_none());
let renewed = store
.issue_for(dest, TICKET_EXPIRY, 2_000.0 + TICKET_INTERVAL as f64)
.unwrap();
assert_eq!(renewed.token, first.token);
let token = store.use_for(&dest, 500.0);
assert_eq!(token, Some([0x01; 16]));
let token = store.use_for(&dest, 500.0);
assert!(token.is_none());
let near_expiry = first.expires - TICKET_RENEW as f64 + 1.0;
let replacement = store.issue_for(dest, TICKET_EXPIRY, near_expiry).unwrap();
assert_ne!(replacement.token, first.token);
}
#[test]
fn test_ticket_store_cull() {
fn snapshot_roundtrip_preserves_directions_and_delivery_gate() {
let mut store = TicketStore::new();
store.add(Ticket::new([0x01; 16], [0xBB; 16], 100.0));
store.add(Ticket::new([0x02; 16], [0xBB; 16], 99999.0));
let dest = [0xCC; 16];
store.add_inbound(Ticket::new([1; 16], dest, 9_999.0));
store.remember_outbound(Ticket::new([2; 16], dest, 9_999.0));
store.mark_ticket_delivered(dest, 100.0);
store.cull(100.0 + TICKET_GRACE as f64 + 1.0);
assert_eq!(store.count_valid(99999.0 - 1.0), 1);
let mut restored = TicketStore::new();
restored.replace_snapshot(store.snapshot());
assert_eq!(restored.inbound_tokens(&dest, 200.0), vec![[1; 16]]);
assert_eq!(restored.find_outbound(&dest, 200.0).unwrap().token, [2; 16]);
assert!(restored.issue_for(dest, TICKET_EXPIRY, 200.0).is_none());
}
#[test]
fn ticket_field_is_native_python_shape_and_rejects_expired_values() {
let ticket = Ticket::new([0x42; 16], [0x11; 16], 2_000.0);
let encoded = ticket.encode_field().unwrap();
let value = rmpv::decode::read_value(&mut encoded.as_slice()).unwrap();
let values = value.as_array().unwrap();
assert_eq!(values[0].as_f64(), Some(2_000.0));
assert_eq!(values[1].as_slice(), Some(&[0x42; 16][..]));
let decoded = Ticket::decode_field([0x11; 16], &encoded, 1_000.0).unwrap();
assert_eq!(decoded, ticket);
assert!(Ticket::decode_field([0x11; 16], &encoded, 2_000.0).is_none());
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use crate::constants::DESTINATION_LENGTH;
/// Reticulum destination hash, as carried in LXMF wire messages.
pub type DestinationHash = [u8; DESTINATION_LENGTH];
/// Reticulum identity hash, used for peer and ticket identity binding.
/// Reticulum identity hash. Ticket stores use delivery destination hashes instead.
pub type IdentityHash = [u8; DESTINATION_LENGTH];
/// Canonical LXMF message id / SHA-256 digest.
+466
View File
@@ -0,0 +1,466 @@
//! Focused public-boundary regressions for durable propagation delivery.
use lxmf_core::admission::*;
use lxmf_core::admission_store::FileAdmissionStore;
use lxmf_core::constants::DeliveryMethod;
use lxmf_core::message::{LxMessage, LxMessageDraft, RecipientStamp};
use lxmf_core::propagation_send::*;
use rns_crypto::{ed25519::Ed25519PrivateKey, sha::full_hash};
// These tests deliberately exhaust the shared production admission budget.
// Exclude only other budget-exhaustion fixtures, without changing its limits.
static PROCESSING_BUDGET_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn message(stamp: Option<RecipientStamp>) -> LxMessage {
let mut draft = LxMessageDraft::new(
[1; 16],
[2; 16],
"title",
"body",
DeliveryMethod::Propagated,
)
.unwrap();
draft.set_timestamp(100.).unwrap();
draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(stamp)
.unwrap()
}
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [4; 16],
node: [5; 16],
transient_id: [n; 32],
}
}
fn record(msg: &LxMessage, n: u8, time: u64, disposition: DurableDisposition) -> AdmissionRecord {
AdmissionRecord {
scope: scope(n),
message_id: msg.message_id(),
received_wire_hash: full_hash(msg.wire_bytes()),
stored_message_wire_hash: None,
disposition,
committed_at: time,
}
}
fn commit(
store: &FileAdmissionStore,
msg: &LxMessage,
n: u8,
time: u64,
disposition: DurableDisposition,
) -> DurableAdmissionReceipt {
DurableAdmissionReceipt::commit(store.prepare(
record(msg, n, time, disposition),
msg.wire_owned(),
true,
))
.unwrap()
}
#[test]
fn duplicate_stamp_images_keep_first_archive_and_one_hook_across_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let first = message(None);
let second = message(Some(RecipientStamp::ProofOfWork([7; 32])));
assert_eq!(first.message_id(), second.message_id());
assert_ne!(first.wire_bytes(), second.wire_bytes());
commit(&store, &first, 1, 100, DurableDisposition::Committed);
let duplicate = commit(&store, &second, 2, 101, DurableDisposition::Committed);
assert_eq!(
duplicate.record().disposition,
DurableDisposition::Duplicate
);
assert_eq!(
duplicate.record().received_wire_hash,
full_hash(second.wire_bytes())
);
assert_eq!(
duplicate.record().stored_message_wire_hash,
Some(full_hash(first.wire_bytes()))
);
assert_eq!(
std::fs::read(bodies.join(format!("{}.lxm", hex::encode(first.message_id())))).unwrap(),
first.wire_bytes()
);
assert_eq!(store.pending_hooks().len(), 1);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
reopened.haves(scope(1).identity, scope(1).node, 102).len(),
2
);
assert_eq!(reopened.pending_hooks().len(), 1);
let event = reopened.pending_hooks()[0].0;
reopened.complete_hook(event).unwrap();
drop(reopened);
assert!(
FileAdmissionStore::open(temp.path(), &bodies)
.unwrap()
.pending_hooks()
.is_empty()
);
}
#[test]
fn published_body_intent_recovers_original_tid_after_missing_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 9, 100, DurableDisposition::Committed);
drop(store);
let dir = temp.path().join("download-admission-v1");
for file in std::fs::read_dir(&dir).unwrap() {
let path = file.unwrap().path();
if path.extension().is_some_and(|s| s == "commit") {
std::fs::remove_file(path).unwrap();
}
}
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope(9).identity, scope(9).node, 101),
vec![scope(9).transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
}
#[test]
fn damaged_archive_never_becomes_purge_authority_on_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::Committed);
drop(store);
let archive = bodies.join(format!("{}.lxm", hex::encode(msg.message_id())));
std::fs::write(&archive, b"preserved corrupt evidence").unwrap();
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert!(
reopened
.haves(scope(1).identity, scope(1).node, 101)
.is_empty()
);
assert!(reopened.pending_hooks().is_empty());
assert_eq!(
std::fs::read(archive).unwrap(),
b"preserved corrupt evidence"
);
}
#[test]
fn expired_policy_receipt_is_revalidated_and_user_deletion_outlives_tid_receipts() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::PolicyDiscard);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
let now = 101 + POLICY_RECEIPT_LIFETIME;
assert!(
store
.haves(scope(1).identity, scope(1).node, now)
.is_empty()
);
assert_eq!(
commit(&store, &msg, 1, now, DurableDisposition::Committed)
.record()
.disposition,
DurableDisposition::Committed
);
store
.mark_user_deleted(scope(1).identity, msg.message_id(), now + 1)
.unwrap();
assert!(store.pending_hooks().is_empty());
assert_eq!(
store.maintain(now + 2 + POLICY_RECEIPT_LIFETIME).unwrap(),
1
);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
commit(
&reopened,
&msg,
2,
now + 3 + POLICY_RECEIPT_LIFETIME,
DurableDisposition::Committed
)
.record()
.disposition,
DurableDisposition::UserDeleted
);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
}
#[test]
fn suppression_retries_transient_failures_and_revalidates_epoch_changes() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(ledger.get(&scope(1)).unwrap().active(101, epoch));
let mut new = epoch;
new.keys[0] = 1;
assert!(!ledger.get(&scope(1)).unwrap().active(101, new));
for _ in 0..20 {
ledger
.record_failure(scope(2), SuppressionReason::StorageBusy, epoch, 100)
.unwrap();
}
let retry = ledger.get(&scope(2)).unwrap();
assert!((3340..=4060).contains(&retry.next_retry));
assert!(!retry.active(retry.next_retry, epoch));
let wire = rmp_serde::to_vec(&ledger).unwrap();
let restored: SuppressionLedger = rmp_serde::from_slice(&wire).unwrap();
assert_eq!(restored.records().count(), 2);
}
#[test]
fn processing_admission_fails_promptly_without_partial_credit_deadlock() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
assert!(matches!(
ProcessingLease::try_acquire(usize::MAX),
Err(SuppressionReason::TooLarge)
));
let workers = (0..MAX_PROCESSORS)
.map(|_| ProcessingLease::try_acquire(100).unwrap())
.collect::<Vec<_>>();
assert!(matches!(
ProcessingLease::try_acquire(100),
Err(SuppressionReason::WorkerUnavailable)
));
drop(workers);
assert!(ProcessingLease::try_acquire(100).is_ok());
}
#[test]
fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
let msg = message(None);
let binding = EncryptionBinding::for_recipient(&[6; 64], None);
let mut envelope = PropagationEnvelope::new(msg, binding, 0.0, |p| Ok(p.to_vec())).unwrap();
let initial = envelope.ciphertext().clone();
let tid = envelope.transient_id();
let policy = AdvertisedNodePolicy {
stamp_cost: 0.0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
let mut ready = propagation_readiness([8; 16], true, true, Some(policy), true, 101.).unwrap();
envelope.pack_for(ready, 101.).unwrap();
ready.policy.stamp_cost = 4.0;
envelope.pack_for(ready, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &initial);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4.0);
assert_eq!(
propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok());
}
#[test]
#[cfg(feature = "sqlite-store")]
fn tickets_and_delivered_claims_are_in_the_state_store_before_they_are_acted_on() {
use lxmf_core::state_store::{FILE_NAME, SqliteStateStore, StateStore};
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
router.load_state(temp.path()).unwrap();
let stale = router.state_snapshot();
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
router.prepare_outbound(&mut draft).unwrap();
// A second connection reads the committed ticket while the router still runs.
let issued = SqliteStateStore::open(&temp.path().join(FILE_NAME))
.unwrap()
.get_inbound_tickets(&[1; 16])
.unwrap()
.expect("ticket committed before prepare_outbound returned");
let msg = draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(None)
.unwrap();
assert!(
msg.fields()
.get(lxmf_core::constants::FIELD_TICKET)
.is_some()
);
// The delivered claim is in the file before the delivery callback runs.
let db = temp.path().join(FILE_NAME);
let claimed_first = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let seen = claimed_first.clone();
router.register_delivery_callback(move |delivered| {
let claimed = SqliteStateStore::open(&db)
.unwrap()
.has_delivered(&delivered.message_id())
.unwrap();
seen.store(claimed, std::sync::atomic::Ordering::Relaxed);
});
assert!(router.deliver_inbound(&msg, false));
assert!(claimed_first.load(std::sync::atomic::Ordering::Relaxed));
// An older checkpoint written afterwards cannot take the ticket away.
stale.save_state(temp.path()).unwrap();
drop(router);
let mut restarted = lxmf_core::router::LxmRouter::new(Default::default());
restarted.load_state(temp.path()).unwrap();
assert_eq!(restarted.get_inbound_tickets(&[1; 16]), Some(issued));
}
#[test]
fn suppression_hydration_rejects_duplicate_scopes_and_node_quota() {
let mut ledger = SuppressionLedger::default();
let row = ledger
.record_failure(
scope(1),
SuppressionReason::InvalidSignature,
AdmissionEpochs::default(),
100,
)
.unwrap()
.clone();
assert!(SuppressionLedger::from_records([row.clone(), row.clone()]).is_err());
let mut keys = row.epochs;
keys.keys[0] = 1;
assert!(!row.active(101, keys));
let mut policy = row.epochs;
policy.policy[0] = 1;
assert!(!row.active(101, policy));
let rows = (0..=SuppressionLedger::PER_NODE).map(|index| {
let mut value = row.clone();
value.scope.transient_id[..8].copy_from_slice(&(index as u64).to_be_bytes());
value
});
assert!(matches!(
SuppressionLedger::from_records(rows),
Err(AdmissionError::DispositionLedgerFull)
));
assert_eq!(
SuppressionLedger::from_records([row])
.unwrap()
.records()
.count(),
1
);
}
#[test]
fn adapter_processing_memory_shares_peak_budget_without_second_worker() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
let worker = ProcessingLease::try_acquire(1).unwrap();
assert!(matches!(
ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::WorkerUnavailable)
));
let extra = ProcessingMemoryLease::try_acquire(8 * 1024 * 1024).unwrap();
drop(extra);
drop(worker);
let all = ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES).unwrap();
assert!(matches!(
ProcessingLease::try_acquire(1),
Err(SuppressionReason::WorkerUnavailable)
));
drop(all);
assert!(ProcessingLease::try_acquire(1).is_ok());
}
fn answer_node_path(
receiver: &mut tokio::sync::mpsc::Receiver<rns_transport::messages::TransportMessage>,
) {
use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse};
while let Ok(message) = receiver.try_recv() {
if let TransportMessage::Rpc {
query: TransportQuery::HasPath { .. },
response_tx,
} = message
{
response_tx
.send(TransportQueryResponse::BoolResult(true))
.unwrap();
}
}
}
fn reject_link_request(
receiver: &mut tokio::sync::mpsc::Receiver<rns_transport::messages::TransportMessage>,
) {
use rns_transport::messages::TransportMessage;
while let Ok(message) = receiver.try_recv() {
if let TransportMessage::SendLinkRequest { result_tx, .. } = message {
result_tx
.send(Err(
rns_transport::link_messages::LinkRequestDispatchError::Capacity(
rns_transport::InterfaceCapacityError::LinkCapacityUnavailable {
interface_id: 7,
clear_mtu: 499,
required: 500,
},
),
))
.unwrap();
return;
}
}
panic!("exact Link request dispatch channel was not staged");
}
#[test]
fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeout() {
use lxmf_core::link_delivery::{DeliveryResult, LinkDeliveryManager};
use lxmf_core::propagation_client::{PropagationClient, PropagationClientState};
use lxmf_core::propagation_sync::{PeerSyncTerminalState, PropagationSyncTask};
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut delivery = LinkDeliveryManager::new(tx.clone(), None, None);
delivery.start_delivery(message(None), [3; 16], 1).unwrap();
reject_link_request(&mut rx);
assert!(delivery.tick().iter().any(
|result| matches!(result,DeliveryResult::Failed {reason,..} if reason.contains("499"))
));
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
answer_node_path(&mut rx);
client.tick();
reject_link_request(&mut rx);
client.tick();
assert_eq!(
client.transfer_status().state,
PropagationClientState::Failed
);
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut sync = PropagationSyncTask::new(tx, [8; 16]);
assert!(sync.request_sync_now([3; 16]));
answer_node_path(&mut rx);
sync.tick();
reject_link_request(&mut rx);
sync.tick();
assert_eq!(
sync.take_terminal_peer_result().unwrap().state,
PeerSyncTerminalState::Failed
);
}
#[test]
fn canceled_download_closes_exact_request_admission_reply() {
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = lxmf_core::propagation_client::PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
answer_node_path(&mut rx);
client.tick();
client.cancel_download();
let mut found = false;
while let Ok(message) = rx.try_recv() {
if let rns_transport::messages::TransportMessage::SendLinkRequest { result_tx, .. } =
message
{
assert!(result_tx.is_closed());
found = true;
}
}
assert!(found);
}
+262
View File
@@ -0,0 +1,262 @@
use bytes::Bytes;
use lxmf_core::propagation_node::{
PropagationAdmission, PropagationAdmissionOutcome, PropagationNode, PropagationNodeConfig,
ValidatedOpaquePropagationBlob, read_planned_messages,
};
use rmpv::Value;
fn payload(destination: [u8; 16]) -> Bytes {
let recipient = rns_identity::identity::Identity::new();
let mut bytes = destination.to_vec();
bytes.extend_from_slice(&recipient.encrypt(b"private test payload", None).unwrap());
bytes.extend_from_slice(&[0; 32]);
bytes.into()
}
fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob {
ValidatedOpaquePropagationBlob::validate(bytes, 0.0).unwrap()
}
fn request(wants: Option<Vec<[u8; 32]>>, haves: Option<Vec<[u8; 32]>>) -> Vec<u8> {
let ids = |value: Option<Vec<[u8; 32]>>| {
value
.map(|v| Value::Array(v.into_iter().map(|id| Value::Binary(id.to_vec())).collect()))
.unwrap_or(Value::Nil)
};
encode(&Value::Array(vec![ids(wants), ids(haves)]))
}
fn reserve(
node: &mut PropagationNode,
bytes: Bytes,
) -> lxmf_core::propagation_node::PropagationStoreWritePlan {
match node.plan_opaque_admission(validated(bytes)) {
PropagationAdmission::Reserved(plan) => *plan,
other => panic!("expected new admission: {other:?}"),
}
}
#[tokio::test]
async fn duplicate_waits_for_exact_commit_and_rechecks_retained_files() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
let task = tokio::spawn(waiter.wait());
tokio::task::yield_now().await;
assert!(!task.is_finished());
assert!(node.commit_store_write(plan.persist().unwrap()));
assert_eq!(task.await.unwrap(), PropagationAdmissionOutcome::Committed);
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("committed duplicate")
};
check.verify().unwrap();
let path = node.plan_message_reads(&[tid]).pop().unwrap().path;
std::fs::write(&path, b"corruption").unwrap();
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes))
else {
panic!("duplicate requires file check")
};
assert!(check.verify().is_err());
drop(node);
assert!(PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).is_err());
}
#[test]
fn restart_skips_body_rereads_and_never_serves_a_damaged_body() {
let dir = tempfile::tempdir().unwrap();
let store = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], store.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes);
assert!(node.commit_store_write(plan.persist().unwrap()));
let path = node.plan_message_reads(&[tid]).pop().unwrap().path;
drop(node);
let mut damaged = std::fs::read(&path).unwrap();
*damaged.last_mut().unwrap() ^= 0xff;
std::fs::write(&path, &damaged).unwrap();
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], store).unwrap();
assert_eq!(reopened.message_count(), 1);
assert!(read_planned_messages(&reopened.plan_message_reads(&[tid])).is_empty());
}
#[tokio::test]
async fn cancelled_reservation_releases_waiters_without_authority_and_can_retry() {
let dir = tempfile::tempdir().unwrap();
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[1; 16],
dir.path().join("store"),
)
.unwrap();
let bytes = payload([2; 16]);
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan);
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let retry = reserve(&mut node, bytes);
assert!(node.commit_store_write(retry.persist().unwrap()));
}
#[tokio::test]
async fn lost_persisted_callback_reuses_first_image_and_restart_has_one_admission() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan.persist().unwrap());
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let objects = legacy.with_extension("v2").join("objects");
let first_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(first_files.len(), 3);
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let retry_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(retry_files, first_files);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
std::fs::read(&reopened.plan_message_reads(&[tid])[0].path).unwrap(),
bytes
);
}
#[test]
fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let destination = [2; 16];
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let objects = legacy.with_extension("v2").join("objects");
let unavailable = legacy.with_extension("v2").join("temporarily-unavailable");
std::fs::rename(&objects, &unavailable).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Nil)
);
assert!(node.contains(&tid));
std::fs::rename(&unavailable, &objects).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Array(vec![]))
);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert!(!reopened.contains(&tid));
}
#[test]
fn purge_is_durable_and_purged_message_is_not_readmitted() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let destination = [2; 16];
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let old_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
let stale = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
let purge = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
assert_eq!(purge.into_response(), encode(&Value::Array(vec![])));
assert!(!node.contains(&tid));
assert!(!old_path.exists());
// A purged message stays processed and is filtered on re-upload.
assert!(matches!(
node.plan_opaque_admission(validated(bytes.clone())),
PropagationAdmission::AlreadyProcessed
));
let _ = stale.into_response();
assert!(!node.contains(&tid));
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap();
assert!(!reopened.contains(&tid));
}
#[test]
fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() {
let dir = tempfile::tempdir().unwrap();
let config = PropagationNodeConfig {
max_storage: 0,
..Default::default()
};
let mut node =
PropagationNode::with_storage(config, [1; 16], dir.path().join("store")).unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes);
assert!(node.commit_store_write(plan.persist().unwrap()));
node.handle_get_request(&request(None, Some(vec![tid])), &[3; 16])
.into_response();
assert!(node.contains(&tid));
let maintenance = node.plan_maintenance();
assert!(!maintenance.is_empty());
assert!(node.contains(&tid));
maintenance.persist().unwrap();
assert!(!node.contains(&tid));
assert!(node.create_offer([4; 16], None).is_empty());
}
#[test]
fn legacy_trees_and_second_live_host_cannot_be_opened_implicitly() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("legacy");
std::fs::create_dir(&old).unwrap();
std::fs::write(old.join("private"), b"plaintext").unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.is_err()
);
assert_eq!(std::fs::read(old.join("private")).unwrap(), b"plaintext");
let fresh = dir.path().join("fresh");
let node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh.clone())
.unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh).is_err()
);
drop(node);
}
fn encode(value: &Value) -> Vec<u8> {
let mut out = Vec::new();
rmpv::encode::write_value(&mut out, value).unwrap();
out
}
+9 -2
View File
@@ -1,9 +1,11 @@
[package]
name = "lxmf-tools"
description = "Rust LXMF daemon and CLI tools for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license-file.workspace = true
autobins = false
[dependencies]
@@ -13,15 +15,20 @@ rns-identity = { workspace = true }
rns-transport = { workspace = true }
rns-wire = { workspace = true }
rns-crypto = { workspace = true }
rns-tools = { workspace = true }
clap = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
hex = { workspace = true }
base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
thiserror = { workspace = true }
zeroize = "1"
[dev-dependencies]
tempfile = { workspace = true }
[[bin]]
name = "lxmd-rs"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+72 -75
View File
@@ -26,16 +26,21 @@ impl SendMethod {
}
}
/// The LXMF release `lxmd-rs` follows, named in its `--version` line and
/// announced as its propagation node version.
pub const LXMF_COMPAT_VERSION: &str = lxmf_core::constants::LXMF_COMPAT_VERSION;
#[derive(Parser)]
#[command(
name = "lxmd-rs",
bin_name = "lxmd-rs",
about = "LXMF Propagation Daemon",
version
disable_version_flag = true,
infer_long_args = true
)]
pub struct Args {
/// Path to configuration directory.
#[arg(short, long)]
#[arg(long, short_alias = 'c')]
pub config: Option<String>,
/// Path to alternative Reticulum configuration directory.
@@ -46,6 +51,23 @@ pub struct Args {
#[arg(short = 'p', long = "propagation-node")]
pub propagation_node: bool,
/// Quarantine the legacy relay store and initialize the separate v2 store.
/// Run only after stopping all old relay writers and their auto-restart jobs.
#[arg(long, requires = "relay_writers_stopped")]
pub migrate_propagation_store: bool,
/// Confirm all legacy app/daemon relay writers are stopped for migration.
#[arg(long, requires = "migrate_propagation_store")]
pub relay_writers_stopped: bool,
/// Import an independently verified legacy opaque-ingress recovery manifest.
#[arg(long, requires_all = ["migrate_propagation_store", "recovery_manifest_sha256"])]
pub recover_propagation_manifest: Option<PathBuf>,
/// Separately approved SHA-256 of the exact recovery manifest file.
#[arg(long, requires = "recover_propagation_manifest")]
pub recovery_manifest_sha256: Option<String>,
/// Executable to run when a message is received, overriding config.
#[arg(short = 'i', long = "on-inbound", value_name = "PATH")]
pub on_inbound: Option<String>,
@@ -62,11 +84,15 @@ pub struct Args {
#[arg(long)]
pub exampleconfig: bool,
/// Run as a system service (no interactive output).
/// Print version and exit.
#[arg(long, short_alias = 'V')]
pub version: bool,
/// Service mode; the process remains in the foreground.
#[arg(short = 's', long)]
pub service: bool,
/// Display local node status and exit.
/// Query node status over Reticulum and exit (use `--remote` for another node).
#[arg(long)]
pub status: bool,
@@ -90,30 +116,33 @@ pub struct Args {
#[arg(short = 'r', long, value_name = "DEST_HASH")]
pub remote: Option<String>,
/// Identity path used for remote query operations.
/// Identity path used for local or remote control queries.
#[arg(long, value_name = "PATH")]
pub identity: Option<PathBuf>,
/// Send a single message and exit: --send <dest_hash> <content>
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
/// Send messages and exit: `--send <dest_hash> <content>...`, one message
/// per content, queued together.
#[arg(long, num_args = 1.., value_names = ["DEST_HASH", "CONTENT"])]
pub send: Option<Vec<String>>,
/// Read outgoing --send content from a UTF-8 file instead of argv.
/// Read outgoing `--send` content from a UTF-8 file instead of argv.
#[arg(long, value_name = "PATH")]
pub send_file: Option<PathBuf>,
/// Delivery method for --send.
/// Delivery method for `--send`.
#[arg(long, value_enum, default_value_t = SendMethod::Opportunistic)]
pub send_method: SendMethod,
/// Link/resource completion timeout for --send.
/// Nominal wait in seconds for each `--send` completion phase. Each poll
/// includes a one-second sleep; discovery and work between polls add time.
#[arg(long, default_value_t = 90)]
pub send_timeout_secs: u64,
/// Attach custom LXMF fields to the outgoing --send message. Accepts a
/// JSON object mapping field-id -> base64(value). Example:
/// --send-fields-json '{"1":"aGVsbG8=","42":"AAECA/8="}'
/// Only meaningful alongside --send.
/// Attach binary LXMF fields to `--send`. Accepts a JSON object mapping
/// decimal field IDs (0–255) to base64-encoded bytes. Example:
/// `--send-fields-json '{"200":"aGVsbG8=","201":"AAECA/8="}'`.
/// Choose IDs agreed with the receiving application. This option does not
/// construct native structured MessagePack fields. Only used with `--send`.
#[arg(long, value_name = "JSON")]
pub send_fields_json: Option<String>,
}
@@ -162,72 +191,22 @@ pub fn parse_destination_hash(raw: &str) -> Result<[u8; 16], String> {
Ok(hash)
}
/// Python `lxmd.__default_lxmd_config__` (LXMF 1.3.0), printed by
/// `--exampleconfig` and written on first run.
pub fn example_config() -> &'static str {
r#"# This is an example LXM Daemon config file.
[propagation]
include_str!("lxmd_default_config.txt")
}
enable_node = no
# control_allowed = 7d7e542829b40f32364499b27438dba8, 437229f8e29598b2282b88bad5e44698
# node_name = Anonymous Propagation Node
announce_interval = 360
announce_at_start = yes
autopeer = yes
autopeer_maxdepth = 6
# 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
delivery_transfer_max_accepted_size = 1000
# on_inbound = /path/to/handler
[logging]
loglevel = 4
"#
/// The file Python `create_default_config` writes: ConfigObj drops the
/// trailing blank line of the default text.
pub fn default_config_file_text() -> String {
format!("{}\n", example_config().trim_end_matches('\n'))
}
/// Parse a plaintext destination-hash list: one 16-byte hex value per line.
/// Missing files return empty. Like Python `lxmd.py`, this accepts only raw
/// 32-byte hex lines; comments and inline comments are ignored only because
/// their raw line length is not exactly 32 bytes.
/// Read errors return an empty list. Each line must contain exactly 32 ASCII
/// hexadecimal characters; a trailing CR is allowed for CRLF files. Whitespace
/// and comments are not stripped, so lines containing them are skipped.
///
/// Python reference: `lxmd.py` reads `ignored` / `allowed` from the config dir.
pub fn load_hash_list(path: &Path) -> Vec<[u8; 16]> {
@@ -293,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 =
+244 -94
View File
@@ -10,10 +10,15 @@ use lxmf_core::propagation_node::PropagationNode;
use lxmf_core::router::LxmRouter;
use rmpv::Value;
use rns_identity::identity::Identity;
use rns_runtime::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_transport::messages::{AnnounceHandlerEvent, TransportMessage};
use rns_transport::messages::TransportMessage;
use tokio::sync::mpsc;
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";
@@ -42,6 +47,7 @@ impl ControlCommandKind {
}
}
/// Query propagation control with a raw peer hash, or no payload for status.
pub async fn query_control(
transport_tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
identity: Identity,
@@ -56,62 +62,58 @@ pub async fn query_control(
target_identity_hash,
CONTROL_APP_NAME,
path,
payload,
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
// letting Link infer the type can truncate or reinterpret a peer address.
// Python sends a bytes object for sync/unpeer and None for status.
encode_value(&if payload.is_empty() {
Value::Nil
} else {
Value::Binary(payload)
})
}
pub async fn resolve_remote_identity_hash(
transport_tx: mpsc::Sender<TransportMessage>,
remote_destination_hash: [u8; 16],
timeout_secs: f64,
) -> Result<[u8; 16], LinkClientError> {
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
transport_tx
.send(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
let send_result = transport_tx
.send(TransportMessage::RequestPath {
destination_hash: remote_destination_hash,
})
.await;
if send_result.is_err() {
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
return Err(LinkClientError::TransportUnavailable);
}
let wait = async {
while let Some(event) = ann_rx.recv().await {
if event.destination_hash == remote_destination_hash
&& let Some(identity_hash) = event.identity_hash
{
return Ok(identity_hash);
}
let recalled = resolve_destination_on_transport(
&transport_tx,
remote_destination_hash,
DestinationResolveOptions::new(Duration::from_secs_f64(timeout_secs.max(0.0))),
)
.await;
let recalled = recalled.map_err(|error| match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("remote identity resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
let result =
match tokio::time::timeout(Duration::from_secs_f64(timeout_secs.max(0.0)), wait).await {
Ok(result) => result,
Err(_) => Err(LinkClientError::Timeout("remote identity resolution")),
};
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
result
})?;
Identity::from_public_key(&recalled.public_key)
.map(|identity| identity.hash)
.map_err(|error| LinkClientError::UnexpectedResponse(error.to_string()))
}
pub fn decode_control_response(response: &[u8]) -> ControlResponse {
@@ -157,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)
@@ -193,6 +192,9 @@ pub fn encode_router_control_stats(
.as_ref()
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.unhandled_messages))
.unwrap_or_else(|| peer.unhandled_message_count());
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -201,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),
@@ -240,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)),
@@ -269,7 +278,7 @@ pub fn encode_router_control_stats(
(Value::String("incoming".into()), Value::from(peer.incoming)),
(
Value::String("unhandled".into()),
Value::from(peer.unhandled_messages() as u64),
Value::from(unhandled as u64),
),
]),
),
@@ -300,31 +309,31 @@ pub fn encode_router_control_stats(
(Value::String("uptime".into()), Value::F64(uptime)),
(
Value::String("delivery_limit".into()),
Value::from(router.config.delivery_limit_kb as u64),
Value::F64(router.config.delivery_limit_kb),
),
(
Value::String("propagation_limit".into()),
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()),
@@ -515,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!(
@@ -591,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()
@@ -612,12 +621,10 @@ pub fn format_remote_status(
}
_ => "never synced".to_string(),
};
let name = map_str(peer, "name")
.unwrap_or("")
.trim()
.replace(['\n', '\r'], "");
let display_name = if name.len() > 45 {
format!("{}...", &name[..45])
let name =
lxmf_core::presentation::sanitize_name_lxmd(map_str(peer, "name").unwrap_or(""));
let display_name = if name.chars().count() > 45 {
format!("{}...", name.chars().take(45).collect::<String>())
} else {
name
};
@@ -635,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!(
@@ -723,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()
@@ -850,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 {
@@ -868,6 +881,109 @@ 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 {
let mut hash = vec![0x41; 16];
hash[0] = prefix;
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash),
"peer prefix {prefix:#04x} must not select a MessagePack type"
);
}
for hash in [
hex::decode("af55b3f0e0b336fdfdbe263c12a688e0").unwrap(),
[vec![0xc4, 14], vec![0x41; 14]].concat(),
[vec![0x9f], vec![0; 15]].concat(),
] {
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash)
);
}
}
#[test]
fn empty_control_payload_matches_python_status_nil() {
assert_eq!(
decode_value(&encode_control_payload(Vec::new())),
Value::Nil
);
}
#[tokio::test]
async fn remote_identity_resolution_uses_recall_and_path_request_without_handlers() {
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportQuery, TransportQueryResponse,
};
let remote_destination_hash = [0x41; 16];
let remote_identity = Identity::new();
let public_key = remote_identity.get_public_key();
let expected_identity_hash = remote_identity.hash;
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("initial recall")
else {
panic!("expected initial recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.expect("return cache miss");
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::RequestPath { destination_hash })
if destination_hash == remote_destination_hash
));
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("post-request recall")
else {
panic!("expected post-request recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some({
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());
});
let resolved = resolve_remote_identity_hash(transport_tx, remote_destination_hash, 1.0)
.await
.expect("resolve remote identity");
assert_eq!(resolved, expected_identity_hash);
responder.await.expect("transport responder");
}
fn decode_value(data: &[u8]) -> Value {
rmpv::decode::read_value(&mut &data[..]).unwrap()
}
@@ -955,15 +1071,42 @@ mod tests {
assert!(out.contains("4 propagation messages served to clients"));
}
#[test]
fn status_formatter_bounds_multibyte_untrusted_peer_names() {
let hostile_name = format!("{}\u{202e}\u{1f680}", "界".repeat(50));
let peer = Value::Map(vec![
(
Value::String("name".into()),
Value::String(hostile_name.into()),
),
(Value::String("alive".into()), Value::Boolean(true)),
]);
let stats = Value::Map(vec![
(
Value::String("destination_hash".into()),
Value::Binary(vec![0x01; 16]),
),
(
Value::String("peers".into()),
Value::Map(vec![(Value::Binary(vec![0x02; 16]), peer)]),
),
]);
let out = format_remote_status(&stats, false, true, 0.0);
let expected = format!("Name : {}...", "界".repeat(45));
assert!(out.contains(&expected));
assert!(!out.contains('\u{202e}'));
assert!(!out.contains('\u{1f680}'));
}
#[test]
fn stats_encoder_uses_python_compile_stats_shape() {
use lxmf_core::peer::LxmPeer;
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);
router.propagation_start_time = Some(1_700_000_000.0);
@@ -975,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()
@@ -1022,6 +1171,7 @@ mod tests {
assert_eq!(map_u64(&stats, "static_peers"), Some(1));
assert_eq!(map_u64(&stats, "discovered_peers"), Some(0));
assert_eq!(map_u64(&stats, "total_peers"), Some(1));
assert_eq!(map_f64(&stats, "delivery_limit"), Some(0.38));
let peers = map_value(&stats, "peers").unwrap().as_map().unwrap();
let peer_stats = &peers[0].1;
@@ -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
+56 -26
View File
@@ -1,7 +1,7 @@
//! Pure `lxmd` runtime helpers extracted from the binary.
//! `lxmd` path selection, control-command preflight, and status formatting.
//!
//! This module keeps daemon path handling and other pure helpers out of the
//! binary so CLI behavior can be tested directly.
//! Path selection reads environment variables and checks the filesystem;
//! these helpers do not start the daemon runtime.
use std::path::{Path, PathBuf};
@@ -18,8 +18,11 @@ pub struct LxmdPaths {
pub propagation_store_dir: PathBuf,
pub ratchets_dir: PathBuf,
pub ratchet_ring_path: PathBuf,
pub received_ratchets_dir: PathBuf,
pub known_identities_path: PathBuf,
pub ratchet_control_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,
@@ -38,8 +41,9 @@ impl LxmdPaths {
let propagation_store_dir = lxmf_storage_dir.join("messagestore");
let ratchets_dir = lxmf_storage_dir.join("ratchets");
let ratchet_ring_path = ratchets_dir.join("ring");
let received_ratchets_dir = ratchets_dir.join("received");
let known_identities_path = ratchets_dir.join("known_identities");
let ratchet_control_path = ratchets_dir.join("ring.control");
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");
@@ -57,8 +61,9 @@ impl LxmdPaths {
propagation_store_dir,
ratchets_dir,
ratchet_ring_path,
received_ratchets_dir,
known_identities_path,
ratchet_control_path,
legacy_received_ratchets_dir,
legacy_known_identities_path,
legacy_lxmf_dir,
legacy_identity_path,
legacy_messages_dir,
@@ -85,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 {
@@ -102,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,
}
}
}
@@ -115,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"
@@ -128,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,
)
}
@@ -160,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)
}
@@ -273,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")?),
@@ -334,11 +345,15 @@ mod tests {
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring")
);
assert_eq!(
paths.received_ratchets_dir,
paths.ratchet_control_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring.control")
);
assert_eq!(
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")
);
}
@@ -410,7 +425,6 @@ mod tests {
propagation_size: 4096,
pending_outbound: 4,
pending_deferred_stamps: 5,
stamp_costs_cached: 6,
};
assert_eq!(
@@ -421,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"
);
}
@@ -445,26 +458,37 @@ mod tests {
#[test]
fn delivery_announce_app_data_matches_python_msgpack() {
// LXMF 1.3.0 LXMRouter.get_announce_app_data output.
assert_eq!(
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
"92c4045465737410"
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)),
"92c0c0"
"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"
)
);
}
@@ -535,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!(
+303 -24
View File
@@ -1,6 +1,10 @@
use std::fs;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::{Child, Stdio};
use std::process::{Command, Output};
#[cfg(unix)]
use std::time::{Duration, Instant};
use std::time::{SystemTime, UNIX_EPOCH};
struct TestDir {
@@ -55,6 +59,49 @@ 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;
loop {
if let Some(status) = child.try_wait().expect("poll lxmd-rs child") {
return Some(status);
}
if Instant::now() >= deadline {
return None;
}
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn help_lists_cli_surface_without_starting_runtime() {
let output = lxmd(&["--help"]);
@@ -76,6 +123,196 @@ fn help_lists_cli_surface_without_starting_runtime() {
assert!(text.contains("[possible values: opportunistic, direct, propagated]"));
}
#[cfg(unix)]
#[test]
fn ctrl_c_exits_during_deferred_start() {
let lxmf_dir = TestDir::new("lxmf-ctrlc");
let rns_dir = TestDir::new("rns-ctrlc");
fs::write(
lxmf_dir.path().join("config"),
"\
[lxmf]
display_name = Test
announce_at_start = yes
[propagation]
enable_node = 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");
// 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");
// 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) = daemon.child().try_wait().expect("poll lxmd-rs startup") {
panic!(
"lxmd-rs exited before startup announce wait ({status}):\n{}",
combined_output(&daemon.output())
);
}
assert!(
Instant::now() < startup_deadline,
"lxmd-rs did not reach startup announce wait"
);
std::thread::sleep(Duration::from_millis(50));
}
std::thread::sleep(Duration::from_millis(100));
let signal_status = Command::new("kill")
.arg("-INT")
.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(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(&daemon.output())
);
}
let output = daemon.output();
assert!(
output.status.success(),
"expected clean shutdown after Ctrl+C, 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]
fn version_reports_binary_name_and_package_version() {
let output = lxmd(&["--version"]);
@@ -87,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());
}
@@ -103,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"]);
@@ -121,11 +403,15 @@ fn example_config_exits_before_runtime_initialisation() {
assert!(text.contains("[lxmf]"));
assert!(text.contains("display_name = Anonymous Peer"));
assert!(text.contains("announce_at_start = no"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1000"));
assert!(text.contains("# stamp_cost = 12"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1"));
assert!(text.contains("[propagation]"));
assert!(text.contains("enable_node = no"));
assert!(text.contains("announce_interval = 360"));
assert!(text.contains("announce_at_start = yes"));
assert!(text.contains("# sequential_pn_stamp_validation = yes"));
assert!(text.contains("# static_peers_bypass_sequential = yes"));
assert!(text.contains("# max_inbound_syncs = 3"));
assert!(text.contains("[logging]"));
assert!(text.contains("loglevel = 4"));
assert!(!text.contains("[control]"));
@@ -175,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_query_control_and_timeout_without_daemon() {
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"));
@@ -198,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())
@@ -207,37 +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 Python-compatible control timeout, got:\n{}",
"expected the control query to time out, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Getting lxmd statistics timed out, exiting now"),
"expected Python-compatible control timeout text, got:\n{}",
combined_output(&output)
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"
);
}
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Verify the complete CLI archive set before checksumming or publishing it."""
from __future__ import annotations
import argparse
import hashlib
from pathlib import Path
import re
import tarfile
import zipfile
ROOT = Path(__file__).resolve().parents[2]
PACKAGE = "rsLXMF"
BINS = ["lxmd-rs"]
DOCS = ("README.md", "LICENSE", "CHANGELOG.md")
PLATFORMS = {"linux-x86_64": "tar.gz", "macos": "tar.gz", "windows-x86_64": "zip"}
def verify(directory: Path, tag: str) -> None:
if not re.fullmatch(r"v\d+\.\d+\.\d+", tag):
raise ValueError("expected a vX.Y.Z tag")
names = {f"{PACKAGE}-{tag}-{platform}.{extension}" for platform, extension in PLATFORMS.items()}
if {p.name for p in directory.iterdir()} != names:
raise ValueError("release directory must contain exactly the three platform archives")
for platform, extension in PLATFORMS.items():
path = directory / f"{PACKAGE}-{tag}-{platform}.{extension}"
payloads = {}
if extension == "zip":
with zipfile.ZipFile(path) as archive:
for member in archive.infolist():
if member.is_dir():
continue
name = member.filename.replace("\\", "/")
if name in payloads:
raise ValueError(f"duplicate archive member: {name}")
payloads[name] = archive.read(member)
else:
with tarfile.open(path) as archive:
for member in archive.getmembers():
if member.isdir():
continue
if not member.isfile() or member.name in payloads:
raise ValueError(f"invalid archive member: {member.name}")
if "/bin/" in member.name and not member.mode & 0o111:
raise ValueError(f"binary is not executable: {member.name}")
stream = archive.extractfile(member)
assert stream is not None
payloads[member.name] = stream.read()
suffix = ".exe" if extension == "zip" else ""
expected = {f"{PACKAGE}/{doc}" for doc in DOCS} | {f"{PACKAGE}/bin/{name}{suffix}" for name in BINS}
if set(payloads) != expected:
raise ValueError(f"incorrect file inventory in {path.name}: {sorted(payloads)}")
for doc in DOCS:
if payloads[f"{PACKAGE}/{doc}"] != (ROOT / doc).read_bytes():
raise ValueError(f"{path.name}: {doc} does not match the qualified source")
for name in BINS:
data = payloads[f"{PACKAGE}/bin/{name}{suffix}"]
valid = (
data.startswith(b"\x7fELF") if platform.startswith("linux") else
data.startswith(b"MZ") if platform.startswith("windows") else
data[:4] in (b"\xcf\xfa\xed\xfe", b"\xfe\xed\xfa\xcf", b"\xca\xfe\xba\xbe")
)
if not valid:
raise ValueError(f"{path.name}: {name} is not a native binary for {platform}")
checksums = "".join(f"{hashlib.sha256((directory / name).read_bytes()).hexdigest()} {name}\n" for name in sorted(names))
(directory / "SHA256SUMS").write_text(checksums)
print(f"verified {PACKAGE} {tag}: three platform archives, native binaries, source documentation, and checksums")
def main() -> None:
parser = argparse.ArgumentParser(
description="Check the three release archives, then write SHA256SUMS."
)
parser.add_argument("--tag", required=True, help="release version in vX.Y.Z form, as used in archive names")
parser.add_argument(
"--directory", type=Path, required=True,
help="directory containing only the three platform archives; SHA256SUMS is written here after validation",
)
args = parser.parse_args()
verify(args.directory, args.tag)
if __name__ == "__main__":
main()
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""Validate rsLXMF's source-release invariants."""
from __future__ import annotations
import argparse
import json
import re
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
EXPECTED_RUST_VERSION = "1.89"
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
def fail(message: str) -> None:
raise SystemExit(f"source-release contract failed: {message}")
def command(*args: str, cwd: Path = ROOT) -> str:
return subprocess.check_output(args, cwd=cwd, text=True).strip()
def metadata() -> dict[str, object]:
output = command(
"cargo",
"metadata",
"--format-version",
"1",
"--locked",
"--no-deps",
)
return json.loads(output)
def check_packages(document: dict[str, object]) -> tuple[str, str]:
packages = document["packages"]
assert isinstance(packages, list)
versions = {package["version"] for package in packages}
if len(versions) != 1:
fail(f"workspace packages do not share one version: {sorted(versions)}")
problems = []
reticulum_requirements: set[str] = set()
for package in packages:
name = package["name"]
if package["publish"] != []:
problems.append(f"{name} is not marked publish = false")
if package["rust_version"] != EXPECTED_RUST_VERSION:
problems.append(
f"{name} exposes rust-version {package['rust_version']!r}, "
f"expected {EXPECTED_RUST_VERSION!r}"
)
for dependency in package["dependencies"]:
if dependency["name"].startswith("rns-"):
reticulum_requirements.add(dependency["req"])
if problems:
fail("; ".join(problems))
if len(reticulum_requirements) != 1:
fail(
"rsReticulum dependencies do not share one compatibility requirement: "
f"{sorted(reticulum_requirements)}"
)
requirement = reticulum_requirements.pop()
# The project permits breaking core APIs in a minor release; caret ranges
# would silently admit the next incompatible minor line.
if not re.fullmatch(r"~\d+\.\d+\.\d+", requirement):
fail(f"unexpected rsReticulum compatibility requirement {requirement!r}")
return str(versions.pop()), requirement.removeprefix("~")
def check_workflow_actions() -> None:
workflows = ROOT / ".github/workflows"
for workflow_path in sorted([*workflows.glob("*.yml"), *workflows.glob("*.yaml")]):
workflow = workflow_path.read_text()
action_uses = re.findall(
r"^\s*(?:-\s+)?uses:\s+([^\s#]+)", workflow, re.MULTILINE
)
for action in action_uses:
if action.startswith("./"):
continue
if "@" not in action or not SHA_PATTERN.fullmatch(
action.rsplit("@", 1)[1]
):
fail(
f"workflow action is not pinned to a commit "
f"({workflow_path.name}): {action}"
)
def check_release_workflow(reticulum_version: str) -> str:
workflow = (ROOT / ".github/workflows/release.yml").read_text()
if not re.search(r"^\s*toolchain:\s*1\.89\.0\s*$", workflow, re.MULTILINE):
fail("release workflow does not select Rust 1.89.0")
if "ref: ${{ env.SOURCE_REF }}" not in workflow or "SOURCE_REF: ${{ github.sha }}" not in workflow:
fail("release workflow must check out the immutable event commit")
if " if: github.event_name == 'push' || !inputs.qualify_only\n needs: package" not in workflow:
fail("publication must exclude qualification and require verified archives")
if "--candidate-tag" not in workflow or "actions/workflows/ci.yml/runs?head_sha=" not in workflow:
fail("release workflow must qualify untagged sources and require exact-source CI")
version_match = re.search(
r"^\s*RSLXMF_RSRETICULUM_VERSION:\s*(\S+)\s*$", workflow, re.MULTILINE
)
commit_match = re.search(
r"^\s*RSLXMF_RSRETICULUM_COMMIT:\s*([0-9a-f]+)\s*$",
workflow,
re.MULTILINE,
)
if not version_match or version_match.group(1) != reticulum_version:
fail("rsReticulum compatibility label does not match the dependency requirement")
if not commit_match or not SHA_PATTERN.fullmatch(commit_match.group(1)):
fail("rsReticulum release dependency is not pinned to a full commit")
if "ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}" not in workflow:
fail("release workflow does not check out the pinned rsReticulum commit")
publishers = re.findall(
r"^ - uses: softprops/action-gh-release@[0-9a-f]{40}[^\n]*\n"
r" with:\n((?: [^\n]*\n)+)",
workflow,
re.MULTILINE,
)
if len(publishers) != 1:
fail("release workflow must have one explicit GitHub publisher")
inputs = dict(re.findall(r"^ ([a-z_]+): (.*)$", publishers[0], re.MULTILINE))
expected = {
"tag_name": "${{ env.RELEASE_TAG }}",
"name": "${{ env.RELEASE_TAG }}",
"body": '""',
"generate_release_notes": "false",
"append_body": "false",
}
if any(inputs.get(key) != value for key, value in expected.items()) or "body_path" in inputs:
fail("GitHub releases must use the exact version tag as title and an empty body")
release_builds = [
line.strip()
for line in workflow.splitlines()
if "cargo build" in line and "--release" in line
]
if not release_builds or any("--locked" not in line for line in release_builds):
fail("every release Cargo build must use --locked")
return commit_match.group(1)
def check_documentation(version: str) -> None:
changelog = (ROOT / "CHANGELOG.md").read_text()
if not re.search(r"^## Unreleased\s*$", changelog, re.MULTILINE):
fail("CHANGELOG.md is missing an Unreleased section")
if not re.search(
rf"^## {re.escape(version)} - \d{{4}}-\d{{2}}-\d{{2}}\s*$",
changelog,
re.MULTILINE,
):
fail(f"CHANGELOG.md is missing the current {version} release section")
readme = (ROOT / "README.md").read_text()
unlocked = re.findall(
r"^.*cargo build --release(?![^\n]*--locked).*$", readme, re.MULTILINE
)
if unlocked:
fail("README.md contains an unlocked release build command")
def check_release_tag(release_tag: str, version: str) -> None:
if not re.fullmatch(r"v\d+\.\d+\.\d+", release_tag):
fail("release tags must have the form vX.Y.Z")
expected_tag = f"v{version}"
if release_tag != expected_tag:
fail(f"release tag {release_tag!r} does not match {expected_tag!r}")
try:
tag_type = command("git", "cat-file", "-t", release_tag)
except subprocess.CalledProcessError:
fail(f"release tag {release_tag!r} is not present in this checkout")
if tag_type != "tag":
fail(f"release tag {release_tag!r} must be an annotated tag")
head = command("git", "rev-parse", "HEAD")
try:
tagged_commit = command("git", "rev-list", "-n", "1", release_tag)
except subprocess.CalledProcessError:
fail(f"release tag {release_tag!r} is not present in this checkout")
if head != tagged_commit:
fail(f"HEAD {head} is not the commit named by {release_tag} ({tagged_commit})")
def check_dependency(dependency_commit: str) -> None:
dependency_root = ROOT.parent / "rsReticulum"
if not dependency_root.is_dir():
fail(f"rsReticulum checkout is missing at {dependency_root}")
actual_dependency = command("git", "rev-parse", "HEAD", cwd=dependency_root)
if actual_dependency != dependency_commit:
fail(
f"rsReticulum checkout is {actual_dependency}, expected {dependency_commit}"
)
def check_candidate_tag(tag: str, version: str) -> None:
if not re.fullmatch(r"v\d+\.\d+\.\d+", tag) or tag != f"v{version}":
fail("candidate tag must match the workspace version as vX.Y.Z")
result = subprocess.run(
["git", "show-ref", "--verify", "--quiet", f"refs/tags/{tag}"], cwd=ROOT
)
if result.returncode != 1:
fail("candidate qualification requires an untagged version")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
tags = parser.add_mutually_exclusive_group()
tags.add_argument("--release-tag", help="also verify the existing annotated vX.Y.Z tag matches the workspace version and HEAD")
tags.add_argument("--candidate-tag", help="also verify vX.Y.Z matches the workspace version and has no local tag yet")
args = parser.parse_args()
version, reticulum_version = check_packages(metadata())
check_workflow_actions()
dependency_commit = check_release_workflow(reticulum_version)
check_documentation(version)
subprocess.run(
["python3", "tools/check-api-baseline.py", "--metadata-only"],
cwd=ROOT,
check=True,
)
if args.candidate_tag or args.release_tag:
check_dependency(dependency_commit)
if args.candidate_tag:
check_candidate_tag(args.candidate_tag, version)
if args.release_tag:
check_release_tag(args.release_tag, version)
print(f"source-release contract passed for rsLXMF {version}")
if __name__ == "__main__":
main()
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/env python3
"""Validate or refresh the reviewed public-API compatibility snapshots."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "api" / "stability.json"
SHA_PATTERN = re.compile(r"^[0-9a-f]{40}$")
HASH_PATTERN = re.compile(r"^[0-9a-f]{64}$")
TIERS = {
"candidate-stable",
"provisional",
"experimental",
"application-internal",
"tool-internal",
}
def fail(message: str) -> None:
print(f"api baseline: {message}", file=sys.stderr)
raise SystemExit(1)
def run(args: list[str], *, env: dict[str, str] | None = None) -> str:
result = subprocess.run(
args,
cwd=ROOT,
env=env,
capture_output=True,
text=True,
)
if result.returncode != 0:
if result.stdout:
print(result.stdout, file=sys.stderr, end="")
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
fail(f"command failed ({result.returncode}): {' '.join(args)}")
return result.stdout
def load_config() -> dict[str, object]:
try:
config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
fail(f"cannot read {CONFIG_PATH.name}: {error}")
if not isinstance(config, dict) or config.get("schemaVersion") != 2:
fail("unsupported api-stability schema")
return config
def require_keys(
record: object, required: set[str], label: str,
optional: set[str] | None = None,
) -> None:
if not isinstance(record, dict):
fail(f"{label} must be an object")
missing = required - set(record)
unknown = set(record) - required - (optional or set())
if missing or unknown:
fail(f"{label}: missing fields {sorted(missing)}, unknown fields {sorted(unknown)}")
def public_packages(manifest_path: str) -> set[str]:
metadata = json.loads(
run(
[
"cargo",
"metadata",
"--format-version",
"1",
"--no-deps",
"--manifest-path",
manifest_path,
]
)
)
return {
str(package["name"])
for package in metadata["packages"]
if any("lib" in target["kind"] for target in package["targets"])
}
def validate_metadata(
config: dict[str, object], *, updating: bool = False
) -> list[dict[str, object]]:
require_keys(
config, {"schemaVersion", "tool", "baseline", "compatibilityFloor", "packages"},
"metadata", {"approvedBreakingChanges"},
)
if config["schemaVersion"] != 2:
fail("unsupported api-stability schema")
require_keys(
config["tool"], {"name", "version", "rustdocToolchain", "target", "arguments"},
"tool",
)
require_keys(config["baseline"], {"commit"}, "baseline")
require_keys(
config["compatibilityFloor"], {"evidenceCommit", "sourceCommit"},
"compatibility floor",
)
if "approvedBreakingChanges" in config:
require_keys(config["approvedBreakingChanges"],
{"releaseLine", "migrationGuide", "removed"}, "approved break")
tool = config.get("tool")
if not isinstance(tool, dict):
fail("tool contract is missing")
if tool.get("name") != "cargo-public-api" or tool.get("version") != "0.52.0":
fail("tool must be cargo-public-api 0.52.0")
if tool.get("rustdocToolchain") != "nightly-2026-08-01":
fail("rustdoc toolchain must be nightly-2026-08-01")
if tool.get("target") != "aarch64-apple-darwin":
fail("API target must be aarch64-apple-darwin")
if tool.get("arguments") != ["--all-features", "-sss"]:
fail("API arguments must remain all-features and simplified")
baseline = config.get("baseline")
if not isinstance(baseline, dict):
fail("baseline identity is missing")
commit = baseline.get("commit")
if not isinstance(commit, str) or not SHA_PATTERN.fullmatch(commit):
fail("baseline commit must be a full Git commit")
commit_check = subprocess.run(
["git", "cat-file", "-e", f"{commit}^{{commit}}"], cwd=ROOT
)
if commit_check.returncode != 0:
fail(f"baseline commit {commit} is unavailable in this checkout")
ancestor_check = subprocess.run(
["git", "merge-base", "--is-ancestor", commit, "HEAD"], cwd=ROOT
)
if ancestor_check.returncode != 0:
fail(f"baseline commit {commit} is not an ancestor of HEAD")
compatibility_floor = config.get("compatibilityFloor")
if not isinstance(compatibility_floor, dict):
fail("compatibility floor identity is missing")
floor_evidence = compatibility_floor.get("evidenceCommit")
floor_source = compatibility_floor.get("sourceCommit")
for label, floor_commit in (
("evidence", floor_evidence),
("source", floor_source),
):
if not isinstance(floor_commit, str) or not SHA_PATTERN.fullmatch(
floor_commit
):
fail(f"compatibility floor {label} commit must be a full Git commit")
floor_check = subprocess.run(
["git", "cat-file", "-e", f"{floor_commit}^{{commit}}"], cwd=ROOT
)
if floor_check.returncode != 0:
fail(f"compatibility floor {label} commit {floor_commit} is unavailable")
floor_ancestor = subprocess.run(
["git", "merge-base", "--is-ancestor", floor_commit, "HEAD"], cwd=ROOT
)
if floor_ancestor.returncode != 0:
fail(f"compatibility floor {label} commit is not an ancestor of HEAD")
packages = config.get("packages")
if not isinstance(packages, list) or not packages:
fail("package ledger is empty")
manifests: dict[str, set[str]] = {}
seen_names: set[tuple[str, str]] = set()
for package in packages:
if not isinstance(package, dict):
fail("package ledger entry is not an object")
require_keys(package, {"name", "manifestPath", "tier", "compatibility",
"snapshot", "itemCount", "sha256"}, "package")
if type(package["itemCount"]) is not int or package["itemCount"] < 0:
fail("package item count must be a non-negative integer")
name = package.get("name")
manifest = package.get("manifestPath")
snapshot = package.get("snapshot")
if not isinstance(name, str) or not isinstance(manifest, str):
fail("package name or manifest path is invalid")
if (manifest, name) in seen_names:
fail(f"duplicate package ledger entry {manifest}:{name}")
seen_names.add((manifest, name))
if package.get("tier") not in TIERS:
fail(f"{name} has an unknown stability tier")
if package.get("compatibility") != "reviewed-snapshot":
fail(f"{name} must use the reviewed-snapshot compatibility policy")
if not isinstance(snapshot, str) or not snapshot.startswith("api/snapshots/"):
fail(f"{name} has an invalid snapshot path")
snapshot_path = (ROOT / snapshot).resolve()
if not snapshot_path.is_relative_to(ROOT / "api/snapshots"):
fail(f"{name} snapshot must stay inside api/snapshots")
if not snapshot_path.is_file() and not updating:
fail(f"{name} snapshot is missing: {snapshot}")
if not updating:
snapshot_bytes = snapshot_path.read_bytes()
expected_hash = package.get("sha256")
actual_hash = hashlib.sha256(snapshot_bytes).hexdigest()
if not isinstance(expected_hash, str) or not HASH_PATTERN.fullmatch(expected_hash):
fail(f"{name} has an invalid snapshot hash")
if actual_hash != expected_hash:
fail(f"{name} snapshot hash is {actual_hash}, expected {expected_hash}")
item_count = len(snapshot_bytes.decode("utf-8").splitlines())
if package.get("itemCount") != item_count:
fail(
f"{name} snapshot has {item_count} items, "
f"expected {package.get('itemCount')}"
)
manifests.setdefault(manifest, public_packages(manifest))
for manifest, actual_names in manifests.items():
recorded_names = {
str(package["name"])
for package in packages
if package["manifestPath"] == manifest
}
if recorded_names != actual_names:
fail(
f"library inventory drift for {manifest}: "
f"recorded={sorted(recorded_names)}, actual={sorted(actual_names)}"
)
return packages
def tool_path_and_environment(config: dict[str, object]) -> tuple[str, dict[str, str]]:
tool_config = config["tool"]
assert isinstance(tool_config, dict)
executable = os.environ.get("CARGO_PUBLIC_API") or shutil.which("cargo-public-api")
if not executable:
fail("cargo-public-api is unavailable; install exact version 0.52.0")
version = run([executable, "public-api", "--version"]).strip()
if version != "cargo-public-api 0.52.0":
fail(f"unexpected cargo-public-api version: {version!r}")
environment = os.environ.copy()
environment["RUSTUP_TOOLCHAIN"] = str(tool_config["rustdocToolchain"])
return executable, environment
def render_snapshot(
executable: str,
environment: dict[str, str],
config: dict[str, object],
package: dict[str, object],
) -> bytes:
tool = config["tool"]
assert isinstance(tool, dict)
arguments = tool["arguments"]
assert isinstance(arguments, list)
output = run(
[
executable,
"public-api",
"--manifest-path",
str(package["manifestPath"]),
"--package",
str(package["name"]),
*[str(argument) for argument in arguments],
"--target",
str(tool["target"]),
"--color",
"never",
],
env=environment,
)
return (output.rstrip() + "\n").encode("utf-8")
def main() -> None:
parser = argparse.ArgumentParser(
description="Compare current public APIs with the stored snapshots, or refresh them after review."
)
parser.add_argument(
"--metadata-only", action="store_true",
help="validate metadata, package inventory and stored snapshot hashes without generating API output; incompatible with --update",
)
parser.add_argument("--update", action="store_true",
help="regenerate snapshots and update their counts/hashes in api/stability.json; review the diff before committing")
parser.add_argument("--snapshot-source-commit",
help="optional HEAD guard for --update; includes uncommitted source changes")
args = parser.parse_args()
if args.metadata_only and args.update:
fail("--metadata-only and --update are mutually exclusive")
config = load_config()
if args.snapshot_source_commit is not None:
if not args.update:
fail("--snapshot-source-commit requires --update")
head = run(["git", "rev-parse", "HEAD"]).strip()
if args.snapshot_source_commit != head:
fail("snapshot source guard must match HEAD")
packages = validate_metadata(config, updating=args.update)
if args.metadata_only:
print("api baseline metadata: ok")
return
executable, environment = tool_path_and_environment(config)
changed = False
for package in packages:
rendered = render_snapshot(executable, environment, config, package)
snapshot_path = ROOT / str(package["snapshot"])
if args.update:
if not snapshot_path.is_file() or snapshot_path.read_bytes() != rendered:
snapshot_path.write_bytes(rendered)
changed = True
package["itemCount"] = len(rendered.decode("utf-8").splitlines())
package["sha256"] = hashlib.sha256(rendered).hexdigest()
elif snapshot_path.read_bytes() != rendered:
fail(
f"{package['name']} public API differs from {package['snapshot']}; "
"review the diff before running --update"
)
if args.update:
updated = json.dumps(config, indent=2) + "\n"
if CONFIG_PATH.read_text(encoding="utf-8") != updated:
CONFIG_PATH.write_text(updated, encoding="utf-8")
changed = True
print("api baseline snapshots updated" if changed else "api baseline unchanged")
else:
print("api baseline: ok")
if __name__ == "__main__":
main()
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Reject unapproved removals from the retained public-API compatibility floor."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LEDGER_PATH = ROOT / "api" / "stability.json"
def fail(message: str) -> None:
print(f"api compatibility: {message}", file=sys.stderr)
raise SystemExit(1)
def git_show(commit: str, path: str) -> str:
result = subprocess.run(
["git", "show", f"{commit}:{path}"],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode != 0:
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
fail(f"cannot read compatibility floor {commit}:{path}")
return result.stdout
def load_floor_ledger(commit: str) -> dict[str, object]:
for path in ("api/stability.json", "api-stability.json"):
result = subprocess.run(
["git", "show", f"{commit}:{path}"],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode == 0:
return json.loads(result.stdout)
fail(f"cannot read API ledger at compatibility floor {commit}")
def approved_removals(ledger: dict[str, object], version: str) -> dict[str, set[str]]:
"""A breaking release allows exact reviewed lines, never a blanket waiver."""
record = ledger.get("approvedBreakingChanges")
if record is None:
return {}
if not isinstance(record, dict) or set(record) != {"releaseLine", "migrationGuide", "removed"}:
fail("approved break needs releaseLine, migrationGuide and exact removed lines")
release_line = record["releaseLine"]
if not isinstance(release_line, str) or not re.fullmatch(r"\d+\.\d+", release_line):
fail("approved break release line is invalid")
if version.split(".")[:2] != release_line.split("."):
fail("approved break does not match the current workspace release line")
guide = record["migrationGuide"]
if not isinstance(guide, str) or not guide.startswith("api/migrations/"):
fail("approved break must link a public API migration guide")
guide_path = (ROOT / guide).resolve()
if not guide_path.is_relative_to(ROOT / "api/migrations") or not guide_path.is_file():
fail("approved break migration guide is missing or outside its directory")
removed = record["removed"]
packages = {package["name"] for package in ledger["packages"]}
if not isinstance(removed, dict) or not removed or not set(removed).issubset(packages):
fail("approved removals must name existing packages")
result = {}
for package, lines in removed.items():
if (not isinstance(lines, list) or not lines
or not all(isinstance(line, str) and line.strip() for line in lines)
or len(set(lines)) != len(lines)):
fail("approved removals must be unique nonempty exact API lines")
result[package] = set(lines)
return result
def validate_removed(package: str, removed: set[str], approved: dict[str, set[str]]) -> None:
allowed = approved.get(package, set())
if removed != allowed:
for line in sorted(removed - allowed):
print(f"unapproved removal: {line}", file=sys.stderr)
for line in sorted(allowed - removed):
print(f"unused removal approval: {line}", file=sys.stderr)
fail(f"{package} removals differ from the exact approved migration")
def main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
)
if metadata.returncode != 0:
fail("snapshot metadata is invalid")
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
metadata_result = subprocess.run(
["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"],
cwd=ROOT, capture_output=True, text=True,
)
if metadata_result.returncode:
fail("cannot resolve workspace release version")
versions = {package["version"] for package in json.loads(metadata_result.stdout)["packages"]}
if len(versions) != 1:
fail("workspace release versions disagree")
approved = approved_removals(ledger, versions.pop())
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
if not isinstance(floor, str):
fail("api/stability.json has no compatibility-floor commit")
floor_ledger = load_floor_ledger(floor)
floor_snapshots = {
package["name"]: package["snapshot"] for package in floor_ledger["packages"]
}
removed_packages = set(floor_snapshots) - {package["name"] for package in ledger["packages"]}
if removed_packages:
fail(f"compatibility-floor packages removed: {sorted(removed_packages)}")
total_added = 0
total_removed = 0
for package in ledger["packages"]:
path = package["snapshot"]
floor_path = floor_snapshots.get(package["name"])
if not isinstance(floor_path, str):
fail(f"{package['name']} is absent from the compatibility floor")
before = set(git_show(floor, floor_path).splitlines())
after = set((ROOT / path).read_text(encoding="utf-8").splitlines())
added = sorted(after - before)
removed = sorted(before - after)
total_added += len(added)
total_removed += len(removed)
print(f"{package['name']}: +{len(added)} -{len(removed)}")
if removed:
for line in removed:
print(f"- {line}", file=sys.stderr)
validate_removed(package["name"], set(removed), approved)
print(f"api compatibility: checked (+{total_added}, -{total_removed}); "
"unapproved removals forbidden")
if __name__ == "__main__":
main()
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Verify the reviewed Cargo manifest and feature contract for library packages."""
from __future__ import annotations
import argparse
import difflib
import json
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LEDGER_PATH = ROOT / "api" / "stability.json"
CONTRACT_PATH = ROOT / "api" / "snapshots" / "manifest-contract.json"
def fail(message: str) -> None:
print(f"api manifest contract: {message}", file=sys.stderr)
raise SystemExit(1)
def metadata(manifest_path: str) -> dict[str, object]:
result = subprocess.run(
[
"cargo",
"metadata",
"--format-version",
"1",
"--no-deps",
"--manifest-path",
manifest_path,
],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode != 0:
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
fail(f"cargo metadata failed for {manifest_path}")
return json.loads(result.stdout)
def dependency_contract(dependency: dict[str, object]) -> dict[str, object]:
source = dependency.get("source")
return {
"name": dependency["name"],
"rename": dependency.get("rename"),
"kind": dependency.get("kind"),
"target": dependency.get("target"),
"requirement": dependency["req"],
"optional": dependency["optional"],
"defaultFeatures": dependency["uses_default_features"],
"features": sorted(dependency["features"]),
"sourceKind": "registry" if source else "path",
}
def package_contract(package: dict[str, object]) -> dict[str, object]:
targets = []
for target in package["targets"]:
if "lib" not in target["kind"]:
continue
targets.append(
{
"name": target["name"],
"kind": sorted(target["kind"]),
"crateTypes": sorted(target["crate_types"]),
"requiredFeatures": sorted(target.get("required-features", [])),
}
)
dependencies = [
dependency_contract(dependency)
for dependency in package["dependencies"]
if dependency.get("kind") != "dev"
]
dependencies.sort(
key=lambda item: (
str(item["kind"]),
str(item["target"]),
str(item["rename"]),
str(item["name"]),
)
)
return {
"name": package["name"],
"version": package["version"],
"rustVersion": package.get("rust_version"),
"edition": package["edition"],
"features": {
name: sorted(values)
for name, values in sorted(package["features"].items())
},
"targets": sorted(targets, key=lambda item: str(item["name"])),
"dependencies": dependencies,
}
def render_contract() -> str:
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
manifests = sorted({entry["manifestPath"] for entry in ledger["packages"]})
recorded_names = {entry["name"] for entry in ledger["packages"]}
packages: list[dict[str, object]] = []
for manifest in manifests:
for package in metadata(manifest)["packages"]:
if package["name"] in recorded_names:
packages.append(package_contract(package))
actual_names = {entry["name"] for entry in packages}
if actual_names != recorded_names:
fail(
f"package inventory differs: expected={sorted(recorded_names)}, "
f"actual={sorted(actual_names)}"
)
contract = {
"schemaVersion": 1,
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
"packages": sorted(packages, key=lambda item: str(item["name"])),
}
return json.dumps(contract, indent=2) + "\n"
def main() -> None:
parser = argparse.ArgumentParser(
description="Compare current library Cargo metadata with api/snapshots/manifest-contract.json."
)
parser.add_argument(
"--print",
action="store_true",
dest="print_contract",
help="print current Cargo contract JSON instead of comparing it with the saved snapshot",
)
args = parser.parse_args()
rendered = render_contract()
if args.print_contract:
print(rendered, end="")
return
if not CONTRACT_PATH.is_file():
fail(f"missing {CONTRACT_PATH.relative_to(ROOT)}")
expected = CONTRACT_PATH.read_text(encoding="utf-8")
if expected != rendered:
print(
"".join(
difflib.unified_diff(
expected.splitlines(keepends=True),
rendered.splitlines(keepends=True),
fromfile=str(CONTRACT_PATH.relative_to(ROOT)),
tofile="current Cargo metadata",
)
),
file=sys.stderr,
end="",
)
fail("manifest, feature, target, or dependency contract drift")
print("api manifest contract: ok")
if __name__ == "__main__":
main()