Compare commits

...
Author SHA1 Message Date
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
71 changed files with 30882 additions and 6003 deletions

No files matched your search

+67 -16
View File
@@ -9,7 +9,47 @@ on:
permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: bf7d16fc36045b6d33ca0d4c85d2b35b1b20751f
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,16 +59,18 @@ 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
@@ -36,28 +78,36 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace --locked
working-directory: rsLXMF
- name: Build embedding examples
run: cargo build -p lxmf-core --examples --locked
working-directory: rsLXMF
lint:
name: Lint
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 --all-features --locked -- -D warnings
@@ -69,22 +119,23 @@ jobs:
working-directory: rsLXMF
msrv:
name: Rust 1.85 MSRV
name: Rust 1.89 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
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@1.85.0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.89.0
components: clippy
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: false
+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.1.0
RSLXMF_RSRETICULUM_VERSION: 1.4.0
RSLXMF_RSRETICULUM_COMMIT: bf7d16fc36045b6d33ca0d4c85d2b35b1b20751f
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/
+78
View File
@@ -2,6 +2,82 @@
## Unreleased
- 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.
## 1.4.0 - 2026-10-12
This section records the source-version transition. It is not a standalone
1.4.0 binary release; the published standalone release remains 1.3.0.
- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions.
- 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.
@@ -14,6 +90,8 @@
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
Generated
+37 -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,11 +645,13 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2 0.6.5",
"proptest",
"rand 0.8.5",
"rmp",
@@ -670,7 +674,7 @@ dependencies = [
[[package]]
name = "lxmf-tools"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
@@ -688,6 +692,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"zeroize",
]
[[package]]
@@ -717,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",
@@ -783,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"
@@ -790,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",
]
@@ -809,7 +823,7 @@ dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
"objc2 0.5.2",
]
[[package]]
@@ -1052,7 +1066,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1070,9 +1084,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmp-serde",
"rmpv",
@@ -1080,6 +1095,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
@@ -1088,7 +1104,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1096,7 +1112,8 @@ dependencies = [
"jni",
"libc",
"md-5",
"objc2",
"mio",
"objc2 0.5.2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
@@ -1116,9 +1133,10 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmpv",
"rns-crypto",
@@ -1126,12 +1144,13 @@ dependencies = [
"rns-wire",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1140,6 +1159,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -1147,7 +1167,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1169,11 +1189,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "rns-transport"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1192,7 +1213,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.1.0"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
+12 -12
View File
@@ -6,25 +6,25 @@ members = [
]
[workspace.package]
version = "1.1.0"
version = "1.4.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
rust-version = "1.89"
[workspace.dependencies]
# Reticulum crates from a sibling rsReticulum checkout during development.
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.1.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.1.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.1.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.1.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.1.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.1.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.1.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.1.0" }
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.1.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.1.0" }
lxmf-core = { path = "crates/lxmf-core", version = "~1.4.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.4.0" }
# Encoding
base64 = "0.22"
+69 -37
View File
@@ -5,8 +5,9 @@
**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 1.0.1](https://img.shields.io/badge/target-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![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) |
@@ -26,6 +27,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 +38,8 @@ LXMF daemons on `PATH` without worry.
## Build It
This guide describes the 1.4.0 source line at `b5c3365b5715f1f36f74963a9d2136238d956467`, used by Ratspeak 1.0.37 with rsReticulum 1.4.0. The published standalone daemon download is [v1.3.0](https://github.com/ratspeak/rsLXMF/releases/tag/v1.3.0); use [its README](https://github.com/ratspeak/rsLXMF/blob/v1.3.0/README.md) and bundled `--help` for that build. The 1.4 message and durable relay APIs require a coordinated source migration.
The current development layout for rsLXMF requires
rsReticulum as a sibling directory/repo next to it, such as:
@@ -50,9 +54,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 5b38cae702a5b3984adf12a435f6d3012fcf90e1
git -C rsLXMF checkout --detach b5c3365b5715f1f36f74963a9d2136238d956467
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 +72,7 @@ xcode-select --install
Build from the sibling checkout:
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Linux / Raspberry Pi
@@ -76,26 +83,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 +112,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 +128,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 +146,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 +160,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 +170,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 +198,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 +224,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.
@@ -249,8 +259,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 +269,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_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 +286,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 +298,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. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. Oversized opportunistic messages are downgraded to Direct by the router. |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. The router switches oversized opportunistic messages to Direct. |
| Direct | Link-backed delivery over a Reticulum Link, with resource transfer for larger content. |
| Propagated | Store-and-forward delivery through a propagation node, including deposit, retrieve, peer sync, stamps, and tickets. |
| Paper | Library support for `lxm://` URI generation and ingest. The CLI does not generate QR images. |
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,13 +319,17 @@ 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.
Library callers requesting a reply ticket set `include_ticket`, call
`LxmRouter::prepare_outbound`, and then sign the message. The router rejects a
requested ticket that would require changing an already-signed message.
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
@@ -312,7 +337,7 @@ requested ticket that would require changing an already-signed message.
| Area | Current behavior |
| --- | --- |
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct downgrade, and compression signalling in delivery announces. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct fallback, and compression signalling in delivery announces. |
| Propagation | Transactional disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
@@ -328,6 +353,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 standalone 1.3.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
+117
View File
@@ -0,0 +1,117 @@
# Rust API
This guide describes the 1.4.0 source API, not the published standalone
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)
}
}
+197
View File
@@ -0,0 +1,197 @@
# Migrating to the 1.4 source API
The 1.4 source line is used by Ratspeak 1.0.37. The published standalone
command-line download remains 1.3.0; these APIs and migration commands require
a matching 1.4 source build.
Messages now retain the exact signed bytes received or finalized for sending.
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.
+138
View File
@@ -0,0 +1,138 @@
# Relay store migration
This guide applies to the 1.4 source API and daemon. Build the matching
source before using these commands; the standalone 1.3.0 binary does not
provide this migration.
Relay nodes now admit only validated opaque propagation data to a durable store.
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>"
]
}
}
}
+1 -1
View File
@@ -1,2 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.85"
msrv = "1.89"
+9 -1
View File
@@ -1,8 +1,10 @@
[package]
name = "lxmf-core"
description = "LXMF messaging protocol implementation for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
@@ -19,13 +21,19 @@ 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 }
proptest = { 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());
}
}
+21 -10
View File
@@ -152,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;
@@ -169,7 +173,7 @@ pub const PATH_REQUEST_WAIT: u64 = 7;
pub const MAX_PATHLESS_TRIES: u32 = 1;
/// Maximum link inactivity before teardown (seconds).
pub const LINK_MAX_INACTIVITY: u64 = 10 * 60;
/// Maximum propagation link inactivity (seconds).
/// 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;
@@ -192,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;
@@ -209,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)]
@@ -259,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;
@@ -292,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);
+49 -26
View File
@@ -57,7 +57,11 @@ pub struct DeliveryRatchetState {
}
impl DeliveryRatchetState {
/// Load verified state, preserving any invalid existing files in place.
/// Load canonical or legacy Rust state, preserving rejected files in place.
/// Canonical signatures cover the packed key list. Accepted legacy signatures
/// cover only the current public key, not retained old keys; canonical rewrite
/// is best-effort and does not establish their historical authenticity.
/// A failed rewrite does not prevent use of the accepted legacy ring.
///
/// A missing ring is generated and persisted before it becomes live. A
/// ring that cannot be stored leaves delivery available but unratcheted.
@@ -87,7 +91,7 @@ impl DeliveryRatchetState {
let format = loaded.format();
let ring = loaded.into_ring();
if format == RatchetRingFormat::LegacyRust {
match ring.save_verified(&ring_path, identity) {
match ring.save_verified_durable(&ring_path, identity) {
Ok(()) => tracing::info!(
path = %ring_path.display(),
"migrated legacy Rust ratchet ring to canonical format"
@@ -145,7 +149,7 @@ impl DeliveryRatchetState {
if ring.is_empty() && ring_file_trusted && control_file_trusted {
let prepared = ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&ring_path, identity) {
match prepared.ring().save_verified_durable(&ring_path, identity) {
Ok(()) => {
ring.commit_prepared_rotation(prepared);
control = control.with_rotation_at(wall_now);
@@ -159,14 +163,15 @@ impl DeliveryRatchetState {
}
}
if control_file_trusted && (!control_existed || control_changed) {
if let Err(error) = control.save_verified(&control_path, identity) {
tracing::warn!(
path = %control_path.display(),
%error,
"could not persist initial ratchet control state; new announces remain deferred until persistence recovers"
);
}
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 {
@@ -210,13 +215,12 @@ impl DeliveryRatchetState {
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind {
if let Some(packet) = self
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind
&& let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
}
{
return Ok(packet);
}
if !self.control_file_trusted {
@@ -241,7 +245,10 @@ impl DeliveryRatchetState {
let mut ratchet_public = self.ring.current_public_key();
if rotation_due && self.ring_file_trusted {
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&self.ring_path, identity) {
match prepared
.ring()
.save_verified_durable(&self.ring_path, identity)
{
Ok(()) => {
ratchet_public = Some(prepared.public_key());
candidate_control = candidate_control.with_rotation_at(wall_now);
@@ -256,7 +263,7 @@ impl DeliveryRatchetState {
}
candidate_control
.save_verified(&self.control_path, identity)
.save_verified_durable(&self.control_path, identity)
.map_err(|source| DeliveryRatchetError::PersistControl {
path: self.control_path.clone(),
source,
@@ -292,18 +299,34 @@ impl DeliveryRatchetState {
/// 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 {
if let Err(error) = self.ring.save_verified(&self.ring_path, identity) {
tracing::warn!(%error, "failed to save ratchet ring");
}
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 {
if let Err(error) = self.control.save_verified(&self.control_path, identity) {
tracing::warn!(%error, "failed to save ratchet control state");
}
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
}
+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,
+55 -43
View File
@@ -1,7 +1,8 @@
//! 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;
@@ -55,18 +56,19 @@ pub enum CompressionSupport {
/// `[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,
@@ -111,7 +113,7 @@ impl PropagationNodeAnnounceData {
/// 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;
@@ -142,13 +144,16 @@ 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
@@ -211,7 +216,7 @@ 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)
}
@@ -222,7 +227,8 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
///
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
///
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1001 (1.0.1).
/// Names are sanitized and limited to [`MAX_ADVERTISED_NAME_CHARS`] characters.
/// Python reference: `LXMRouter.get_announce_app_data`.
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
use rmpv::Value;
@@ -246,8 +252,10 @@ pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>)
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
///
/// Accepts both Python LXMF <=0.9.8's 2-element form and the 3-element
/// feature-list form emitted from 1.0.1 (and 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()?;
@@ -268,14 +276,14 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
/// Extract just the display name from delivery-announce `app_data`.
///
/// 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)
}
@@ -285,7 +293,7 @@ pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
/// Legacy 2-element app_data, malformed data, and missing feature lists are
/// treated as unknown. A present feature list is authoritative.
///
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
/// Related Python helper: `compression_support_from_app_data`.
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return CompressionSupport::Unknown;
@@ -312,20 +320,18 @@ pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSuppor
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
///
/// Fail-open like Python: legacy 2-element app_data, malformed data, and
/// non-list feature entries all count as supported; only an explicit feature
/// list that omits `SF_COMPRESSION` disables compression.
///
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
/// 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)?;
@@ -374,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,
@@ -399,9 +408,9 @@ impl PropagationRequestHandler {
}
}
/// Handle a `/pn/get/stats` request: validates identity and access, then returns msgpack stats.
/// Return MessagePack stats when the supplied verified identity is control-allowed.
///
/// Python reference: `LXMRouter.stats_get_request` — LXMRouter.py:819-822.
/// Related Python handler: `LXMRouter.stats_get_request`.
pub fn handle_stats_request(
&self,
remote_identity_hash: Option<&[u8; 16]>,
@@ -423,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]>,
@@ -469,7 +479,9 @@ impl PropagationRequestHandler {
/// [`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]>,
@@ -494,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]>,
@@ -527,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]>,
@@ -564,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);
+15 -10
View File
@@ -62,7 +62,8 @@ impl From<InboundResourceConclusion> for InboundResourceStatus {
}
}
/// Owned, non-sensitive snapshot of one inbound transfer.
/// Owned snapshot containing link/Resource IDs, sizes, progress and status.
/// It contains no transferred payload bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InboundResourceSnapshot {
pub key: InboundResourceKey,
@@ -133,10 +134,12 @@ impl InboundResourceHandle {
self.snapshot_rx.borrow().clone()
}
/// Wait for the next lifecycle/progress update.
/// Wait for an unseen lifecycle/progress state. Intermediate updates may
/// be coalesced by the watch channel.
///
/// Returns `None` after the terminal snapshot has been published and the
/// actor owner has dropped its sender.
/// Returns `None` once the sender is gone and its latest value has been seen.
/// Dropping the tracker can close the channel without publishing a terminal
/// state; terminal states require the corresponding lifecycle event.
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
if self.snapshot_rx.changed().await.is_err() {
return None;
@@ -166,9 +169,10 @@ struct ActiveInboundResource {
/// Single-owner active Resource registry.
///
/// Terminal records are removed immediately, so the registry is bounded by
/// concurrent transfers. Previously returned handles retain the final owned
/// snapshot without keeping actor state alive.
/// Concluded and LinkClosed events remove records immediately. The embedder
/// must forward those events to keep the registry limited to active transfers;
/// the tracker has no independent entry cap or timeout. Previously returned
/// handles retain their latest snapshot without keeping tracker state alive.
#[derive(Default)]
pub struct InboundResourceTracker {
active: HashMap<InboundResourceKey, ActiveInboundResource>,
@@ -203,8 +207,8 @@ impl InboundResourceTracker {
/// Return the active Resource matching `resource_id`.
///
/// A cryptographic ID collision across two Links fails closed instead of
/// choosing the wrong cancellation authority.
/// If the same Resource ID is active on more than one Link, returns `None`.
/// Use [`Self::inbound_resource_exact`] with the full key to disambiguate.
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
let mut matches = self
.active
@@ -237,7 +241,8 @@ impl InboundResourceTracker {
/// Queue cancellation for a stable snapshot of every active Resource.
///
/// The returned count is the number accepted by the bounded command
/// channel, matching Python's count-oriented `cancel_all_inbound` API.
/// channel, not the number of completed cancellations. Closure is reported
/// by subsequent lifecycle events.
pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resources()
.into_iter()
+48 -7
View File
@@ -4,20 +4,20 @@
//!
//! This crate implements the LXMF wire model and is the core LXMF building
//! block for `lxmf-tools` (the `lxmd-rs` daemon) and embedding applications.
//! Its Reticulum dependency is `rns-transport` from rsReticulum; LXMF sits one
//! layer above the Reticulum stack.
//! It uses rsReticulum for transport, links, identities and Resources; LXMF
//! sits one layer above the Reticulum stack.
//!
//! # Module map
//!
//! | Module | What it does |
//! | --------------------- | -------------------------------------------------- |
//! | [`message`] | Message object: fields, packing, stamp, encryption |
//! | [`message`] | Message types, packing, verification and encryption hooks |
//! | [`delivery_ratchet`] | Durable delivery-announce ratchet transaction |
//! | [`inbound_resource`] | Public inbound Resource tracking/cancellation |
//! | [`presentation`] | Safe bounded presentation of untrusted names |
//! | [`router`] | Actor-driven routing and delivery state machine |
//! | [`router`] | Caller-driven routing and delivery state machine |
//! | [`peer`] | Propagation-peer state and sync bookkeeping |
//! | [`propagation`] | On-disk store-and-forward message pool |
//! | [`propagation`] | In-memory propagation message index and selection |
//! | [`propagation_node`] | Propagation-node role logic |
//! | [`propagation_client`]| Client side of propagation sync |
//! | [`propagation_sync`] | Wire-level peer sync exchange |
@@ -25,9 +25,16 @@
//! | [`discovery_stamper`] | [`DiscoveryStamper`] impl for on-network discovery |
//! | [`sync`] | Shared peer-to-peer sync primitives |
//! | [`link_delivery`] | Reticulum-link-based delivery path |
//! | [`handlers`] | Callback trait surface for delivery events |
//! | [`ticket`] | Small typed identifier for propagation workflows |
//! | [`handlers`] | Announce parsing and propagation control handlers |
//! | [`ticket`] | Directional tickets for bypassing recipient stamp work |
//! | [`persist`] | MessagePack-based on-disk state |
//! | [`admission`] | Durable inbox admission and receipt state |
//! | [`admission_store`] | Admission-store interface and file-backed adapter |
//! | [`propagation_admission`] | Inbound propagation offer and transfer states |
//! | [`propagation_offer`] | Propagation-offer evaluation outcomes |
//! | [`propagation_send`] | Outbound propagation payload preparation |
//! | [`propagation_store_v2`] | Durable propagation store and recovery |
//! | [`types`] | Message, destination and identity hash aliases |
//! | [`constants`] | Wire constants: STATE, METHOD, field IDs, etc. |
//!
//! See also `crates/lxmf-tools/` for the `lxmd-rs` binary, and `rsReticulum`
@@ -43,6 +50,20 @@ pub(crate) fn now_f64() -> f64 {
.as_secs_f64()
}
/// `Instant::now() - age`, or return from the test when the monotonic clock is
/// younger than `age`: Windows counts from boot, so fresh CI runners can't.
#[cfg(test)]
macro_rules! ago_or_skip {
($age:expr) => {
match std::time::Instant::now().checked_sub($age) {
Some(instant) => instant,
None => return,
}
};
}
pub mod admission;
pub mod admission_store;
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
@@ -58,6 +79,8 @@ 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;
@@ -65,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"
);
}
}
+35 -21
View File
@@ -164,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,
@@ -290,10 +291,13 @@ impl LxmPeer {
peer
}
/// Refresh announce-derived policy only when `timebase` is newer.
/// Refresh policy when the supplied `timebase` is newer. The caller must
/// keep both supplied and stored timebases finite; this method does not
/// validate them, and NaN bypasses the ordering guard.
///
/// Returns `true` when the peer was updated. Runtime counters, handled
/// messages and static-peer status remain owned by the existing peer.
/// Returns `true` when updated. Handled messages and static-peer status are
/// retained. Calling `heard()` updates liveness/last-heard and resets the
/// unreachable count and sync backoff; the next sync attempt is reset to zero.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce(
&mut self,
@@ -316,7 +320,9 @@ impl LxmPeer {
)
}
/// Refresh announce-derived policy and bounded metadata only when newer.
/// Refresh policy and bounded metadata with the ordering and liveness
/// behavior of [`Self::refresh_from_announce`]. Both supplied and stored
/// timebases must be finite; this method does not reject NaN.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce_with_metadata(
&mut self,
@@ -548,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
@@ -563,7 +571,8 @@ impl LxmPeer {
}
}
/// Peering-key value (leading zero bits), if generated.
/// Cached peering-key work value (leading zero bits), if present.
/// Restored or caller-supplied values are returned without recomputation.
pub fn peering_key_value(&self) -> Option<u32> {
self.peering_key.map(|(_, value)| value)
}
@@ -573,7 +582,12 @@ impl LxmPeer {
/// Key material is `peer_identity_hash || our_identity_hash` (16 + 16 bytes), run through the
/// 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],
@@ -625,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;
@@ -637,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;
@@ -694,11 +706,13 @@ impl From<&LxmPeer> for OutboundOfferPolicy {
}
}
/// Select the best peer to sync with from a set of candidates.
/// Return the input index of an idle peer with unhandled messages.
///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
/// 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;
+175 -54
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>`
//! * `outbound_stamp_costs` — destination stamp costs and observation times
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//! * `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;
@@ -34,51 +38,75 @@ pub struct PersistedNodeStats {
pub unpeered_propagation_rx_bytes: u64,
}
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
///
/// Tmp name is `<path>.tmp.<pid>.<16 random hex>` so concurrent writers (or
/// other processes) never collide; the tmp file is unlinked on error. An fsync
/// failure is logged as a warning and is non-fatal, matching Python
/// `LXMessage.write_to_directory` — LXMessage.py:674-696 (1.0.1).
/// Publish exact bytes through the strict platform durability boundary.
/// CommitUncertain remains an error: readback alone cannot authorize a receipt.
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write;
rns_identity::persistence::durable_write(path, data)
.map(|_| ())
.map_err(io::Error::other)
}
let random: [u8; 8] = rand::random();
let tmp_name = format!(
"{}.tmp.{}.{}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
std::process::id(),
hex::encode(random)
);
let tmp = path.with_file_name(tmp_name);
/// Suppression state cannot authorize a remote purge. Adapters nevertheless
/// persist it before allowing the next automatic wants selection.
pub fn save_suppression(
dir: &Path,
ledger: &crate::admission::SuppressionLedger,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_suppression_v1"), ledger)
}
let result = (|| {
let mut file = fs::File::create(&tmp)?;
file.write_all(data)?;
file.flush()?;
if let Err(e) = file.sync_all() {
tracing::warn!(
"Error while waiting for persist fsync for {}: {e}",
tmp.display()
);
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")
}
drop(file);
fs::rename(&tmp, path)
})();
if result.is_err() && tmp.exists() {
if let Err(e) = fs::remove_file(&tmp) {
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut seen = std::collections::HashSet::new();
let mut records = Vec::new();
while let Some((scope,record))=map.next_entry::<crate::admission::AdmissionScope,crate::admission::SuppressionRecord>()? {
if scope!=record.scope || !seen.insert(scope) || records.len()>=crate::admission::SuppressionLedger::GLOBAL {
return Err(serde::de::Error::custom("invalid suppression scope or capacity"));
}
records.push(record);
}
Ok(records)
}
}
deserializer.deserialize_map(Records)
}
result
pub fn save_node_policies(
dir: &Path,
policies: &HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_node_policies_v1"), policies)
}
pub fn load_node_policies(
dir: &Path,
) -> io::Result<HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>> {
Ok(read_mpk(&dir.join("propagation_node_policies_v1"))?.unwrap_or_default())
}
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
@@ -91,15 +119,33 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
}
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
match fs::read(path) {
Ok(bytes) => {
let value = rmp_serde::from_slice(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(value))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
read_mpk_bounded(path, 64 * 1024 * 1024)
}
fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
path: &Path,
limit: usize,
) -> io::Result<Option<T>> {
use std::io::Read;
let file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut bytes = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > limit {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"router state exceeds bounded capacity",
));
}
// 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<()> {
@@ -110,8 +156,83 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
/// Process-local revision of a captured ticket state. All production ticket
/// writes pass through the same path coordinator, so a delayed checkpoint can
/// never replace a ticket that a newer signing intent already committed.
#[derive(Debug, Clone)]
pub(crate) struct TicketPersistenceSnapshot {
revision: u64,
snapshot: std::sync::Arc<TicketStoreSnapshot>,
}
impl TicketPersistenceSnapshot {
pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
// Rust 1.99 renamed this operation; keep the identical Rust 1.89 API.
#[allow(deprecated)]
let revision = NEXT
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
.expect("ticket checkpoint revision exhausted");
Self {
revision,
snapshot: std::sync::Arc::new(snapshot),
}
}
pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> {
use std::sync::{Mutex, OnceLock};
struct Latest {
revision: u64,
committed: bool,
}
static WRITERS: OnceLock<Mutex<HashMap<std::path::PathBuf, Latest>>> = OnceLock::new();
fs::create_dir_all(dir)?;
let path = fs::canonicalize(dir)?.join(TICKETS_FILE);
let mut writers = WRITERS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?;
if !writers.contains_key(&path) && writers.len() >= 4096 {
return Err(io::Error::other("ticket persistence path quota exhausted"));
}
let latest = writers.entry(path.clone()).or_insert(Latest {
revision: self.revision,
committed: false,
});
if self.revision < latest.revision {
if !latest.committed {
return Err(io::Error::other(
"newer ticket checkpoint is uncertain and must be retried",
));
}
if let Some(required) = required {
let (stored, _) = load_tickets(dir)?;
if !stored.inbound.contains(required) {
return Err(io::Error::other(
"newer ticket state no longer contains this signing intent",
));
}
}
return Ok(());
}
if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) {
return Err(io::Error::other(
"ticket snapshot does not contain this signing intent",
));
}
latest.revision = self.revision;
latest.committed = false;
// Even an uncertain publication raises the revision floor. Older
// snapshots fail closed until this or a newly captured current state
// reestablishes the strict barrier. No failed payload is retained by
// this bounded process-wide metadata coordinator.
write_mpk(&path, &*self.snapshot)?;
latest.committed = true;
Ok(())
}
}
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None)
}
#[derive(serde::Deserialize)]
+38 -3
View File
@@ -7,10 +7,29 @@ pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name.
///
/// The result is NFKC-normalized, contains no control or presentation-control
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is
/// truncated by Unicode scalar values rather than UTF-8 bytes.
/// 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();
}
@@ -146,6 +165,22 @@ mod tests {
assert_eq!(sanitize_name("A B", 3), "A B");
}
#[test]
fn normalization_reaches_fixed_point_after_filtered_separators() {
for input in [
"A\u{0000}\u{030A}",
"e\u{034f}\u{0301}",
"o\u{200d}\u{0308}",
] {
for limit in 0..8 {
let once = sanitize_name(input, limit);
assert_eq!(sanitize_name(&once, limit), once);
assert_eq!(once.nfkc().collect::<String>(), once);
}
}
assert_eq!(sanitize_name("™", 128), "TM");
}
proptest! {
#[test]
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
+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) {
@@ -23,9 +23,9 @@ use crate::constants::PN_STAMP_THROTTLE;
const PROPAGATION_DESTINATION_NAME: &str = "lxmf.propagation";
/// Default maximum number of concurrently transferring or validating syncs.
/// Default active-sync threshold used when admitting new offers.
pub const PN_DEFAULT_MAX_INBOUND_SYNCS: usize = 3;
/// Smallest accepted configured inbound-sync limit.
/// Lower bound applied to the configured inbound-sync threshold.
pub const PN_MIN_MAX_INBOUND_SYNCS: usize = 1;
/// Duration applied after a known peer submits an invalid-stamp batch.
pub const PN_INVALID_STAMP_THROTTLE: Duration = Duration::from_secs(PN_STAMP_THROTTLE);
@@ -40,7 +40,9 @@ pub struct PnInboundAdmissionConfig {
/// The LXMF default is `false`, so a configured static peer bypasses both
/// admission gates.
pub static_sequential: bool,
/// Maximum concurrent Resources in `Transferring` or `Validating` state.
/// Reject new non-bypassing offers when this many records are Transferring
/// or Validating. Values below one are clamped to one. Accepted offers do
/// not reserve slots, and starting them does not recheck this threshold.
pub max_inbound_syncs: usize,
/// Accept propagation offers only from configured static peers.
pub from_static_only: bool,
@@ -286,7 +288,8 @@ impl PnInboundAdmission {
///
/// A successful preflight creates no admission record. The returned
/// candidate binds the link and peer values that the caller must use for
/// external key validation.
/// external key validation. The caller must supply the remote identity
/// verified on that Link; this coordinator receives hashes, not identity proofs.
pub fn preflight_offer(
&mut self,
link_id: [u8; 16],
@@ -461,6 +464,7 @@ impl PnInboundAdmission {
}
/// Transition an accepted offer when its inbound Resource starts.
/// This checks the previous state but does not rerun offer admission gates.
pub fn resource_started(&mut self, link_id: &[u8; 16]) -> Result<(), PnTransitionError> {
self.transition(
link_id,
@@ -480,7 +484,7 @@ impl PnInboundAdmission {
)
}
/// Conclude stamp validation and release all active accounting.
/// Conclude stamp validation and release this link's active accounting.
///
/// Only [`PnValidationResult::InvalidStamp`] installs a throttle, and a
/// throttle is possible only for a known peer retained in a valid record.
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
+4 -1
View File
@@ -13,7 +13,10 @@ use crate::types::PropagationTransientId;
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
/// A peering-key-validated offer and the subset not present in local storage.
/// Offer outcome and the subset absent from local storage. The variants are
/// publicly constructible, so this value alone is not proof of authentication
/// or admission. Obtain it through [`crate::propagation_node::PropagationNode::evaluate_offer_request`]
/// after preflight, then commit it to that same admission candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PnOfferEvaluation {
HaveAll,
+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
+3 -1
View File
@@ -47,7 +47,9 @@ impl Ticket {
Ok(encoded)
}
/// Decode a signed inbound Python-compatible ticket field.
/// Decode a Python-compatible ticket field with a finite future expiry and
/// a 16-byte token. The caller must authenticate the containing message and
/// bind `destination_hash` to its sender before storing the learned ticket.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
+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
}
+3
View File
@@ -1,8 +1,10 @@
[package]
name = "lxmf-tools"
description = "Rust LXMF daemon and CLI tools for Reticulum"
publish = false
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
autobins = false
@@ -22,6 +24,7 @@ hex = { workspace = true }
base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
zeroize = "1"
[dev-dependencies]
tempfile = { workspace = true }
File diff suppressed because it is too large. Load diff
+41 -27
View File
@@ -1,4 +1,4 @@
//! LXMF daemon configuration and runner.
//! LXMF daemon configuration and inbound-hook helpers.
//!
//! Python reference: LXMF/Utilities/lxmd.py.
@@ -11,9 +11,8 @@ 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,
@@ -190,7 +189,7 @@ pub struct DaemonConfig {
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: f64,
}
@@ -227,9 +226,9 @@ impl Default for DaemonConfig {
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
// Current Python lxmd 1.1.0 deliberately narrows the standalone
// daemon default to 1 decimal KB. The reusable RouterConfig keeps
// its 1000 KB library default, matching Python LXMRouter.
// 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,
}
}
@@ -324,17 +323,16 @@ impl DaemonConfig {
dc.outbound_propagation_node = Some(trimmed.to_string());
}
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none() {
if let Some(cost) = sec.get_uint("propagation_stamp_cost") {
dc.propagation_stamp_cost = cost as u8;
}
if get_int(Some(sec), "propagation_stamp_cost_target").is_none()
&& let Some(cost) = sec.get_uint("propagation_stamp_cost")
{
dc.propagation_stamp_cost = cost as u8;
}
if get_float(Some(sec), "propagation_message_max_accepted_size").is_none()
&& get_float(Some(sec), "propagation_transfer_max_accepted_size").is_none()
&& let Some(limit) = sec.get_uint("propagation_limit")
{
if let Some(limit) = sec.get_uint("propagation_limit") {
dc.propagation_limit_kb = limit as usize;
}
dc.propagation_limit_kb = limit as usize;
}
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -343,14 +341,14 @@ impl DaemonConfig {
if !dc.auth_required {
dc.auth_required = sec.get_bool_or("auth_required", false);
}
if dc.control_allowed.is_empty() {
if let Some(allowed) = sec.get("allowed") {
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
if dc.control_allowed.is_empty()
&& let Some(allowed) = sec.get("allowed")
{
dc.control_allowed = allowed
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
}
@@ -405,6 +403,17 @@ 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 = split_command_line(command)?;
@@ -417,10 +426,15 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
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(())
}
@@ -509,9 +523,9 @@ fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
Ok(parts)
}
/// Persist a received message before invoking the configured hook. Keeping
/// both operations in one blocking job prevents the hook from racing the
/// atomic file write and keeps process execution off the async daemon loop.
/// 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],
+35 -14
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,7 +108,7 @@ 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>,
@@ -98,22 +116,24 @@ pub struct Args {
#[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>,
}
@@ -186,7 +206,8 @@ autopeer_maxdepth = 6
# Let configured static peers bypass sequential validation and inbound limits.
# static_peers_bypass_sequential = yes
# Maximum concurrent inbound propagation sync transfers.
# Threshold for new inbound propagation sync offers. Already accepted offers
# and static-peer bypass can exceed this value.
# max_inbound_syncs = 3
# message_storage_limit = 500
@@ -236,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]> {
+130 -49
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 {
if 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 {
@@ -123,10 +111,10 @@ pub fn decode_control_response(response: &[u8]) -> ControlResponse {
return ControlResponse::Success;
};
if let Some(code) = value.as_u64() {
if let Some(error) = peer_error_from_code(code as u8) {
return ControlResponse::Error(error);
}
if let Some(code) = value.as_u64()
&& let Some(error) = peer_error_from_code(code as u8)
{
return ControlResponse::Error(error);
}
if value.is_nil() {
@@ -869,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()
}
+3 -3
View File
@@ -1,7 +1,7 @@
//! Pure `lxmd` runtime helpers extracted from the binary.
//! `lxmd` path selection, control-command preflight, and status formatting.
//!
//! This module keeps daemon path handling and other pure helpers out of the
//! 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};
+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()