Compare commits

...
Author SHA1 Message Date
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
74 changed files with 43032 additions and 6334 deletions

No files matched your search

+94 -12
View File
@@ -9,7 +9,47 @@ on:
permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
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: v1.0.1
RSLXMF_RSRETICULUM_VERSION: 1.4.0
RSLXMF_RSRETICULUM_COMMIT: 14241a383910e6ee7665303eff1e7c8d98957cc0
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/
+103
View File
@@ -0,0 +1,103 @@
# Changelog
## Unreleased
## 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
+68 -16
View File
@@ -11,6 +11,7 @@ dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"zeroize",
]
[[package]]
@@ -138,7 +139,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2",
"objc2 0.5.2",
]
[[package]]
@@ -191,6 +192,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
"zeroize",
]
[[package]]
@@ -643,13 +645,16 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2 0.6.5",
"proptest",
"rand 0.8.5",
"rmp",
"rmp-serde",
"rmpv",
"rns-crypto",
@@ -664,11 +669,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"unicode-normalization",
]
[[package]]
name = "lxmf-tools"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
@@ -682,9 +688,11 @@ dependencies = [
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
"zeroize",
]
[[package]]
@@ -714,9 +722,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",
@@ -780,6 +788,15 @@ dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
@@ -787,7 +804,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2 0.5.2",
"objc2-foundation",
]
@@ -806,7 +823,7 @@ dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
"objc2 0.5.2",
]
[[package]]
@@ -1049,7 +1066,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1067,34 +1084,41 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.0.1"
version = "1.4.0"
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 = "1.0.1"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
"if-addrs",
"jni",
"libc",
"objc2",
"md-5",
"mio",
"objc2 0.5.2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-transport",
"rns-wire",
"serde",
@@ -1109,9 +1133,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmpv",
"rns-crypto",
@@ -1119,12 +1144,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1133,6 +1159,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -1140,7 +1167,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1162,11 +1189,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "rns-transport"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1185,7 +1213,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.0.1"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
@@ -1478,6 +1506,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"
@@ -1590,6 +1633,15 @@ 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"
+15 -13
View File
@@ -6,30 +6,31 @@ members = [
]
[workspace.package]
version = "1.0.1"
version = "1.4.0"
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", version = "1.0.1" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.0.1" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.0.1" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.0.1" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.0.1" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.0.1" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.0.1" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.0.1" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.4.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.4.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.4.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.4.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.4.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.4.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.4.0" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.0.1" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.0.1" }
lxmf-core = { path = "crates/lxmf-core", version = "~1.4.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.4.0" }
# Encoding
base64 = "0.22"
# Serialization
rmp = "0.8"
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
@@ -56,6 +57,7 @@ thiserror = "2"
# Misc
hex = "0.4"
tempfile = "3"
unicode-normalization = "0.1"
# 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.
+90 -42
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)
[![Compatibility floor: LXMF 1.0.1](https://img.shields.io/badge/compatibility%20floor-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Supplementary release reference: LXMF 1.1.0](https://img.shields.io/badge/supplementary%20release%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[LXMF Reference](https://github.com/markqvist/LXMF) |
@@ -18,7 +19,11 @@
---
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.
rsLXMF is a Rust port of [LXMF](https://github.com/markqvist/LXMF), the
Reticulum messaging layer, from the reference implementation by Mark Qvist. It
was written from the reference source, not from a specification, and tracks the
reference's wire behavior release by release. The Python reference
implementation remains the source of truth. See [License](#license).
Commands are intentionally namespaced for Rust with the Rust-specific `lxmd-rs` command, so rsLXMF can live beside other
LXMF daemons on `PATH` without worry.
@@ -26,6 +31,7 @@ LXMF daemons on `PATH` without worry.
## Contents
- [Build It](#build-it)
- [Rust API](api/README.md)
- [Operating lxmd-rs](#operating-lxmd-rs)
- [Configuration](#configuration)
- [Delivery Model](#delivery-model)
@@ -36,6 +42,8 @@ LXMF daemons on `PATH` without worry.
## Build It
This guide describes the 1.4.0 release, [v1.4.0](https://github.com/ratspeak/rsLXMF/releases/tag/v1.4.0), built with rsReticulum [v1.4.0](https://github.com/ratspeak/rsReticulum/releases/tag/v1.4.0); it is the source line Ratspeak builds from. For the 1.3.0 daemon, use [the v1.3.0 README](https://github.com/ratspeak/rsLXMF/blob/v1.3.0/README.md) and that build's `--help`. The 1.4 message and durable relay APIs require a coordinated source migration.
The current development layout for rsLXMF requires
rsReticulum as a sibling directory/repo next to it, such as:
@@ -50,9 +58,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.4.0
git -C rsLXMF checkout --detach v1.4.0
cd rsLXMF
```
Run the build commands below from that `rsLXMF` directory. The host crates require Rust 1.89 or newer.
### macOS
Install Rust with `rustup`, then install Apple's build tools:
@@ -64,8 +76,7 @@ xcode-select --install
Build from the sibling checkout:
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Linux / Raspberry Pi
@@ -76,26 +87,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 +116,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 +132,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 +150,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 +164,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 +174,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 +202,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 +228,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.
@@ -238,8 +252,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 +263,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 +273,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`, `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 +290,10 @@ 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.
## Delivery Model
@@ -284,11 +302,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,19 +323,27 @@ 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 1.4 library preserves signed
and unsigned integer IDs beyond the CLI’s 0–255 range and rejects duplicate
outer IDs. Encoding a structured field as a binary blob changes its meaning.
In the 1.4 API, construct `LxMessageDraft` and set `include_ticket` before
calling `LxmRouter::prepare_outbound`. Persist the returned ticket intent before
signing; a pending intent blocks signing. Signing consumes the draft, and
finalization produces an immutable message. See the [1.4 migration guide](api/migrations/1.4.md)
for stamp work, typed fields, inbound verification and propagation storage.
## 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, cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
| Access lists | `ignored` and `allowed` hash-list files in the LXMF config directory. |
@@ -324,6 +357,13 @@ Most daemon and control flags are implemented: `--config`, `--rnsconfig`,
Additional rsLXMF-only flags: `--send`, `--send-file`, `--send-method`,
`--send-timeout-secs`, and `--send-fields-json`.
The complete corpus and live matrix for 1.3.0 and 1.4.0 use Python LXMF 1.0.1
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
same Reticulum 1.4.2 source. Historical vectors retain their original
provenance. Later source changes include selected LXMF 1.2.0 behavior; that
does not establish complete compatibility with every later Python release.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
@@ -333,4 +373,12 @@ PRs are closed for now until I have time to catch up on everything. I'm tired.
## 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.
+117
View File
@@ -0,0 +1,117 @@
# Rust API
This guide describes the 1.4.0 API, published as v1.4.0, not the 1.3.0
daemon. Application code should use `lxmf_core::message_api`, which
re-exports the message types without wrappers. The equivalent module-qualified
paths remain available. The [1.4 migration guide](migrations/1.4.md) explains
the source-breaking change from mutable messages to drafts, signed messages
and immutable finalized messages.
The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path.
## Stability
`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 does change message and persistence
APIs; follow the migration guide. Further reductions to the broader module tree
require a reviewed API diff, downstream migration and an explicit version decision.
## 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 (LXMF-02/03, RET-05/07), 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.
+1055
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.
+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
+190
View File
@@ -0,0 +1,190 @@
pub mod lxmf_tools
pub mod lxmf_tools::daemon
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: u8
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: u8
pub lxmf_tools::daemon::DaemonConfig::prioritise_destinations: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::propagation_enabled: bool
pub lxmf_tools::daemon::DaemonConfig::propagation_limit_kb: usize
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_cost: u8
pub lxmf_tools::daemon::DaemonConfig::propagation_stamp_flex: u8
pub lxmf_tools::daemon::DaemonConfig::sequential_pn_stamp_validation: bool
pub lxmf_tools::daemon::DaemonConfig::stamp_cost: core::option::Option<u8>
pub lxmf_tools::daemon::DaemonConfig::static_peers: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::DaemonConfig::static_peers_bypass_sequential: bool
pub lxmf_tools::daemon::DaemonConfig::sync_limit_kb: usize
impl lxmf_tools::daemon::DaemonConfig
pub fn lxmf_tools::daemon::DaemonConfig::from_config(&rns_runtime::config::Config) -> Self
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: i64
pub lxmf_tools::daemon::PythonLxmdConfig::peering_cost: i64
pub lxmf_tools::daemon::PythonLxmdConfig::prioritised_lxmf_destinations: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_flexibility: i64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_stamp_cost_target: i64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_sync_max_accepted_size: f64
pub lxmf_tools::daemon::PythonLxmdConfig::propagation_transfer_max_accepted_size: f64
pub lxmf_tools::daemon::PythonLxmdConfig::remote_peering_cost_max: i64
pub lxmf_tools::daemon::PythonLxmdConfig::sequential_pn_stamp_validation: bool
pub lxmf_tools::daemon::PythonLxmdConfig::static_peers: alloc::vec::Vec<alloc::string::String>
pub lxmf_tools::daemon::PythonLxmdConfig::static_peers_bypass_sequential: bool
pub lxmf_tools::daemon::PythonLxmdConfig::target_loglevel: core::option::Option<i64>
impl lxmf_tools::daemon::PythonLxmdConfig
pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::Config) -> Self
pub fn lxmf_tools::daemon::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 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_nil_response() -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_peer_error(lxmf_core::constants::PeerError) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::encode_router_control_stats(&lxmf_core::router::LxmRouter, [u8; 16], [u8; 16], core::option::Option<&lxmf_core::propagation_node::PropagationNode>, f64) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_control::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
pub lxmf_tools::lxmd_runtime::LocalStatusView::stamp_costs_cached: usize
impl lxmf_tools::lxmd_runtime::LocalStatusView
pub fn lxmf_tools::lxmd_runtime::LocalStatusView::from_router_stats([u8; 16], bool, &lxmf_core::router::RouterStats) -> Self
pub struct lxmf_tools::lxmd_runtime::LxmdPaths
pub lxmf_tools::lxmd_runtime::LxmdPaths::config_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::identity_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::known_identities_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_identity_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::legacy_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::lxmf_storage_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::messages_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::propagation_store_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchet_control_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchet_ring_path: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::received_ratchets_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::router_state_dir: std::path::PathBuf
pub lxmf_tools::lxmd_runtime::LxmdPaths::storage_dir: std::path::PathBuf
impl lxmf_tools::lxmd_runtime::LxmdPaths
pub fn lxmf_tools::lxmd_runtime::LxmdPaths::new(impl core::convert::Into<std::path::PathBuf>) -> Self
pub fn lxmf_tools::lxmd_runtime::LxmdPaths::preferred_identity_path(&self) -> &std::path::Path
pub fn lxmf_tools::lxmd_runtime::delivery_announce_app_data(core::option::Option<&str>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
pub fn lxmf_tools::lxmd_runtime::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)
+467
View File
@@ -0,0 +1,467 @@
{
"schemaVersion": 1,
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
"packages": [
{
"name": "lxmf-core",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
"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.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-link",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-protocol",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"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-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.4.0",
"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.4.0",
"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.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-runtime",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [
"serial"
],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.4.0",
"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": "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": "tracing-subscriber",
"rename": null,
"kind": null,
"target": null,
"requirement": "^0.3",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "zeroize",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
}
]
}
+110
View File
@@ -0,0 +1,110 @@
{
"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": "80bb96f799330e28a0125367d4c29826f5147cc3",
"sourceCommit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 2227,
"sha256": "30d1006f3149b0e812c3d772f226467887cbba036beb23d686ae79d3c50860ee"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 190,
"sha256": "c8591cf56d1d315da43ecab8149057447ff02726fa371e01439a4106be45976f"
}
],
"approvedBreakingChanges": {
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"removed": {
"lxmf-core": [
"pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self",
"pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted<F>(&mut self, F) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted_with_stamp<F>(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId, u32), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec<u8>)",
"pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec<u8>) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign_with<F, E>(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display",
"pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> bool",
"pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool",
"pub fn lxmf_core::propagation_client::PropagationClient::take_received_messages(&mut self) -> alloc::vec::Vec<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_propagated_blob(&mut self, &[u8], u8) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_message(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_propagated_blob(&mut self, &[u8], u8) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_sync::PropagationSyncTask::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::message::LxMessage>",
"pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessage) -> core::result::Result<(), lxmf_core::router::TicketPreparationError>",
"pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::message::LxMessage",
"pub lxmf_core::message::LxMessage::auto_compress: bool",
"pub lxmf_core::message::LxMessage::callbacks: lxmf_core::message::MessageCallbacks",
"pub lxmf_core::message::LxMessage::content: alloc::string::String",
"pub lxmf_core::message::LxMessage::delivery_attempts: u32",
"pub lxmf_core::message::LxMessage::destination_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::hash: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::include_ticket: bool",
"pub lxmf_core::message::LxMessage::incoming: bool",
"pub lxmf_core::message::LxMessage::last_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::message_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::method: lxmf_core::constants::DeliveryMethod",
"pub lxmf_core::message::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::message::LxMessage::next_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::outbound_ticket: core::option::Option<[u8; 16]>",
"pub lxmf_core::message::LxMessage::progress: f64",
"pub lxmf_core::message::LxMessage::propagation_stamp: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation",
"pub lxmf_core::message::LxMessage::signature: core::option::Option<[u8; 64]>",
"pub lxmf_core::message::LxMessage::signature_validated: bool",
"pub lxmf_core::message::LxMessage::source_blackholed: bool",
"pub lxmf_core::message::LxMessage::source_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::stamp: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message::LxMessage::stamp_value: core::option::Option<u16>",
"pub lxmf_core::message::LxMessage::state: lxmf_core::constants::MessageState",
"pub lxmf_core::message::LxMessage::timestamp: f64",
"pub lxmf_core::message::LxMessage::title: alloc::string::String",
"pub lxmf_core::message::LxMessage::transient_id: core::option::Option<lxmf_core::types::PropagationTransientId>",
"pub lxmf_core::message::LxMessage::transport_encrypted: bool",
"pub lxmf_core::message::LxMessage::transport_encryption: core::option::Option<alloc::string::String>",
"pub lxmf_core::message::LxMessage::unverified_reason: core::option::Option<lxmf_core::constants::UnverifiedReason>",
"pub lxmf_core::message::LxMessage::wire_payload: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::LxMessage>"
]
}
}
}
+2
View File
@@ -0,0 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.89"
+12 -2
View File
@@ -1,9 +1,11 @@
[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
[dependencies]
base64 = { workspace = true }
@@ -17,12 +19,20 @@ 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 }
[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)
));
}
}
+609
View File
@@ -0,0 +1,609 @@
//! 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,
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> {
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(),
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| Some((c.intent.hook_event?, c.intent.body_path.clone()?)))
.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 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.parent() != Some(self.bodies.as_path())
|| path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
{
return Err(other("admission archive path escapes configured inbox"));
}
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());
}
}
+76 -10
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:23.
pub const FIELD_REPLY_TO: u8 = 0x30;
/// Bytes, quoted content in UTF-8 encoding. Python reference: LXMF.py:24.
pub const FIELD_REPLY_QUOTE: u8 = 0x31;
/// Dict keyed by [`REACTION_TO`] / [`REACTION_CONTENT`]. Python reference: LXMF.py:25.
pub const FIELD_REACTION: u8 = 0x40;
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py:26.
pub const FIELD_COMMENT: u8 = 0x41;
/// Dict keyed by [`CONTINUATION_OF`]. Python reference: LXMF.py:27.
pub const FIELD_CONTINUATION: u8 = 0x42;
// Unallocated fields between 0x00 and 0x80, both included, should be
// considered reserved for future extensibility. For experimental and
// unstable features, it is recommended to use fields above 0xFF.
// Python reference: LXMF.py:29-32.
pub const FIELD_CUSTOM_TYPE: u8 = 0xFB;
pub const FIELD_CUSTOM_DATA: u8 = 0xFC;
pub const FIELD_CUSTOM_META: u8 = 0xFD;
@@ -49,6 +66,27 @@ 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:104-110.
/// 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:112-118.
/// Bytes, full `LXMessage` hash.
pub const COMMENT_FOR: u8 = 0x00;
// Continuation content is carried as the normal LXM content, so clients that
// do not support continuations display them as normal messages.
// FIELD_CONTINUATION dict key — Python reference: LXMF.py:120-126.
/// Bytes, full `LXMessage` hash.
pub const CONTINUATION_OF: u8 = 0x00;
pub const PN_META_VERSION: u8 = 0x00;
pub const PN_META_NAME: u8 = 0x01;
pub const PN_META_SYNC_STRATUM: u8 = 0x02;
@@ -114,6 +152,10 @@ 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;
pub const PAPER_MDU: usize = 2210;
pub const TICKET_EXPIRY: u64 = 21 * 24 * 60 * 60;
@@ -131,12 +173,15 @@ 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).
/// Python propagation-link inactivity limit, in seconds; retained as a reference value.
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.
@@ -151,7 +196,7 @@ pub const PN_STAMP_THROTTLE: u64 = 180;
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 +213,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 +263,23 @@ 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.
/// 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 +297,12 @@ mod tests {
assert_eq!(LXMF_OVERHEAD, 112);
}
/// LXMF 1.2.0 `ENCRYPTED_PACKET_MAX_CONTENT` (LXMessage.py:64-79, 3fc60af).
#[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);
@@ -341,4 +393,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:23-27 field allocations plus dict-key constants (LXMF.py:104-126).
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);
}
}
+583
View File
@@ -0,0 +1,583 @@
//! 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_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 destination = Destination::new(
Some(identity),
Direction::In,
DestType::Single,
DELIVERY_APP_NAME,
)?;
if destination.hash != destination_hash {
return Err(DeliveryRatchetError::DestinationMismatch);
}
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
}
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.
pub fn create_announce(
&mut self,
identity: &Identity,
app_data: &[u8],
wall_now: u64,
cache_now: f64,
kind: DeliveryAnnounceKind<'_>,
) -> 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_at(
identity,
Some(app_data),
ratchet_public.as_ref(),
path_response,
tag,
AnnounceTime::new(wire_now, announce_time.cache)?,
)
.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,
)
.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,
),
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,
)
.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,
)
.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,
)
.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,
)
.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,
)
.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,
),
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) },
)
.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) },
)
.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,
),
Err(DeliveryRatchetError::Destination(_))
));
assert_eq!(state.control.last_announce_wire(), live_wire);
assert_eq!(state.ring.current_public_key(), live_public);
}
}
+14 -17
View File
@@ -2,15 +2,15 @@
//!
//! # Layering
//!
//! Python `RNS/Discovery.py:41` imports `LXMF.LXStamper` directly; the
//! discovery subsystem cannot work without LXMF installed. Rust keeps
//! Python `RNS.Discovery.InterfaceAnnouncer` loads `LXMF.LXStamper` when
//! initialized, requiring LXMF for on-network discovery. Rust keeps
//! Reticulum below LXMF, so `rns-transport` depends on a trait object and
//! the concrete implementation lives here.
//!
//! # Workblock: Python parity
//!
//! Python discovery uses `LXStamper.stamp_workblock(infohash, expand_rounds=20)`
//! (RNS/Discovery.py:220), where `stamp_workblock` is the
//! in `InterfaceAnnouncer`, where `stamp_workblock` is the
//! HKDF-expanded construction: one HKDF expand per round, each round
//! producing 256 bytes, total `expand_rounds * 256` bytes.
//! [`crate::stamper::stamp_workblock`] is the same construction.
@@ -26,14 +26,10 @@ use crate::stamper::{stamp_valid, stamp_value, stamp_workblock};
/// interface, so this path has to stay cheap enough for periodic announces.
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.
/// Default attempt budget for one discovery stamp search. Exhaustion returns
/// `None`, allowing the announcer to skip this preparation attempt and retry.
/// The budget limits attempts, not elapsed time. The requested generation cost
/// comes from the per-interface announce configuration.
pub const DISCOVERY_MAX_ITERATIONS: u64 = 5_000_000;
/// PoW stamper for on-network discovery announces. Thin wrapper around
@@ -50,8 +46,9 @@ pub struct LxmfDiscoveryStamper {
}
impl LxmfDiscoveryStamper {
/// Build a stamper with a custom iteration cap. Most callers want
/// [`LxmfDiscoveryStamper::default`].
/// Build a stamper with a custom iteration cap. Zero selects
/// [`DISCOVERY_MAX_ITERATIONS`], as does [`LxmfDiscoveryStamper::default`].
/// This differs from [`generate_discovery_stamp`], where zero allows no attempts.
pub fn with_max_iterations(max_iterations: u64) -> Self {
Self { max_iterations }
}
@@ -107,10 +104,10 @@ impl DiscoveryStamper for LxmfDiscoveryStamper {
}
}
/// 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_limited`], without a transport runtime.
/// For nonzero cost, a zero iteration limit returns `None`.
pub fn generate_discovery_stamp(
infohash: &[u8; 32],
target_value: u8,
+256 -87
View File
@@ -1,11 +1,13 @@
//! Announce handlers for `lxmf.delivery` and `lxmf.propagation` destinations, plus the
//! propagation-node control endpoint dispatcher.
//!
//! Python reference: LXMF/Handlers.py, LXMF.py:172-198, LXMRouter.py:306-318, LXMRouter.py:985-1000.
//! Related Python code: LXMF/Handlers.py, the announce helpers in LXMF.py,
//! and the request handlers in LXMRouter.py.
use std::collections::HashMap;
use crate::constants::*;
use crate::presentation::{MAX_ADVERTISED_NAME_CHARS, sanitize_name};
/// Announce handler type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -37,24 +39,36 @@ pub enum AnnounceResult {
Rejected(String),
}
/// Advertised delivery compression support from LXMF delivery-announce app data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionSupport {
/// No explicit supported-functionality metadata was present or parseable.
Unknown,
/// A supported-functionality list was present and omitted `SF_COMPRESSION`.
Unsupported,
/// A supported-functionality list was present and included `SF_COMPRESSION`.
Supported,
}
/// Parsed propagation-node announce data.
///
/// Wire layout is a 7-element msgpack array:
/// `[false, timebase, node_state, transfer_limit_kb, sync_limit_kb,
/// [stamp_cost, stamp_flex, peering_cost], metadata]`.
///
/// Python reference: LXMRouter.py:306-318.
/// Python reference: `LXMRouter.get_propagation_node_app_data`.
#[derive(Debug, Clone)]
pub struct PropagationNodeAnnounceData {
/// Legacy LXMF PN-support flag, always false.
/// Compatibility field. The constructor/parser set it to false, and the
/// encoder always writes false regardless of this field.
pub legacy: bool,
/// Node timebase as Unix seconds.
pub timebase: i64,
/// True when the node is actively serving propagation.
pub node_state: bool,
/// Per-transfer limit in kilobytes.
/// Per-transfer limit in decimal kilobytes (1 kB = 1000 bytes).
pub transfer_limit: u64,
/// Per-sync limit in kilobytes.
/// Per-sync limit in decimal kilobytes (1 kB = 1000 bytes).
pub sync_limit: u64,
pub stamp_cost: u8,
pub stamp_flex: u8,
@@ -88,13 +102,18 @@ impl PropagationNodeAnnounceData {
}
pub fn set_name(&mut self, name: &str) {
self.metadata.insert(PN_META_NAME, name.as_bytes().to_vec());
let name = sanitize_name(name, MAX_ADVERTISED_NAME_CHARS);
if name.is_empty() {
self.metadata.remove(&PN_META_NAME);
} else {
self.metadata.insert(PN_META_NAME, name.into_bytes());
}
}
}
/// Encode propagation-node announce `app_data` as msgpack.
///
/// Python reference: LXMRouter.py:306-318.
/// Python reference: `LXMRouter.get_propagation_node_app_data`.
pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<u8> {
use rmpv::Value;
@@ -125,14 +144,28 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
crate::encode_value(&announce_data)
}
/// Parse propagation-node announce data. Returns `None` if the data is
/// malformed (not msgpack, not an array, fewer than 7 elements, or any
/// element of the wrong type) — same rejection criteria as Python's
/// `pn_announce_data_is_valid` at `LXMF.py:172-198`. The validator and
/// the parser used to be two separate functions; the validator was
/// dropped because it duplicated this function's checks and every
/// in-tree caller called both back-to-back.
/// Parse a propagation-node announce array with at least seven elements.
///
/// Requires a boolean state, numeric timebase, nonnegative finite limits/costs,
/// a cost array with at least three values, and a metadata map. Rust casts apply; costs must
/// fit in `u8` after conversion. The legacy slot is ignored. Only metadata with
/// `u8` keys and binary values is retained. Extra array elements and trailing
/// MessagePack bytes are not rejected.
///
/// This parser does not authenticate the announce or enforce timebase freshness.
/// Its coercion and filtering rules differ from Python `pn_announce_data_is_valid`.
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_i64().and_then(|number| number.try_into().ok()))
.or_else(|| {
value.as_f64().and_then(|number| {
(number.is_finite() && number >= 0.0).then_some(number as u64)
})
})
}
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
if arr.len() < 7 {
@@ -144,38 +177,27 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
.or_else(|| arr[1].as_u64().map(|u| u as i64))
.or_else(|| arr[1].as_f64().map(|f| f as i64))?;
let node_state = arr[2].as_bool()?;
let transfer_limit = arr[3]
.as_u64()
.or_else(|| arr[3].as_i64().map(|i| i as u64))
.or_else(|| arr[3].as_f64().map(|f| f as u64))?;
let sync_limit = arr[4]
.as_u64()
.or_else(|| arr[4].as_i64().map(|i| i as u64))
.or_else(|| arr[4].as_f64().map(|f| f as u64))?;
let transfer_limit = nonnegative_u64(&arr[3])?;
let sync_limit = nonnegative_u64(&arr[4])?;
let costs = arr[5].as_array()?;
if costs.len() < 3 {
return None;
}
let stamp_cost = costs[0]
.as_u64()
.or_else(|| costs[0].as_i64().map(|i| i as u64))? as u8;
let stamp_flex = costs[1]
.as_u64()
.or_else(|| costs[1].as_i64().map(|i| i as u64))? as u8;
let peering_cost = costs[2]
.as_u64()
.or_else(|| costs[2].as_i64().map(|i| i as u64))? as u8;
let stamp_cost = u8::try_from(nonnegative_u64(&costs[0])?).ok()?;
let stamp_flex = u8::try_from(nonnegative_u64(&costs[1])?).ok()?;
let peering_cost = u8::try_from(nonnegative_u64(&costs[2])?).ok()?;
// Python's `pn_announce_data_is_valid()` requires the metadata element to
// be a map. Unknown keys and non-binary values are ignored here because
// the typed Rust API can only retain metadata it can represent safely.
let mut metadata = HashMap::new();
if let Some(map) = arr[6].as_map() {
for (k, v) in map {
if let (Some(key), Some(val)) = (
k.as_u64().map(|u| u as u8),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
for (k, v) in arr[6].as_map()? {
if let (Some(key), Some(val)) = (
k.as_u64().and_then(|number| number.try_into().ok()),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
}
@@ -194,38 +216,46 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
/// Extract stamp cost from propagation-node announce data.
///
/// Python reference: `pn_stamp_cost_from_app_data` — LXMF.py:163-170.
/// Uses [`parse_pn_announce_data`] and its numeric conversion rules.
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_pn_announce_data(data).map(|p| p.stamp_cost)
}
/// Encode delivery-announce `app_data` as msgpack `[display_name, stamp_cost]`.
/// Encode delivery-announce `app_data` as msgpack
/// `[display_name, stamp_cost, supported_functionality]` where the feature
/// list advertises [`SF_COMPRESSION`].
///
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
///
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1000.
/// Names are sanitized and limited to [`MAX_ADVERTISED_NAME_CHARS`] characters.
/// Python reference: `LXMRouter.get_announce_app_data`.
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
use rmpv::Value;
let name_val = match display_name {
Some(name) => Value::Binary(name.as_bytes().to_vec()),
None => Value::Nil,
};
let name_val = display_name
.map(|name| sanitize_name(name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
.map_or(Value::Nil, |name| Value::Binary(name.into_bytes()));
let cost_val = match stamp_cost {
Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64),
_ => Value::Nil,
};
let peer_data = Value::Array(vec![name_val, cost_val]);
let supported_functionality =
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]);
let peer_data = Value::Array(vec![name_val, cost_val, supported_functionality]);
crate::encode_value(&peer_data)
}
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
///
/// Accepts both Python LXMF 0.9.6's 2-element form and the optional 3-element
/// feature-list form used by newer/extended peers.
/// Requires an array with at least two elements; later elements are ignored.
/// A binary UTF-8 name is sanitized and bounded. Unsigned stamp costs are cast
/// to `u8`, retaining the low byte; this does not apply the encoder's `1..=254`
/// filter. Original raw-text announce names are not parsed by this helper.
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
@@ -236,7 +266,8 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
let display_name = arr[0]
.as_slice()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.map(|name| name.replace('\0', "").trim().to_string());
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty());
let stamp_cost = arr[1].as_u64().map(|c| c as u8);
@@ -245,50 +276,69 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
/// Extract just the display name from delivery-announce `app_data`.
///
/// Python reference: `display_name_from_app_data` — LXMF.py:131-143.
/// Uses [`parse_announce_app_data`], including its name sanitization and array-only format.
pub fn display_name_from_app_data(data: &[u8]) -> Option<String> {
parse_announce_app_data(data).and_then(|(name, _)| name)
}
/// Extract just the stamp cost from delivery-announce `app_data`.
///
/// Python reference: `stamp_cost_from_app_data` — LXMF.py:145-152.
/// Uses [`parse_announce_app_data`], including its unsigned-to-`u8` cast.
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_announce_app_data(data).and_then(|(_, cost)| cost)
}
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
/// Parse advertised `SF_COMPRESSION` support in delivery-announce `app_data`.
///
/// Returns `false` for legacy 2-element app_data or when the feature list is missing/empty.
/// Legacy 2-element app_data, malformed data, and missing feature lists are
/// treated as unknown. A present feature list is authoritative.
///
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
/// Related Python helper: `compression_support_from_app_data`.
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return false;
return CompressionSupport::Unknown;
};
let Some(arr) = value.as_array() else {
return false;
return CompressionSupport::Unknown;
};
if arr.len() < 3 {
return false;
return CompressionSupport::Unknown;
}
let Some(features) = arr[2].as_array() else {
return false;
return CompressionSupport::Unknown;
};
features
if features
.iter()
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
{
CompressionSupport::Supported
} else {
CompressionSupport::Unsupported
}
}
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
///
/// Returns true for Supported or Unknown, including empty/malformed input and
/// missing or non-list feature metadata. Only a present feature list without
/// `SF_COMPRESSION` returns false. This boolean default differs from Python
/// helper cases that return `None` or raise a decode error.
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
}
/// Extract the advertised name from propagation-node announce data.
///
/// Reads the [`PN_META_NAME`] metadata entry and decodes it as UTF-8.
///
/// Python reference: `pn_name_from_app_data` — LXMF.py:172-181.
/// Reads binary [`PN_META_NAME`] metadata, decodes UTF-8, then sanitizes and
/// bounds the name. Returns `None` if parsing fails or the result is empty.
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
let parsed = parse_pn_announce_data(data)?;
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
String::from_utf8(name_bytes.clone()).ok()
String::from_utf8(name_bytes.clone())
.ok()
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
}
/// Outcome of a resource transfer, matching Python `resource_concluded` /
@@ -330,21 +380,24 @@ pub enum ControlResult {
/// Propagation-node request handler.
///
/// Owns the access-control state and dispatches the three request paths (`/pn/get/stats`,
/// `/offer`, `/get`) to [`crate::propagation_node::PropagationNode`]. Python reference:
/// LXMRouter.py:650-657.
/// Provides handlers for `/pn/get/stats`, `/offer`, `/get`, `/pn/peer/sync` and
/// `/pn/peer/unpeer`. The embedder must supply identities already verified by
/// the Link; these methods accept identity hashes and do not authenticate them.
/// Sync/unpeer handlers authorize a request; the caller performs those actions.
pub struct PropagationRequestHandler {
pub local_identity_hash: [u8; 16],
pub control_allowed: Vec<[u8; 16]>,
/// When true, only peers in [`static_peers`](Self::static_peers) may submit offers.
/// When true, offers require the supplied remote identity hash to be in
/// [`static_peers`](Self::static_peers). This helper uses identity hashes.
pub from_static_only: bool,
pub static_peers: std::collections::HashSet<[u8; 16]>,
/// Throttled peers mapped to their expiry Unix timestamp.
/// Supplied remote identity hashes mapped to throttle-expiry Unix timestamps.
pub throttled_peers: HashMap<[u8; 16], f64>,
}
impl PropagationRequestHandler {
/// Create a handler seeded with the local identity hash, which is always control-allowed.
/// Create a handler with the local identity hash in its initial control allowlist.
/// The allowlist remains mutable, including removal of that identity.
pub fn new(identity_hash: [u8; 16]) -> Self {
Self {
local_identity_hash: identity_hash,
@@ -355,9 +408,9 @@ impl PropagationRequestHandler {
}
}
/// Handle a `/pn/get/stats` request: validates identity and access, then returns msgpack stats.
/// Return MessagePack stats when the supplied verified identity is control-allowed.
///
/// Python reference: `LXMRouter.stats_get_request` — LXMRouter.py:819-822.
/// Related Python handler: `LXMRouter.stats_get_request`.
pub fn handle_stats_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -379,9 +432,10 @@ impl PropagationRequestHandler {
/// Handle an `/offer` request from a syncing peer.
///
/// Validates identity, throttle status, access, and peering key, then delegates to
/// [`crate::propagation_node::PropagationNode::handle_offer_request`]. Python reference:
/// `LXMRouter.offer_request` — LXMRouter.py:2139-2189.
/// Build identity-presence, throttle and static-access context, then delegate
/// decoding and peering-key checks to
/// [`crate::propagation_node::PropagationNode::handle_offer_request`].
/// Supply an already verified remote identity; this helper does not verify it.
pub fn handle_offer_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -407,12 +461,10 @@ impl PropagationRequestHandler {
true
};
let peer_hash = remote_identity_hash.copied().unwrap_or([0u8; 16]);
node.handle_offer_request(
request_data,
crate::propagation_node::OfferRequestContext {
peer_hash,
peer_hash: remote_identity_hash.copied().unwrap_or([0u8; 16]),
identity_known,
is_throttled,
access_allowed,
@@ -423,10 +475,13 @@ impl PropagationRequestHandler {
}
/// Handle a `/get` request from a client downloading messages. Phase-2
/// responses come back as a [`GetRequestAction::ServeFiles`] plan — the
/// embedder resolves it after releasing the node lock.
/// responses come back as a
/// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles)
/// plan — the embedder resolves it after releasing the node lock.
///
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499.
/// The caller must derive `client_dest_hash` from the verified remote identity
/// and enforce its access policy. This helper checks only that an identity
/// was supplied; it does not bind the two arguments.
pub fn handle_message_get_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -451,7 +506,7 @@ impl PropagationRequestHandler {
/// Handle a `/pn/peer/sync` request. Returns msgpack `true` on success; the caller performs
/// the actual sync trigger.
///
/// Python reference: `LXMRouter.peer_sync_request` — LXMRouter.py:824-834.
/// Related Python handler: `LXMRouter.peer_sync_request`.
pub fn handle_peer_sync_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -484,7 +539,7 @@ impl PropagationRequestHandler {
/// Handle a `/pn/peer/unpeer` request. Returns msgpack `true` on success; the caller performs
/// the actual peer removal.
///
/// Python reference: `LXMRouter.peer_unpeer_request` — LXMRouter.py:836-846.
/// Related Python handler: `LXMRouter.peer_unpeer_request`.
pub fn handle_peer_unpeer_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -521,7 +576,7 @@ impl PropagationRequestHandler {
/// Throttle `peer_hash` for `duration_secs` starting now.
///
/// Python reference: `LXMRouter.propagation_resource_concluded` — LXMRouter.py:2277-2278.
/// Related Python handler: `LXMRouter.propagation_resource_concluded`.
pub fn throttle_peer(&mut self, peer_hash: [u8; 16], duration_secs: f64) {
let expiry = now_f64() + duration_secs;
self.throttled_peers.insert(peer_hash, expiry);
@@ -683,6 +738,47 @@ mod tests {
assert!(parse_pn_announce_data(&[]).is_none());
assert!(parse_pn_announce_data(&[0x91, 0xC2]).is_none());
assert!(parse_pn_announce_data(&[0x01]).is_none());
let non_map_metadata = rmpv::Value::Array(vec![
rmpv::Value::Boolean(false),
rmpv::Value::from(1_777_716_440u64),
rmpv::Value::Boolean(true),
rmpv::Value::from(10_240),
rmpv::Value::from(10_240),
rmpv::Value::Array(vec![
rmpv::Value::from(16),
rmpv::Value::from(3),
rmpv::Value::from(18),
]),
rmpv::Value::Array(Vec::new()),
]);
assert!(
parse_pn_announce_data(&crate::encode_value(&non_map_metadata)).is_none(),
"Python rejects propagation announces whose metadata is not a map"
);
}
#[test]
fn test_pn_announce_data_rejects_wrapping_policy_values() {
use rmpv::Value;
let encode = |transfer_limit: Value, stamp_cost: Value| {
let value = Value::Array(vec![
Value::Boolean(false),
Value::from(1_777_716_440u64),
Value::Boolean(true),
transfer_limit,
Value::from(10240),
Value::Array(vec![stamp_cost, Value::from(3), Value::from(18)]),
Value::Map(vec![]),
]);
let mut packed = Vec::new();
rmpv::encode::write_value(&mut packed, &value).unwrap();
packed
};
assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none());
assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none());
}
#[test]
@@ -707,6 +803,16 @@ mod tests {
assert_eq!(cost, Some(12));
}
#[test]
fn test_delivery_announce_data_matches_python_101_bytes() {
// Python 1.0.1 oracle: msgpack([b"Test", 16, [SF_COMPRESSION]]) — LXMRouter.py:999-1001.
assert_eq!(
hex::encode(get_announce_app_data(Some("Test"), Some(16))),
"93c40454657374109100"
);
assert_eq!(hex::encode(get_announce_app_data(None, None)), "93c0c09100");
}
#[test]
fn test_delivery_announce_data_no_name() {
let packed = get_announce_app_data(None, Some(8));
@@ -760,6 +866,18 @@ mod tests {
);
}
#[test]
fn test_display_name_from_app_data_sanitizes_untrusted_unicode() {
let packed = get_announce_app_data(
Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "),
Some(12),
);
assert_eq!(
display_name_from_app_data(&packed),
Some("AliceNetwork".to_string())
);
}
#[test]
fn test_stamp_cost_from_app_data() {
let packed = get_announce_app_data(Some("Alice"), Some(12));
@@ -771,8 +889,18 @@ mod tests {
#[test]
fn test_compression_support_from_app_data() {
let python_096 = get_announce_app_data(Some("Alice"), Some(12));
assert!(!compression_support_from_app_data(&python_096));
// Legacy <=0.9.8 2-element app_data: unknown state, fail-open true
// (Python returns True for len < 3 — LXMF.py:161).
let python_098 = {
use rmpv::Value;
let arr = Value::Array(vec![Value::Binary(b"Alice".to_vec()), Value::from(12u64)]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&python_098),
CompressionSupport::Unknown
);
assert!(compression_support_from_app_data(&python_098));
let supported = {
use rmpv::Value;
@@ -783,8 +911,30 @@ mod tests {
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&supported),
CompressionSupport::Supported
);
assert!(compression_support_from_app_data(&supported));
let ratspeak_extended_supported = {
use rmpv::Value;
let arr = Value::Array(vec![
Value::Binary(b"Alice".to_vec()),
Value::from(12u64),
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]),
Value::Map(vec![]),
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&ratspeak_extended_supported),
CompressionSupport::Supported
);
assert!(compression_support_from_app_data(
&ratspeak_extended_supported
));
// 3-element form with empty feature list -> unsupported.
let empty_features = {
use rmpv::Value;
@@ -795,7 +945,26 @@ mod tests {
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&empty_features),
CompressionSupport::Unsupported
);
assert!(!compression_support_from_app_data(&empty_features));
// Malformed data: unknown state, fail-open true (Python treats the
// original non-msgpack announce format as supported — LXMF.py:167).
assert_eq!(
compression_support_state_from_app_data(&[0xc1]),
CompressionSupport::Unknown
);
assert!(compression_support_from_app_data(&[0xc1]));
// Our own 1.0.1 emission round-trips as explicitly supported.
let own = get_announce_app_data(Some("Alice"), Some(12));
assert_eq!(
compression_support_state_from_app_data(&own),
CompressionSupport::Supported
);
}
#[test]
+489
View File
@@ -0,0 +1,489 @@
//! 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()
})
}
}
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()
}
/// 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;
}
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);
}
}
}
#[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);
}
}
+56 -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`
@@ -40,16 +50,37 @@ pub(crate) fn now_f64() -> f64 {
.as_secs_f64()
}
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
#[cfg(test)]
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
pub mod admission;
pub mod admission_store;
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
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;
@@ -57,6 +88,24 @@ 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
+423
View File
@@ -0,0 +1,423 @@
//! 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<u8>,
ticket_barrier: Option<Arc<()>>,
}
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<u8>,
}
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,
ticket_barrier: 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(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) {
self.ticket_barrier = Some(owner);
}
pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool {
if self
.ticket_barrier
.as_ref()
.is_some_and(|pending| Arc::ptr_eq(pending, owner))
{
self.ticket_barrier = None;
true
} else {
false
}
}
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
self.fields.get(&id.into())
}
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> {
self.set_field_value(
id,
FieldValue::MessagePack(EncodedFieldValue::new(bytes.into())?),
)
}
pub fn set_field_value(
&mut self,
id: impl Into<FieldId>,
value: FieldValue,
) -> Result<(), MessageError> {
let id = id.into();
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> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&ImageFieldRef { format, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_IMAGE, encoded)
}
pub fn set_audio_field(&mut self, mode: u8, bytes: &[u8]) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&AudioFieldRef { mode, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_AUDIO, encoded)
}
pub fn set_file_attachment_field(
&mut self,
file_name: &str,
bytes: &[u8],
) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded =
rmp_serde::to_vec(&FileAttachmentsFieldRef { file_name, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_FILE_ATTACHMENTS, encoded)
}
/// 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>(self, sign: F) -> Result<SignedLxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
if self.ticket_barrier.is_some() {
return Err(MessageError::TicketNotCommitted);
}
let size = self.checked_wire_len()?;
let mut signed = Vec::with_capacity(size);
signed.extend_from_slice(&self.destination);
signed.extend_from_slice(&self.source);
self.write_payload(&mut signed)?;
let id = sha256(&signed);
signed.extend_from_slice(&id);
let signature = sign(&signed).map_err(packed)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.destination);
wire.extend_from_slice(&self.source);
wire.extend_from_slice(&signature);
wire.extend_from_slice(&signed[32..signed.len() - 32]);
drop(signed);
let mut message = LxMessage::unpack_owned(wire.into(), self.limits)?;
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<u8>,
) -> 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()
}
pub fn stamp_cost(&self) -> Option<u8> {
self.stamp_cost
}
pub fn outbound_ticket(&self) -> Option<[u8; 16]> {
self.outbound_ticket
}
/// Compute the optional recipient stamp without changing the signed body.
/// Runs synchronously; proof of work uses [`crate::stamper::generate_stamp`]
/// and its attempt budget.
pub fn generate_recipient_stamp(&self) -> 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)
.map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp)))
.ok_or_else(|| packed("recipient stamp generation failed"))
}
pub fn finalize(self, stamp: Option<RecipientStamp>) -> Result<LxMessage, MessageError> {
let Some(stamp) = stamp else {
return Ok(self.message);
};
let size = self
.message
.wire
.len()
.checked_add(2 + stamp.as_bytes().len())
.ok_or_else(|| packed("length overflow"))?;
self.message.limits.check_wire(size)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.message.wire);
wire[96] = 0x95;
write_bin(&mut wire, stamp.as_bytes())?;
let mut message = LxMessage::unpack_owned(wire.into(), self.message.limits)?;
debug_assert_eq!(message.message_id, self.message.message_id);
message.metadata = self.message.metadata;
Ok(message)
}
}
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)
}
+341
View File
@@ -0,0 +1,341 @@
//! 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))
}
pub fn encoded(&self) -> &[u8] {
&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::new(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.
/// Duplicate map keys remain opaque until a recognized schema asks for
/// `unique_map`; 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 @@
/�äxîÒÝfPpVJך�*uÁ”qPp÷_I#D‰H®8
+129
View File
@@ -0,0 +1,129 @@
//! 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 = 1;
const DIGEST_LEN: usize = 16;
const FLOOR_AT: usize = HEADER_LEN + MAGIC.len() + 1;
const STAMP_AT: usize = FLOOR_AT + 2;
/// A signed, unstamped message stored so delivery can resume after a restart.
///
/// Version 1 holds, in order:
/// - the signed header: destination, source and signature (96 bytes);
/// - the bytes `0xC1`, `L`, `X`, `R`, then the version byte;
/// - the stamp cost the message was signed under: a presence byte and a value;
/// - reserved slots for a finished recipient stamp (a length byte of 0, 16
/// or 32, then the stamp) and a propagation envelope (a big-endian `u32`
/// length, then the envelope). Version 1 writes both empty, and a reader of
/// 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<u8>,
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<u8>) -> Self {
let mut bytes = Vec::with_capacity(wire.len() + STAMP_AT + 5 + DIGEST_LEN);
bytes.extend_from_slice(&wire[..HEADER_LEN]);
bytes.extend_from_slice(&MAGIC);
bytes.push(VERSION);
bytes.extend_from_slice(&[u8::from(stamp_cost.is_some()), stamp_cost.unwrap_or(0)]);
bytes.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"));
}
if bytes[HEADER_LEN + MAGIC.len()] != VERSION {
return Err(invalid("unsupported version"));
}
let digest_at = bytes.len() - DIGEST_LEN;
if sha256(&bytes[..digest_at])[..DIGEST_LEN] != bytes[digest_at..] {
return Err(invalid("damaged"));
}
let stamp_cost_floor = match bytes[FLOOR_AT..STAMP_AT] {
[0, 0] => None,
[1, cost] => Some(cost),
_ => 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<u8> {
self.stamp_cost_floor
}
/// 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())
}
}
+847
View File
@@ -0,0 +1,847 @@
use super::*;
use rns_crypto::ed25519::Ed25519PrivateKey;
fn key() -> Ed25519PrivateKey {
Ed25519PrivateKey::from_bytes(&[7; 32])
}
fn draft() -> LxMessageDraft {
LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct).unwrap()
}
fn freeze(draft: LxMessageDraft) -> LxMessage {
draft.sign(&key()).unwrap().finalize(None).unwrap()
}
fn payload(fields: &[u8], stamp: Option<&[u8]>) -> Vec<u8> {
let mut p = vec![if stamp.is_some() { 0x95 } else { 0x94 }];
rmp::encode::write_f64(&mut p, 1_700_000_000.).unwrap();
p.extend_from_slice(&[0xc4, 1, b'T', 0xc4, 1, b'C']);
p.extend_from_slice(fields);
if let Some(s) = stamp {
p.extend_from_slice(s);
}
p
}
fn wire(payload: &[u8]) -> Vec<u8> {
let mut signed = vec![1; 16];
signed.extend_from_slice(&[2; 16]);
if let Some(body) = first_four_msgpack_array_body(payload) {
signed.push(0x94);
signed.extend_from_slice(body);
} else {
signed.extend_from_slice(payload);
}
let hash = sha256(&signed);
signed.extend_from_slice(&hash);
let mut out = vec![1; 16];
out.extend_from_slice(&[2; 16]);
out.extend_from_slice(&key().sign(&signed));
out.extend_from_slice(payload);
out
}
#[test]
fn signed_body_finalization_defaults_and_states() {
let d = draft();
assert!(d.timestamp() > 0.);
assert_eq!(d.state, MessageState::Generating);
assert!(d.auto_compress);
assert!(!d.source_blackholed);
let signed = d.sign(&key()).unwrap();
let id = signed.message_id();
let mut m = signed.finalize(None).unwrap();
assert_eq!(m.state, MessageState::Outbound);
assert_eq!(m.message_id(), id);
let before = m.wire_owned();
m.mark_sending();
m.mark_sent();
m.mark_delivered();
assert_eq!(m.state, MessageState::Delivered);
m.mark_failed();
assert_eq!(m.state, MessageState::Failed);
m.mark_rejected();
assert_eq!(m.state, MessageState::Rejected);
assert_eq!(m.wire_bytes(), before.as_ref());
}
#[test]
fn received_wire_identity_repeated_verification_and_ownership() {
let mut p = payload(&[0x82, 0x0f, 0x01, 0x0c, 0x92, 0x00, 0xc4, 0x00], None);
// A retained noncanonical f32 timestamp cannot be reencoded as f64.
p.splice(1..10, [0xca, 0x3f, 0x80, 0x00, 0x00]);
let wire = Bytes::from(wire(&p));
let ptr = wire.as_ptr();
let mut m = LxMessage::unpack_owned(wire.clone(), MessageDecodeLimits::default()).unwrap();
assert_eq!(m.wire_bytes().as_ptr(), ptr);
let id = m.message_id();
assert!(m.verify_signature(&key().public_key()));
assert!(m.verify_signature(&key().public_key()));
assert_eq!(m.pack().unwrap(), wire);
assert_eq!(m.pack_payload().unwrap(), p);
assert_eq!(m.message_id(), id);
m.method = DeliveryMethod::Propagated;
m.progress = 0.8;
assert_eq!(m.clone().wire_bytes().as_ptr(), ptr);
assert_eq!(m.pack().unwrap(), wire);
let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap();
assert_eq!(restored.wire_bytes(), wire);
assert_eq!(restored.message_id(), id);
assert!(restored.verify_signature(&key().public_key()));
}
#[test]
fn received_wire_identity_real_python_reordered_vector() {
// Emitted by Python LXMF 1.0.1: renderer precedes the subsequently added reply ticket.
let raw = include_bytes!("fixtures/python-reordered.bin");
let public = include_bytes!("fixtures/python-reordered-public.bin");
let key =
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(public.as_slice().try_into().unwrap())
.unwrap();
let m = LxMessage::unpack(raw).unwrap();
assert!(m.verify_signature(&key));
assert!(m.verify_signature(&key));
assert_eq!(m.pack().unwrap(), raw);
let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap();
assert_eq!(restored.wire_bytes(), raw);
assert_eq!(restored.message_id(), m.message_id());
assert!(restored.verify_signature(&key));
}
#[test]
fn received_wire_identity_source_binding() {
let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap();
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
let d = LxMessageDraft::new([1; 16], source, "", "", DeliveryMethod::Direct).unwrap();
let m = freeze(d);
assert!(m.verify(&identity.get_public_key()).is_ok());
assert!(m.verify(&identity.get_public_key()).is_ok());
let mut altered = identity.get_public_key();
altered[..32].fill(8);
assert!(matches!(
m.verify(&altered),
Err(MessageError::SourceMismatch)
));
let wrong_source = freeze(draft());
assert!(wrong_source.verify_signature(&key().public_key()));
assert!(matches!(
wrong_source.verify(&identity.get_public_key()),
Err(MessageError::SourceMismatch)
));
assert!(!m.verify_signature(&Ed25519PrivateKey::from_bytes(&[9; 32]).public_key()));
}
#[test]
fn owned_verification_retains_exact_source_and_shared_wire_after_handoff() {
let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap();
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
let message = freeze(
LxMessageDraft::new([1; 16], source, "title", "content", DeliveryMethod::Direct).unwrap(),
);
let pointer = message.wire_bytes().as_ptr();
let hash = message.message_id();
let owned = message
.verify(&identity.get_public_key())
.unwrap()
.to_owned();
drop(message);
let verified = owned.as_verified();
assert_eq!(verified.message().wire_bytes().as_ptr(), pointer);
assert_eq!(verified.message().message_id(), hash);
assert_eq!(verified.source_public_key(), &identity.get_public_key());
assert_eq!(verified.message().source_hash(), source);
}
#[test]
fn field_id_entire_domain_and_serde_roundtrip() {
let values = [
i64::MIN as i128,
-1,
0,
255,
256,
i64::MAX as i128,
i64::MAX as i128 + 1,
u64::MAX as i128,
];
let mut d = draft();
for v in values {
let id = FieldId::try_from(v).unwrap();
let bytes = rmp_serde::to_vec(&id).unwrap();
let decoded: FieldId = rmp_serde::from_slice(&bytes).unwrap();
assert_eq!(decoded, id);
d.set_field(id, vec![42]).unwrap();
}
let m = freeze(d);
for v in values {
assert_eq!(
m.get_field(FieldId::try_from(v).unwrap())
.unwrap()
.as_binary(),
Some(&[42][..])
);
}
assert!(FieldId::try_from(i64::MIN as i128 - 1).is_err());
assert!(FieldId::try_from(u64::MAX as i128 + 1).is_err());
assert!(FieldId::from(256u64).as_standard().is_none());
assert_eq!(FieldId::from(1u64), FieldId::from(1i64));
}
#[test]
fn field_id_never_aliases_native_ids() {
let mut d = draft();
d.set_field(0x105u64, vec![1]).unwrap();
d.set_field(0x10cu64, vec![2]).unwrap();
d.set_field(-1i64, vec![3]).unwrap();
let m = freeze(d);
assert!(!m.fields().contains(5u8));
assert!(!m.fields().contains(12u8));
assert!(!m.fields().contains(255u8));
assert_eq!(m.fields().len(), 3);
}
#[test]
fn field_id_duplicate_numeric_encodings_rejected() {
for map in [
vec![0x82, 1, 0xc0, 1, 0xc0],
vec![0x82, 1, 0xc0, 0xd1, 0, 1, 0xc0],
vec![0x82, 0xcf, 0, 0, 0, 0, 0, 0, 0, 1, 0xc0, 0xcc, 1, 0xc0],
] {
assert!(matches!(
LxMessage::unpack(&wire(&payload(&map, None))),
Err(MessageError::DuplicateField)
));
let mut dto = vec![0x94, 0xcb];
dto.extend_from_slice(&0f64.to_be_bytes());
dto.extend_from_slice(&[0xc4, 0, 0xc4, 0]);
dto.extend_from_slice(&map);
assert!(rmp_serde::from_slice::<MessagePayload>(&dto).is_err());
}
}
#[test]
fn field_id_coherent_replacement_and_binary_is_not_structure() {
let mut d = draft();
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0])
.unwrap();
d.set_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0]).unwrap();
let m = freeze(d);
let value = m.get_field(FIELD_AUDIO).unwrap();
assert_eq!(value.as_binary(), Some(&[0x92, 0x10, 0xc4, 0][..]));
assert!(m.audio_field().is_err());
assert!(LxMessage::unpack(m.wire_bytes()).is_ok());
let mut d = draft();
d.set_field(FIELD_AUDIO, vec![0]).unwrap();
d.set_audio_field(0x10, &[1, 2]).unwrap();
assert_eq!(freeze(d).audio_field().unwrap().unwrap().bytes, &[1, 2]);
}
#[test]
fn field_id_opaque_nested_duplicate_map_is_preserved() {
let raw = vec![0x82, 1, 0x01, 0xd1, 0, 1, 0x02];
let mut d = draft();
d.set_msgpack_field(300u64, raw.clone()).unwrap();
let m = freeze(d);
assert_eq!(m.get_field(300u64).unwrap().encoded(), raw);
assert_eq!(
LxMessage::unpack(m.wire_bytes()).unwrap().pack().unwrap(),
m.wire_bytes()
);
}
#[test]
fn field_id_profile_counts_inbound_and_outbound() {
let mut d = draft();
for i in 0..4096u64 {
d.set_field(i, Bytes::new()).unwrap();
}
d.set_field(0u64, vec![1]).unwrap();
assert!(matches!(
d.set_field(4096u64, Bytes::new()),
Err(MessageError::TooManyFields)
));
let m = freeze(d);
assert_eq!(m.fields().len(), 4096);
let smaller = MessageDecodeLimits {
max_top_level_fields: 4095,
..MessageDecodeLimits::default()
};
assert!(matches!(
LxMessage::unpack_owned(m.wire_owned(), smaller),
Err(MessageError::TooManyFields)
));
let profile = MessageDecodeLimits {
max_top_level_fields: 1,
..MessageDecodeLimits::default()
};
let mut d =
LxMessageDraft::new_with_limits([1; 16], [2; 16], "", "", DeliveryMethod::Direct, profile)
.unwrap();
d.set_field(1u8, vec![]).unwrap();
assert!(d.set_field(FIELD_TICKET, vec![]).is_err());
d.set_field(1u8, vec![2]).unwrap();
assert_eq!(freeze(d).fields().len(), 1);
let map = [0xdf, 0xff, 0xff, 0xff, 0xff];
assert!(LxMessage::unpack(&wire(&payload(&map, None))).is_err());
}
#[test]
fn signed_body_finalization_enforces_exact_stamp_limit() {
let base = freeze(draft()).wire_bytes().len();
let mut profile = MessageDecodeLimits {
max_wire_bytes: base,
max_top_level_fields: 4096,
};
let d = LxMessageDraft::new_with_limits(
[1; 16],
[2; 16],
"title",
"content",
DeliveryMethod::Direct,
profile,
)
.unwrap();
assert!(matches!(
d.sign(&key())
.unwrap()
.finalize(Some(RecipientStamp::Ticket([1; 16]))),
Err(MessageError::TooLarge { .. })
));
profile.max_wire_bytes = base + 18;
let d = LxMessageDraft::new_with_limits(
[1; 16],
[2; 16],
"title",
"content",
DeliveryMethod::Direct,
profile,
)
.unwrap();
assert_eq!(
d.sign(&key())
.unwrap()
.finalize(Some(RecipientStamp::Ticket([1; 16])))
.unwrap()
.wire_bytes()
.len(),
base + 18
);
}
#[test]
fn signed_body_finalization_stamp_preserves_id_and_signature() {
let mut d = draft();
d.set_timestamp(1700000000.).unwrap();
let no_stamp = freeze(d.clone());
for stamp in [
RecipientStamp::Ticket([3; 16]),
RecipientStamp::ProofOfWork([4; 32]),
] {
let m = d
.clone()
.sign(&key())
.unwrap()
.finalize(Some(stamp))
.unwrap();
assert_eq!(m.message_id(), no_stamp.message_id());
assert_eq!(m.signature(), no_stamp.signature());
assert!(m.verify_signature(&key().public_key()));
assert_eq!(m.recipient_stamp(), Some(&stamp));
assert_eq!(
LxMessage::unpack(m.wire_bytes()).unwrap().message_id(),
no_stamp.message_id()
);
}
}
#[test]
fn recipient_stamp_array_range_and_malformed_dispositions() {
for (element, valid) in [
(vec![0], true),
(vec![0xcc, 255], true),
(vec![0xd1, 0, 255], true),
(vec![0xff], false),
(vec![0xcd, 1, 0], false),
(vec![0xcf, 255, 255, 255, 255, 255, 255, 255, 255], false),
] {
let mut stamp = vec![0xdc, 0, 16];
for _ in 0..16 {
stamp.extend_from_slice(&element);
}
let bytes = wire(&payload(&[0x80], Some(&stamp)));
let m = LxMessage::unpack(&bytes).unwrap();
assert_eq!(m.recipient_stamp().is_some(), valid);
assert_eq!(m.wire_bytes(), bytes);
assert!(m.verify_signature(&key().public_key()));
if !valid {
assert!(!m.validate_stamp_with_tickets(0, None));
}
}
for stamp in [vec![0xc0], vec![0x91, 0], vec![0xc4, 1, 0], vec![0xa0]] {
let m = LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).unwrap();
assert!(m.recipient_stamp().is_none());
}
for stamp in [vec![], vec![0xc4], {
let mut s = vec![0xdc, 0, 16];
s.extend_from_slice(&[0xc0; 16]);
s
}] {
assert!(LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).is_err());
}
}
#[test]
fn recipient_ticket_stamp_and_missing_stamp_policy() {
let mut d = draft();
d.outbound_ticket = Some([3; 16]);
let signed = d.sign(&key()).unwrap();
let stamp = signed.generate_recipient_stamp().unwrap();
let m = signed.finalize(stamp).unwrap();
assert!(m.validate_stamp_with_tickets(255, Some(&[vec![3; 16]])));
assert_eq!(
m.validated_stamp_value(255, Some(&[vec![3; 16]])),
Some(COST_TICKET)
);
assert!(!m.validate_stamp_with_tickets(1, Some(&[vec![4; 16]])));
assert!(!freeze(draft()).validate_stamp_with_tickets(0, None));
let signed = draft().sign(&key()).unwrap();
assert_eq!(signed.generate_recipient_stamp().unwrap(), None);
}
#[test]
fn signed_body_finalization_matches_semantic_dto() {
let mut d = draft();
d.set_timestamp(1700000000.).unwrap();
d.set_field(256u64, vec![1, 2]).unwrap();
d.set_msgpack_field(-1i64, vec![0x92, 1, 0xc4, 0]).unwrap();
let dto = MessagePayload {
timestamp: d.timestamp(),
title: "title".into(),
content: "content".into(),
fields: d.fields().clone(),
stamp: None,
};
let encoded = rmp_serde::to_vec(&dto).unwrap();
assert_eq!(d.pack_payload().unwrap(), encoded);
let decoded: MessagePayload = rmp_serde::from_slice(&encoded).unwrap();
assert_eq!(decoded.fields, dto.fields);
}
#[test]
fn native_attachments_borrow_exact_image_and_clone() {
let data = vec![0xa5; 2 * 1024 * 1024];
let mut d = draft();
d.set_audio_field(AM_OPUS_OGG, &data).unwrap();
d.set_image_field("webp", &[2, 3]).unwrap();
d.set_file_attachment_field("test.bin", &[4, 5]).unwrap();
let m = freeze(d);
let audio = m.audio_field().unwrap().unwrap();
assert_eq!(audio.bytes, data);
let start = m.wire_bytes().as_ptr() as usize;
assert!((start..start + m.wire_bytes().len()).contains(&(audio.bytes.as_ptr() as usize)));
assert_eq!(m.clone().wire_bytes().as_ptr(), m.wire_bytes().as_ptr());
assert_eq!(
m.image_attachment().unwrap(),
Some(("webp".into(), &[2, 3][..]))
);
assert_eq!(
m.first_file_attachment().unwrap(),
Some(("test.bin".into(), &[4, 5][..]))
);
assert_eq!(m.packed_len().unwrap(), m.pack().unwrap().len());
assert!(m.verify_signature(&key().public_key()));
assert_eq!(
m.audio_field().unwrap().unwrap().bytes.as_ptr(),
audio.bytes.as_ptr()
);
}
#[test]
fn native_audio_shape_and_optional_failure() {
for malformed in [
vec![0xc0],
vec![0x91, 0x10],
vec![0x93, 0x10, 0xc4, 0, 0xc0],
vec![0x92, 0xff, 0xc4, 0],
vec![0x92, 0xcd, 1, 0, 0xc4, 0],
vec![0x92, 0xc0, 0xc4, 0],
vec![0x92, 0x10, 0xa0],
] {
let mut d = draft();
d.set_msgpack_field(FIELD_AUDIO, malformed).unwrap();
let m = freeze(d);
assert!(m.audio_field().is_err());
assert_eq!(m.content_text(), "content");
assert!(m.verify_signature(&key().public_key()));
}
let mut d = draft();
assert!(
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4])
.is_err()
);
assert!(
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0, 0xc0])
.is_err()
);
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0xcd, 0, 255, 0xc4, 0])
.unwrap();
assert_eq!(freeze(d).audio_field().unwrap().unwrap().mode, 255);
}
#[test]
fn received_wire_identity_paper_and_opportunistic_use_exact_tail() {
let mut m = freeze(draft());
m.method = DeliveryMethod::Paper;
let uri = m.to_paper_uri(|tail| Ok(tail.to_vec())).unwrap();
assert!(uri.starts_with("lxm://"));
let read = LxMessage::from_paper_uri(&uri, |tail| Ok(tail.to_vec())).unwrap();
assert_eq!(read.wire_bytes(), m.wire_bytes());
assert!(read.verify_signature(&key().public_key()));
assert_eq!(
m.pack_opportunistic_encrypted(|tail| Ok(tail.to_vec()))
.unwrap(),
m.wire_bytes()[16..]
);
assert!(LxMessage::decode_paper_uri("not-uri").is_err());
assert!(LxMessage::decode_paper_uri("lxm://!!").is_err());
m.method = DeliveryMethod::Direct;
assert!(m.to_paper_uri(|b| Ok(b.to_vec())).is_err());
}
#[test]
fn received_wire_identity_file_and_method_roundtrips() {
let dir = tempfile::tempdir().unwrap();
let mut m = freeze(draft());
m.state = MessageState::Delivered;
m.transport_encrypted = true;
m.transport_encryption = Some("ECIES".into());
for method in [
DeliveryMethod::Direct,
DeliveryMethod::Propagated,
DeliveryMethod::Paper,
DeliveryMethod::Opportunistic,
] {
m.method = method;
let path = m.write_to_directory(dir.path().to_str().unwrap()).unwrap();
let read = LxMessage::read_from_file(&path).unwrap();
assert_eq!(read.method, method);
assert_eq!(read.state, MessageState::Delivered);
assert_eq!(read.wire_bytes(), m.wire_bytes());
assert_eq!(read.transport_encryption, m.transport_encryption);
assert!(read.verify_signature(&key().public_key()));
}
}
#[test]
fn message_callbacks_and_compression_metadata_do_not_mutate_wire() {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut m = freeze(draft());
let before = m.wire_owned();
let calls = Arc::new(AtomicUsize::new(0));
let c = calls.clone();
m.register_delivery_callback(move |_| {
c.fetch_add(1, Ordering::SeqCst);
});
let c = calls.clone();
m.register_failed_callback(move |_| {
c.fetch_add(10, Ordering::SeqCst);
});
m.mark_delivered();
m.mark_failed();
assert_eq!(calls.load(Ordering::SeqCst), 11);
m.determine_compression_support(None);
assert!(m.auto_compress);
m.determine_compression_support(Some(&[0x93, 0xc0, 0xc0, 0x90]));
assert!(!m.auto_compress);
assert_eq!(m.wire_bytes(), before);
}
#[test]
fn propagation_wrapper_compatibility_and_bounds() {
let entry = vec![1; LxMessage::MIN_PROPAGATION_ENTRY_SIZE];
let entries = [entry.as_slice()];
let encoded = rmp_serde::to_vec(&PropagationWrapperRef {
timestamp: 1.,
entries: &entries,
})
.unwrap();
assert_eq!(
LxMessage::unpack_propagation_wrapper(&encoded).unwrap().1,
vec![entry]
);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len()).is_ok());
assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len() - 1).is_err());
assert_eq!(
LxMessage::compute_propagation_transient_id(&encoded),
full_hash(&encoded)
);
}
#[test]
fn received_wire_identity_bounds_and_invalid_utf8_preserved() {
for len in 0..97 {
assert!(LxMessage::unpack(&vec![0; len]).is_err());
}
let mut p = payload(&[0x80], None);
p[12] = 255;
let raw = wire(&p);
let m = LxMessage::unpack(&raw).unwrap();
assert_eq!(m.title_bytes(), &[255]);
assert_eq!(m.title_text(), "\u{fffd}");
assert_eq!(m.wire_bytes(), raw);
assert!(m.verify_signature(&key().public_key()));
let limits = MessageDecodeLimits {
max_wire_bytes: raw.len() - 1,
..MessageDecodeLimits::default()
};
assert!(LxMessage::unpack_owned(raw.into(), limits).is_err());
}
#[test]
fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
for encoded in [
vec![0x82, 0xa1, b'a', 1, 0xa1, b'a', 2],
vec![0x82, 1, 0, 0xd1, 0, 1, 1],
vec![0x81, 0xc3, 0],
] {
let mut d = draft();
d.set_msgpack_field(300u64, encoded).unwrap();
let m = freeze(d);
assert!(m.get_field(300u64).unwrap().unique_map().is_err());
assert!(m.verify_signature(&key().public_key()));
}
let mut d = draft();
d.set_msgpack_field(300u64, vec![0x82, 0xa1, b'a', 0xc4, 1, 7, 0x01, 0x02])
.unwrap();
let m = freeze(d);
let map = m.get_field(300u64).unwrap().unique_map().unwrap();
assert_eq!(map.len(), 2);
assert_eq!(
map.get(FieldMapKey::Text("a")).unwrap().as_binary(),
Some(&[7][..])
);
assert_eq!(
map.get(FieldMapKey::Integer(1u8.into())).unwrap().encoded(),
&[2]
);
}
#[test]
fn signed_body_finalization_ticket_barrier_blocks_signer() {
let owner = Arc::new(());
let mut d = draft();
d.mark_ticket_pending(owner.clone());
assert!(!d.release_ticket_barrier(&Arc::new(())));
assert!(matches!(
d.clone()
.sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }),
Err(MessageError::TicketNotCommitted)
));
assert!(d.release_ticket_barrier(&owner));
assert!(!d.release_ticket_barrier(&owner));
assert!(d.sign(&key()).is_ok());
}
#[test]
fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() {
for bytes in [
b"".as_slice(),
b"valid \xf0\x9f\xa6\x80".as_slice(),
b"\xff\xff\xff".as_slice(),
b"a\xf0\x90\x80".as_slice(),
b"a\xed\xa0\x80b\xc0\x80c".as_slice(),
] {
let actual = bounded_lossy_text(bytes);
assert_eq!(actual, String::from_utf8_lossy(bytes));
match actual {
Cow::Borrowed(text) => assert_eq!(text.as_ptr(), bytes.as_ptr()),
Cow::Owned(text) => assert_eq!(text.capacity(), text.len()),
}
}
let bytes = vec![0xff; 1024 * 1024];
let repaired = bounded_lossy_text(&bytes).into_owned();
assert_eq!(repaired.len(), bytes.len() * 3);
assert_eq!(repaired.capacity(), repaired.len());
}
proptest::proptest! {
#[test]
fn bounded_lossy_projection_matches_standard(bytes in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..4096)) {
let actual = bounded_lossy_text(&bytes);
proptest::prop_assert_eq!(&actual, &String::from_utf8_lossy(&bytes));
if let Cow::Owned(text) = actual {
proptest::prop_assert_eq!(text.capacity(), text.len());
proptest::prop_assert!(text.len() <= 3 * bytes.len());
}
}
}
#[test]
fn borrowed_encoded_field_validates_shape_without_copy_or_implicit_conversion() {
let encoded = b"\xa4text";
let field = FieldValueRef::from_encoded(encoded).unwrap();
assert_eq!(field.encoded().as_ptr(), encoded.as_ptr());
assert_eq!(field.as_text(), Some("text"));
assert!(field.as_binary().is_none());
assert!(
FieldValueRef::from_encoded(b"\xc4\x04text")
.unwrap()
.as_text()
.is_none()
);
assert!(
FieldValueRef::from_encoded(b"\xa1\xff")
.unwrap()
.as_text()
.is_none()
);
for invalid in [b"".as_slice(), b"\xa5text", b"\xa4text\xc0", b"\x81\x01"] {
assert!(FieldValueRef::from_encoded(invalid).is_err());
}
let duplicate = FieldValueRef::from_encoded(b"\x82\x01\x02\xcc\x01\x03").unwrap();
assert!(matches!(
duplicate.unique_map(),
Err(MessageError::DuplicateField)
));
}
#[test]
fn owned_propagation_wrapper_shares_binary_and_preserves_legacy_byte_arrays() {
let entry = vec![0xff; LxMessage::MIN_PROPAGATION_ENTRY_SIZE];
let entries = [entry.as_slice()];
let binary = Bytes::from(
rmp_serde::to_vec(&PropagationWrapperRef {
timestamp: 1.,
entries: &entries,
})
.unwrap(),
);
let (_, decoded) =
LxMessage::unpack_propagation_wrapper_owned(binary.clone(), binary.len()).unwrap();
assert_eq!(decoded[0].as_ref(), entry);
assert_eq!(
decoded[0].as_ptr(),
binary[binary.len() - entry.len()..].as_ptr()
);
drop(binary);
assert_eq!(decoded[0].as_ref(), entry);
let legacy = rmp_serde::to_vec(&(1.0, vec![entry.clone()])).unwrap();
assert_eq!(
LxMessage::unpack_propagation_wrapper_bounded(&legacy, legacy.len())
.unwrap()
.1,
vec![entry]
);
}
#[test]
fn bounded_propagation_wrapper_rejects_forged_counts_and_lengths_before_allocation() {
let forged_count = [0x92, 0x01, 0xdd, 0xff, 0xff, 0xff, 0xff];
assert!(
LxMessage::unpack_propagation_wrapper_owned(
Bytes::copy_from_slice(&forged_count),
usize::MAX
)
.is_err()
);
for marker in [0xdd, 0xc6] {
let mut forged_length = vec![0x92, 0x01, 0x91, marker, 0xff, 0xff, 0xff, 0xff];
forged_length.resize(1024, 0);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&forged_length, 1024).is_err());
}
let mut trailing = rmp_serde::to_vec(&(1.0, Vec::<Vec<u8>>::new())).unwrap();
trailing.push(0);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&trailing, trailing.len()).is_err());
}
fn resumable_identity() -> rns_identity::identity::Identity {
let mut key = [0x11; 64];
key[32..].fill(0x22);
rns_identity::identity::Identity::from_private_key(&key).unwrap()
}
fn resumable_signed(
identity: &rns_identity::identity::Identity,
cost: Option<u8>,
) -> SignedLxMessage {
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
let mut draft = LxMessageDraft::new(
[0x5a; 16],
source,
"Resume",
"Hello",
DeliveryMethod::Direct,
)
.unwrap();
draft.set_timestamp(1_700_000_000.).unwrap();
draft.stamp_cost = cost;
draft.sign(&identity.get_signing_key().unwrap()).unwrap()
}
#[test]
fn resumable_form_bytes_are_pinned() {
let signed = resumable_signed(&resumable_identity(), Some(8));
let stored = signed.to_resumable();
let bytes = stored.as_bytes().to_vec();
let wire = signed.finalize(None).unwrap().wire_bytes().to_vec();
assert_eq!(bytes[..96], wire[..96], "the signed header leads");
assert_eq!(bytes[96..100], [0xc1, b'L', b'X', b'R']);
assert_eq!(bytes[100], 1, "version");
assert_eq!(bytes[101..103], [1, 8], "stamp-cost floor");
assert_eq!(bytes[103], 0, "no recipient stamp yet");
assert_eq!(bytes[104..108], [0; 4], "no propagation envelope yet");
let digest_at = bytes.len() - 16;
assert_eq!(
bytes[108..digest_at],
wire[96..],
"the signed payload follows"
);
assert_eq!(bytes[digest_at..], sha256(&bytes[..digest_at])[..16]);
// Source hash and signature checked against Python RNS 1.5.5.
assert_eq!(
hex::encode(&bytes),
concat!(
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
"58ead48e0227a546df7a9712ea53572c",
"cbdadee740fb728eef746f5e23c3bc3121fcaea60eaff41eb4d011d4ae64eb8f",
"8a900be403ca81baac788cf29bd9d64cab486ff0c3923571f11e4a21b4c34005",
"c14c5852",
"01",
"0108",
"00",
"00000000",
"94cb41d954fc40000000c406526573756d65c40548656c6c6f80",
"370fdcdb14f43dd52931349474302403",
)
);
}
#[test]
fn resumable_form_is_not_a_wire_message() {
for _ in 0..64 {
let identity = rns_identity::identity::Identity::new();
let stored = resumable_signed(&identity, None).to_resumable();
assert!(LxMessage::unpack(stored.as_bytes()).is_err());
assert!(
LxMessage::unpack_owned(
Bytes::copy_from_slice(stored.as_bytes()),
MessageDecodeLimits::default()
)
.is_err()
);
}
}
#[test]
fn resumable_form_round_trips_and_rejects_damage() {
let stored = resumable_signed(&resumable_identity(), Some(8)).to_resumable();
let bytes = stored.as_bytes().to_vec();
assert_eq!(
ResumableLxMessage::from_bytes(bytes.clone()).unwrap(),
stored
);
for at in 0..bytes.len() {
let mut damaged = bytes.clone();
damaged[at] ^= 0x01;
assert!(
ResumableLxMessage::from_bytes(damaged).is_err(),
"flipped byte {at} accepted"
);
assert!(ResumableLxMessage::from_bytes(bytes[..at].to_vec()).is_err());
}
let redigest = |mut bytes: Vec<u8>| {
let at = bytes.len() - 16;
let digest = sha256(&bytes[..at]);
bytes[at..].copy_from_slice(&digest[..16]);
bytes
};
for (at, value) in [(100, 2), (101, 2), (103, 7), (108, 0x95)] {
let mut unknown = bytes.clone();
unknown[at] = value;
assert!(
ResumableLxMessage::from_bytes(redigest(unknown)).is_err(),
"byte {at} = {value:#x} accepted"
);
}
}
+532 -38
View File
@@ -2,12 +2,15 @@
//!
//! Python reference: LXMF/LXMPeer.py.
use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::constants::*;
use crate::types::PropagationTransientId;
type StoredPeer = (
type LegacyStoredPeer = (
Vec<u8>,
f64,
u32,
@@ -19,6 +22,133 @@ type StoredPeer = (
Vec<Vec<u8>>,
);
const STORED_PEER_VERSION: u8 = 2;
const MAX_PEER_METADATA_ENTRIES: usize = 16;
const MAX_PEER_METADATA_VALUE_BYTES: usize = 1024;
const MAX_PEER_METADATA_BYTES: usize = 4096;
fn bounded_peer_metadata(metadata: Option<HashMap<u8, Vec<u8>>>) -> Option<HashMap<u8, Vec<u8>>> {
let metadata = metadata?;
let mut entries = metadata.into_iter().collect::<Vec<_>>();
entries.sort_by_key(|(key, _)| *key);
let mut retained = HashMap::new();
let mut retained_bytes = 0usize;
for (key, value) in entries.into_iter().take(MAX_PEER_METADATA_ENTRIES) {
if value.len() > MAX_PEER_METADATA_VALUE_BYTES {
continue;
}
let entry_bytes = 1usize.saturating_add(value.len());
if retained_bytes.saturating_add(entry_bytes) > MAX_PEER_METADATA_BYTES {
continue;
}
retained_bytes += entry_bytes;
retained.insert(key, value);
}
Some(retained)
}
/// Versioned peer persistence used by propagation sync.
///
/// The original Rust format was a nine-element tuple. Readers continue to
/// accept that tuple, while new writes retain the announce-derived policy
/// needed to prepare a correct outbound offer after restart.
#[derive(Debug, Serialize, Deserialize)]
struct StoredPeerV2 {
version: u8,
destination_hash: Vec<u8>,
last_sync: f64,
unreachable_count: u32,
peering_cost: u8,
stamp_cost: Option<u8>,
stamp_cost_flexibility: Option<u8>,
autopeered: bool,
is_static: bool,
handled_ids: Vec<Vec<u8>>,
peering_timebase: f64,
propagation_transfer_limit: Option<f64>,
propagation_sync_limit: Option<f64>,
peering_key: Option<(Vec<u8>, u32)>,
metadata: Option<HashMap<u8, Vec<u8>>>,
last_heard: f64,
alive: bool,
}
/// Immutable inputs for one outbound propagation offer.
///
/// `LxmPeer` remains the authoritative mutable owner. The network task gets a
/// clone of this snapshot so offer selection cannot silently fall back to a
/// newly-created peer that lacks announce or handled-message state.
#[derive(Debug, Clone, PartialEq)]
pub struct OutboundOfferPolicy {
pub peer_hash: [u8; 16],
pub handled_messages: HashSet<PropagationTransientId>,
pub stamp_cost: Option<u8>,
pub stamp_cost_flexibility: Option<u8>,
pub minimum_stamp_cost: u8,
pub peering_cost: u8,
pub propagation_transfer_limit: Option<f64>,
pub propagation_sync_limit: Option<f64>,
pub peering_key: Vec<u8>,
pub peering_key_value: Option<u32>,
pub peering_timebase: f64,
pub autopeered: bool,
pub is_static: bool,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
}
impl OutboundOfferPolicy {
/// Compatibility policy for callers that only know a peer hash.
///
/// This preserves the old unbounded selection behavior. Production
/// callers should construct a snapshot from the authoritative `LxmPeer`.
pub fn unrestricted(peer_hash: [u8; 16]) -> Self {
Self {
peer_hash,
handled_messages: HashSet::new(),
stamp_cost: None,
stamp_cost_flexibility: None,
minimum_stamp_cost: 0,
peering_cost: PEERING_COST,
propagation_transfer_limit: None,
propagation_sync_limit: None,
peering_key: Vec::new(),
peering_key_value: None,
peering_timebase: 0.0,
autopeered: false,
is_static: false,
metadata: None,
}
}
pub(crate) fn to_peer(&self) -> LxmPeer {
let mut peer = LxmPeer::new(self.peer_hash);
self.apply_to_peer(&mut peer);
peer
}
pub(crate) fn apply_to_peer(&self, peer: &mut LxmPeer) {
if self.peering_timebase >= peer.peering_timebase {
peer.peering_timebase = self.peering_timebase;
peer.stamp_cost = self.stamp_cost;
peer.stamp_cost_flexibility = self.stamp_cost_flexibility;
peer.peering_cost = self.peering_cost;
peer.propagation_transfer_limit = self.propagation_transfer_limit;
peer.propagation_sync_limit = self.propagation_sync_limit;
peer.peering_key = self.peering_key_value.and_then(|value| {
let stamp: [u8; 32] = self.peering_key.clone().try_into().ok()?;
Some((stamp, value))
});
peer.autopeered = self.autopeered;
peer.is_static = self.is_static;
peer.metadata = self.metadata.clone();
}
peer.handled_messages
.extend(self.handled_messages.iter().copied());
}
}
/// An LXMF peer propagation node.
#[derive(Debug)]
pub struct LxmPeer {
@@ -34,11 +164,12 @@ pub struct LxmPeer {
pub stamp_cost_flexibility: Option<u8>,
/// Peering cost used for outbound peering-key generation.
pub peering_cost: u8,
/// Generated peering key `(stamp, value)`. `None` until [`LxmPeer::generate_peering_key`] succeeds.
/// Cached peering stamp and work value, generated or restored from storage.
/// Use [`Self::peering_key_ready`] to check it against the current cost.
pub peering_key: Option<([u8; 32], u32)>,
/// Per-transfer propagation limit in KB.
/// Per-transfer propagation limit in decimal kilobytes (1 kB = 1000 bytes).
pub propagation_transfer_limit: Option<f64>,
/// Per-sync propagation limit in KB.
/// Per-sync propagation limit in decimal kilobytes (1 kB = 1000 bytes).
pub propagation_sync_limit: Option<f64>,
pub currently_transferring_messages: Option<Vec<PropagationTransientId>>,
pub link_alive: bool,
@@ -58,11 +189,15 @@ pub struct LxmPeer {
pub last_sync_attempt: f64,
pub next_sync_attempt: f64,
pub sync_backoff: f64,
pub metadata: Option<Vec<u8>>,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
/// Last local propagation-store revision conclusively processed by this
/// peer. This is intentionally process-local because node revisions reset
/// when the store is reconstructed at startup.
pub last_offer_generation: u64,
/// Static peers are operator-configured; autopeered peers come from announces.
pub is_static: bool,
/// Message hashes already handled by this peer, for sync filtering.
pub handled_messages: std::collections::HashSet<PropagationTransientId>,
pub handled_messages: HashSet<PropagationTransientId>,
}
impl LxmPeer {
@@ -100,8 +235,9 @@ impl LxmPeer {
next_sync_attempt: 0.0,
sync_backoff: 0.0,
metadata: None,
last_offer_generation: 0,
is_static: false,
handled_messages: std::collections::HashSet::new(),
handled_messages: HashSet::new(),
}
}
@@ -118,22 +254,127 @@ impl LxmPeer {
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> Self {
Self::from_announce_with_metadata(
destination_hash,
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
None,
)
}
/// Construct a peer from announce data, retaining bounded metadata.
#[allow(clippy::too_many_arguments)]
pub fn from_announce_with_metadata(
destination_hash: [u8; 16],
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> Self {
let mut peer = Self::new(destination_hash);
peer.peering_timebase = timebase;
peer.propagation_transfer_limit = transfer_limit;
peer.propagation_sync_limit = sync_limit;
peer.propagation_sync_limit = sync_limit.or(transfer_limit);
peer.stamp_cost = stamp_cost;
peer.stamp_cost_flexibility = stamp_flexibility;
peer.peering_cost = peering_cost.unwrap_or(PEERING_COST);
peer.metadata = bounded_peer_metadata(metadata);
peer.autopeered = true;
peer
}
/// Effective minimum stamp cost this peer will accept.
/// Refresh policy when the supplied `timebase` is newer. The caller must
/// keep both supplied and stored timebases finite; this method does not
/// validate them, and NaN bypasses the ordering guard.
///
/// Returns `true` when updated. Handled messages and static-peer status are
/// retained. Calling `heard()` updates liveness/last-heard and resets the
/// unreachable count and sync backoff; the next sync attempt is reset to zero.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> bool {
let metadata = self.metadata.clone();
self.refresh_from_announce_with_metadata(
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
)
}
/// Refresh policy and bounded metadata with the ordering and liveness
/// behavior of [`Self::refresh_from_announce`]. Both supplied and stored
/// timebases must be finite; this method does not reject NaN.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce_with_metadata(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> bool {
if timebase <= self.peering_timebase {
return false;
}
let offer_constraints_changed = self.propagation_transfer_limit != transfer_limit
|| self.propagation_sync_limit != sync_limit.or(transfer_limit)
|| self.stamp_cost != stamp_cost
|| self.stamp_cost_flexibility != stamp_flexibility
|| self.peering_cost != peering_cost.unwrap_or(PEERING_COST);
self.peering_timebase = timebase;
self.propagation_transfer_limit = transfer_limit;
self.propagation_sync_limit = sync_limit.or(transfer_limit);
self.stamp_cost = stamp_cost;
self.stamp_cost_flexibility = stamp_flexibility;
self.peering_cost = peering_cost.unwrap_or(PEERING_COST);
self.metadata = bounded_peer_metadata(metadata);
if offer_constraints_changed {
self.last_offer_generation = 0;
}
// A key remains usable when it still meets the new target. Otherwise
// the daemon must generate a replacement before taking a snapshot.
if self
.peering_key
.is_some_and(|(_, value)| value < self.peering_cost as u32)
{
self.peering_key = None;
}
self.heard();
self.next_sync_attempt = 0.0;
true
}
/// Effective minimum stamp cost this peer will accept, using the peer's
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
match self.stamp_cost {
Some(cost) => cost.saturating_sub(PROPAGATION_COST_FLEX),
Some(cost) => {
cost.saturating_sub(self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX))
}
None => 0,
}
}
@@ -142,6 +383,11 @@ impl LxmPeer {
self.stamp_cost.is_some() && self.stamp_cost_flexibility.is_some()
}
/// Snapshot the complete immutable policy for one outbound sync offer.
pub fn outbound_offer_policy(&self) -> OutboundOfferPolicy {
OutboundOfferPolicy::from(self)
}
pub fn add_unhandled_message(&mut self) {
self.unhandled_count_cached = false;
self.unhandled_count += 1;
@@ -171,27 +417,50 @@ impl LxmPeer {
self.handled_messages.contains(hash)
}
pub fn needs_offer_generation(&self, generation: u64) -> bool {
generation > self.last_offer_generation
}
pub fn mark_offer_generation_processed(&mut self, generation: u64) {
self.last_offer_generation = self.last_offer_generation.max(generation);
}
/// Serialize peer state, including handled messages, for persistence.
pub fn to_bytes_with_handled(&self) -> Vec<u8> {
let handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
let data = (
self.destination_hash.to_vec(),
self.last_sync,
self.unreachable_count,
self.peering_cost,
self.stamp_cost,
self.stamp_cost_flexibility,
self.autopeered,
self.is_static,
handled,
);
rmp_serde::to_vec(&data).unwrap_or_default()
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
handled.sort();
let data = StoredPeerV2 {
version: STORED_PEER_VERSION,
destination_hash: self.destination_hash.to_vec(),
last_sync: self.last_sync,
unreachable_count: self.unreachable_count,
peering_cost: self.peering_cost,
stamp_cost: self.stamp_cost,
stamp_cost_flexibility: self.stamp_cost_flexibility,
autopeered: self.autopeered,
is_static: self.is_static,
handled_ids: handled,
peering_timebase: self.peering_timebase,
propagation_transfer_limit: self.propagation_transfer_limit,
propagation_sync_limit: self.propagation_sync_limit,
peering_key: self
.peering_key
.map(|(stamp, value)| (stamp.to_vec(), value)),
metadata: self.metadata.clone(),
last_heard: self.last_heard,
alive: self.alive,
};
rmp_serde::to_vec_named(&data).unwrap_or_default()
}
/// Deserialize peer state, including handled messages, from [`to_bytes_with_handled`] output.
///
/// [`to_bytes_with_handled`]: Self::to_bytes_with_handled
pub fn from_bytes_with_handled(data: &[u8]) -> Option<Self> {
if let Ok(stored) = rmp_serde::from_slice::<StoredPeerV2>(data) {
return Self::from_stored_v2(stored);
}
let (
dest_hash_vec,
last_sync,
@@ -202,7 +471,7 @@ impl LxmPeer {
autopeered,
is_static,
handled_vec,
): StoredPeer = rmp_serde::from_slice(data).ok()?;
): LegacyStoredPeer = rmp_serde::from_slice(data).ok()?;
if dest_hash_vec.len() != 16 {
return None;
}
@@ -231,6 +500,39 @@ impl LxmPeer {
Some(peer)
}
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
if stored.version != STORED_PEER_VERSION || stored.destination_hash.len() != 16 {
return None;
}
let mut destination_hash = [0u8; 16];
destination_hash.copy_from_slice(&stored.destination_hash);
let mut peer = Self::new(destination_hash);
peer.last_sync = stored.last_sync;
peer.unreachable_count = stored.unreachable_count;
peer.peering_cost = stored.peering_cost;
peer.stamp_cost = stored.stamp_cost;
peer.stamp_cost_flexibility = stored.stamp_cost_flexibility;
peer.autopeered = stored.autopeered;
peer.is_static = stored.is_static;
peer.peering_timebase = stored.peering_timebase;
peer.propagation_transfer_limit = stored.propagation_transfer_limit;
peer.propagation_sync_limit = stored.propagation_sync_limit;
peer.peering_key = stored.peering_key.and_then(|(stamp, value)| {
let stamp: [u8; 32] = stamp.try_into().ok()?;
Some((stamp, value))
});
peer.metadata = stored.metadata;
peer.last_heard = stored.last_heard;
peer.alive = stored.alive;
peer.handled_messages = stored
.handled_ids
.into_iter()
.filter_map(|value| value.try_into().ok())
.collect();
Some(peer)
}
pub fn mark_unreachable(&mut self) {
self.unreachable_count += 1;
let now = now_f64();
@@ -252,13 +554,15 @@ impl LxmPeer {
self.sync_backoff
}
/// Peers unseen for [`PEER_STALE_TIME`] are stale and should be rotated to the back of the queue.
/// Whether more than [`PEER_STALE_TIME`] seconds have elapsed since last heard.
/// This check does not rotate or remove the peer.
pub fn is_stale(&self) -> bool {
let now = now_f64();
now - self.last_heard > PEER_STALE_TIME as f64
}
/// Whether the peering key has been generated and meets [`Self::peering_cost`].
/// Whether a cached key's recorded work value meets [`Self::peering_cost`].
/// This trusts the stored/public value; it does not revalidate the key.
pub fn peering_key_ready(&self) -> bool {
if let Some((_, value)) = self.peering_key {
value >= self.peering_cost as u32
@@ -267,7 +571,8 @@ impl LxmPeer {
}
}
/// Peering-key value (leading zero bits), if generated.
/// Cached peering-key work value (leading zero bits), if present.
/// Restored or caller-supplied values are returned without recomputation.
pub fn peering_key_value(&self) -> Option<u32> {
self.peering_key.map(|(_, value)| value)
}
@@ -277,7 +582,12 @@ impl LxmPeer {
/// Key material is `peer_identity_hash || our_identity_hash` (16 + 16 bytes), run through the
/// stamp PoW system with [`STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING`] expand rounds.
///
/// Python reference: `LXMPeer.generate_peering_key` — LXMPeer.py:242-265.
/// Returns immediately when a key is already cached; it does not revalidate
/// that key against a changed cost. Use [`Self::peering_key_ready`] for that
/// check. Otherwise runs synchronous proof of work with
/// [`crate::stamper::generate_stamp`]'s attempt budget.
///
/// Python reference: `LXMPeer.generate_peering_key`.
pub fn generate_peering_key(
&mut self,
peer_identity_hash: &[u8; 16],
@@ -329,7 +639,7 @@ impl LxmPeer {
/// `next_sync_attempt` so sync can proceed immediately, updates `last_heard`, and marks the
/// peer alive.
///
/// Python reference: LXMPeer.py:530-538.
/// This updates local peer state; it does not identify the link or start a sync.
pub fn link_established(&mut self, _link_id: [u8; 16], establishment_rate: Option<f64>) {
if let Some(rate) = establishment_rate {
self.link_establishment_rate = rate;
@@ -341,12 +651,10 @@ impl LxmPeer {
self.link_alive = true;
}
/// Link-closed callback: clears the link and transitions to [`PeerState::Idle`].
/// Clear the link-alive flag and transition to [`PeerState::Idle`].
///
/// If the peer was mid-sync, the in-flight transfer list is cleared so backoff logic
/// treats it as a sync failure.
///
/// Python reference: LXMPeer.py:540-542.
/// If the previous state was active, clear the in-flight transfer list.
/// This callback does not itself increment backoff or mark the peer unreachable.
pub fn link_closed(&mut self) {
let was_active = self.state != PeerState::Idle;
self.link_alive = false;
@@ -372,11 +680,39 @@ impl LxmPeer {
}
}
/// Select the best peer to sync with from a set of candidates.
impl From<&LxmPeer> for OutboundOfferPolicy {
fn from(peer: &LxmPeer) -> Self {
let peering_key = peer
.peering_key
.filter(|(_, value)| *value >= peer.peering_cost as u32)
.map(|(stamp, _)| stamp.to_vec())
.unwrap_or_default();
Self {
peer_hash: peer.destination_hash,
handled_messages: peer.handled_messages.clone(),
stamp_cost: peer.stamp_cost,
stamp_cost_flexibility: peer.stamp_cost_flexibility,
minimum_stamp_cost: peer.minimum_accepted_stamp_cost(),
peering_cost: peer.peering_cost,
propagation_transfer_limit: peer.propagation_transfer_limit,
propagation_sync_limit: peer.propagation_sync_limit,
peering_key,
peering_key_value: peer.peering_key.map(|(_, value)| value),
peering_timebase: peer.peering_timebase,
autopeered: peer.autopeered,
is_static: peer.is_static,
metadata: peer.metadata.clone(),
}
}
}
/// Return the input index of an idle peer with unhandled messages.
///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
/// mix in unknown-speed peers, and fall back to unresponsive peers that have passed their sync
/// backoff.
/// Alive peers take priority: sort them by descending transfer rate and choose
/// the first. This selection is deterministic; adding unknown-speed peers to
/// the candidate pool does not randomize the choice as Python `sync_peers()` does.
/// If no alive peer qualifies, choose the first unresponsive peer whose backoff
/// has elapsed. Backoff is not checked in the alive-peer branch.
pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option<usize> {
if peers.is_empty() {
return None;
@@ -465,6 +801,164 @@ mod tests {
// cost < flex must saturate at 0.
peer.stamp_cost = Some(2);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
// Announced flexibility overrides the default.
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(5);
assert_eq!(peer.minimum_accepted_stamp_cost(), 11);
peer.stamp_cost_flexibility = Some(0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
}
#[test]
fn outbound_offer_policy_captures_authoritative_peer_state() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(3);
peer.propagation_transfer_limit = Some(1.5);
peer.propagation_sync_limit = Some(4.5);
peer.peering_cost = 18;
peer.peering_key = Some(([0x77; 32], 18));
peer.add_handled_message(&tid(0x11));
let policy = peer.outbound_offer_policy();
assert_eq!(policy.peer_hash, [0xAA; 16]);
assert_eq!(policy.minimum_stamp_cost, 13);
assert_eq!(policy.propagation_transfer_limit, Some(1.5));
assert_eq!(policy.propagation_sync_limit, Some(4.5));
assert_eq!(policy.peering_key, vec![0x77; 32]);
assert!(policy.handled_messages.contains(&tid(0x11)));
}
#[test]
fn stale_announce_cannot_overwrite_newer_peer_policy() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
200.0,
Some(2.0),
Some(8.0),
Some(16),
Some(3),
Some(18),
);
assert!(!peer.refresh_from_announce(
199.0,
Some(1.0),
Some(4.0),
Some(8),
Some(1),
Some(4),
));
assert_eq!(peer.peering_timebase, 200.0);
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
assert_eq!(peer.stamp_cost, Some(16));
peer.peering_key = Some(([0x55; 32], 18));
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
assert_eq!(peer.propagation_sync_limit, Some(3.0));
assert_eq!(peer.stamp_cost, Some(20));
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
}
#[test]
fn peer_persistence_retains_offer_policy_and_reads_legacy_tuple() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
1234.0,
Some(1.25),
Some(9.5),
Some(16),
Some(3),
Some(18),
);
peer.peering_key = Some(([0x66; 32], 19));
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
peer.add_handled_message(&tid(0x22));
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.peering_timebase, 1234.0);
assert_eq!(restored.propagation_transfer_limit, Some(1.25));
assert_eq!(restored.propagation_sync_limit, Some(9.5));
assert_eq!(restored.peering_key, Some(([0x66; 32], 19)));
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
assert!(restored.has_handled(&tid(0x22)));
let legacy: LegacyStoredPeer = (
vec![0xBB; 16],
42.0,
2,
18,
Some(12),
Some(2),
true,
false,
vec![tid(0x33).to_vec()],
);
let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap();
let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap();
assert_eq!(restored_legacy.destination_hash, [0xBB; 16]);
assert_eq!(restored_legacy.stamp_cost, Some(12));
assert!(restored_legacy.has_handled(&tid(0x33)));
}
#[test]
fn announce_metadata_is_typed_bounded_and_persisted() {
let mut metadata = HashMap::new();
metadata.insert(0, b"node name".to_vec());
metadata.insert(1, vec![0xAA; MAX_PEER_METADATA_VALUE_BYTES + 1]);
for key in 2..=30 {
metadata.insert(key, vec![key; 8]);
}
let peer = LxmPeer::from_announce_with_metadata(
[0xAA; 16],
10.0,
Some(1.0),
Some(2.0),
Some(12),
Some(3),
Some(18),
Some(metadata),
);
let retained = peer.metadata.as_ref().unwrap();
assert_eq!(retained.get(&0), Some(&b"node name".to_vec()));
assert!(!retained.contains_key(&1));
assert!(retained.len() <= MAX_PEER_METADATA_ENTRIES);
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.metadata, peer.metadata);
let empty = LxmPeer::from_announce_with_metadata(
[0xBB; 16],
10.0,
None,
None,
None,
None,
None,
Some(HashMap::new()),
);
assert_eq!(empty.metadata, Some(HashMap::new()));
}
#[test]
fn newer_policy_invalidates_processed_store_generation() {
let mut peer =
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None);
peer.mark_offer_generation_processed(7);
assert!(!peer.needs_offer_generation(7));
assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None));
assert!(peer.needs_offer_generation(7));
peer.mark_offer_generation_processed(7);
assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None));
assert!(
!peer.needs_offer_generation(7),
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
);
}
/// T0-4: an absurd announce-supplied peering cost must fail the bounded
+372 -31
View File
@@ -1,14 +1,18 @@
//! 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>`
//! * `outbound_stamp_costs` — destination stamp costs and observation times
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — delivered transient IDs and timestamps
//! * `locally_processed` — processed transient IDs and timestamps
//! * `node_stats` — propagation-node counters
//! * `propagation_suppression_v1` — bounded download suppression records
//! * `propagation_node_policies_v1` — recorded propagation-node policies
//!
//! 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.
//! These files use the Rust types' MessagePack representations; matching Python
//! filenames does not establish interchangeable contents. Missing files yield
//! empty/default state. Other I/O, malformed-data and capacity errors propagate
//! to the caller.
use std::collections::HashMap;
use std::fs;
@@ -16,13 +20,94 @@ use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::Ticket;
use crate::ticket::{Ticket, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
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";
/// 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,22 +115,37 @@ 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<()> {
@@ -56,12 +156,98 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &[Ticket]) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), &tickets)
/// Process-local revision of a captured ticket state. All production ticket
/// writes pass through the same path coordinator, so a delayed checkpoint can
/// never replace a ticket that a newer signing intent already committed.
#[derive(Debug, Clone)]
pub(crate) struct TicketPersistenceSnapshot {
revision: u64,
snapshot: std::sync::Arc<TicketStoreSnapshot>,
}
impl TicketPersistenceSnapshot {
pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
// Rust 1.99 renamed this operation; keep the identical Rust 1.89 API.
#[allow(deprecated)]
let revision = NEXT
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
.expect("ticket checkpoint revision exhausted");
Self {
revision,
snapshot: std::sync::Arc::new(snapshot),
}
}
pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> {
use std::sync::{Mutex, OnceLock};
struct Latest {
revision: u64,
committed: bool,
}
static WRITERS: OnceLock<Mutex<HashMap<std::path::PathBuf, Latest>>> = OnceLock::new();
fs::create_dir_all(dir)?;
let path = fs::canonicalize(dir)?.join(TICKETS_FILE);
let mut writers = WRITERS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?;
if !writers.contains_key(&path) && writers.len() >= 4096 {
return Err(io::Error::other("ticket persistence path quota exhausted"));
}
let latest = writers.entry(path.clone()).or_insert(Latest {
revision: self.revision,
committed: false,
});
if self.revision < latest.revision {
if !latest.committed {
return Err(io::Error::other(
"newer ticket checkpoint is uncertain and must be retried",
));
}
if let Some(required) = required {
let (stored, _) = load_tickets(dir)?;
if !stored.inbound.contains(required) {
return Err(io::Error::other(
"newer ticket state no longer contains this signing intent",
));
}
}
return Ok(());
}
if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) {
return Err(io::Error::other(
"ticket snapshot does not contain this signing intent",
));
}
latest.revision = self.revision;
latest.committed = false;
// Even an uncertain publication raises the revision floor. Older
// snapshots fail closed until this or a newly captured current state
// reestablishes the strict barrier. No failed payload is retained by
// this bounded process-wide metadata coordinator.
write_mpk(&path, &*self.snapshot)?;
latest.committed = true;
Ok(())
}
}
pub fn load_tickets(dir: &Path) -> io::Result<Vec<Ticket>> {
Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default())
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None)
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PersistedTickets {
Directional(TicketStoreSnapshot),
Legacy(Vec<Ticket>),
}
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
None => (TicketStoreSnapshot::default(), None),
})
}
pub fn save_local_deliveries(
@@ -86,6 +272,17 @@ pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTrans
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
}
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
let bytes = rmp_serde::to_vec_named(stats)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
fs::create_dir_all(dir)?;
write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes)
}
pub fn load_node_stats(dir: &Path) -> io::Result<PersistedNodeStats> {
Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -111,12 +308,26 @@ mod tests {
#[test]
fn tickets_roundtrip() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
let tickets = TicketStoreSnapshot {
version: 1,
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
};
save_tickets(tmp.path(), &tickets).unwrap();
let loaded = load_tickets(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].token, [0x01; 16]);
assert_eq!(loaded[0].destination_hash, [0x02; 16]);
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
assert!(legacy.is_none());
assert_eq!(loaded, tickets);
}
#[test]
fn legacy_flat_tickets_are_detected_for_migration() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(snapshot, TicketStoreSnapshot::default());
assert_eq!(legacy.unwrap(), tickets);
}
#[test]
@@ -133,8 +344,138 @@ mod tests {
fn missing_file_returns_default() {
let tmp = TempDir::new().unwrap();
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
assert!(load_tickets(tmp.path()).unwrap().is_empty());
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(tickets, TicketStoreSnapshot::default());
assert!(legacy.is_none());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
load_node_stats(tmp.path()).unwrap(),
PersistedNodeStats::default()
);
}
#[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:687).
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:691-693).
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);
}
}
+192
View File
@@ -0,0 +1,192 @@
//! 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.
///
/// 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
)
}
#[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);
}
}
}
+30 -11
View File
@@ -1,6 +1,7 @@
//! Store-and-forward message storage for LXMF propagation nodes.
//! In-memory propagation-entry accounting, deduplication caches and distribution queue.
//!
//! Mirrors propagation entry management in Python LXMRouter.py.
//! The owning router or node handles durable files and admission. Weight-based
//! culling uses the formula from Python `LXMRouter.get_weight`.
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -17,7 +18,7 @@ pub struct PropagationEntry {
pub stamp_value: u8,
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,
@@ -73,7 +74,11 @@ impl PropagationEntry {
/// 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.
/// defaults to 0). Shortened 32-hex transient IDs are rejected.
///
/// # Panics
/// Non-ASCII input can panic when sliced at hexadecimal byte-pair offsets.
/// Validate that untrusted filenames are ASCII before calling.
pub fn parse_filename(filename: &str) -> Option<(PropagationTransientId, f64, u8)> {
let parts: Vec<&str> = filename.split('_').collect();
match parts.len() {
@@ -93,7 +98,8 @@ impl PropagationEntry {
}
}
/// Owned by the router actor; no shared access.
/// In-memory index and accounting state. Mutations require exclusive access;
/// the owner handles synchronization, durable storage and admission policy.
#[derive(Debug, Default)]
pub struct PropagationStore {
entries: HashMap<PropagationTransientId, PropagationEntry>,
@@ -106,7 +112,8 @@ pub struct PropagationStore {
/// Prioritised destinations receive a 0.1x weight multiplier during culling.
prioritised_destinations: HashSet<[u8; 16]>,
peer_distribution_queue: VecDeque<(PropagationTransientId, Option<[u8; 16]>)>,
/// `None` disables the byte-size cap.
/// Optional byte-limit setting. This type does not enforce it automatically;
/// the owner must call culling with its chosen limit.
pub storage_limit: Option<usize>,
}
@@ -116,10 +123,21 @@ impl PropagationStore {
}
/// Returns `false` if the destination is in the ignored list.
///
/// The caller must exclude an existing transient ID before inserting.
/// Replacing one adds the new size without subtracting the previous size.
/// This method performs no persistence, stamp validation or size-limit check.
pub fn insert(&mut self, entry: PropagationEntry) -> bool {
if self.ignored_destinations.contains(&entry.destination_hash) {
return false;
}
self.insert_admitted(entry)
}
/// Account for an entry whose admission policy was checked before its
/// durable publication. Later ignore-list changes affect future admissions,
/// not a write already accepted under the node's reservation authority.
pub(crate) fn insert_admitted(&mut self, entry: PropagationEntry) -> bool {
self.total_size += entry.size;
self.entries.insert(entry.transient_id, entry);
true
@@ -171,11 +189,12 @@ impl PropagationStore {
}
}
/// Cull messages by weighted score until total size is within `limit_bytes`.
/// Remove indexed entries by weighted score until accounted size is within
/// `limit_bytes`, assuming each transient ID was inserted only once.
///
/// Score = priority_weight * age_weight * size. Evicts highest-weight first
/// (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;
@@ -292,7 +311,7 @@ impl PropagationStore {
}
/// Age out dedup-cache entries older than `MESSAGE_EXPIRY * 6` (Python
/// `LXMRouter.clean_transient_id_caches`, LXMRouter.py:956). Retention is
/// `LXMRouter.clean_transient_id_caches`). Retention is
/// purely age-based: entries must outlive their store membership so a
/// culled-and-reoffered message is still recognised as already handled.
pub fn clean_transient_caches(&mut self, now: f64) {
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
+330
View File
@@ -0,0 +1,330 @@
//! 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: u8,
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: u8,
mut contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
where
F: FnMut(&PropagationTransientId) -> bool,
{
let peering_key_valid = match offer.peering_key {
DecodedPeeringKey::Empty => peering_cost == 0,
DecodedPeeringKey::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, 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, 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, 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, usize::MAX, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[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, 1024, |_| false),
Ok(PnOfferEvaluation::WantAll)
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 1, 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, 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()])
);
}
}
+297
View File
@@ -0,0 +1,297 @@
//! Shared propagation preparation for daemon and embedding applications.
use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN;
use crate::message::{LxMessage, MessageError};
use bytes::Bytes;
use std::sync::atomic::AtomicBool;
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct AdvertisedNodePolicy {
pub stamp_cost: u8,
pub transfer_limit_kb: f64,
pub recorded_at: f64,
}
#[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: [u8; 32],
stamp: [u8; 32],
stamp_value: u32,
required_cost: u8,
}
impl PropagationEnvelope {
pub fn new<F>(
message: LxMessage,
encryption_binding: [u8; 32],
required_cost: u8,
encrypt: F,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
Self::new_cancellable(
message,
encryption_binding,
required_cost,
encrypt,
&AtomicBool::new(false),
)
}
pub fn new_cancellable<F>(
message: LxMessage,
encryption_binding: [u8; 32],
required_cost: u8,
encrypt: F,
cancel: &AtomicBool,
) -> 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, generated_value) = crate::stamper::generate_stamp_cancellable(
&transient_id,
required_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp generation failed".into()))?;
// The general stamper's cost-zero shortcut reports the required lower
// bound. Envelopes carry the measured value used by strict relay ingress.
let stamp_value = if required_cost == 0 {
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
&stamp,
)
} else {
generated_value
};
if cancel.load(std::sync::atomic::Ordering::Acquire) {
return Err(MessageError::PackFailed(
"PN stamp generation cancelled".into(),
));
}
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) -> u32 {
self.stamp_value
}
pub fn matches(&self, message: &LxMessage, encryption_binding: &[u8; 32]) -> 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, &AtomicBool::new(false))
}
pub fn pack_for_cancellable(
&mut self,
node: PreparedNode,
timestamp: f64,
cancel: &AtomicBool,
) -> Result<Vec<u8>, MessageError> {
if !timestamp.is_finite() {
return Err(MessageError::PackFailed(
"propagation timestamp must be finite".into(),
));
}
if self.stamp_value < u32::from(node.policy.stamp_cost) {
(self.stamp, self.stamp_value) = crate::stamper::generate_stamp_cancellable(
&self.transient_id,
node.policy.stamp_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp regeneration failed".into()))?;
}
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();
let resource_limit = rns_protocol::resource::MAX_EFFICIENT_SIZE
.checked_mul(rns_protocol::resource::MAX_SEGMENTS)
.unwrap_or(0);
if packed_len as f64 > limit || packed_len > resource_limit {
return Err(MessageError::TooLarge {
size: packed_len,
limit: (limit as usize).min(resource_limit),
});
}
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,
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 mut envelope = PropagationEnvelope::new(msg, [4; 32], 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,
transfer_limit_kb: 256.,
recorded_at: 100.,
},
};
let first = envelope.pack_for(prepared, 101.).unwrap();
prepared.policy.stamp_cost = 4;
let next = envelope.pack_for(prepared, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &before);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4);
assert_ne!(first, next);
assert!(
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp()
) >= 4
);
}
}
@@ -0,0 +1,475 @@
//! 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: u8,
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)
}
pub(crate) fn filename(&self) -> String {
format!(
"{}_{}",
self.entry().filename(),
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);
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,332 @@
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: u8,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryReport {
pub imported: usize,
pub already_present: usize,
}
fn validate(
record: &RecoveryEntry,
bytes: &[u8],
minimum_stamp_cost: u8,
) -> 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)?;
let workblock = crate::stamper::stamp_workblock(
&record.transient_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8;
if value < minimum_stamp_cost {
return Err(invalid("recovered stamp does not meet node policy"));
}
value
} else {
if minimum_stamp_cost > 0 {
return Err(invalid("unstamped recovery does not meet node policy"));
}
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,
}
}
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
+46 -14
View File
@@ -8,8 +8,10 @@
//! workblock. Only the expand-round count differs per kind (see
//! `STAMP_WORKBLOCK_EXPAND_ROUNDS{,_PN,_PEERING}` in constants.rs).
//!
//! Validity check: `SHA-256(workblock || stamp)` must have >= `cost` leading
//! zero bits. Matches Python's `int.from_bytes(result) <= (1 << (256-cost))`.
//! Rust validation requires at least `cost` leading zero bits in
//! `SHA-256(workblock || stamp)`. Python uses an inclusive numeric threshold,
//! `result <= 1 << (256 - cost)`; the exact equality boundary differs for
//! nonzero cost.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -80,11 +82,10 @@ pub fn stamp_valid(stamp: &[u8; 32], cost: u8, workblock: &[u8]) -> bool {
stamp_value(workblock, stamp) >= cost as u32
}
/// Give-up bound for stamp searches: 64× the expected `2^cost` work, so the
/// failure probability for an honest cost is ~e^-64 while a hostile cost can
/// no longer pin a thread forever. Costs ≥ 58 (cap would overflow u64) are
/// unsatisfiable on real hardware and fail immediately. Python has no cap and
/// blocks until success — deliberate divergence, see fix-registry.
/// Attempt budget for [`generate_stamp`] and [`generate_stamp_cancellable`]:
/// `64 * 2^cost`. Returns `None` for costs at least 58 because the budget would
/// overflow `u64`. This limits attempts, not elapsed time. Deferred stamp
/// workers use explicit cancellation and do not use this budget.
pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
if cost >= 58 {
return None;
@@ -94,8 +95,24 @@ pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
/// Single-threaded brute-force stamp search. Bounded by
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
/// cost is unsatisfiable.
/// requested cost has no supported iteration budget.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
}
/// Synchronous search with the [`stamp_iteration_cap`] attempt budget.
/// Checks cancellation before workblock construction and every 1,000 attempts;
/// workblock construction itself is not interrupted. Run on a blocking worker
/// when called from async code.
pub fn generate_stamp_cancellable(
material: &[u8],
cost: u8,
expand_rounds: usize,
cancel: &AtomicBool,
) -> Option<([u8; 32], u32)> {
if cancel.load(Ordering::Acquire) {
return None;
}
if cost == 0 {
return Some(([0u8; 32], 0));
}
@@ -107,7 +124,10 @@ pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
for iteration in 0..max_iterations {
if iteration % 1000 == 0 && cancel.load(Ordering::Acquire) {
return None;
}
let stamp = rand_bytes_from(&mut rng);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
@@ -162,7 +182,7 @@ pub fn validate_stamp(
stamp_valid(stamp, cost, &workblock)
}
/// Python reference: LXStamper.py:48-51 (`validate_peering_key`).
/// Python reference: `LXStamper.validate_peering_key`.
///
/// `peering_id` = self_identity_hash || remote_identity_hash (32 bytes typical).
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PEERING` for workblock generation.
@@ -174,7 +194,7 @@ pub fn validate_peering_key(peering_id: &[u8], peering_key: &[u8; 32], target_co
stamp_valid(peering_key, target_cost, &workblock)
}
/// Python reference: LXStamper.py:53-65 (`validate_pn_stamp`).
/// Python reference: `LXStamper.validate_pn_stamp`.
///
/// `transient_data = lxm_data || stamp` where stamp is the last 32 bytes.
/// Uses `STAMP_WORKBLOCK_EXPAND_ROUNDS_PN` for workblock generation.
@@ -205,7 +225,9 @@ pub fn validate_pn_stamp(transient_data: &[u8], target_cost: u8) -> Option<Propa
Some((transient_id, lxm_data.to_vec(), value, stamp))
}
/// 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>,
@@ -230,6 +252,11 @@ pub enum DeferredStampResult {
/// Spawn a deferred stamp-generation task on a blocking worker.
///
/// Returns a cancellation handle and a oneshot receiver for the result.
/// The search has no iteration cap; see [`spawn_deferred_stamp_on`] for its
/// cancellation contract.
///
/// # Panics
/// Panics when called outside a Tokio runtime.
#[tracing::instrument(
level = "debug",
name = "stamper.compute",
@@ -252,8 +279,13 @@ pub fn spawn_deferred_stamp(
spawn_deferred_stamp_on(&handle, message_id, cost, expand_rounds)
}
/// Handle-explicit variant: callable from `spawn_blocking` threads (no
/// implicit runtime context) — the manager tick runs there.
/// Spawn on an explicit runtime handle, without requiring a current runtime
/// context on the calling thread.
///
/// After workblock construction, a nonzero-cost search checks cancellation
/// between batches of 1,000 attempts and runs until success or cancellation.
/// It does not apply [`stamp_iteration_cap`]. Keep the cancellation handle and
/// call `cancel()` when abandoning the result.
pub fn spawn_deferred_stamp_on(
runtime: &tokio::runtime::Handle,
message_id: [u8; 32],
+20 -9
View File
@@ -1,7 +1,9 @@
//! LXMF Propagation Sync Protocol -- Offer/Get between peers.
//! Propagation offer/response values and local sync-session bookkeeping.
//!
//! The network task in [`crate::propagation_sync`] follows this exchange:
//!
//! 1. Peer A opens a Link to Peer B.
//! 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
+240 -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,130 @@ 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().find(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
}) {
return Some(ticket.clone());
}
let token: [u8; TICKET_LENGTH] = rand::random();
let ticket = Ticket::new(token, destination_hash, now + expiry_secs as f64);
self.inbound.push(ticket.clone());
Some(ticket)
}
pub fn should_issue_for(&self, destination_hash: &[u8; 16], now: f64) -> bool {
!self
.last_deliveries
.get(destination_hash)
.is_some_and(|last| now - *last < TICKET_INTERVAL as f64)
}
pub fn mark_ticket_delivered(&mut self, destination_hash: [u8; 16], delivered_at: f64) {
self.last_deliveries.insert(destination_hash, delivered_at);
}
/// Drop expired outbound tickets and inbound tickets after their grace
/// period. Delivery timestamps need only survive one interval.
pub fn cull(&mut self, now: f64) {
self.tickets
.retain(|t| !t.used && now < t.expires + TICKET_GRACE as f64);
self.outbound.retain(|_, ticket| ticket.is_valid(now));
self.inbound
.retain(|ticket| now < ticket.expires + TICKET_GRACE as f64);
self.last_deliveries
.retain(|_, delivered| now - *delivered < TICKET_INTERVAL as f64);
}
pub fn count_valid(&self, now: f64) -> usize {
self.tickets.iter().filter(|t| t.is_valid(now)).count()
self.outbound
.values()
.filter(|ticket| ticket.is_valid(now))
.count()
+ self
.inbound
.iter()
.filter(|ticket| ticket.is_valid(now))
.count()
}
/// Snapshot of all stored tickets (including expired / used).
pub fn all(&self) -> &[Ticket] {
&self.tickets
pub fn inbound(&self) -> &[Ticket] {
&self.inbound
}
/// Replace the entire ticket set — used when restoring from persisted state.
pub fn replace_all(&mut self, tickets: Vec<Ticket>) {
self.tickets = tickets;
pub fn snapshot(&self) -> TicketStoreSnapshot {
TicketStoreSnapshot {
version: ticket_store_version(),
outbound: self.outbound.values().cloned().collect(),
inbound: self.inbound.clone(),
last_deliveries: self.last_deliveries.clone(),
}
}
pub fn replace_snapshot(&mut self, snapshot: TicketStoreSnapshot) {
self.outbound = snapshot
.outbound
.into_iter()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = snapshot.inbound;
self.last_deliveries = snapshot.last_deliveries;
}
/// Migrate the legacy flat representation conservatively. Old Rust used
/// every entry for both directions, so retaining entries in both stores
/// preserves working stamps while all new state is direction-correct.
pub fn replace_legacy(&mut self, tickets: Vec<Ticket>) {
self.outbound = tickets
.iter()
.cloned()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = tickets;
self.last_deliveries.clear();
}
}
@@ -96,66 +250,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.
+560
View File
@@ -0,0 +1,560 @@
//! 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 mut envelope = PropagationEnvelope::new(msg, [6; 32], 0, |p| Ok(p.to_vec())).unwrap();
let initial = envelope.ciphertext().clone();
let tid = envelope.transient_id();
let policy = AdvertisedNodePolicy {
stamp_cost: 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;
envelope.pack_for(ready, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &initial);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4);
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]
fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
let intent = router.prepare_outbound(&mut draft).unwrap();
assert!(intent.requires_persistence());
assert!(
draft
.clone()
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.is_err()
);
let mut other =
LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap();
other.include_ticket = true;
assert!(matches!(
router.prepare_outbound(&mut other),
Err(lxmf_core::router::TicketPreparationError::PendingPersistence)
));
intent.persist(temp.path(), &mut draft).unwrap();
let msg = draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(None)
.unwrap();
assert!(
msg.fields()
.get(lxmf_core::constants::FIELD_TICKET)
.is_some()
);
let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap();
assert!(!loaded.0.inbound.is_empty());
assert!(router.prepare_outbound(&mut other).is_ok());
}
#[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 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());
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]));
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());
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);
}
#[test]
fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() {
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
let stale = router.state_snapshot();
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
let intent = router.prepare_outbound(&mut draft).unwrap();
intent.persist(temp.path(), &mut draft).unwrap();
let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0;
assert_eq!(committed.inbound.len(), 1);
stale.save_state(temp.path()).unwrap();
assert_eq!(
lxmf_core::persist::load_tickets(temp.path()).unwrap().0,
committed
);
// A newer checkpoint can commit while a draft is waiting for its exact
// intent. The old intent verifies that its ticket is still present.
drop(draft);
let mut next =
LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap();
next.include_ticket = true;
let intent = router.prepare_outbound(&mut next).unwrap();
router.state_snapshot().save_state(temp.path()).unwrap();
intent.persist(temp.path(), &mut next).unwrap();
assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok());
assert_eq!(
lxmf_core::persist::load_tickets(temp.path())
.unwrap()
.0
.inbound
.len(),
2
);
}
#[test]
fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() {
let temp = tempfile::tempdir().unwrap();
let mut ledger = SuppressionLedger::default();
ledger
.record_failure(
scope(1),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap();
assert_eq!(
lxmf_core::persist::load_suppression(temp.path())
.unwrap()
.records()
.count(),
1
);
let path = temp.path().join("propagation_suppression_v1");
let bytes = std::fs::read(&path).unwrap();
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
let rmpv::Value::Array(fields) = &mut value else {
panic!("ledger wrapper")
};
let rmpv::Value::Map(rows) = &mut fields[0] else {
panic!("ledger records")
};
rows.push(rows[0].clone());
let mut duplicate = Vec::new();
rmpv::encode::write_value(&mut duplicate, &value).unwrap();
std::fs::write(&path, duplicate).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
}
#[test]
fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() {
use rns_identity::{
announce_state::RatchetControlState,
identity::Identity,
ratchet::{RatchetRing, ReceivedRatchet},
};
let temp = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut ring = RatchetRing::new();
let public = ring.rotate_at(100.);
let ring_path = temp.path().join("ring");
ring.save_verified_durable(&ring_path, &identity).unwrap();
assert_eq!(
RatchetRing::load_verified(&ring_path, &identity)
.unwrap()
.ring()
.current_public_key(),
Some(public)
);
let control = RatchetControlState::new(identity.hash, [2; 16])
.prepare_announce(100)
.unwrap()
.unwrap();
let control_path = temp.path().join("control");
control
.save_verified_durable(&control_path, &identity)
.unwrap();
assert_eq!(
RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(),
control
);
let received = ReceivedRatchet::new_at(public, 100.);
let received_path = temp.path().join("received");
received.save_durable(&received_path).unwrap();
assert_eq!(
ReceivedRatchet::load(&received_path).unwrap().ratchet_pub,
public
);
let blocker = temp.path().join("not-a-directory");
std::fs::write(&blocker, b"preserve").unwrap();
assert!(
ring.save_verified_durable(&blocker.join("ring"), &identity)
.is_err()
);
assert!(
control
.save_verified_durable(&blocker.join("control"), &identity)
.is_err()
);
assert!(received.save_durable(&blocker.join("received")).is_err());
assert_eq!(std::fs::read(blocker).unwrap(), b"preserve");
}
+264
View File
@@ -0,0 +1,264 @@
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).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_before_success_and_old_plan_cannot_delete_readmission() {
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());
let replacement = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(replacement.persist().unwrap()));
let new_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
assert_ne!(old_path, new_path);
// The old plan fails or sees an already completed retirement; it cannot
// gain authority over the distinct new admission path.
let _ = stale.into_response();
assert!(node.contains(&tid));
assert_eq!(std::fs::read(&new_path).unwrap(), bytes);
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
}
+7 -1
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]
@@ -22,6 +24,10 @@ hex = { workspace = true }
base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { 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
+308 -30
View File
@@ -1,21 +1,24 @@
//! LXMF daemon configuration and runner.
//! LXMF daemon configuration and inbound-hook helpers.
//!
//! Python reference: LXMF/Utilities/lxmd.py.
use lxmf_core::constants::*;
use lxmf_core::propagation_admission::{
PN_DEFAULT_MAX_INBOUND_SYNCS, PN_MIN_MAX_INBOUND_SYNCS, PnInboundAdmissionConfig,
};
use lxmf_core::router::{LxmRouter, RouterConfig, RouterConfigExt};
use rns_runtime::config::{Config, ConfigSection};
/// Normalized view of Python `lxmd.apply_config()` behavior.
///
/// This intentionally mirrors Python's active_configuration keys and units.
/// It is kept separate from [`DaemonConfig`] while the daemon still has legacy
/// Rust fields and storage layout.
/// Values retain Python's configuration units before conversion into
/// [`DaemonConfig`], including decimal KB/MB and announce intervals in seconds.
#[derive(Debug, Clone, PartialEq)]
pub struct PythonLxmdConfig {
pub display_name: String,
pub peer_announce_at_start: bool,
pub peer_announce_interval: Option<i64>,
pub peer_stamp_cost: i64,
pub delivery_transfer_max_accepted_size: f64,
pub on_inbound: Option<String>,
pub enable_propagation_node: bool,
@@ -24,6 +27,9 @@ pub struct PythonLxmdConfig {
pub node_announce_at_start: bool,
pub autopeer: bool,
pub autopeer_maxdepth: Option<i64>,
pub sequential_pn_stamp_validation: bool,
pub static_peers_bypass_sequential: bool,
pub max_inbound_syncs: i64,
pub node_announce_interval: Option<i64>,
pub message_storage_limit: f64,
pub propagation_transfer_max_accepted_size: f64,
@@ -58,10 +64,13 @@ impl PythonLxmdConfig {
.to_string(),
peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false),
peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60),
peer_stamp_cost: get_int(lxmf, "stamp_cost")
.map(|value| value.max(1))
.unwrap_or(12),
delivery_transfer_max_accepted_size: get_float_or_floor(
lxmf,
"delivery_transfer_max_accepted_size",
1000.0,
1.0,
0.38,
),
on_inbound: lxmf
@@ -75,6 +84,19 @@ impl PythonLxmdConfig {
node_announce_at_start: get_bool_or(propagation, "announce_at_start", false),
autopeer: get_bool_or(propagation, "autopeer", true),
autopeer_maxdepth: get_int(propagation, "autopeer_maxdepth"),
sequential_pn_stamp_validation: get_bool_or(
propagation,
"sequential_pn_stamp_validation",
true,
),
static_peers_bypass_sequential: get_bool_or(
propagation,
"static_peers_bypass_sequential",
true,
),
max_inbound_syncs: get_int(propagation, "max_inbound_syncs")
.map(|value| value.max(PN_MIN_MAX_INBOUND_SYNCS as i64))
.unwrap_or(PN_DEFAULT_MAX_INBOUND_SYNCS as i64),
node_announce_interval: get_int(propagation, "announce_interval").map(|v| v * 60),
message_storage_limit: get_float_or_floor(
propagation,
@@ -152,6 +174,9 @@ pub struct DaemonConfig {
pub max_peers: usize,
pub autopeer: bool,
pub autopeer_maxdepth: usize,
pub sequential_pn_stamp_validation: bool,
pub static_peers_bypass_sequential: bool,
pub max_inbound_syncs: usize,
pub propagation_limit_kb: usize,
pub sync_limit_kb: usize,
pub on_inbound_command: Option<String>,
@@ -161,13 +186,12 @@ pub struct DaemonConfig {
pub control_allowed: Vec<String>,
pub static_peers: Vec<String>,
pub prioritise_destinations: Vec<String>,
pub enforce_ratchets: bool,
pub enforce_stamps: bool,
pub message_storage_limit: Option<usize>,
pub from_static_only: bool,
/// Max accepted inbound delivery transfer size in KB. Python reference:
/// Max accepted inbound delivery transfer size in decimal KB. Python reference:
/// `delivery_transfer_max_accepted_size` in `lxmd.py`.
pub delivery_transfer_max_accepted_size: usize,
pub delivery_transfer_max_accepted_size: f64,
}
impl Default for DaemonConfig {
@@ -177,7 +201,7 @@ impl Default for DaemonConfig {
node_name: None,
announce_at_start: false,
announce_interval: None,
stamp_cost: None,
stamp_cost: Some(12),
propagation_enabled: false,
outbound_propagation_node: None,
propagation_stamp_cost: PROPAGATION_COST,
@@ -187,6 +211,9 @@ impl Default for DaemonConfig {
max_peers: MAX_PEERS,
autopeer: true,
autopeer_maxdepth: AUTOPEER_MAXDEPTH,
sequential_pn_stamp_validation: true,
static_peers_bypass_sequential: true,
max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS,
propagation_limit_kb: PROPAGATION_LIMIT,
sync_limit_kb: SYNC_LIMIT,
on_inbound_command: None,
@@ -196,11 +223,13 @@ impl Default for DaemonConfig {
control_allowed: Vec::new(),
static_peers: Vec::new(),
prioritise_destinations: Vec::new(),
enforce_ratchets: false,
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
delivery_transfer_max_accepted_size: DELIVERY_LIMIT,
// Current Python LXMF 1.1.0's standalone lxmd defaults
// direct-delivery Resource admission to 1 decimal KB when the
// setting is omitted. LXMRouter's library default is separate.
delivery_transfer_max_accepted_size: 1.0,
}
}
}
@@ -221,8 +250,6 @@ impl DaemonConfig {
autopeer_maxdepth: self.autopeer_maxdepth,
peering_cost: self.peering_cost,
max_peering_cost: self.max_peering_cost,
enforce_ratchets: self.enforce_ratchets,
enforce_stamps: self.enforce_stamps,
auth_required: self.auth_required,
message_storage_limit: self.message_storage_limit,
name: self.node_name.clone(),
@@ -232,6 +259,16 @@ impl DaemonConfig {
}
}
/// Build the long-lived inbound propagation admission policy.
pub fn to_inbound_admission_config(&self) -> PnInboundAdmissionConfig {
PnInboundAdmissionConfig {
sequential_validation: self.sequential_pn_stamp_validation,
static_sequential: !self.static_peers_bypass_sequential,
max_inbound_syncs: self.max_inbound_syncs,
from_static_only: self.from_static_only,
}
}
/// Parse from `[lxmf]`, `[propagation]`, and `[control]` sections.
pub fn from_config(config: &Config) -> Self {
let py = PythonLxmdConfig::from_config(config);
@@ -240,6 +277,7 @@ impl DaemonConfig {
node_name: py.node_name,
announce_at_start: py.peer_announce_at_start,
announce_interval: seconds_to_u64(py.peer_announce_interval),
stamp_cost: normalize_peer_stamp_cost(py.peer_stamp_cost),
propagation_enabled: py.enable_propagation_node,
propagation_stamp_cost: clamp_python_cost_to_u8(
py.propagation_stamp_cost_target,
@@ -260,6 +298,9 @@ impl DaemonConfig {
.autopeer_maxdepth
.and_then(|value| usize::try_from(value).ok())
.unwrap_or(AUTOPEER_MAXDEPTH),
sequential_pn_stamp_validation: py.sequential_pn_stamp_validation,
static_peers_bypass_sequential: py.static_peers_bypass_sequential,
max_inbound_syncs: usize::try_from(py.max_inbound_syncs).unwrap_or(usize::MAX),
propagation_limit_kb: kb_to_usize_ceil(py.propagation_transfer_max_accepted_size),
sync_limit_kb: kb_to_usize_ceil(py.propagation_sync_max_accepted_size),
on_inbound_command: py.on_inbound,
@@ -271,18 +312,10 @@ impl DaemonConfig {
prioritise_destinations: py.prioritised_lxmf_destinations,
message_storage_limit: megabytes_to_bytes(py.message_storage_limit),
from_static_only: py.from_static_only,
delivery_transfer_max_accepted_size: kb_to_usize_ceil(
py.delivery_transfer_max_accepted_size,
),
delivery_transfer_max_accepted_size: py.delivery_transfer_max_accepted_size,
..DaemonConfig::default()
};
if let Some(sec) = config.section("lxmf")
&& let Some(cost) = sec.get_uint("stamp_cost")
{
dc.stamp_cost = Some(cost as u8);
}
if let Some(sec) = config.section("propagation") {
if let Some(node) = sec.get("outbound_node") {
let trimmed = node.trim();
@@ -301,7 +334,6 @@ impl DaemonConfig {
{
dc.propagation_limit_kb = limit as usize;
}
dc.enforce_ratchets = sec.get_bool_or("enforce_ratchets", false);
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -328,6 +360,13 @@ fn clamp_python_cost_to_u8(value: i64, floor: i64) -> u8 {
value.max(floor).min(u8::MAX as i64) as u8
}
/// Apply Python lxmd's signed floor, then mirror `set_inbound_stamp_cost`:
/// delivery stamp costs are valid only in `1..=254`.
fn normalize_peer_stamp_cost(value: i64) -> Option<u8> {
let cost = u8::try_from(value.max(1)).ok()?;
(cost < u8::MAX).then_some(cost)
}
fn get_float(section: Option<&ConfigSection>, key: &str) -> Option<f64> {
section.and_then(|sec| sec.get_float(key))
}
@@ -364,22 +403,137 @@ pub fn create_router_with_transport(
/// argument rather than interpolating into a shell string, so untrusted path
/// contents cannot inject shell metacharacters.
pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> {
execute_on_inbound_with_event(command, message_path, "")
}
/// Execute an inbound hook with `event_id` in the `LXMF_EVENT_ID` environment
/// variable when the identifier is nonempty. Durable propagation outbox events
/// may replay after a crash; the hook can use the identifier to deduplicate them.
pub fn execute_on_inbound_with_event(
command: &str,
message_path: &str,
event_id: &str,
) -> std::io::Result<()> {
use std::process::Command;
let parts: Vec<&str> = command.split_whitespace().collect();
let parts = split_command_line(command)?;
if parts.is_empty() {
return Ok(());
}
let mut cmd = Command::new(parts[0]);
let mut cmd = Command::new(&parts[0]);
for arg in &parts[1..] {
cmd.arg(arg);
}
cmd.arg(message_path);
if !event_id.is_empty() {
cmd.env("LXMF_EVENT_ID", event_id);
}
let status = cmd.status()?;
if !status.success() {
tracing::warn!("on_inbound command exited with status: {}", status);
return Err(std::io::Error::other(format!(
"on_inbound command exited with status: {status}"
)));
}
Ok(())
}
/// Parse the configured hook using the shell-like quoting supported by
/// Python's `shlex.split()`, without invoking a shell.
fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
use std::io::{Error, ErrorKind};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut parts = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut escaped = false;
let mut started = false;
for ch in command.chars() {
if escaped {
current.push(ch);
escaped = false;
started = true;
continue;
}
match quote {
Quote::Single => {
if ch == '\'' {
quote = Quote::None;
} else {
current.push(ch);
}
started = true;
}
Quote::Double => {
if ch == '"' {
quote = Quote::None;
} else if ch == '\\' {
escaped = true;
} else {
current.push(ch);
}
started = true;
}
Quote::None => match ch {
'\'' => {
quote = Quote::Single;
started = true;
}
'"' => {
quote = Quote::Double;
started = true;
}
'\\' => {
escaped = true;
started = true;
}
c if c.is_whitespace() => {
if started {
parts.push(std::mem::take(&mut current));
started = false;
}
}
_ => {
current.push(ch);
started = true;
}
},
}
}
if escaped || quote != Quote::None {
return Err(Error::new(
ErrorKind::InvalidInput,
"unterminated quote or escape in on_inbound command",
));
}
if started {
parts.push(current);
}
Ok(parts)
}
/// Persist a received message, then invoke the configured hook after the write
/// succeeds. This function blocks; async callers must run it on a blocking
/// worker. A hook error is returned after the message has already been saved.
pub fn persist_inbound_and_execute(
message_path: &std::path::Path,
packed: &[u8],
command: Option<&str>,
) -> std::io::Result<()> {
lxmf_core::persist::write_file_atomic(message_path, packed)?;
if let Some(command) = command {
execute_on_inbound(command, &message_path.to_string_lossy())?;
}
Ok(())
}
@@ -388,12 +542,55 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
mod tests {
use super::*;
#[test]
fn on_inbound_parser_matches_shell_like_quoting_without_a_shell() {
assert_eq!(
split_command_line("/tmp/a\\ b --label 'two words' \"\" --quoted=\"x y\"").unwrap(),
["/tmp/a b", "--label", "two words", "", "--quoted=x y"]
);
assert!(split_command_line("hook 'unterminated").is_err());
assert!(split_command_line("hook trailing\\").is_err());
}
#[cfg(unix)]
#[test]
fn inbound_hook_observes_fully_persisted_message() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let hook = dir.path().join("hook with spaces.sh");
let message = dir.path().join("message.lxm");
let observed = dir.path().join("observed");
std::fs::write(
&hook,
"#!/bin/sh\nexpected=$1\nobserved=$2\nmessage=$3\ncmp \"$expected\" \"$message\" && printf ok > \"$observed\"\n",
)
.unwrap();
let mut permissions = std::fs::metadata(&hook).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&hook, permissions).unwrap();
let expected = dir.path().join("expected");
std::fs::write(&expected, b"complete payload").unwrap();
let command = format!(
"'{}' '{}' '{}'",
hook.display(),
expected.display(),
observed.display()
);
persist_inbound_and_execute(&message, b"complete payload", Some(&command)).unwrap();
assert_eq!(std::fs::read(&message).unwrap(), b"complete payload");
assert_eq!(std::fs::read(&observed).unwrap(), b"ok");
}
#[test]
fn test_default_config() {
let dc = DaemonConfig::default();
assert_eq!(dc.display_name.as_deref(), Some("Anonymous Peer"));
assert!(!dc.announce_at_start);
assert_eq!(dc.announce_interval, None);
assert_eq!(dc.stamp_cost, Some(12));
assert!(!dc.propagation_enabled);
assert_eq!(dc.propagation_stamp_cost, 16);
assert_eq!(dc.propagation_stamp_flex, 3);
@@ -402,12 +599,19 @@ mod tests {
assert_eq!(dc.max_peers, 20);
assert!(dc.autopeer);
assert_eq!(dc.autopeer_maxdepth, AUTOPEER_MAXDEPTH);
assert!(dc.sequential_pn_stamp_validation);
assert!(dc.static_peers_bypass_sequential);
assert_eq!(dc.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS);
assert_eq!(
dc.to_inbound_admission_config(),
PnInboundAdmissionConfig::default()
);
assert_eq!(dc.propagation_limit_kb, 256);
assert_eq!(dc.sync_limit_kb, 10_240);
assert!(!dc.node_announce_at_start);
assert_eq!(dc.node_announce_interval, None);
assert_eq!(dc.message_storage_limit, Some(500_000_000));
assert_eq!(dc.delivery_transfer_max_accepted_size, 1000);
assert_eq!(dc.delivery_transfer_max_accepted_size, 1.0);
assert!(!dc.from_static_only);
}
@@ -419,7 +623,8 @@ mod tests {
assert_eq!(py.display_name, "Anonymous Peer");
assert!(!py.peer_announce_at_start);
assert_eq!(py.peer_announce_interval, None);
assert_eq!(py.delivery_transfer_max_accepted_size, 1000.0);
assert_eq!(py.peer_stamp_cost, 12);
assert_eq!(py.delivery_transfer_max_accepted_size, 1.0);
assert_eq!(py.on_inbound, None);
assert!(!py.enable_propagation_node);
assert_eq!(py.node_name, None);
@@ -427,6 +632,9 @@ mod tests {
assert!(!py.node_announce_at_start);
assert!(py.autopeer);
assert_eq!(py.autopeer_maxdepth, None);
assert!(py.sequential_pn_stamp_validation);
assert!(py.static_peers_bypass_sequential);
assert_eq!(py.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS as i64);
assert_eq!(py.node_announce_interval, None);
assert_eq!(py.message_storage_limit, 500.0);
assert_eq!(py.propagation_transfer_max_accepted_size, 256.0);
@@ -460,9 +668,13 @@ prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
control_allowed = 11111111111111111111111111111111
from_static_only = yes
max_peers = 7
sequential_pn_stamp_validation = no
static_peers_bypass_sequential = no
max_inbound_syncs = 0
[lxmf]
announce_interval = 3
stamp_cost = -9
delivery_transfer_max_accepted_size = 0.1
[logging]
@@ -473,6 +685,7 @@ loglevel = 6
assert_eq!(py.peer_announce_interval, Some(180));
assert_eq!(py.node_announce_interval, Some(120));
assert_eq!(py.peer_stamp_cost, 1);
assert_eq!(py.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(py.message_storage_limit, 0.005);
assert_eq!(py.propagation_transfer_max_accepted_size, 0.38);
@@ -491,6 +704,9 @@ loglevel = 6
["11111111111111111111111111111111"]
);
assert_eq!(py.max_peers, Some(7));
assert!(!py.sequential_pn_stamp_validation);
assert!(!py.static_peers_bypass_sequential);
assert_eq!(py.max_inbound_syncs, PN_MIN_MAX_INBOUND_SYNCS as i64);
assert!(py.from_static_only);
assert_eq!(py.target_loglevel, Some(6));
}
@@ -531,7 +747,8 @@ propagation_transfer_max_accepted_size = 12
let rc = dc.to_router_config();
assert!(!rc.propagation_enabled);
assert_eq!(rc.max_peers, 20);
assert_eq!(rc.delivery_limit_kb, 1000);
assert_eq!(rc.delivery_limit_kb, 1.0);
assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0);
assert_eq!(rc.propagation_limit_kb, 256);
assert_eq!(rc.sync_limit_kb, 10_240);
assert_eq!(rc.propagation_stamp_cost, 16);
@@ -587,6 +804,9 @@ remote_peering_cost_max = -2
max_peers = 10
autopeer = no
autopeer_maxdepth = 2
sequential_pn_stamp_validation = no
static_peers_bypass_sequential = no
max_inbound_syncs = 5
static_peers = 00112233445566778899aabbccddeeff
prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
control_allowed = 11111111111111111111111111111111
@@ -597,7 +817,7 @@ from_static_only = yes
assert_eq!(dc.display_name.as_deref(), Some("TestNode"));
assert!(dc.announce_at_start);
assert_eq!(dc.announce_interval, Some(180));
assert_eq!(dc.delivery_transfer_max_accepted_size, 1);
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(dc.stamp_cost, Some(8));
assert!(dc.propagation_enabled);
assert_eq!(dc.node_name.as_deref(), Some("PropNode"));
@@ -617,6 +837,18 @@ from_static_only = yes
assert_eq!(dc.max_peers, 10);
assert!(!dc.autopeer);
assert_eq!(dc.autopeer_maxdepth, 2);
assert!(!dc.sequential_pn_stamp_validation);
assert!(!dc.static_peers_bypass_sequential);
assert_eq!(dc.max_inbound_syncs, 5);
assert_eq!(
dc.to_inbound_admission_config(),
PnInboundAdmissionConfig {
sequential_validation: false,
static_sequential: true,
max_inbound_syncs: 5,
from_static_only: true,
}
);
assert_eq!(dc.static_peers, ["00112233445566778899aabbccddeeff"]);
assert_eq!(
dc.prioritise_destinations,
@@ -626,6 +858,38 @@ from_static_only = yes
assert!(dc.from_static_only);
}
#[test]
fn delivery_stamp_cost_matches_python_floor_and_destination_range() {
for (configured, normalized, expected) in [
(-7, 1, Some(1)),
(0, 1, Some(1)),
(254, 254, Some(254)),
(255, 255, None),
(256, 256, None),
(1000, 1000, None),
] {
let input = format!("[lxmf]\nstamp_cost = {configured}\n");
let config = rns_runtime::config::Config::parse(&input).unwrap();
let py = PythonLxmdConfig::from_config(&config);
let dc = DaemonConfig::from_config(&config);
assert_eq!(py.peer_stamp_cost, normalized, "configured {configured}");
assert_eq!(dc.stamp_cost, expected, "configured {configured}");
}
}
#[test]
fn fractional_delivery_limit_survives_daemon_and_router_config() {
let config = rns_runtime::config::Config::parse(
"[lxmf]\ndelivery_transfer_max_accepted_size = 0.38\n",
)
.unwrap();
let dc = DaemonConfig::from_config(&config);
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(dc.to_router_config().delivery_limit_kb, 0.38);
}
#[test]
fn test_parse_python_stamp_target_key_with_floor() {
let input = r#"
@@ -654,4 +918,18 @@ propagation_stamp_cost = 19
assert_eq!(dc.propagation_stamp_cost, 19);
assert_eq!(dc.to_router_config().propagation_stamp_cost, 19);
}
/// Python lxmd exposes no enforce_ratchets option; the key must parse as a no-op.
#[test]
fn test_enforce_ratchets_key_ignored_matching_python_lxmd() {
let input = r#"
[propagation]
enforce_ratchets = yes
enforce_stamps = yes
"#;
let config = rns_runtime::config::Config::parse(input).unwrap();
let dc = DaemonConfig::from_config(&config);
assert!(dc.enforce_stamps);
}
}
+47 -15
View File
@@ -46,6 +46,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 +79,12 @@ pub struct Args {
#[arg(long)]
pub exampleconfig: bool,
/// Run as a system service (no interactive output).
/// Default to warning-level logging for service use; -v/-q override this.
/// The process remains in the foreground.
#[arg(short = 's', long)]
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 +108,32 @@ 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>
/// Send a single message and exit: `--send <dest_hash> <content>`.
#[arg(long, num_args = 1..=2, 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>,
}
@@ -180,6 +200,16 @@ autopeer = yes
autopeer_maxdepth = 6
# Validate inbound propagation stamp batches sequentially by default.
# sequential_pn_stamp_validation = yes
# Let configured static peers bypass sequential validation and inbound limits.
# static_peers_bypass_sequential = yes
# Threshold for new inbound propagation sync offers. Already accepted offers
# and static-peer bypass can exceed this value.
# max_inbound_syncs = 3
# message_storage_limit = 500
# propagation_message_max_accepted_size = 256
@@ -213,7 +243,9 @@ announce_at_start = no
# announce_interval = 360
delivery_transfer_max_accepted_size = 1000
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
@@ -225,9 +257,9 @@ loglevel = 4
}
/// 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]> {
+165 -53
View File
@@ -10,8 +10,11 @@ use lxmf_core::propagation_node::PropagationNode;
use lxmf_core::router::LxmRouter;
use rmpv::Value;
use rns_identity::identity::Identity;
use rns_runtime::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_transport::messages::{AnnounceHandlerEvent, TransportMessage};
use rns_transport::messages::TransportMessage;
use tokio::sync::mpsc;
pub const CONTROL_APP_NAME: &str = "lxmf.propagation.control";
@@ -42,6 +45,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 +60,46 @@ 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)),
)
.await
}
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 {
@@ -193,6 +181,9 @@ pub fn encode_router_control_stats(
.as_ref()
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.handled_messages))
.unwrap_or_else(|| peer.unhandled_messages() as usize);
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -269,7 +260,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,7 +291,7 @@ 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()),
@@ -612,12 +603,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(map_str(peer, "name").unwrap_or(""), 46);
let display_name = if name.chars().count() > 45 {
format!("{}...", name.chars().take(45).collect::<String>())
} else {
name
};
@@ -868,6 +857,99 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[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(
RecalledDestinationRpcEntry {
dest_hash: remote_destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
},
)))
.expect("return resolved identity");
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_remote_identity_hash(transport_tx, remote_destination_hash, 1.0)
.await
.expect("resolve remote identity");
assert_eq!(resolved, expected_identity_hash);
responder.await.expect("transport responder");
}
fn decode_value(data: &[u8]) -> Value {
rmpv::decode::read_value(&mut &data[..]).unwrap()
}
@@ -955,6 +1037,34 @@ 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;
@@ -964,6 +1074,7 @@ mod tests {
propagation_enabled: true,
..Default::default()
};
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);
@@ -1022,6 +1133,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;
+14 -5
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,6 +18,7 @@ pub struct LxmdPaths {
pub propagation_store_dir: PathBuf,
pub ratchets_dir: PathBuf,
pub ratchet_ring_path: PathBuf,
pub ratchet_control_path: PathBuf,
pub received_ratchets_dir: PathBuf,
pub known_identities_path: PathBuf,
pub legacy_lxmf_dir: PathBuf,
@@ -38,6 +39,7 @@ 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 ratchet_control_path = ratchets_dir.join("ring.control");
let received_ratchets_dir = ratchets_dir.join("received");
let known_identities_path = ratchets_dir.join("known_identities");
@@ -57,6 +59,7 @@ impl LxmdPaths {
propagation_store_dir,
ratchets_dir,
ratchet_ring_path,
ratchet_control_path,
received_ratchets_dir,
known_identities_path,
legacy_lxmf_dir,
@@ -333,6 +336,10 @@ mod tests {
paths.ratchet_ring_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring")
);
assert_eq!(
paths.ratchet_control_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring.control")
);
assert_eq!(
paths.received_ratchets_dir,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/received")
@@ -445,13 +452,15 @@ mod tests {
#[test]
fn delivery_announce_app_data_matches_python_msgpack() {
// Python 1.0.1: msgpack([display_name, stamp_cost, [SF_COMPRESSION]])
// — LXMRouter.py:999-1001.
assert_eq!(
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
"92c4045465737410"
"93c40454657374109100"
);
assert_eq!(
hex::encode(delivery_announce_app_data(None, None)),
"92c0c0"
"93c0c09100"
);
}
+10 -5
View File
@@ -227,11 +227,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]"));
@@ -285,7 +289,7 @@ fn clap_requires_send_argument() {
}
#[test]
fn status_and_peers_query_control_and_timeout_without_daemon() {
fn status_and_peers_fail_before_link_without_an_online_interface() {
let lxmf_dir = TestDir::new("lxmf");
let rns_dir = TestDir::new("rns");
write_rust_identity(&lxmf_dir.path().join("identity"));
@@ -319,12 +323,13 @@ discover_interfaces = No
assert_eq!(
output.status.code(),
Some(200),
"expected Python-compatible control timeout, got:\n{}",
"expected interface-readiness failure, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Getting lxmd statistics timed out, exiting now"),
"expected Python-compatible control timeout text, got:\n{}",
combined_output(&output)
.contains("No online Reticulum interface became available, exiting now"),
"expected specific interface-readiness error, got:\n{}",
combined_output(&output)
);
assert!(
+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()