Compare commits

...
Author SHA1 Message Date
DeFiDude d58ea18011 ci: qualify release source with full history 2026-08-17 15:54:17 -06:00
DeFiDude c0053734f5 release: prepare rsLXMF 1.2.0 2026-08-17 15:00:05 -06:00
DeFiDude 1aee9dc1ed ci: follow clean Reticulum API source 2026-08-17 12:53:34 -06:00
DeFiDude 7da6df836c api: require clean snapshot source 2026-08-17 12:52:42 -06:00
DeFiDude 84c59c87b4 ci: follow reviewed Reticulum API source 2026-08-17 12:37:03 -06:00
DeFiDude 7d0285f46d api: bind snapshots to reviewed source 2026-08-17 12:36:12 -06:00
DeFiDude c934ccc5fe api: add canonical message facade 2026-08-17 11:50:43 -06:00
DeFiDude a8f74d2aed api: enforce manifest and additive compatibility 2026-08-17 11:43:25 -06:00
DeFiDude 133b9e2f60 ci: pin qualified Reticulum API source 2026-08-17 11:42:11 -06:00
DeFiDude 80bb96f799 api: record public compatibility baseline 2026-08-17 10:23:02 -06:00
DeFiDude b8d7afce73 ci: run source contract from workspace 2026-08-17 04:06:39 -06:00
DeFiDude ca9f119cbb release: pin qualified Reticulum source 2026-08-17 02:20:13 -06:00
DeFiDude 8101523fb9 lint: adopt Rust 1.87 integer divisibility 2026-08-17 02:20:13 -06:00
DeFiDude 92ea14b485 release: raise unified MSRV to Rust 1.87 2026-08-17 01:42:44 -06:00
DeFiDude 8b641971d9 ci: pin source qualification actions 2026-08-17 00:38:58 -06:00
DeFiDude c787312b48 release: pin compatible Reticulum source 2026-08-17 00:14:20 -06:00
DeFiDude 00de17cf26 release: enforce source qualification contract 2026-08-17 00:10:25 -06:00
DeFiDude 8a6316c635 lxmd: own announce discovery subscriptions 2026-08-16 20:18:31 -06:00
DeFiDude 0bd4220db6 docs: distinguish LXMF reference baselines 2026-08-16 18:41:23 -06:00
DeFiDude 44af77dc98 lxmd: follow current Python resource policy 2026-08-16 18:34:25 -06:00
DeFiDude 42355b4f46 lxmd: restore Python resource limit default 2026-08-16 17:32:26 -06:00
DeFiDude d100e3eae5 docs: explain established Link binding 2026-08-16 15:39:49 -06:00
DeFiDude 502795c70d link: observe typed endpoint send results 2026-08-16 15:37:13 -06:00
DeFiDude a530ad77c0 tools: map Link identity send errors 2026-08-16 15:19:59 -06:00
DeFiDude f91747b1d8 docs: record Link delivery hardening 2026-08-16 15:17:11 -06:00
DeFiDude 29804534ce propagation: pin Link sessions to proof interfaces 2026-08-16 15:17:08 -06:00
DeFiDude f89b6a2811 direct: bind Links and retain reverse proofs 2026-08-16 15:17:04 -06:00
DeFiDude 094bc95662 core: add native LXMF audio fields 2026-08-15 12:48:04 -06:00
DeFiDude b40dcd37f2 delivery: reconcile backchannel outcomes and reverse resources 2026-08-14 13:49:48 -06:00
DeFiDude 681c0f5961 delivery: reduce large message allocation 2026-08-13 12:42:35 -06:00
DeFiDude f9ed81e3ae docs: clarify Opportunistic proof lifecycle 2026-08-13 02:10:40 -06:00
DeFiDude 326022cae8 runtime: complete tickets and durable propagation 2026-08-12 23:58:24 -06:00
DeFiDude 27a49aed00 runtime: harden LXMF daemon parity 2026-08-12 20:15:30 -06:00
DeFiDude 2e124b1006 ci: enforce strict Clippy across supported targets 2026-08-06 18:49:06 -06:00
DeFiDude c0bd1ef82f core, lxmd: make inbound link delivery lossless 2026-07-27 00:07:19 -06:00
dude.eth a1c3a29603 Merge pull request #5 from ratspeak/feature/api-parity
propagation: harden delivery and complete parity APIs
2026-07-26 13:41:20 -06:00
DeFiDude 830db46735 presentation: avoid trailing separator truncation 2026-07-26 13:38:34 -06:00
DeFiDude b4c2e09ca6 tests: await bounded offer preparation 2026-07-26 13:35:35 -06:00
DeFiDude 7dfe9c18bd release: prepare v1.1.0 2026-07-26 13:24:34 -06:00
DeFiDude 4350dd1a88 ci: gate public API documentation 2026-07-26 06:57:59 -06:00
DeFiDude e38bab9d16 docs: keep public API rustdoc clean 2026-07-26 06:55:49 -06:00
DeFiDude 115c9dd17c lxmd: restore Python delivery limit default 2026-07-26 02:56:51 -06:00
DeFiDude 3070484a5f propagation: guard transfer restarts 2026-07-26 02:01:04 -06:00
DeFiDude c52c0a254f presentation: unify safe transfer status 2026-07-26 01:57:08 -06:00
DeFiDude 42e3907835 router: make inbound state durable 2026-07-26 01:39:48 -06:00
DeFiDude 5c37690bd6 router: expose inbound Resource control 2026-07-26 01:29:38 -06:00
DeFiDude 703942ecf5 lxmd: align delivery defaults and limits 2026-07-25 23:24:07 -06:00
DeFiDude d22fa362fa propagation: complete live peer offer sync 2026-07-25 23:18:26 -06:00
DeFiDude b47a2d29b9 propagation: integrate bounded inbound runtime 2026-07-25 22:14:07 -06:00
DeFiDude bd9d51b6b7 propagation: harden inbound throttle policy 2026-07-25 21:39:51 -06:00
DeFiDude 356ba6a305 propagation: isolate bounded offer evaluation 2026-07-25 21:28:37 -06:00
DeFiDude 3a17ca6845 lxmd: parse inbound sync policy 2026-07-25 20:21:57 -06:00
DeFiDude e55074595c propagation: model inbound admission 2026-07-25 19:55:14 -06:00
DeFiDude e0257d6fd6 build: refresh Reticulum dependency lock 2026-07-25 19:47:33 -06:00
DeFiDude 663bfb6066 tests: include inbound packet metrics 2026-07-25 19:36:08 -06:00
DeFiDude 68f84ce0a6 lxmd: bind receipts to destination identity 2026-07-24 03:50:02 -06:00
DeFiDude 93f4257068 deps: refresh Reticulum lock 2026-07-20 21:23:14 -06:00
DeFiDude 90606fdb3f lxmd: make delivery ratchets crash-safe 2026-07-20 17:28:39 -06:00
DeFiDude 393478019b style: rustfmt 2026-07-18 22:35:11 -06:00
DeFiDude 3e048eda1a lxmf: drop dead enforce_stamps router mirror; stamp-gate propagation downloads 2026-07-18 19:58:02 -06:00
DeFiDude b99c177f01 lxmf: drop inert enforce_ratchets knob for Python lxmd parity 2026-07-18 19:01:18 -06:00
DeFiDude b08de427a9 docs: retarget README to LXMF 1.0.1 2026-07-17 08:37:47 -06:00
DeFiDude 22b1907d4c parity: LXMF 1.0.1 — reply/reaction/comment field standards, compression signalling in announces, blackholed-source drop, atomic message persist 2026-07-15 14:24:04 -06:00
DeFiDude 20ef834281 lxmf: check every valid ticket in stamp validation, cull state at load, use announced stamp flexibility 2026-07-10 18:10:17 -05:00
DeFiDude 68ad7c8351 lxmf: expose delivery compression capability state 2026-06-26 16:01:15 -06:00
50 changed files with 23712 additions and 2358 deletions

No files matched your search

+94 -12
View File
@@ -9,7 +9,47 @@ on:
permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: dc6bc4ee82daf66b3b40386f9777dbe62b08fec2
jobs:
api-compat:
name: Public API baseline
runs-on: macos-15
timeout-minutes: 45
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: nightly-2026-08-01
targets: aarch64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: true
- name: Install API snapshot tool
run: cargo install cargo-public-api --version 0.52.0 --locked
- name: Check reviewed public API baseline
run: python3 tools/check-api-baseline.py
working-directory: rsLXMF
- name: Check manifest and feature contract
run: python3 tools/check-api-manifest.py
working-directory: rsLXMF
- name: Check additions-only compatibility floor
run: python3 tools/check-api-compatibility.py
working-directory: rsLXMF
- name: Check canonical and legacy external consumer
run: cargo check --manifest-path api-fixtures/Cargo.toml --locked
working-directory: rsLXMF
test:
name: Test (${{ matrix.os }})
timeout-minutes: 30
@@ -19,22 +59,27 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace
- run: cargo test --workspace --locked
working-directory: rsLXMF
- name: Build embedding examples
run: cargo build -p lxmf-core --examples --locked
working-directory: rsLXMF
lint:
@@ -42,23 +87,60 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
components: clippy, rustfmt
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Check source-release contract
run: python3 scripts/ci/check_source_release_contract.py
working-directory: rsLXMF
- run: cargo fmt --all -- --check
working-directory: rsLXMF
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
- name: Check public API documentation
env:
RUSTDOCFLAGS: "-D warnings"
run: cargo doc --workspace --no-deps --locked
working-directory: rsLXMF
msrv:
name: Rust 1.87 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.87.0
components: clippy
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: false
- name: Install system deps
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- name: Clippy (all targets and features)
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
working-directory: rsLXMF
+37 -11
View File
@@ -17,11 +17,35 @@ env:
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_REF: v1.0.1
RSLXMF_RSRETICULUM_VERSION: 1.2.0
RSLXMF_RSRETICULUM_COMMIT: dc6bc4ee82daf66b3b40386f9777dbe62b08fec2
jobs:
verify:
name: Verify release source
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
ref: ${{ env.RELEASE_TAG }}
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.87.0
- name: Verify release source and dependency
working-directory: rsLXMF
run: python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
build:
name: Build ${{ matrix.artifact_suffix }}
needs: verify
timeout-minutes: 30
strategy:
fail-fast: false
@@ -40,17 +64,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 }}
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.87.0
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps (Linux)
@@ -58,7 +84,7 @@ 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
@@ -72,7 +98,7 @@ jobs:
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
fi
done
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
cp README.md LICENSE CHANGELOG.md RELEASING.md "dist/${PACKAGE_ROOT}/"
- name: Create tar archive
if: runner.os != 'Windows'
shell: bash
@@ -83,7 +109,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: |
@@ -98,14 +124,14 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/download-artifact@v7
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
with:
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 }}
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
+1
View File
@@ -1,4 +1,5 @@
/target/
/api-fixtures/target/
*.swp
.DS_Store
proptest-regressions/
+56
View File
@@ -0,0 +1,56 @@
# API stability
rsLXMF is currently source-distributed with `publish = false`. The current
Rust module tree is useful to source consumers, but only part of it is an
intentional long-term library boundary.
`api-stability.json` classifies every library package and pins the exact
pre-boundary commit. `api-baseline/*.txt` contains the complete explicit public
surface observed by pinned `cargo-public-api` and rustdoc versions. CI rejects
unreviewed drift. These snapshots are compatibility evidence, not a promise
that every listed state-machine field or helper will remain public forever.
`lxmf-core` is **candidate stable** as a package. Its message, presentation,
ticket, routing, propagation, sync, and public delivery concepts are intended
consumer capabilities. Its current modules also expose handler plumbing,
persistence representations, admission machinery, Link-delivery state, and
other orchestration details that remain provisional until the API-boundary
checkpoint. `lxmf-tools` is **tool internal** and exists to support `lxmd-rs`;
it is not a library compatibility commitment.
[`lxmf_core::message_api`](MESSAGE_API.md) is the canonical candidate message
path. It re-exports existing identities without adaptation, and the original
module paths remain supported. Router, delivery, propagation, handler, and
persistence ownership are not promoted by this narrow facade.
No visibility, signature, serialization, wire, persistence, or runtime change
is made by establishing this baseline. Any later boundary reduction must first
show the public API diff, migrate Ratspeak and other first-party users, preserve
the supported facade, and make an explicit version/changelog decision.
The canonical snapshot uses all features on `aarch64-apple-darwin` and omits
auto-derived, auto-trait, and blanket implementations. Other target overlays
remain covered by existing build and interop gates rather than this first
host API snapshot.
```sh
cargo install cargo-public-api --version 0.52.0 --locked
rustup toolchain install nightly-2026-08-01 --profile minimal
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
```
The immutable floor and current captured snapshot source are separate
identities in `api-stability.json`. A capture names its clean basis commit and
reviewed change record; CI renders the current tree and requires a byte-exact
snapshot, avoiding an impossible self-referential commit identifier. The
manifest contract covers features,
targets, MSRV, and non-development dependencies that one Apple/all-feature API
view cannot prove. The compatibility check currently rejects every removal
from the Wave C floor; it complements rather than replaces feature, platform,
wire, persistence, and interoperability evidence.
Run with `--update` only after reviewing and recording the compatibility
impact; refreshing a snapshot is never a substitute for that review.
+60
View File
@@ -0,0 +1,60 @@
# Changelog
## Unreleased
## 1.2.0 - 2026-08-17
- Added the exact-reexport `lxmf_core::message_api` facade, a compiled message
example, and canonical/legacy external-consumer coverage while retaining all
existing module paths and leaving router, delivery, propagation, wire, and
persistence behavior unchanged.
- Classified `lxmf-core` as candidate stable and `lxmf-tools` as tool internal,
with pinned CI-enforced public API snapshots and no visibility or signature
change.
- Made source releases reproducible from an existing immutable component tag:
packages are non-publishable by default and expose Rust 1.87 metadata,
release builds use the committed lockfile and exact dependency commits,
actions are commit-pinned, and CI verifies the release-source contract.
- Replaced temporary aspect-wide announce handlers in remote-control lookup
with bounded validated destination recall, and made lxmd's delivery and
propagation observers exact owned subscriptions with deterministic cleanup.
- Matched current Python LXMF 1.1.0's fresh `lxmd` direct-delivery Resource
admission default of 1 decimal KB, while keeping the reusable router's
separate 1000 KB library default and preserving explicit configured limits.
- Bound Direct-delivery, propagation-download, and propagation-sync Link
initiators to the authenticated LRPROOF ingress interface before LRRTT,
routed all established-Link traffic through ordered typed endpoints, and
made reverse delivery proofs durable before plaintext publication.
- Bounded propagation-sync transport staging, scoped Link endpoint failures
to their owning operation, and prevented Resource responses from becoming
visible when their delivery proof cannot be retained.
- Made typed Link sends fail closed on rejected transport admission, delayed
reverse plaintext and propagation responses until their proofs are reliably
admitted, and made failed graceful closes unbind before deregistration.
- Added automatic pre-sign reply-ticket issue, signature-gated inbound
learning, directional migration-safe persistence, and proof-gated delivery
accounting, with live Python restart/reply interoperability.
- Made Opportunistic one-shot delivery wait for an authenticated Reticulum
proof, with atomic receipt-first dispatch and bounded retries.
- Moved propagation-store persistence off the daemon loop through
reserve/write/commit transactions so visibility, handled IDs and counters
advance only after durable writes.
- Added coalescing announce handoff, live allow-list rotation and split
peer-Resource convergence coverage.
- Made one-shot remote control commands wait for a real online Reticulum
interface before opening their Link, avoiding stale-path startup loss.
- This source line targets the rsReticulum 1.2 dependency line and includes
API evolution since the alpha-stage 1.1.0 source release.
## 1.1.0 - 2026-07-26
- Added bounded propagation-node admission, exact inbound Resource ownership,
asynchronous validation, and peer-specific throttling.
- Completed live peer offer preparation, encrypted Resource synchronization,
cancellation, and proof-gated convergence.
- Added public inbound Resource tracking and cancellation plus restart-safe
persistence and packet/Resource deduplication.
- Unified safe name presentation and authoritative propagation transfer
status, including restart protection.
- Aligned `lxmd-rs` delivery and stamp defaults with the proven Python LXMF
compatibility target.
Generated
+41 -10
View File
@@ -643,13 +643,14 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"base64",
"bytes",
"hex",
"proptest",
"rand 0.8.5",
"rmp",
"rmp-serde",
"rmpv",
"rns-crypto",
@@ -664,11 +665,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"unicode-normalization",
]
[[package]]
name = "lxmf-tools"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"base64",
"bytes",
@@ -682,6 +684,7 @@ dependencies = [
"rns-transport",
"rns-wire",
"serde_json",
"tempfile",
"tokio",
"tracing",
"tracing-subscriber",
@@ -1049,7 +1052,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"aes",
"cbc",
@@ -1067,7 +1070,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1076,25 +1079,29 @@ dependencies = [
"rns-crypto",
"rns-wire",
"serde",
"serde_bytes",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
"zeroize",
]
[[package]]
name = "rns-interface"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"bytes",
"hex",
"if-addrs",
"jni",
"libc",
"md-5",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-transport",
"rns-wire",
"serde",
@@ -1109,7 +1116,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1124,7 +1131,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"bzip2",
"hex",
@@ -1140,7 +1147,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"bytes",
"hex",
@@ -1166,7 +1173,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"bytes",
"hex",
@@ -1185,7 +1192,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.0.1"
version = "1.2.0"
dependencies = [
"rns-crypto",
"sha2",
@@ -1478,6 +1485,21 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.50.0"
@@ -1590,6 +1612,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-xid"
version = "0.2.6"
+14 -12
View File
@@ -6,30 +6,31 @@ members = [
]
[workspace.package]
version = "1.0.1"
version = "1.2.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
rust-version = "1.87"
[workspace.dependencies]
# Reticulum crates from a sibling rsReticulum checkout during development.
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.0.1" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.0.1" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.0.1" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.0.1" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.0.1" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.0.1" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.0.1" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.0.1" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "1.2.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.2.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.2.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.2.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.2.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.2.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.2.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.2.0" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.0.1" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.0.1" }
lxmf-core = { path = "crates/lxmf-core", version = "1.2.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.2.0" }
# Encoding
base64 = "0.22"
# Serialization
rmp = "0.8"
rmp-serde = "1"
rmpv = "1"
serde = { version = "1", features = ["derive"] }
@@ -56,6 +57,7 @@ thiserror = "2"
# Misc
hex = "0.4"
tempfile = "3"
unicode-normalization = "0.1"
# Testing
proptest = "1"
+20
View File
@@ -0,0 +1,20 @@
# LXMF message API
`lxmf_core::message_api` is the canonical application path for constructing
and inspecting LXMF message values. It contains exact re-exports of the
existing message, status, and identifier identities; all module-qualified
paths remain supported.
The compiled `lxmf-core` `message` example demonstrates construction, signing,
packing, and unpacking. Its imports are the facade conformance contract.
This first boundary is deliberately narrower than an LXMF router facade.
`LxmRouter`, delivery ownership, propagation clients/nodes, handlers,
persistence, and raw Reticulum transport channels remain provisional,
module-qualified orchestration APIs. The facade does not alter wire fields,
signatures, serialization, delivery methods, proofs, or persistence.
Compatibility is checked by the reviewed API snapshot, the manifest/feature
contract, an additions-only comparison with the immutable Wave C floor, and an
external crate that compiles both canonical and retained imports. Platform,
wire, persistence, and Python interoperability gates remain separate evidence.
+37 -13
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 0.9.8](https://img.shields.io/badge/target-LXMF%200.9.8-success.svg)](https://github.com/markqvist/LXMF)
[![Rust 1.87+](https://img.shields.io/badge/rust-1.87%2B-orange.svg)](https://www.rust-lang.org)
[![Compatibility floor: LXMF 1.0.1](https://img.shields.io/badge/compatibility%20floor-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Current reference: LXMF 1.1.0](https://img.shields.io/badge/current%20reference-LXMF%201.1.0-blue.svg)](https://github.com/markqvist/LXMF)
[![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)
- [Message API](MESSAGE_API.md)
- [Operating lxmd-rs](#operating-lxmd-rs)
- [Configuration](#configuration)
- [Delivery Model](#delivery-model)
@@ -65,7 +67,7 @@ Build from the sibling checkout:
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Linux / Raspberry Pi
@@ -95,7 +97,7 @@ sudo pacman -S --needed base-devel pkgconf systemd
```bash
cd rsLXMF
cargo build --release
cargo build --release --locked
```
### Windows
@@ -107,7 +109,7 @@ 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
@@ -238,8 +240,8 @@ Minimal config:
[lxmf]
display_name = Rat
announce_at_start = no
delivery_transfer_max_accepted_size = 1000
# stamp_cost = 8
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
[propagation]
@@ -259,12 +261,17 @@ auth_required = no
loglevel = 4
```
The standalone daemon follows current Python LXMF 1.1.0 and defaults this
setting to 1 decimal KB when it is omitted. This is intentionally distinct
from the reusable router library's 1000 KB default. Applications that accept
larger incoming messages should set their own explicit policy.
Supported sections:
| Section | Keys |
| --- | --- |
| `[lxmf]` | `display_name`, `announce_at_start`, `announce_interval`, `delivery_transfer_max_accepted_size`, `stamp_cost`, `on_inbound` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_ratchets`, `enforce_stamps` |
| `[propagation]` | `enable_node`, `node_name`, `auth_required`, `announce_at_start`, `announce_interval`, `autopeer`, `autopeer_maxdepth`, `message_storage_limit`, `propagation_message_max_accepted_size`, `propagation_sync_max_accepted_size`, `propagation_stamp_cost_target`, `propagation_stamp_cost_flexibility`, `peering_cost`, `remote_peering_cost_max`, `max_peers`, `static_peers`, `prioritise_destinations`, `control_allowed`, `from_static_only`, `outbound_node`, `propagation_stamp_cost`, `propagation_limit`, `enforce_stamps` |
| `[control]` | `auth_required`, `allowed` |
| `[logging]` | `loglevel` |
@@ -284,11 +291,18 @@ and, where network-backed, through `lxmd-rs --send-method`.
| Method | Behavior |
| --- | --- |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Oversized opportunistic messages are downgraded to Direct by the router. |
| Opportunistic | Single-packet delivery when the packed message fits the Reticulum packet path. Delivery completes only after an authenticated Reticulum proof; bounded retries remain in flight until then. Oversized opportunistic messages are downgraded to Direct by the router. |
| 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
@@ -302,15 +316,19 @@ payload MessagePack([timestamp, title, content, fields, optional_stamp
application-defined data such as tickets, attachments, location data, or
application envelopes.
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.
## Feature Status
| Area | Current behavior |
| --- | --- |
| Message format | Signed LXMF envelopes, custom field maps, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, and opportunistic-to-direct downgrade. |
| Propagation | Disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, propagation tickets, and restart-safe ticket persistence. |
| Message format | Signed LXMF envelopes, custom field maps, standard reply/reaction/comment fields, propagation wrappers, `.lxm` containers, and paper URI encode/decode. |
| Delivery | Opportunistic, Direct, Propagated, callbacks, failure callbacks, cancellation, progress state, opportunistic-to-direct downgrade, and compression signalling in delivery announces. |
| Propagation | Transactional disk-backed store, deposit, retrieve, peer sync, autopeer/static peers, weighted culling, duplicate checks, size checks, and stamp checks. |
| Stamps and tickets | Soft/hard stamp validation, HKDF-expanded workblocks, cached destination stamp costs, automatic reply-ticket issue and signed learning, ticket-backed stamps, and restart-safe directional persistence. |
| Control | `--status`, `--peers`, `--sync`, and `--break` over the propagation-control link. |
| Access lists | `ignored` and `allowed` hash-list files in the LXMF config directory. |
@@ -324,6 +342,12 @@ 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 compatibility-floor corpus is Python LXMF 1.0.1 with Reticulum 1.3.8;
current daemon, delivery, Resource/proof, and propagation behavior is also
checked against exact LXMF 1.1.0 and Reticulum 1.4.2 sources. Version-specific
legacy vectors retain their original provenance instead of being silently
rewritten to current expectations.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
+28
View File
@@ -0,0 +1,28 @@
# Source release policy
rsLXMF source releases are built from immutable Git history. A release is
identified by an annotated `vX.Y.Z` tag whose version matches the workspace
package version and a dated `X.Y.Z` section in `CHANGELOG.md`.
Before creating a tag:
1. Move the relevant `Unreleased` changelog entries into a dated version
section.
2. Set the workspace version to that same semantic version and keep the
declared rsReticulum compatibility version accurate.
3. Record the exact rsReticulum commit used by the release workflow. The
compatibility version describes the manifest contract; the commit is the
source actually built and must be proven in an isolated sibling checkout.
4. Run `python3 scripts/ci/check_source_release_contract.py` and the normal CI
suite with the committed `Cargo.lock`.
5. Create the tag only after the release commit is final. Published tags are
immutable and must not be retargeted.
The release workflow checks out the requested existing tag, verifies that the
tag, manifest, changelog, dependency checkout, and release commit agree, and
builds with `--locked` on Rust 1.87.0. Release artifacts include this policy
and the changelog alongside the README and license.
All workspace packages are intentionally marked `publish = false`. Changing
that safeguard requires a separate package-distribution decision; a source
release does not change it.
File diff suppressed because it is too large. Load diff
+185
View File
@@ -0,0 +1,185 @@
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::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::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::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)
+432
View File
@@ -0,0 +1,432 @@
{
"schemaVersion": 1,
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
"packages": [
{
"name": "lxmf-core",
"version": "1.2.0",
"rustVersion": "1.87",
"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": [],
"sourceKind": "registry"
},
{
"name": "rns-crypto",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-link",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-protocol",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.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": "lxmf-tools",
"version": "1.2.0",
"rustVersion": "1.87",
"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.2.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.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-runtime",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [
"serial"
],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.2.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"
}
]
}
]
}
+911
View File
@@ -0,0 +1,911 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bitflags"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
dependencies = [
"generic-array",
]
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "bzip2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"libbz2-rs-sys",
]
[[package]]
name = "cbc"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
dependencies = [
"cipher",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "const-oid"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "der"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
name = "ed25519"
version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [
"pkcs8",
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
dependencies = [
"curve25519-dalek",
"ed25519",
"rand_core",
"serde",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fiat-crypto"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hkdf"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"block-padding",
"generic-array",
]
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "lxmf-core"
version = "1.2.0"
dependencies = [
"base64",
"bytes",
"hex",
"rand",
"rmp",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-link",
"rns-protocol",
"rns-transport",
"rns-wire",
"serde",
"sha2",
"thiserror",
"tokio",
"tracing",
"unicode-normalization",
]
[[package]]
name = "lxmf-message-api-fixture"
version = "0.0.0"
dependencies = [
"lxmf-core",
]
[[package]]
name = "mio"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pkcs8"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "rmp"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
dependencies = [
"num-traits",
]
[[package]]
name = "rmp-serde"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
dependencies = [
"rmp",
"serde",
]
[[package]]
name = "rmpv"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
dependencies = [
"rmp",
]
[[package]]
name = "rns-crypto"
version = "1.2.0"
dependencies = [
"aes",
"cbc",
"ed25519-dalek",
"hkdf",
"hmac",
"rand",
"rand_core",
"sha2",
"subtle",
"thiserror",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "rns-identity"
version = "1.2.0"
dependencies = [
"hex",
"rand",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-wire",
"serde",
"serde_bytes",
"thiserror",
"tracing",
"windows-sys",
"zeroize",
]
[[package]]
name = "rns-link"
version = "1.2.0"
dependencies = [
"hex",
"rand",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-wire",
"thiserror",
"tracing",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.2.0"
dependencies = [
"bzip2",
"hex",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-link",
"rns-wire",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "rns-transport"
version = "1.2.0"
dependencies = [
"bytes",
"hex",
"rand",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-wire",
"serde",
"subtle",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "rns-wire"
version = "1.2.0"
dependencies = [
"rns-crypto",
"sha2",
"thiserror",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_bytes"
version = "0.11.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
dependencies = [
"serde",
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"rand_core",
]
[[package]]
name = "smallvec"
version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "spki"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "tinyvec"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "x25519-dalek"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
dependencies = [
"curve25519-dalek",
"rand_core",
"serde",
"zeroize",
]
[[package]]
name = "zerocopy"
version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.56"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zeroize"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
+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" }
+42
View File
@@ -0,0 +1,42 @@
//! 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>();
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"schemaVersion": 1,
"snapshotSourceCommit": "c934ccc5feaaddb55461404094ed6bb514aae2cc",
"capabilities": ["LXMF-01"],
"canonicalPath": "lxmf_core::message_api",
"retainedPaths": [
"lxmf_core::message",
"lxmf_core::constants",
"lxmf_core::types"
],
"internalSpiExcluded": [
"router",
"delivery ownership",
"propagation",
"handlers",
"persistence",
"raw Reticulum transport channels"
],
"classification": "additive-minor",
"publicApiDiff": {"added": 70, "removed": 0},
"semver": "compatible additive facade; version selection is deferred to Wave D",
"deprecations": "none",
"wirePersistenceRuntimeImpact": "none; exact re-exports only",
"consumers": [
"Ratspeak messaging",
"external canonical fixture",
"retained legacy fixture"
],
"platformEvidence": [
"host example/test/clippy/rustdoc",
"Rust 1.87 external fixture",
"downstream product target gates at dependency handoff"
]
}
+46
View File
@@ -0,0 +1,46 @@
{
"schemaVersion": 1,
"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",
"capturedOn": "2026-08-17"
},
"compatibilityFloor": {
"evidenceCommit": "80bb96f799330e28a0125367d4c29826f5147cc3",
"sourceCommit": "b8d7afce73f7f098706029361568e63f22888ea3"
},
"snapshotSource": {
"commit": "c934ccc5feaaddb55461404094ed6bb514aae2cc",
"capturedOn": "2026-08-17",
"changeRecord": "api-reviews/wave-c-message-api.json"
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api-baseline/lxmf-core.txt",
"itemCount": 1622,
"sha256": "c958cfdcb53117b02d1dbe907af6afaf5017d5ba92364267e21d204fe5ef3023"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api-baseline/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
}
]
}
+2
View File
@@ -0,0 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.87"
+4
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]
@@ -17,12 +19,14 @@ thiserror = { workspace = true }
tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
rmp = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
serde = { workspace = true }
sha2 = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
unicode-normalization = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
+21
View File
@@ -0,0 +1,21 @@
//! Construct, sign, pack, and inspect an LXMF message through the canonical API.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, MessageState};
use rns_crypto::ed25519::Ed25519PrivateKey;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut message = LxMessage::new(
[0x11; 16],
[0x22; 16],
"Hello",
"LXMF from Rust",
DeliveryMethod::Direct,
);
message.sign(&Ed25519PrivateKey::generate())?;
let packed = message.pack()?;
let unpacked = LxMessage::unpack(&packed)?;
assert_eq!(unpacked.title, "Hello");
assert_eq!(unpacked.state, MessageState::Generating);
Ok(())
}
+55
View File
@@ -9,6 +9,7 @@ pub const FIELD_ICON_APPEARANCE: u8 = 0x04;
pub const FIELD_FILE_ATTACHMENTS: u8 = 0x05;
pub const FIELD_IMAGE: u8 = 0x06;
pub const FIELD_AUDIO: u8 = 0x07;
/// Bytes, full thread ID hash.
pub const FIELD_THREAD: u8 = 0x08;
pub const FIELD_COMMANDS: u8 = 0x09;
pub const FIELD_RESULTS: u8 = 0x0A;
@@ -17,6 +18,22 @@ pub const FIELD_TICKET: u8 = 0x0C;
pub const FIELD_EVENT: u8 = 0x0D;
pub const FIELD_RNR_REFS: u8 = 0x0E;
pub const FIELD_RENDERER: u8 = 0x0F;
/// Bytes, full `LXMessage` hash. Python reference: LXMF.py:23.
pub const FIELD_REPLY_TO: u8 = 0x30;
/// Bytes, quoted content in UTF-8 encoding. Python reference: LXMF.py:24.
pub const FIELD_REPLY_QUOTE: u8 = 0x31;
/// Dict keyed by [`REACTION_TO`] / [`REACTION_CONTENT`]. Python reference: LXMF.py:25.
pub const FIELD_REACTION: u8 = 0x40;
/// Dict keyed by [`COMMENT_FOR`]. Python reference: LXMF.py:26.
pub const FIELD_COMMENT: u8 = 0x41;
/// Dict keyed by [`CONTINUATION_OF`]. Python reference: LXMF.py:27.
pub const FIELD_CONTINUATION: u8 = 0x42;
// Unallocated fields between 0x00 and 0x80, both included, should be
// considered reserved for future extensibility. For experimental and
// unstable features, it is recommended to use fields above 0xFF.
// Python reference: LXMF.py:29-32.
pub const FIELD_CUSTOM_TYPE: u8 = 0xFB;
pub const FIELD_CUSTOM_DATA: u8 = 0xFC;
pub const FIELD_CUSTOM_META: u8 = 0xFD;
@@ -49,6 +66,27 @@ pub const RENDERER_MICRON: u8 = 0x01;
pub const RENDERER_MARKDOWN: u8 = 0x02;
pub const RENDERER_BBCODE: u8 = 0x03;
// Clients choose how to handle reaction content, if at all. While reactions
// are typically a single unicode emoji or similar, the exact implementation
// and sanitization is left up to the client. FIELD_REACTION dict keys —
// Python reference: LXMF.py:104-110.
/// Bytes, full `LXMessage` hash.
pub const REACTION_TO: u8 = 0x00;
/// Bytes, the reaction content in UTF-8 encoding.
pub const REACTION_CONTENT: u8 = 0x01;
// Comment content is carried as the normal LXM content, so clients that do
// not support comments display them as normal messages. FIELD_COMMENT dict
// key — Python reference: LXMF.py:112-118.
/// Bytes, full `LXMessage` hash.
pub const COMMENT_FOR: u8 = 0x00;
// Continuation content is carried as the normal LXM content, so clients that
// do not support continuations display them as normal messages.
// FIELD_CONTINUATION dict key — Python reference: LXMF.py:120-126.
/// Bytes, full `LXMessage` hash.
pub const CONTINUATION_OF: u8 = 0x00;
pub const PN_META_VERSION: u8 = 0x00;
pub const PN_META_NAME: u8 = 0x01;
pub const PN_META_SYNC_STRATUM: u8 = 0x02;
@@ -137,6 +175,9 @@ pub const MESSAGE_EXPIRY: u64 = 30 * 24 * 60 * 60;
pub const STAMP_COST_EXPIRY: u64 = 45 * 24 * 60 * 60;
/// Delay before announcing propagation node (seconds).
pub const NODE_ANNOUNCE_DELAY: u64 = 20;
/// LXMF configuration and announce values use decimal kilobytes, matching
/// Python's `limit_kb * 1000` accounting.
pub const BYTES_PER_KILOBYTE: usize = 1000;
pub const PROPAGATION_LIMIT: usize = 256;
pub const DELIVERY_LIMIT: usize = 1000;
/// PROPAGATION_LIMIT * 40, in KB.
@@ -341,4 +382,18 @@ mod tests {
assert_eq!(MAX_UNREACHABLE, 14 * 24 * 60 * 60);
assert_eq!(SYNC_BACKOFF_STEP, 12 * 60);
}
#[test]
fn test_field_standards_match_python_101() {
// LXMF.py:23-27 field allocations plus dict-key constants (LXMF.py:104-126).
assert_eq!(FIELD_REPLY_TO, 0x30);
assert_eq!(FIELD_REPLY_QUOTE, 0x31);
assert_eq!(FIELD_REACTION, 0x40);
assert_eq!(FIELD_COMMENT, 0x41);
assert_eq!(FIELD_CONTINUATION, 0x42);
assert_eq!(REACTION_TO, 0x00);
assert_eq!(REACTION_CONTENT, 0x01);
assert_eq!(COMMENT_FOR, 0x00);
assert_eq!(CONTINUATION_OF, 0x00);
}
}
+560
View File
@@ -0,0 +1,560 @@
//! Crash-safe ratchet ownership for an LXMF delivery destination.
//!
//! A delivery announce is returned only after any candidate private ratchet
//! and the associated announce-ordering state are durably committed. The
//! propagation destination intentionally does not use this type.
use std::path::{Path, PathBuf};
use rns_identity::announce_state::RatchetControlState;
use rns_identity::destination::{AnnounceTime, DestType, Destination, Direction};
use rns_identity::identity::Identity;
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
use thiserror::Error;
/// Reticulum aspect used by an LXMF delivery destination.
pub const DELIVERY_APP_NAME: &str = "lxmf.delivery";
/// Whether a delivery announce is a normal broadcast or a tagged path reply.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryAnnounceKind<'a> {
Broadcast,
PathResponse { tag: Option<&'a [u8]> },
}
#[derive(Debug, Error)]
pub enum DeliveryRatchetError {
#[error("LXMF delivery destination does not match the supplied identity")]
DestinationMismatch,
#[error("ratchet control state at {path} is untrusted; refusing to overwrite it")]
UntrustedControl { path: PathBuf },
#[error("announce coalesced until wall time advances")]
Coalesced,
#[error("failed to plan announce time: {0}")]
Plan(#[source] std::io::Error),
#[error("failed to persist announce ordering state at {path}: {source}")]
PersistControl {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error(transparent)]
Destination(#[from] rns_identity::destination::DestinationError),
#[error("internal ratchet invariant failed: {0}")]
Invariant(&'static str),
}
/// Owns the private-key ring, signed control sidecar, and exact tagged-response
/// cache for one `lxmf.delivery` destination.
pub struct DeliveryRatchetState {
destination: Destination,
ring: RatchetRing,
control: RatchetControlState,
ring_path: PathBuf,
control_path: PathBuf,
ring_file_trusted: bool,
control_file_trusted: bool,
}
impl DeliveryRatchetState {
/// Load verified state, preserving any invalid existing files in place.
///
/// A missing ring is generated and persisted before it becomes live. A
/// ring that cannot be stored leaves delivery available but unratcheted.
/// An invalid control sidecar defers new announces because their ordering
/// cannot be proven safely.
pub fn load_or_initialize(
identity: &Identity,
destination_hash: [u8; 16],
ring_path: PathBuf,
control_path: PathBuf,
wall_now: u64,
) -> Result<Self, DeliveryRatchetError> {
let destination = Destination::new(
Some(identity),
Direction::In,
DestType::Single,
DELIVERY_APP_NAME,
)?;
if destination.hash != destination_hash {
return Err(DeliveryRatchetError::DestinationMismatch);
}
let ring_existed = ring_path.exists();
let (mut ring, ring_file_trusted) = if ring_existed {
match RatchetRing::load_verified(&ring_path, identity) {
Ok(loaded) => {
let format = loaded.format();
let ring = loaded.into_ring();
if format == RatchetRingFormat::LegacyRust {
match ring.save_verified(&ring_path, identity) {
Ok(()) => tracing::info!(
path = %ring_path.display(),
"migrated legacy Rust ratchet ring to canonical format"
),
Err(error) => tracing::warn!(
path = %ring_path.display(),
%error,
"legacy ratchet ring is valid but canonical rewrite failed"
),
}
}
(ring, true)
}
Err(error) => {
tracing::error!(
path = %ring_path.display(),
%error,
"ratchet ring is untrusted; preserving it and announcing without a ratchet"
);
(RatchetRing::new(), false)
}
}
} else {
(RatchetRing::new(), true)
};
let control_existed = control_path.exists();
let (mut control, control_file_trusted) = if control_existed {
match RatchetControlState::load_verified(&control_path, identity, destination_hash) {
Ok(state) => (state, true),
Err(error) => {
tracing::error!(
path = %control_path.display(),
%error,
"ratchet control state is untrusted; preserving it and deferring new announces"
);
(
RatchetControlState::new(identity.hash, destination_hash),
false,
)
}
}
} else {
(
RatchetControlState::new(identity.hash, destination_hash),
true,
)
};
let mut control_changed = false;
if control_file_trusted && control.last_rotation_wall().is_none() {
control.anchor_rotation_if_unknown(wall_now);
control_changed = true;
}
if ring.is_empty() && ring_file_trusted && control_file_trusted {
let prepared = ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&ring_path, identity) {
Ok(()) => {
ring.commit_prepared_rotation(prepared);
control = control.with_rotation_at(wall_now);
control_changed = true;
}
Err(error) => tracing::error!(
path = %ring_path.display(),
%error,
"could not durably initialise ratchet ring; delivery announces will be unratcheted"
),
}
}
if control_file_trusted && (!control_existed || control_changed) {
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"
);
}
}
Ok(Self {
destination,
ring,
control,
ring_path,
control_path,
ring_file_trusted,
control_file_trusted,
})
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination.hash
}
pub fn ring(&self) -> &RatchetRing {
&self.ring
}
pub fn control(&self) -> &RatchetControlState {
&self.control
}
/// Build an announce after committing all state that its wire bytes claim.
///
/// `wall_now` supplies both rotation age and the 40-bit wire ordering
/// value. `cache_now` is a separate local elapsed-time domain used only for
/// tagged path-response expiry.
pub fn create_announce(
&mut self,
identity: &Identity,
app_data: &[u8],
wall_now: u64,
cache_now: f64,
kind: DeliveryAnnounceKind<'_>,
) -> Result<Vec<u8>, DeliveryRatchetError> {
if identity.hash != self.control.identity_hash() {
return Err(DeliveryRatchetError::DestinationMismatch);
}
let announce_time = AnnounceTime::new(wall_now, cache_now)?;
if let DeliveryAnnounceKind::PathResponse { tag: Some(tag) } = kind {
if let Some(packet) = self
.destination
.cached_path_response_packet(tag, cache_now)?
{
return Ok(packet);
}
}
if !self.control_file_trusted {
return Err(DeliveryRatchetError::UntrustedControl {
path: self.control_path.clone(),
});
}
let Some(mut candidate_control) = self
.control
.prepare_announce(wall_now)
.map_err(DeliveryRatchetError::Plan)?
else {
return Err(DeliveryRatchetError::Coalesced);
};
let rotation_due = self.ring.is_empty()
|| self
.control
.rotation_due(wall_now, self.ring.ratchet_interval());
let mut prepared_rotation = None;
let mut ratchet_public = self.ring.current_public_key();
if rotation_due && self.ring_file_trusted {
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&self.ring_path, identity) {
Ok(()) => {
ratchet_public = Some(prepared.public_key());
candidate_control = candidate_control.with_rotation_at(wall_now);
prepared_rotation = Some(prepared);
}
Err(error) => tracing::error!(
path = %self.ring_path.display(),
%error,
"ratchet rotation was not persisted; reusing the last durable ratchet"
),
}
}
candidate_control
.save_verified(&self.control_path, identity)
.map_err(|source| DeliveryRatchetError::PersistControl {
path: self.control_path.clone(),
source,
})?;
let wire_now =
candidate_control
.last_announce_wire()
.ok_or(DeliveryRatchetError::Invariant(
"prepared announce has no wire-order value",
))?;
if let Some(prepared) = prepared_rotation {
self.ring.commit_prepared_rotation(prepared);
}
self.control = candidate_control;
let (path_response, tag) = match kind {
DeliveryAnnounceKind::Broadcast => (false, None),
DeliveryAnnounceKind::PathResponse { tag } => (true, tag),
};
self.destination
.announce_packet_at(
identity,
Some(app_data),
ratchet_public.as_ref(),
path_response,
tag,
AnnounceTime::new(wire_now, announce_time.cache)?,
)
.map_err(DeliveryRatchetError::from)
}
/// Best-effort shutdown checkpoint. Invalid files detected during load are
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted {
if let Err(error) = self.ring.save_verified(&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");
}
}
}
pub fn ring_path(&self) -> &Path {
&self.ring_path
}
pub fn control_path(&self) -> &Path {
&self.control_path
}
}
#[cfg(test)]
mod tests {
use super::*;
use rns_identity::ratchet::ratchet_public_bytes;
fn unpack_announce(
raw: &[u8],
) -> (
rns_wire::header::PacketHeader,
rns_identity::announce::AnnounceData,
) {
let (header, header_len) = rns_wire::header::PacketHeader::unpack(raw).unwrap();
let announce = rns_identity::announce::AnnounceData::unpack(
&raw[header_len..],
header.flags.context_flag,
)
.unwrap();
(header, announce)
}
fn state_at(dir: &Path, identity: &Identity, wall_now: u64) -> DeliveryRatchetState {
let destination_hash =
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
DeliveryRatchetState::load_or_initialize(
identity,
destination_hash,
dir.join("ring"),
dir.join("ring.control"),
wall_now,
)
.unwrap()
}
#[test]
fn survives_restart_rotates_and_retains_the_previous_private_key() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let initial_public = state.ring.current_public_key().unwrap();
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
assert!(header.flags.context_flag);
assert_eq!(announce.ratchet, Some(initial_public));
let committed_wire_time = state.control.last_announce_wire();
assert!(matches!(
state.create_announce(
&identity,
b"changed",
101,
101.5,
DeliveryAnnounceKind::Broadcast,
),
Err(DeliveryRatchetError::Coalesced)
));
assert_eq!(state.control.last_announce_wire(), committed_wire_time);
let mut restarted = state_at(dir.path(), &identity, 102);
assert_eq!(restarted.ring.current_public_key(), Some(initial_public));
let raw = restarted
.create_announce(
&identity,
b"app",
102,
102.0,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
assert_eq!(unpack_announce(&raw).1.ratchet, Some(initial_public));
let rotate_at = 100 + restarted.ring.ratchet_interval();
let raw = restarted
.create_announce(
&identity,
b"app",
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
let rotated_public = unpack_announce(&raw).1.ratchet.unwrap();
assert_ne!(rotated_public, initial_public);
assert_eq!(restarted.ring.len(), 2);
assert!(
restarted
.ring
.private_keys()
.iter()
.any(|private| ratchet_public_bytes(private) == initial_public)
);
}
#[test]
fn unavailable_ring_storage_can_only_emit_an_unratcheted_announce() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let destination =
Destination::hash_from_name_and_identity(DELIVERY_APP_NAME, Some(&identity.hash));
let mut state = DeliveryRatchetState::load_or_initialize(
&identity,
destination,
dir.path().join("missing/ring"),
dir.path().join("ring.control"),
100,
)
.unwrap();
assert!(state.ring.is_empty());
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
let (header, announce) = unpack_announce(&raw);
assert!(!header.flags.context_flag);
assert_eq!(announce.ratchet, None);
assert!(state.ring.is_empty());
}
#[test]
fn corrupt_ring_is_preserved_and_never_advertised() {
let dir = tempfile::tempdir().unwrap();
let ring_path = dir.path().join("ring");
let corrupt = b"not-a-ratchet-ring";
std::fs::write(&ring_path, corrupt).unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let raw = state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
assert!(!unpack_announce(&raw).0.flags.context_flag);
assert_eq!(std::fs::read(ring_path).unwrap(), corrupt);
}
#[test]
fn failed_control_commit_cannot_publish_or_commit_a_prepared_rotation() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
state
.create_announce(
&identity,
b"app",
101,
101.0,
DeliveryAnnounceKind::Broadcast,
)
.unwrap();
let live_public = state.ring.current_public_key();
let live_wire_time = state.control.last_announce_wire();
state.control_path = dir.path().join("missing/ring.control");
let rotate_at = 100 + state.ring.ratchet_interval();
assert!(matches!(
state.create_announce(
&identity,
b"app",
rotate_at,
rotate_at as f64,
DeliveryAnnounceKind::Broadcast,
),
Err(DeliveryRatchetError::PersistControl { .. })
));
assert_eq!(state.ring.current_public_key(), live_public);
assert_eq!(state.control.last_announce_wire(), live_wire_time);
}
#[test]
fn same_tag_replays_exact_packet_without_consuming_announce_time() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let tag = b"path-request-tag";
let first = state
.create_announce(
&identity,
b"first",
101,
101.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
)
.unwrap();
let committed_wire = state.control.last_announce_wire();
let replay = state
.create_announce(
&identity,
b"changed",
101,
102.0,
DeliveryAnnounceKind::PathResponse { tag: Some(tag) },
)
.unwrap();
assert_eq!(
replay, first,
"removing the cache lookup changes signed bytes"
);
assert_eq!(state.control.last_announce_wire(), committed_wire);
assert_eq!(
unpack_announce(&replay).0.context,
rns_wire::context::PacketContext::PathResponse
);
}
#[test]
fn invalid_cache_clock_cannot_commit_announce_state() {
let dir = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut state = state_at(dir.path(), &identity, 100);
let live_wire = state.control.last_announce_wire();
let live_public = state.ring.current_public_key();
assert!(matches!(
state.create_announce(
&identity,
b"app",
101,
f64::NAN,
DeliveryAnnounceKind::Broadcast,
),
Err(DeliveryRatchetError::Destination(_))
));
assert_eq!(state.control.last_announce_wire(), live_wire);
assert_eq!(state.ring.current_public_key(), live_public);
}
}
+217 -60
View File
@@ -6,6 +6,7 @@
use std::collections::HashMap;
use crate::constants::*;
use crate::presentation::{MAX_ADVERTISED_NAME_CHARS, sanitize_name};
/// Announce handler type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -37,6 +38,17 @@ pub enum AnnounceResult {
Rejected(String),
}
/// Advertised delivery compression support from LXMF delivery-announce app data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionSupport {
/// No explicit supported-functionality metadata was present or parseable.
Unknown,
/// A supported-functionality list was present and omitted `SF_COMPRESSION`.
Unsupported,
/// A supported-functionality list was present and included `SF_COMPRESSION`.
Supported,
}
/// Parsed propagation-node announce data.
///
/// Wire layout is a 7-element msgpack array:
@@ -88,7 +100,12 @@ impl PropagationNodeAnnounceData {
}
pub fn set_name(&mut self, name: &str) {
self.metadata.insert(PN_META_NAME, name.as_bytes().to_vec());
let name = sanitize_name(name, MAX_ADVERTISED_NAME_CHARS);
if name.is_empty() {
self.metadata.remove(&PN_META_NAME);
} else {
self.metadata.insert(PN_META_NAME, name.into_bytes());
}
}
}
@@ -133,6 +150,17 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
/// dropped because it duplicated this function's checks and every
/// in-tree caller called both back-to-back.
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_i64().and_then(|number| number.try_into().ok()))
.or_else(|| {
value.as_f64().and_then(|number| {
(number.is_finite() && number >= 0.0).then_some(number as u64)
})
})
}
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
if arr.len() < 7 {
@@ -144,38 +172,27 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
.or_else(|| arr[1].as_u64().map(|u| u as i64))
.or_else(|| arr[1].as_f64().map(|f| f as i64))?;
let node_state = arr[2].as_bool()?;
let transfer_limit = arr[3]
.as_u64()
.or_else(|| arr[3].as_i64().map(|i| i as u64))
.or_else(|| arr[3].as_f64().map(|f| f as u64))?;
let sync_limit = arr[4]
.as_u64()
.or_else(|| arr[4].as_i64().map(|i| i as u64))
.or_else(|| arr[4].as_f64().map(|f| f as u64))?;
let transfer_limit = nonnegative_u64(&arr[3])?;
let sync_limit = nonnegative_u64(&arr[4])?;
let costs = arr[5].as_array()?;
if costs.len() < 3 {
return None;
}
let stamp_cost = costs[0]
.as_u64()
.or_else(|| costs[0].as_i64().map(|i| i as u64))? as u8;
let stamp_flex = costs[1]
.as_u64()
.or_else(|| costs[1].as_i64().map(|i| i as u64))? as u8;
let peering_cost = costs[2]
.as_u64()
.or_else(|| costs[2].as_i64().map(|i| i as u64))? as u8;
let stamp_cost = u8::try_from(nonnegative_u64(&costs[0])?).ok()?;
let stamp_flex = u8::try_from(nonnegative_u64(&costs[1])?).ok()?;
let peering_cost = u8::try_from(nonnegative_u64(&costs[2])?).ok()?;
// Python's `pn_announce_data_is_valid()` requires the metadata element to
// be a map. Unknown keys and non-binary values are ignored here because
// the typed Rust API can only retain metadata it can represent safely.
let mut metadata = HashMap::new();
if let Some(map) = arr[6].as_map() {
for (k, v) in map {
if let (Some(key), Some(val)) = (
k.as_u64().map(|u| u as u8),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
for (k, v) in arr[6].as_map()? {
if let (Some(key), Some(val)) = (
k.as_u64().and_then(|number| number.try_into().ok()),
v.as_slice().map(|s| s.to_vec()),
) {
metadata.insert(key, val);
}
}
@@ -199,33 +216,38 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_pn_announce_data(data).map(|p| p.stamp_cost)
}
/// Encode delivery-announce `app_data` as msgpack `[display_name, stamp_cost]`.
/// Encode delivery-announce `app_data` as msgpack
/// `[display_name, stamp_cost, supported_functionality]` where the feature
/// list advertises [`SF_COMPRESSION`].
///
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
///
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1000.
/// Python reference: `get_announce_app_data` — LXMRouter.py:985-1001 (1.0.1).
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
use rmpv::Value;
let name_val = match display_name {
Some(name) => Value::Binary(name.as_bytes().to_vec()),
None => Value::Nil,
};
let name_val = display_name
.map(|name| sanitize_name(name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
.map_or(Value::Nil, |name| Value::Binary(name.into_bytes()));
let cost_val = match stamp_cost {
Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64),
_ => Value::Nil,
};
let peer_data = Value::Array(vec![name_val, cost_val]);
let supported_functionality =
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]);
let peer_data = Value::Array(vec![name_val, cost_val, supported_functionality]);
crate::encode_value(&peer_data)
}
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
///
/// Accepts both Python LXMF 0.9.6's 2-element form and the optional 3-element
/// feature-list form used by newer/extended peers.
/// 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).
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
@@ -236,7 +258,8 @@ pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8
let display_name = arr[0]
.as_slice()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.map(|name| name.replace('\0', "").trim().to_string());
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty());
let stamp_cost = arr[1].as_u64().map(|c| c as u8);
@@ -257,27 +280,45 @@ pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_announce_app_data(data).and_then(|(_, cost)| cost)
}
/// Parse advertised `SF_COMPRESSION` support in delivery-announce `app_data`.
///
/// Legacy 2-element app_data, malformed data, and missing feature lists are
/// treated as unknown. A present feature list is authoritative.
///
/// Python reference: `compression_support_from_app_data` — LXMF.py:154-164.
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return CompressionSupport::Unknown;
};
let Some(arr) = value.as_array() else {
return CompressionSupport::Unknown;
};
if arr.len() < 3 {
return CompressionSupport::Unknown;
}
let Some(features) = arr[2].as_array() else {
return CompressionSupport::Unknown;
};
if features
.iter()
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
{
CompressionSupport::Supported
} else {
CompressionSupport::Unsupported
}
}
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
///
/// Returns `false` for legacy 2-element app_data or when the feature list is missing/empty.
/// 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.
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return false;
};
let Some(arr) = value.as_array() else {
return false;
};
if arr.len() < 3 {
return false;
}
let Some(features) = arr[2].as_array() else {
return false;
};
features
.iter()
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
}
/// Extract the advertised name from propagation-node announce data.
@@ -288,7 +329,10 @@ pub fn compression_support_from_app_data(data: &[u8]) -> bool {
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
let parsed = parse_pn_announce_data(data)?;
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
String::from_utf8(name_bytes.clone()).ok()
String::from_utf8(name_bytes.clone())
.ok()
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
}
/// Outcome of a resource transfer, matching Python `resource_concluded` /
@@ -407,12 +451,10 @@ impl PropagationRequestHandler {
true
};
let peer_hash = remote_identity_hash.copied().unwrap_or([0u8; 16]);
node.handle_offer_request(
request_data,
crate::propagation_node::OfferRequestContext {
peer_hash,
peer_hash: remote_identity_hash.copied().unwrap_or([0u8; 16]),
identity_known,
is_throttled,
access_allowed,
@@ -423,8 +465,9 @@ impl PropagationRequestHandler {
}
/// Handle a `/get` request from a client downloading messages. Phase-2
/// responses come back as a [`GetRequestAction::ServeFiles`] plan — the
/// embedder resolves it after releasing the node lock.
/// responses come back as a
/// [`GetRequestAction::ServeFiles`](crate::propagation_node::GetRequestAction::ServeFiles)
/// plan — the embedder resolves it after releasing the node lock.
///
/// Python reference: `LXMRouter.message_get_request` — LXMRouter.py:1425-1499.
pub fn handle_message_get_request(
@@ -683,6 +726,47 @@ mod tests {
assert!(parse_pn_announce_data(&[]).is_none());
assert!(parse_pn_announce_data(&[0x91, 0xC2]).is_none());
assert!(parse_pn_announce_data(&[0x01]).is_none());
let non_map_metadata = rmpv::Value::Array(vec![
rmpv::Value::Boolean(false),
rmpv::Value::from(1_777_716_440u64),
rmpv::Value::Boolean(true),
rmpv::Value::from(10_240),
rmpv::Value::from(10_240),
rmpv::Value::Array(vec![
rmpv::Value::from(16),
rmpv::Value::from(3),
rmpv::Value::from(18),
]),
rmpv::Value::Array(Vec::new()),
]);
assert!(
parse_pn_announce_data(&crate::encode_value(&non_map_metadata)).is_none(),
"Python rejects propagation announces whose metadata is not a map"
);
}
#[test]
fn test_pn_announce_data_rejects_wrapping_policy_values() {
use rmpv::Value;
let encode = |transfer_limit: Value, stamp_cost: Value| {
let value = Value::Array(vec![
Value::Boolean(false),
Value::from(1_777_716_440u64),
Value::Boolean(true),
transfer_limit,
Value::from(10240),
Value::Array(vec![stamp_cost, Value::from(3), Value::from(18)]),
Value::Map(vec![]),
]);
let mut packed = Vec::new();
rmpv::encode::write_value(&mut packed, &value).unwrap();
packed
};
assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none());
assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none());
}
#[test]
@@ -707,6 +791,16 @@ mod tests {
assert_eq!(cost, Some(12));
}
#[test]
fn test_delivery_announce_data_matches_python_101_bytes() {
// Python 1.0.1 oracle: msgpack([b"Test", 16, [SF_COMPRESSION]]) — LXMRouter.py:999-1001.
assert_eq!(
hex::encode(get_announce_app_data(Some("Test"), Some(16))),
"93c40454657374109100"
);
assert_eq!(hex::encode(get_announce_app_data(None, None)), "93c0c09100");
}
#[test]
fn test_delivery_announce_data_no_name() {
let packed = get_announce_app_data(None, Some(8));
@@ -760,6 +854,18 @@ mod tests {
);
}
#[test]
fn test_display_name_from_app_data_sanitizes_untrusted_unicode() {
let packed = get_announce_app_data(
Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "),
Some(12),
);
assert_eq!(
display_name_from_app_data(&packed),
Some("AliceNetwork".to_string())
);
}
#[test]
fn test_stamp_cost_from_app_data() {
let packed = get_announce_app_data(Some("Alice"), Some(12));
@@ -771,8 +877,18 @@ mod tests {
#[test]
fn test_compression_support_from_app_data() {
let python_096 = get_announce_app_data(Some("Alice"), Some(12));
assert!(!compression_support_from_app_data(&python_096));
// Legacy <=0.9.8 2-element app_data: unknown state, fail-open true
// (Python returns True for len < 3 — LXMF.py:161).
let python_098 = {
use rmpv::Value;
let arr = Value::Array(vec![Value::Binary(b"Alice".to_vec()), Value::from(12u64)]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&python_098),
CompressionSupport::Unknown
);
assert!(compression_support_from_app_data(&python_098));
let supported = {
use rmpv::Value;
@@ -783,8 +899,30 @@ mod tests {
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&supported),
CompressionSupport::Supported
);
assert!(compression_support_from_app_data(&supported));
let ratspeak_extended_supported = {
use rmpv::Value;
let arr = Value::Array(vec![
Value::Binary(b"Alice".to_vec()),
Value::from(12u64),
Value::Array(vec![Value::from(crate::constants::SF_COMPRESSION as u64)]),
Value::Map(vec![]),
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&ratspeak_extended_supported),
CompressionSupport::Supported
);
assert!(compression_support_from_app_data(
&ratspeak_extended_supported
));
// 3-element form with empty feature list -> unsupported.
let empty_features = {
use rmpv::Value;
@@ -795,7 +933,26 @@ mod tests {
]);
crate::encode_value(&arr)
};
assert_eq!(
compression_support_state_from_app_data(&empty_features),
CompressionSupport::Unsupported
);
assert!(!compression_support_from_app_data(&empty_features));
// Malformed data: unknown state, fail-open true (Python treats the
// original non-msgpack announce format as supported — LXMF.py:167).
assert_eq!(
compression_support_state_from_app_data(&[0xc1]),
CompressionSupport::Unknown
);
assert!(compression_support_from_app_data(&[0xc1]));
// Our own 1.0.1 emission round-trips as explicitly supported.
let own = get_announce_app_data(Some("Alice"), Some(12));
assert_eq!(
compression_support_state_from_app_data(&own),
CompressionSupport::Supported
);
}
#[test]
+484
View File
@@ -0,0 +1,484 @@
//! Actor-owned tracking for inbound LXMF delivery Resources.
//!
//! The Reticulum runtime owns the actual transfers. Embedders project its
//! lifecycle notifications into [`InboundResourceEvent`] and forward bounded
//! [`InboundResourceCancelRequest`] values back to that owner. This keeps the
//! public LXMF API independent of a concrete Reticulum runtime while retaining
//! exact `(link_id, logical_resource_id)` cancellation authority.
use std::collections::HashMap;
use tokio::sync::{mpsc, watch};
/// Exact owner key for one logical inbound Resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct InboundResourceKey {
pub link_id: [u8; 16],
pub resource_id: [u8; 32],
}
impl InboundResourceKey {
pub const fn new(link_id: [u8; 16], resource_id: [u8; 32]) -> Self {
Self {
link_id,
resource_id,
}
}
}
/// Terminal result of an inbound Resource transfer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InboundResourceConclusion {
Complete,
Cancelled,
Rejected,
Failed,
}
/// Current public state of an inbound Resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InboundResourceStatus {
Receiving,
Complete,
Cancelled,
Rejected,
Failed,
}
impl InboundResourceStatus {
pub const fn is_closed(self) -> bool {
!matches!(self, Self::Receiving)
}
}
impl From<InboundResourceConclusion> for InboundResourceStatus {
fn from(value: InboundResourceConclusion) -> Self {
match value {
InboundResourceConclusion::Complete => Self::Complete,
InboundResourceConclusion::Cancelled => Self::Cancelled,
InboundResourceConclusion::Rejected => Self::Rejected,
InboundResourceConclusion::Failed => Self::Failed,
}
}
}
/// Owned, non-sensitive snapshot of one inbound transfer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InboundResourceSnapshot {
pub key: InboundResourceKey,
pub data_size: usize,
pub transferred: usize,
pub total_segments: usize,
pub status: InboundResourceStatus,
}
impl InboundResourceSnapshot {
pub const fn is_closed(&self) -> bool {
self.status.is_closed()
}
}
/// Transport-neutral lifecycle input consumed by [`InboundResourceTracker`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InboundResourceEvent {
Started {
key: InboundResourceKey,
data_size: usize,
total_segments: usize,
},
Progress {
key: InboundResourceKey,
transferred: usize,
total: usize,
},
Concluded {
key: InboundResourceKey,
conclusion: InboundResourceConclusion,
},
LinkClosed {
link_id: [u8; 16],
},
}
/// Exact cancellation request for the embedding runtime's Resource owner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InboundResourceCancelRequest {
key: InboundResourceKey,
}
impl InboundResourceCancelRequest {
pub const fn new(key: InboundResourceKey) -> Self {
Self { key }
}
pub const fn key(self) -> InboundResourceKey {
self.key
}
}
/// Cloneable live handle retained by a caller after the active list changes.
#[derive(Debug, Clone)]
pub struct InboundResourceHandle {
key: InboundResourceKey,
snapshot_rx: watch::Receiver<InboundResourceSnapshot>,
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
}
impl InboundResourceHandle {
pub const fn key(&self) -> InboundResourceKey {
self.key
}
pub fn snapshot(&self) -> InboundResourceSnapshot {
self.snapshot_rx.borrow().clone()
}
/// Wait for the next lifecycle/progress update.
///
/// Returns `None` after the terminal snapshot has been published and the
/// actor owner has dropped its sender.
pub async fn changed(&mut self) -> Option<InboundResourceSnapshot> {
if self.snapshot_rx.changed().await.is_err() {
return None;
}
Some(self.snapshot())
}
/// Queue exact inbound cancellation without blocking the actor owner.
///
/// `false` means the transfer is already closed, cancellation is not
/// wired by the embedder, or the bounded command channel cannot accept the
/// request. Authoritative closure arrives through the lifecycle stream.
pub fn cancel(&self) -> bool {
if self.snapshot().is_closed() {
return false;
}
self.cancel_tx.as_ref().is_some_and(|tx| {
tx.try_send(InboundResourceCancelRequest::new(self.key))
.is_ok()
})
}
}
struct ActiveInboundResource {
snapshot_tx: watch::Sender<InboundResourceSnapshot>,
}
/// Single-owner active Resource registry.
///
/// 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.
#[derive(Default)]
pub struct InboundResourceTracker {
active: HashMap<InboundResourceKey, ActiveInboundResource>,
cancel_tx: Option<mpsc::Sender<InboundResourceCancelRequest>>,
}
impl InboundResourceTracker {
pub fn new(cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) -> Self {
Self {
active: HashMap::new(),
cancel_tx: Some(cancel_tx),
}
}
pub fn set_cancel_sender(&mut self, cancel_tx: mpsc::Sender<InboundResourceCancelRequest>) {
self.cancel_tx = Some(cancel_tx);
}
/// Number of currently active inbound Resources.
pub fn inbound_count(&self) -> usize {
self.active.len()
}
/// Deterministic snapshot of all active Resource handles.
pub fn inbound_resources(&self) -> Vec<InboundResourceHandle> {
let mut keys = self.active.keys().copied().collect::<Vec<_>>();
keys.sort_unstable();
keys.into_iter()
.filter_map(|key| self.handle_for(key))
.collect()
}
/// Return the active Resource matching `resource_id`.
///
/// A cryptographic ID collision across two Links fails closed instead of
/// choosing the wrong cancellation authority.
pub fn inbound_resource(&self, resource_id: &[u8; 32]) -> Option<InboundResourceHandle> {
let mut matches = self
.active
.keys()
.filter(|key| &key.resource_id == resource_id)
.copied();
let key = matches.next()?;
if matches.next().is_some() {
return None;
}
self.handle_for(key)
}
/// Return one exact active Resource.
pub fn inbound_resource_exact(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
self.handle_for(key)
}
/// Queue cancellation for one unique active logical Resource.
pub fn cancel_inbound(&self, resource_id: &[u8; 32]) -> bool {
self.inbound_resource(resource_id)
.is_some_and(|handle| handle.cancel())
}
/// Queue cancellation for one exact active Resource.
pub fn cancel_inbound_exact(&self, key: InboundResourceKey) -> bool {
self.handle_for(key).is_some_and(|handle| handle.cancel())
}
/// Queue cancellation for a stable snapshot of every active Resource.
///
/// The returned count is the number accepted by the bounded command
/// channel, matching Python's count-oriented `cancel_all_inbound` API.
pub fn cancel_all_inbound(&self) -> usize {
self.inbound_resources()
.into_iter()
.filter(InboundResourceHandle::cancel)
.count()
}
/// Apply one lifecycle update from the embedding runtime.
pub fn handle_event(&mut self, event: InboundResourceEvent) {
match event {
InboundResourceEvent::Started {
key,
data_size,
total_segments,
} => self.started(key, data_size, total_segments),
InboundResourceEvent::Progress {
key,
transferred,
total,
} => self.progress(key, transferred, total),
InboundResourceEvent::Concluded { key, conclusion } => self.concluded(key, conclusion),
InboundResourceEvent::LinkClosed { link_id } => self.link_closed(link_id),
}
}
fn handle_for(&self, key: InboundResourceKey) -> Option<InboundResourceHandle> {
let active = self.active.get(&key)?;
Some(InboundResourceHandle {
key,
snapshot_rx: active.snapshot_tx.subscribe(),
cancel_tx: self.cancel_tx.clone(),
})
}
fn started(&mut self, key: InboundResourceKey, data_size: usize, total_segments: usize) {
if let Some(active) = self.active.get(&key) {
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.data_size = snapshot.data_size.max(data_size);
snapshot.total_segments = snapshot.total_segments.max(total_segments.max(1));
active.snapshot_tx.send_replace(snapshot);
return;
}
let snapshot = InboundResourceSnapshot {
key,
data_size,
transferred: 0,
total_segments: total_segments.max(1),
status: InboundResourceStatus::Receiving,
};
let (snapshot_tx, _snapshot_rx) = watch::channel(snapshot);
self.active
.insert(key, ActiveInboundResource { snapshot_tx });
}
fn progress(&mut self, key: InboundResourceKey, transferred: usize, total: usize) {
let Some(active) = self.active.get(&key) else {
return;
};
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.data_size = snapshot.data_size.max(total);
snapshot.transferred = transferred.min(snapshot.data_size);
active.snapshot_tx.send_replace(snapshot);
}
fn concluded(&mut self, key: InboundResourceKey, conclusion: InboundResourceConclusion) {
let Some(active) = self.active.remove(&key) else {
return;
};
let mut snapshot = active.snapshot_tx.borrow().clone();
snapshot.status = conclusion.into();
if conclusion == InboundResourceConclusion::Complete {
snapshot.transferred = snapshot.data_size;
}
active.snapshot_tx.send_replace(snapshot);
}
fn link_closed(&mut self, link_id: [u8; 16]) {
let keys = self
.active
.keys()
.filter(|key| key.link_id == link_id)
.copied()
.collect::<Vec<_>>();
for key in keys {
self.concluded(key, InboundResourceConclusion::Failed);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(link: u8, resource: u8) -> InboundResourceKey {
InboundResourceKey::new([link; 16], [resource; 32])
}
fn started(key: InboundResourceKey, size: usize) -> InboundResourceEvent {
InboundResourceEvent::Started {
key,
data_size: size,
total_segments: 1,
}
}
#[tokio::test]
async fn active_handle_tracks_progress_and_terminal_snapshot() {
let (cancel_tx, _cancel_rx) = mpsc::channel(4);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let resource = key(1, 2);
tracker.handle_event(started(resource, 100));
let mut handle = tracker.inbound_resource(&resource.resource_id).unwrap();
assert_eq!(tracker.inbound_count(), 1);
assert_eq!(handle.snapshot().transferred, 0);
tracker.handle_event(InboundResourceEvent::Progress {
key: resource,
transferred: 40,
total: 100,
});
assert_eq!(handle.changed().await.unwrap().transferred, 40);
tracker.handle_event(InboundResourceEvent::Concluded {
key: resource,
conclusion: InboundResourceConclusion::Complete,
});
let terminal = handle.changed().await.unwrap();
assert_eq!(terminal.status, InboundResourceStatus::Complete);
assert_eq!(terminal.transferred, 100);
assert!(terminal.is_closed());
assert_eq!(tracker.inbound_count(), 0);
assert!(!handle.cancel());
assert!(handle.changed().await.is_none());
}
#[test]
fn cancellation_is_exact_bounded_and_snapshot_based() {
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let first = key(1, 3);
let second = key(2, 4);
tracker.handle_event(started(first, 10));
tracker.handle_event(started(second, 20));
assert!(tracker.cancel_inbound(&first.resource_id));
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
assert_eq!(tracker.cancel_all_inbound(), 2);
assert_eq!(cancel_rx.try_recv().unwrap().key(), first);
assert_eq!(cancel_rx.try_recv().unwrap().key(), second);
assert!(!tracker.cancel_inbound(&[9; 32]));
}
#[test]
fn full_cancel_channel_fails_without_removing_active_state() {
let (cancel_tx, _cancel_rx) = mpsc::channel(1);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let first = key(1, 5);
let second = key(1, 6);
tracker.handle_event(started(first, 10));
tracker.handle_event(started(second, 10));
assert!(tracker.cancel_inbound_exact(first));
assert!(!tracker.cancel_inbound_exact(second));
assert_eq!(tracker.inbound_count(), 2);
}
#[test]
fn duplicate_start_preserves_one_logical_handle() {
let (cancel_tx, _cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let split = key(3, 7);
tracker.handle_event(InboundResourceEvent::Started {
key: split,
data_size: 100,
total_segments: 3,
});
tracker.handle_event(InboundResourceEvent::Started {
key: split,
data_size: 100,
total_segments: 3,
});
assert_eq!(tracker.inbound_count(), 1);
let snapshot = tracker.inbound_resource_exact(split).unwrap().snapshot();
assert_eq!(snapshot.total_segments, 3);
}
#[test]
fn rejected_or_unknown_resources_never_become_visible() {
let mut tracker = InboundResourceTracker::default();
let unknown = key(4, 8);
tracker.handle_event(InboundResourceEvent::Progress {
key: unknown,
transferred: 5,
total: 10,
});
tracker.handle_event(InboundResourceEvent::Concluded {
key: unknown,
conclusion: InboundResourceConclusion::Rejected,
});
assert_eq!(tracker.inbound_count(), 0);
}
#[tokio::test]
async fn link_close_fails_only_resources_owned_by_that_link() {
let mut tracker = InboundResourceTracker::default();
let closed = key(5, 9);
let retained = key(6, 10);
tracker.handle_event(started(closed, 10));
tracker.handle_event(started(retained, 20));
let mut closed_handle = tracker.inbound_resource_exact(closed).unwrap();
tracker.handle_event(InboundResourceEvent::LinkClosed {
link_id: closed.link_id,
});
assert_eq!(
closed_handle.changed().await.unwrap().status,
InboundResourceStatus::Failed
);
assert!(tracker.inbound_resource_exact(closed).is_none());
assert!(tracker.inbound_resource_exact(retained).is_some());
}
#[test]
fn cancel_then_complete_is_terminal_and_not_requeued() {
let (cancel_tx, mut cancel_rx) = mpsc::channel(2);
let mut tracker = InboundResourceTracker::new(cancel_tx);
let resource = key(7, 11);
tracker.handle_event(started(resource, 10));
let handle = tracker.inbound_resource_exact(resource).unwrap();
assert!(handle.cancel());
assert_eq!(cancel_rx.try_recv().unwrap().key(), resource);
tracker.handle_event(InboundResourceEvent::Concluded {
key: resource,
conclusion: InboundResourceConclusion::Complete,
});
assert_eq!(handle.snapshot().status, InboundResourceStatus::Complete);
assert!(!handle.cancel());
assert_eq!(tracker.inbound_count(), 0);
}
}
+21
View File
@@ -12,6 +12,9 @@
//! | Module | What it does |
//! | --------------------- | -------------------------------------------------- |
//! | [`message`] | Message object: fields, packing, stamp, encryption |
//! | [`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 |
//! | [`peer`] | Propagation-peer state and sync bookkeeping |
//! | [`propagation`] | On-disk store-and-forward message pool |
@@ -41,15 +44,20 @@ pub(crate) fn now_f64() -> f64 {
}
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
pub mod handlers;
pub mod inbound_resource;
pub mod link_delivery;
pub mod message;
pub mod peer;
pub mod persist;
pub mod presentation;
pub mod propagation;
pub mod propagation_admission;
pub mod propagation_client;
pub mod propagation_node;
pub mod propagation_offer;
pub mod propagation_sync;
pub mod router;
pub mod stamper;
@@ -57,6 +65,19 @@ 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, LxMessage, MessageError};
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
+501 -21
View File
@@ -2,12 +2,15 @@
//!
//! Python reference: LXMF/LXMPeer.py.
use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::constants::*;
use crate::types::PropagationTransientId;
type StoredPeer = (
type LegacyStoredPeer = (
Vec<u8>,
f64,
u32,
@@ -19,6 +22,133 @@ type StoredPeer = (
Vec<Vec<u8>>,
);
const STORED_PEER_VERSION: u8 = 2;
const MAX_PEER_METADATA_ENTRIES: usize = 16;
const MAX_PEER_METADATA_VALUE_BYTES: usize = 1024;
const MAX_PEER_METADATA_BYTES: usize = 4096;
fn bounded_peer_metadata(metadata: Option<HashMap<u8, Vec<u8>>>) -> Option<HashMap<u8, Vec<u8>>> {
let metadata = metadata?;
let mut entries = metadata.into_iter().collect::<Vec<_>>();
entries.sort_by_key(|(key, _)| *key);
let mut retained = HashMap::new();
let mut retained_bytes = 0usize;
for (key, value) in entries.into_iter().take(MAX_PEER_METADATA_ENTRIES) {
if value.len() > MAX_PEER_METADATA_VALUE_BYTES {
continue;
}
let entry_bytes = 1usize.saturating_add(value.len());
if retained_bytes.saturating_add(entry_bytes) > MAX_PEER_METADATA_BYTES {
continue;
}
retained_bytes += entry_bytes;
retained.insert(key, value);
}
Some(retained)
}
/// Versioned peer persistence used by propagation sync.
///
/// The original Rust format was a nine-element tuple. Readers continue to
/// accept that tuple, while new writes retain the announce-derived policy
/// needed to prepare a correct outbound offer after restart.
#[derive(Debug, Serialize, Deserialize)]
struct StoredPeerV2 {
version: u8,
destination_hash: Vec<u8>,
last_sync: f64,
unreachable_count: u32,
peering_cost: u8,
stamp_cost: Option<u8>,
stamp_cost_flexibility: Option<u8>,
autopeered: bool,
is_static: bool,
handled_ids: Vec<Vec<u8>>,
peering_timebase: f64,
propagation_transfer_limit: Option<f64>,
propagation_sync_limit: Option<f64>,
peering_key: Option<(Vec<u8>, u32)>,
metadata: Option<HashMap<u8, Vec<u8>>>,
last_heard: f64,
alive: bool,
}
/// Immutable inputs for one outbound propagation offer.
///
/// `LxmPeer` remains the authoritative mutable owner. The network task gets a
/// clone of this snapshot so offer selection cannot silently fall back to a
/// newly-created peer that lacks announce or handled-message state.
#[derive(Debug, Clone, PartialEq)]
pub struct OutboundOfferPolicy {
pub peer_hash: [u8; 16],
pub handled_messages: HashSet<PropagationTransientId>,
pub stamp_cost: Option<u8>,
pub stamp_cost_flexibility: Option<u8>,
pub minimum_stamp_cost: u8,
pub peering_cost: u8,
pub propagation_transfer_limit: Option<f64>,
pub propagation_sync_limit: Option<f64>,
pub peering_key: Vec<u8>,
pub peering_key_value: Option<u32>,
pub peering_timebase: f64,
pub autopeered: bool,
pub is_static: bool,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
}
impl OutboundOfferPolicy {
/// Compatibility policy for callers that only know a peer hash.
///
/// This preserves the old unbounded selection behavior. Production
/// callers should construct a snapshot from the authoritative `LxmPeer`.
pub fn unrestricted(peer_hash: [u8; 16]) -> Self {
Self {
peer_hash,
handled_messages: HashSet::new(),
stamp_cost: None,
stamp_cost_flexibility: None,
minimum_stamp_cost: 0,
peering_cost: PEERING_COST,
propagation_transfer_limit: None,
propagation_sync_limit: None,
peering_key: Vec::new(),
peering_key_value: None,
peering_timebase: 0.0,
autopeered: false,
is_static: false,
metadata: None,
}
}
pub(crate) fn to_peer(&self) -> LxmPeer {
let mut peer = LxmPeer::new(self.peer_hash);
self.apply_to_peer(&mut peer);
peer
}
pub(crate) fn apply_to_peer(&self, peer: &mut LxmPeer) {
if self.peering_timebase >= peer.peering_timebase {
peer.peering_timebase = self.peering_timebase;
peer.stamp_cost = self.stamp_cost;
peer.stamp_cost_flexibility = self.stamp_cost_flexibility;
peer.peering_cost = self.peering_cost;
peer.propagation_transfer_limit = self.propagation_transfer_limit;
peer.propagation_sync_limit = self.propagation_sync_limit;
peer.peering_key = self.peering_key_value.and_then(|value| {
let stamp: [u8; 32] = self.peering_key.clone().try_into().ok()?;
Some((stamp, value))
});
peer.autopeered = self.autopeered;
peer.is_static = self.is_static;
peer.metadata = self.metadata.clone();
}
peer.handled_messages
.extend(self.handled_messages.iter().copied());
}
}
/// An LXMF peer propagation node.
#[derive(Debug)]
pub struct LxmPeer {
@@ -58,11 +188,15 @@ pub struct LxmPeer {
pub last_sync_attempt: f64,
pub next_sync_attempt: f64,
pub sync_backoff: f64,
pub metadata: Option<Vec<u8>>,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
/// Last local propagation-store revision conclusively processed by this
/// peer. This is intentionally process-local because node revisions reset
/// when the store is reconstructed at startup.
pub last_offer_generation: u64,
/// Static peers are operator-configured; autopeered peers come from announces.
pub is_static: bool,
/// Message hashes already handled by this peer, for sync filtering.
pub handled_messages: std::collections::HashSet<PropagationTransientId>,
pub handled_messages: HashSet<PropagationTransientId>,
}
impl LxmPeer {
@@ -100,8 +234,9 @@ impl LxmPeer {
next_sync_attempt: 0.0,
sync_backoff: 0.0,
metadata: None,
last_offer_generation: 0,
is_static: false,
handled_messages: std::collections::HashSet::new(),
handled_messages: HashSet::new(),
}
}
@@ -118,22 +253,122 @@ impl LxmPeer {
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> Self {
Self::from_announce_with_metadata(
destination_hash,
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
None,
)
}
/// Construct a peer from announce data, retaining bounded metadata.
#[allow(clippy::too_many_arguments)]
pub fn from_announce_with_metadata(
destination_hash: [u8; 16],
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> Self {
let mut peer = Self::new(destination_hash);
peer.peering_timebase = timebase;
peer.propagation_transfer_limit = transfer_limit;
peer.propagation_sync_limit = sync_limit;
peer.propagation_sync_limit = sync_limit.or(transfer_limit);
peer.stamp_cost = stamp_cost;
peer.stamp_cost_flexibility = stamp_flexibility;
peer.peering_cost = peering_cost.unwrap_or(PEERING_COST);
peer.metadata = bounded_peer_metadata(metadata);
peer.autopeered = true;
peer
}
/// Effective minimum stamp cost this peer will accept.
/// Refresh announce-derived policy only when `timebase` is newer.
///
/// Returns `true` when the peer was updated. Runtime counters, handled
/// messages and static-peer status remain owned by the existing peer.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
) -> bool {
let metadata = self.metadata.clone();
self.refresh_from_announce_with_metadata(
timebase,
transfer_limit,
sync_limit,
stamp_cost,
stamp_flexibility,
peering_cost,
metadata,
)
}
/// Refresh announce-derived policy and bounded metadata only when newer.
#[allow(clippy::too_many_arguments)]
pub fn refresh_from_announce_with_metadata(
&mut self,
timebase: f64,
transfer_limit: Option<f64>,
sync_limit: Option<f64>,
stamp_cost: Option<u8>,
stamp_flexibility: Option<u8>,
peering_cost: Option<u8>,
metadata: Option<HashMap<u8, Vec<u8>>>,
) -> bool {
if timebase <= self.peering_timebase {
return false;
}
let offer_constraints_changed = self.propagation_transfer_limit != transfer_limit
|| self.propagation_sync_limit != sync_limit.or(transfer_limit)
|| self.stamp_cost != stamp_cost
|| self.stamp_cost_flexibility != stamp_flexibility
|| self.peering_cost != peering_cost.unwrap_or(PEERING_COST);
self.peering_timebase = timebase;
self.propagation_transfer_limit = transfer_limit;
self.propagation_sync_limit = sync_limit.or(transfer_limit);
self.stamp_cost = stamp_cost;
self.stamp_cost_flexibility = stamp_flexibility;
self.peering_cost = peering_cost.unwrap_or(PEERING_COST);
self.metadata = bounded_peer_metadata(metadata);
if offer_constraints_changed {
self.last_offer_generation = 0;
}
// A key remains usable when it still meets the new target. Otherwise
// the daemon must generate a replacement before taking a snapshot.
if self
.peering_key
.is_some_and(|(_, value)| value < self.peering_cost as u32)
{
self.peering_key = None;
}
self.heard();
self.next_sync_attempt = 0.0;
true
}
/// Effective minimum stamp cost this peer will accept, using the peer's
/// announced flexibility when known (Python `LXMPeer.sync`: cost - flex).
pub fn minimum_accepted_stamp_cost(&self) -> u8 {
match self.stamp_cost {
Some(cost) => cost.saturating_sub(PROPAGATION_COST_FLEX),
Some(cost) => {
cost.saturating_sub(self.stamp_cost_flexibility.unwrap_or(PROPAGATION_COST_FLEX))
}
None => 0,
}
}
@@ -142,6 +377,11 @@ impl LxmPeer {
self.stamp_cost.is_some() && self.stamp_cost_flexibility.is_some()
}
/// Snapshot the complete immutable policy for one outbound sync offer.
pub fn outbound_offer_policy(&self) -> OutboundOfferPolicy {
OutboundOfferPolicy::from(self)
}
pub fn add_unhandled_message(&mut self) {
self.unhandled_count_cached = false;
self.unhandled_count += 1;
@@ -171,27 +411,50 @@ impl LxmPeer {
self.handled_messages.contains(hash)
}
pub fn needs_offer_generation(&self, generation: u64) -> bool {
generation > self.last_offer_generation
}
pub fn mark_offer_generation_processed(&mut self, generation: u64) {
self.last_offer_generation = self.last_offer_generation.max(generation);
}
/// Serialize peer state, including handled messages, for persistence.
pub fn to_bytes_with_handled(&self) -> Vec<u8> {
let handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
let data = (
self.destination_hash.to_vec(),
self.last_sync,
self.unreachable_count,
self.peering_cost,
self.stamp_cost,
self.stamp_cost_flexibility,
self.autopeered,
self.is_static,
handled,
);
rmp_serde::to_vec(&data).unwrap_or_default()
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
handled.sort();
let data = StoredPeerV2 {
version: STORED_PEER_VERSION,
destination_hash: self.destination_hash.to_vec(),
last_sync: self.last_sync,
unreachable_count: self.unreachable_count,
peering_cost: self.peering_cost,
stamp_cost: self.stamp_cost,
stamp_cost_flexibility: self.stamp_cost_flexibility,
autopeered: self.autopeered,
is_static: self.is_static,
handled_ids: handled,
peering_timebase: self.peering_timebase,
propagation_transfer_limit: self.propagation_transfer_limit,
propagation_sync_limit: self.propagation_sync_limit,
peering_key: self
.peering_key
.map(|(stamp, value)| (stamp.to_vec(), value)),
metadata: self.metadata.clone(),
last_heard: self.last_heard,
alive: self.alive,
};
rmp_serde::to_vec_named(&data).unwrap_or_default()
}
/// Deserialize peer state, including handled messages, from [`to_bytes_with_handled`] output.
///
/// [`to_bytes_with_handled`]: Self::to_bytes_with_handled
pub fn from_bytes_with_handled(data: &[u8]) -> Option<Self> {
if let Ok(stored) = rmp_serde::from_slice::<StoredPeerV2>(data) {
return Self::from_stored_v2(stored);
}
let (
dest_hash_vec,
last_sync,
@@ -202,7 +465,7 @@ impl LxmPeer {
autopeered,
is_static,
handled_vec,
): StoredPeer = rmp_serde::from_slice(data).ok()?;
): LegacyStoredPeer = rmp_serde::from_slice(data).ok()?;
if dest_hash_vec.len() != 16 {
return None;
}
@@ -231,6 +494,39 @@ impl LxmPeer {
Some(peer)
}
fn from_stored_v2(stored: StoredPeerV2) -> Option<Self> {
if stored.version != STORED_PEER_VERSION || stored.destination_hash.len() != 16 {
return None;
}
let mut destination_hash = [0u8; 16];
destination_hash.copy_from_slice(&stored.destination_hash);
let mut peer = Self::new(destination_hash);
peer.last_sync = stored.last_sync;
peer.unreachable_count = stored.unreachable_count;
peer.peering_cost = stored.peering_cost;
peer.stamp_cost = stored.stamp_cost;
peer.stamp_cost_flexibility = stored.stamp_cost_flexibility;
peer.autopeered = stored.autopeered;
peer.is_static = stored.is_static;
peer.peering_timebase = stored.peering_timebase;
peer.propagation_transfer_limit = stored.propagation_transfer_limit;
peer.propagation_sync_limit = stored.propagation_sync_limit;
peer.peering_key = stored.peering_key.and_then(|(stamp, value)| {
let stamp: [u8; 32] = stamp.try_into().ok()?;
Some((stamp, value))
});
peer.metadata = stored.metadata;
peer.last_heard = stored.last_heard;
peer.alive = stored.alive;
peer.handled_messages = stored
.handled_ids
.into_iter()
.filter_map(|value| value.try_into().ok())
.collect();
Some(peer)
}
pub fn mark_unreachable(&mut self) {
self.unreachable_count += 1;
let now = now_f64();
@@ -372,6 +668,32 @@ impl LxmPeer {
}
}
impl From<&LxmPeer> for OutboundOfferPolicy {
fn from(peer: &LxmPeer) -> Self {
let peering_key = peer
.peering_key
.filter(|(_, value)| *value >= peer.peering_cost as u32)
.map(|(stamp, _)| stamp.to_vec())
.unwrap_or_default();
Self {
peer_hash: peer.destination_hash,
handled_messages: peer.handled_messages.clone(),
stamp_cost: peer.stamp_cost,
stamp_cost_flexibility: peer.stamp_cost_flexibility,
minimum_stamp_cost: peer.minimum_accepted_stamp_cost(),
peering_cost: peer.peering_cost,
propagation_transfer_limit: peer.propagation_transfer_limit,
propagation_sync_limit: peer.propagation_sync_limit,
peering_key,
peering_key_value: peer.peering_key.map(|(_, value)| value),
peering_timebase: peer.peering_timebase,
autopeered: peer.autopeered,
is_static: peer.is_static,
metadata: peer.metadata.clone(),
}
}
}
/// Select the best peer to sync with from a set of candidates.
///
/// Mirrors Python `sync_peers()`: draw from the fastest [`FASTEST_N_RANDOM_POOL`] alive peers,
@@ -465,6 +787,164 @@ mod tests {
// cost < flex must saturate at 0.
peer.stamp_cost = Some(2);
assert_eq!(peer.minimum_accepted_stamp_cost(), 0);
// Announced flexibility overrides the default.
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(5);
assert_eq!(peer.minimum_accepted_stamp_cost(), 11);
peer.stamp_cost_flexibility = Some(0);
assert_eq!(peer.minimum_accepted_stamp_cost(), 16);
}
#[test]
fn outbound_offer_policy_captures_authoritative_peer_state() {
let mut peer = LxmPeer::new([0xAA; 16]);
peer.stamp_cost = Some(16);
peer.stamp_cost_flexibility = Some(3);
peer.propagation_transfer_limit = Some(1.5);
peer.propagation_sync_limit = Some(4.5);
peer.peering_cost = 18;
peer.peering_key = Some(([0x77; 32], 18));
peer.add_handled_message(&tid(0x11));
let policy = peer.outbound_offer_policy();
assert_eq!(policy.peer_hash, [0xAA; 16]);
assert_eq!(policy.minimum_stamp_cost, 13);
assert_eq!(policy.propagation_transfer_limit, Some(1.5));
assert_eq!(policy.propagation_sync_limit, Some(4.5));
assert_eq!(policy.peering_key, vec![0x77; 32]);
assert!(policy.handled_messages.contains(&tid(0x11)));
}
#[test]
fn stale_announce_cannot_overwrite_newer_peer_policy() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
200.0,
Some(2.0),
Some(8.0),
Some(16),
Some(3),
Some(18),
);
assert!(!peer.refresh_from_announce(
199.0,
Some(1.0),
Some(4.0),
Some(8),
Some(1),
Some(4),
));
assert_eq!(peer.peering_timebase, 200.0);
assert_eq!(peer.propagation_transfer_limit, Some(2.0));
assert_eq!(peer.stamp_cost, Some(16));
peer.peering_key = Some(([0x55; 32], 18));
assert!(peer.refresh_from_announce(201.0, Some(3.0), None, Some(20), Some(4), Some(19),));
assert_eq!(peer.propagation_sync_limit, Some(3.0));
assert_eq!(peer.stamp_cost, Some(20));
assert!(peer.peering_key.is_none(), "under-cost key must be cleared");
}
#[test]
fn peer_persistence_retains_offer_policy_and_reads_legacy_tuple() {
let mut peer = LxmPeer::from_announce(
[0xAA; 16],
1234.0,
Some(1.25),
Some(9.5),
Some(16),
Some(3),
Some(18),
);
peer.peering_key = Some(([0x66; 32], 19));
peer.metadata = Some(HashMap::from([(0, vec![1, 2, 3])]));
peer.add_handled_message(&tid(0x22));
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.peering_timebase, 1234.0);
assert_eq!(restored.propagation_transfer_limit, Some(1.25));
assert_eq!(restored.propagation_sync_limit, Some(9.5));
assert_eq!(restored.peering_key, Some(([0x66; 32], 19)));
assert_eq!(restored.metadata, Some(HashMap::from([(0, vec![1, 2, 3])])));
assert!(restored.has_handled(&tid(0x22)));
let legacy: LegacyStoredPeer = (
vec![0xBB; 16],
42.0,
2,
18,
Some(12),
Some(2),
true,
false,
vec![tid(0x33).to_vec()],
);
let legacy_bytes = rmp_serde::to_vec(&legacy).unwrap();
let restored_legacy = LxmPeer::from_bytes_with_handled(&legacy_bytes).unwrap();
assert_eq!(restored_legacy.destination_hash, [0xBB; 16]);
assert_eq!(restored_legacy.stamp_cost, Some(12));
assert!(restored_legacy.has_handled(&tid(0x33)));
}
#[test]
fn announce_metadata_is_typed_bounded_and_persisted() {
let mut metadata = HashMap::new();
metadata.insert(0, b"node name".to_vec());
metadata.insert(1, vec![0xAA; MAX_PEER_METADATA_VALUE_BYTES + 1]);
for key in 2..=30 {
metadata.insert(key, vec![key; 8]);
}
let peer = LxmPeer::from_announce_with_metadata(
[0xAA; 16],
10.0,
Some(1.0),
Some(2.0),
Some(12),
Some(3),
Some(18),
Some(metadata),
);
let retained = peer.metadata.as_ref().unwrap();
assert_eq!(retained.get(&0), Some(&b"node name".to_vec()));
assert!(!retained.contains_key(&1));
assert!(retained.len() <= MAX_PEER_METADATA_ENTRIES);
let restored = LxmPeer::from_bytes_with_handled(&peer.to_bytes_with_handled()).unwrap();
assert_eq!(restored.metadata, peer.metadata);
let empty = LxmPeer::from_announce_with_metadata(
[0xBB; 16],
10.0,
None,
None,
None,
None,
None,
Some(HashMap::new()),
);
assert_eq!(empty.metadata, Some(HashMap::new()));
}
#[test]
fn newer_policy_invalidates_processed_store_generation() {
let mut peer =
LxmPeer::from_announce([0xAA; 16], 10.0, None, None, Some(16), Some(3), None);
peer.mark_offer_generation_processed(7);
assert!(!peer.needs_offer_generation(7));
assert!(peer.refresh_from_announce(11.0, None, None, Some(12), Some(3), None));
assert!(peer.needs_offer_generation(7));
peer.mark_offer_generation_processed(7);
assert!(peer.refresh_from_announce(12.0, None, None, Some(12), Some(3), None));
assert!(
!peer.needs_offer_generation(7),
"a newer announce with unchanged offer constraints must not rescan an unchanged store"
);
}
/// T0-4: an absurd announce-supplied peering cost must fail the bounded
+236 -16
View File
@@ -2,7 +2,7 @@
//!
//! Files:
//! * `outbound_stamp_costs` — `HashMap<dest_hash, StampCostEntry>`
//! * `available_tickets` — `Vec<Ticket>`
//! * `available_tickets` — versioned directional ticket state
//! * `local_deliveries` — `HashMap<transient_id, timestamp>`
//! * `locally_processed` — `HashMap<transient_id, timestamp>`
//!
@@ -16,13 +16,70 @@ use std::io;
use std::path::Path;
use crate::router::StampCostEntry;
use crate::ticket::Ticket;
use crate::ticket::{Ticket, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
pub const STAMP_COSTS_FILE: &str = "outbound_stamp_costs";
pub const TICKETS_FILE: &str = "available_tickets";
pub const LOCAL_DELIVERIES_FILE: &str = "local_deliveries";
pub const LOCALLY_PROCESSED_FILE: &str = "locally_processed";
pub const NODE_STATS_FILE: &str = "node_stats";
/// Counters persisted by Python's `LXMRouter.save_node_stats`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PersistedNodeStats {
pub client_propagation_messages_received: u64,
pub client_propagation_messages_served: u64,
pub unpeered_propagation_incoming: u64,
pub unpeered_propagation_rx_bytes: u64,
}
/// 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).
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write;
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);
let result = (|| {
let mut file = fs::File::create(&tmp)?;
file.write_all(data)?;
file.flush()?;
if let Err(e) = file.sync_all() {
tracing::warn!(
"Error while waiting for persist fsync for {}: {e}",
tmp.display()
);
}
drop(file);
fs::rename(&tmp, path)
})();
if result.is_err() && tmp.exists() {
if let Err(e) = fs::remove_file(&tmp) {
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
}
}
result
}
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
let bytes =
@@ -30,10 +87,7 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let tmp = path.with_extension("tmp");
fs::write(&tmp, &bytes)?;
fs::rename(&tmp, path)?;
Ok(())
write_file_atomic(path, &bytes)
}
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
@@ -56,12 +110,23 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
pub fn save_tickets(dir: &Path, tickets: &[Ticket]) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), &tickets)
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
}
pub fn load_tickets(dir: &Path) -> io::Result<Vec<Ticket>> {
Ok(read_mpk(&dir.join(TICKETS_FILE))?.unwrap_or_default())
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum PersistedTickets {
Directional(TicketStoreSnapshot),
Legacy(Vec<Ticket>),
}
pub fn load_tickets(dir: &Path) -> io::Result<(TicketStoreSnapshot, Option<Vec<Ticket>>)> {
Ok(match read_mpk(&dir.join(TICKETS_FILE))? {
Some(PersistedTickets::Directional(snapshot)) => (snapshot, None),
Some(PersistedTickets::Legacy(tickets)) => (TicketStoreSnapshot::default(), Some(tickets)),
None => (TicketStoreSnapshot::default(), None),
})
}
pub fn save_local_deliveries(
@@ -86,6 +151,17 @@ pub fn load_locally_processed(dir: &Path) -> io::Result<HashMap<PropagationTrans
Ok(read_mpk(&dir.join(LOCALLY_PROCESSED_FILE))?.unwrap_or_default())
}
pub fn save_node_stats(dir: &Path, stats: &PersistedNodeStats) -> io::Result<()> {
let bytes = rmp_serde::to_vec_named(stats)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
fs::create_dir_all(dir)?;
write_file_atomic(&dir.join(NODE_STATS_FILE), &bytes)
}
pub fn load_node_stats(dir: &Path) -> io::Result<PersistedNodeStats> {
Ok(read_mpk(&dir.join(NODE_STATS_FILE))?.unwrap_or_default())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -111,12 +187,26 @@ mod tests {
#[test]
fn tickets_roundtrip() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
let tickets = TicketStoreSnapshot {
version: 1,
outbound: vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)],
inbound: vec![Ticket::new([0x03; 16], [0x04; 16], 8_888.0)],
last_deliveries: HashMap::from([([0x02; 16], 7_777.0)]),
};
save_tickets(tmp.path(), &tickets).unwrap();
let loaded = load_tickets(tmp.path()).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].token, [0x01; 16]);
assert_eq!(loaded[0].destination_hash, [0x02; 16]);
let (loaded, legacy) = load_tickets(tmp.path()).unwrap();
assert!(legacy.is_none());
assert_eq!(loaded, tickets);
}
#[test]
fn legacy_flat_tickets_are_detected_for_migration() {
let tmp = TempDir::new().unwrap();
let tickets = vec![Ticket::new([0x01; 16], [0x02; 16], 9_999.0)];
write_mpk(&tmp.path().join(TICKETS_FILE), &tickets).unwrap();
let (snapshot, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(snapshot, TicketStoreSnapshot::default());
assert_eq!(legacy.unwrap(), tickets);
}
#[test]
@@ -133,8 +223,138 @@ mod tests {
fn missing_file_returns_default() {
let tmp = TempDir::new().unwrap();
assert!(load_stamp_costs(tmp.path()).unwrap().is_empty());
assert!(load_tickets(tmp.path()).unwrap().is_empty());
let (tickets, legacy) = load_tickets(tmp.path()).unwrap();
assert_eq!(tickets, TicketStoreSnapshot::default());
assert!(legacy.is_none());
assert!(load_local_deliveries(tmp.path()).unwrap().is_empty());
assert!(load_locally_processed(tmp.path()).unwrap().is_empty());
assert_eq!(
load_node_stats(tmp.path()).unwrap(),
PersistedNodeStats::default()
);
}
#[test]
fn node_stats_roundtrip_uses_named_python_fields() {
let tmp = TempDir::new().unwrap();
let expected = PersistedNodeStats {
client_propagation_messages_received: 11,
client_propagation_messages_served: 12,
unpeered_propagation_incoming: 13,
unpeered_propagation_rx_bytes: 14,
};
save_node_stats(tmp.path(), &expected).unwrap();
assert_eq!(load_node_stats(tmp.path()).unwrap(), expected);
let encoded = fs::read(tmp.path().join(NODE_STATS_FILE)).unwrap();
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(encoded)).unwrap();
let keys = value
.as_map()
.unwrap()
.iter()
.filter_map(|(key, _)| key.as_str())
.collect::<std::collections::HashSet<_>>();
assert!(keys.contains("client_propagation_messages_received"));
assert!(keys.contains("client_propagation_messages_served"));
assert!(keys.contains("unpeered_propagation_incoming"));
assert!(keys.contains("unpeered_propagation_rx_bytes"));
}
#[test]
fn write_file_atomic_writes_and_replaces_without_leftover_tmp() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("message");
write_file_atomic(&path, b"first").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"first");
// Replaces existing content (os.replace semantics — LXMessage.py:687).
write_file_atomic(&path, b"second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"second");
// No .tmp.* residue in the directory after successful writes.
let leftovers: Vec<_> = fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn write_file_atomic_cleans_tmp_on_error() {
let tmp = TempDir::new().unwrap();
// Destination is a directory: the final rename fails, and the tmp
// file must be unlinked (LXMessage.py:691-693).
let dir_path = tmp.path().join("collide");
fs::create_dir(&dir_path).unwrap();
assert!(write_file_atomic(&dir_path, b"data").is_err());
let leftovers: Vec<_> = fs::read_dir(tmp.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn serialization_failure_preserves_existing_file_without_temp_residue() {
struct FailsToSerialize;
impl serde::Serialize for FailsToSerialize {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("intentional failure"))
}
}
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("state");
fs::write(&path, b"previous-good-state").unwrap();
assert!(write_mpk(&path, &FailsToSerialize).is_err());
assert_eq!(fs::read(&path).unwrap(), b"previous-good-state");
assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1);
}
#[test]
fn concurrent_atomic_writers_never_publish_torn_data_or_collide_on_temp_names() {
use std::sync::{Arc, Barrier};
let tmp = TempDir::new().unwrap();
let path = Arc::new(tmp.path().join("shared"));
let barrier = Arc::new(Barrier::new(8));
let payloads = (0u8..8)
.map(|value| vec![value; 16 * 1024])
.collect::<Vec<_>>();
let threads = payloads
.iter()
.cloned()
.map(|payload| {
let path = Arc::clone(&path);
let barrier = Arc::clone(&barrier);
std::thread::spawn(move || {
barrier.wait();
write_file_atomic(path.as_ref(), &payload).unwrap();
})
})
.collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
let published = fs::read(path.as_ref()).unwrap();
assert!(payloads.contains(&published));
let leftovers = fs::read_dir(tmp.path())
.unwrap()
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp."))
.count();
assert_eq!(leftovers, 0);
}
}
+157
View File
@@ -0,0 +1,157 @@
//! Safe presentation helpers for untrusted announce metadata.
use unicode_normalization::UnicodeNormalization;
/// Maximum retained characters for an advertised LXMF display/node name.
pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name.
///
/// 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.
pub fn sanitize_name(input: &str, max_chars: usize) -> String {
if max_chars == 0 {
return String::new();
}
let mut output = String::new();
let mut pending_space = false;
let mut retained = 0usize;
for character in input.nfkc() {
if is_filtered_name_character(character) {
continue;
}
if character.is_whitespace() {
pending_space = !output.is_empty();
continue;
}
if pending_space {
// A collapsed separator is useful only when the current visible
// character also fits. Never consume the final slot with a
// trailing space that disappears on the next sanitization pass.
if max_chars.saturating_sub(retained) < 2 {
break;
}
output.push(' ');
retained += 1;
pending_space = false;
}
if retained == max_chars {
break;
}
output.push(character);
retained += 1;
}
output
}
fn is_filtered_name_character(character: char) -> bool {
let codepoint = character as u32;
character.is_control()
|| is_bidi_control(codepoint)
|| is_private_use(codepoint)
|| is_zero_width(codepoint)
|| is_variation_selector(codepoint)
|| is_emoji(codepoint)
}
fn is_bidi_control(codepoint: u32) -> bool {
matches!(
codepoint,
0x061C
| 0x200E
| 0x200F
| 0x202A..=0x202E
| 0x2066..=0x2069
| 0x206A..=0x206F
)
}
fn is_private_use(codepoint: u32) -> bool {
matches!(
codepoint,
0xE000..=0xF8FF | 0xF0000..=0xFFFFD | 0x100000..=0x10FFFD
)
}
fn is_zero_width(codepoint: u32) -> bool {
matches!(
codepoint,
0x034F | 0x180E | 0x200B..=0x200D | 0x2060 | 0xFEFF
)
}
fn is_variation_selector(codepoint: u32) -> bool {
matches!(codepoint, 0xFE00..=0xFE0F | 0xE0100..=0xE01EF)
}
// Bounded presentation policy, intentionally broader than a font-dependent
// emoji lookup. It covers the Unicode emoji blocks and legacy symbol ranges
// that gain emoji presentation through variation selectors.
fn is_emoji(codepoint: u32) -> bool {
matches!(
codepoint,
0x00A9
| 0x00AE
| 0x203C
| 0x2049
| 0x2122
| 0x2139
| 0x2190..=0x21FF
| 0x2300..=0x23FF
| 0x2460..=0x24FF
| 0x25A0..=0x27BF
| 0x2934..=0x2935
| 0x2B00..=0x2BFF
| 0x3030
| 0x303D
| 0x3297
| 0x3299
| 0x1F000..=0x1FAFF
)
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn normalizes_nfkc_and_collapses_unicode_whitespace() {
assert_eq!(
sanitize_name(" RNS\u{00A0}\tCommunity ", 128),
"RNS Community"
);
}
#[test]
fn removes_controls_bidi_private_use_emoji_variants_and_zero_width() {
let hostile = "safe\n\u{202E}txt\u{E000}\u{1F680}\u{FE0F}\u{200D} name";
assert_eq!(sanitize_name(hostile, 128), "safetxt name");
}
#[test]
fn truncates_multibyte_text_by_characters_without_panicking() {
assert_eq!(sanitize_name("Ångström東京", 8), "Ångström");
assert_eq!(sanitize_name("東京通信", 3), "東京通");
assert_eq!(sanitize_name("anything", 0), "");
}
#[test]
fn truncation_never_retains_a_separator_without_following_text() {
assert_eq!(sanitize_name("¡ A", 2), "¡");
assert_eq!(sanitize_name("A B", 3), "A B");
}
proptest! {
#[test]
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
let sanitized = sanitize_name(&input, limit);
prop_assert!(sanitized.chars().count() <= limit);
prop_assert_eq!(sanitize_name(&sanitized, limit), sanitized);
}
}
}
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
+327
View File
@@ -0,0 +1,327 @@
//! Typed evaluation of an inbound propagation-node `/offer` request.
//!
//! Admission policy and lifecycle accounting deliberately live in
//! [`crate::propagation_admission`]. Callers must pass that cheap preflight
//! before performing the peering-key work in this module, then commit the
//! returned wanted outcome to the same admission candidate.
use crate::propagation_admission::PnOfferResponse;
use crate::stamper;
use crate::sync::OfferResponse;
use crate::types::PropagationTransientId;
/// A binary 32-byte transient ID requires at least 34 MessagePack bytes.
const ENCODED_TRANSIENT_ID_MIN_BYTES: usize = 34;
/// A peering-key-validated offer and the subset not present in local storage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PnOfferEvaluation {
HaveAll,
WantAll,
WantSome(Vec<PropagationTransientId>),
}
impl PnOfferEvaluation {
/// Lifecycle outcome recorded by [`crate::propagation_admission`].
pub fn admission_response(&self) -> PnOfferResponse {
match self {
Self::HaveAll => PnOfferResponse::HaveAll,
Self::WantAll => PnOfferResponse::WantAll,
Self::WantSome(_) => PnOfferResponse::WantSome,
}
}
/// Python-compatible response value for the `/offer` request.
pub fn into_wire_response(self) -> OfferResponse {
match self {
Self::HaveAll => OfferResponse::HaveAll,
Self::WantAll => OfferResponse::WantAll,
Self::WantSome(ids) => {
OfferResponse::WantSome(ids.into_iter().map(Vec::from).collect())
}
}
}
}
/// Failure before an offer can be committed to admission accounting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PnOfferEvaluationError {
InvalidData,
InvalidKey,
}
impl PnOfferEvaluationError {
pub fn wire_response(self) -> OfferResponse {
match self {
Self::InvalidData => OfferResponse::ErrorInvalidData,
Self::InvalidKey => OfferResponse::ErrorInvalidKey,
}
}
}
enum DecodedPeeringKey {
Empty,
Key([u8; 32]),
InvalidLength,
}
pub(crate) struct DecodedOffer {
peering_key: DecodedPeeringKey,
transient_ids: Vec<PropagationTransientId>,
}
/// Decode, validate, and determine the wanted subset without mutating
/// admission state.
pub(crate) fn evaluate<F>(
request_data: &[u8],
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: u8,
max_offer_size: usize,
contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
where
F: FnMut(&PropagationTransientId) -> bool,
{
let offer = decode(request_data, max_offer_size)?;
evaluate_decoded(
offer,
local_identity_hash,
remote_identity_hash,
peering_cost,
contains,
)
}
pub(crate) fn evaluate_decoded<F>(
offer: DecodedOffer,
local_identity_hash: &[u8; 16],
remote_identity_hash: &[u8; 16],
peering_cost: u8,
mut contains: F,
) -> Result<PnOfferEvaluation, PnOfferEvaluationError>
where
F: FnMut(&PropagationTransientId) -> bool,
{
let peering_key_valid = match offer.peering_key {
DecodedPeeringKey::Empty => peering_cost == 0,
DecodedPeeringKey::Key(key) => {
let mut peering_id = [0u8; 32];
peering_id[..16].copy_from_slice(local_identity_hash);
peering_id[16..].copy_from_slice(remote_identity_hash);
stamper::validate_peering_key(&peering_id, &key, peering_cost)
}
DecodedPeeringKey::InvalidLength => false,
};
if !peering_key_valid {
return Err(PnOfferEvaluationError::InvalidKey);
}
let wanted: Vec<PropagationTransientId> = offer
.transient_ids
.iter()
.filter(|transient_id| !contains(transient_id))
.copied()
.collect();
if wanted.is_empty() {
Ok(PnOfferEvaluation::HaveAll)
} else if wanted.len() == offer.transient_ids.len() {
Ok(PnOfferEvaluation::WantAll)
} else {
Ok(PnOfferEvaluation::WantSome(wanted))
}
}
pub(crate) fn decode(
data: &[u8],
max_offer_size: usize,
) -> Result<DecodedOffer, PnOfferEvaluationError> {
use std::io::Read;
if data.len() > max_offer_size {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut remaining = data;
let field_count = rmp::decode::read_array_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
if field_count != 2 {
return Err(PnOfferEvaluationError::InvalidData);
}
let peering_key_len = rmp::decode::read_bin_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if peering_key_len > remaining.len() {
return Err(PnOfferEvaluationError::InvalidData);
}
let peering_key = match peering_key_len {
0 => DecodedPeeringKey::Empty,
32 => {
let mut key = [0u8; 32];
key.copy_from_slice(&remaining[..32]);
DecodedPeeringKey::Key(key)
}
_ => DecodedPeeringKey::InvalidLength,
};
remaining = &remaining[peering_key_len..];
let transient_id_count = rmp::decode::read_array_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if transient_id_count > remaining.len() / ENCODED_TRANSIENT_ID_MIN_BYTES {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut transient_ids = Vec::with_capacity(transient_id_count);
for _ in 0..transient_id_count {
let encoded_len = rmp::decode::read_bin_len(&mut remaining)
.map_err(|_| PnOfferEvaluationError::InvalidData)? as usize;
if encoded_len != 32 {
return Err(PnOfferEvaluationError::InvalidData);
}
let mut transient_id = [0u8; 32];
remaining
.read_exact(&mut transient_id)
.map_err(|_| PnOfferEvaluationError::InvalidData)?;
transient_ids.push(transient_id);
}
if !remaining.is_empty() {
return Err(PnOfferEvaluationError::InvalidData);
}
Ok(DecodedOffer {
peering_key,
transient_ids,
})
}
#[cfg(test)]
mod tests {
use super::*;
use rmpv::Value;
fn encode_offer(key: Value, ids: Value) -> Vec<u8> {
crate::encode_value(&Value::Array(vec![key, ids]))
}
fn id(value: u8) -> PropagationTransientId {
[value; 32]
}
#[test]
fn strict_decode_rejects_malformed_fields_and_trailing_bytes() {
let malformed = [
vec![0xc1],
crate::encode_value(&Value::Array(vec![])),
crate::encode_value(&Value::Array(vec![
Value::Binary(vec![]),
Value::Array(vec![]),
Value::Nil,
])),
encode_offer(Value::Nil, Value::Array(vec![])),
encode_offer(Value::String("key".into()), Value::Array(vec![])),
encode_offer(Value::Binary(vec![]), Value::Nil),
encode_offer(
Value::Binary(vec![]),
Value::Array(vec![Value::Binary(vec![1; 31])]),
),
encode_offer(Value::Binary(vec![]), Value::Array(vec![Value::from(1)])),
encode_offer(
Value::Binary(vec![]),
Value::Array(vec![Value::String(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
)]),
),
];
for request in malformed {
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
let mut trailing = encode_offer(Value::Binary(vec![]), Value::Array(vec![]));
trailing.push(0xc0);
assert_eq!(
evaluate(&trailing, &[1; 16], &[2; 16], 0, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn decode_rejects_requests_over_the_bounded_sync_budget() {
let request = vec![0xc0; 65];
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 64, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn decode_rejects_declared_id_count_before_allocating_entries() {
let mut request = Vec::new();
rmp::encode::write_array_len(&mut request, 2).unwrap();
rmp::encode::write_bin_len(&mut request, 0).unwrap();
rmp::encode::write_array_len(&mut request, u32::MAX).unwrap();
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, usize::MAX, |_| false),
Err(PnOfferEvaluationError::InvalidData)
);
}
#[test]
fn empty_key_is_valid_only_when_peering_work_is_disabled() {
let request = encode_offer(
Value::Binary(vec![]),
Value::Array(vec![Value::Binary(id(3).to_vec())]),
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |_| false),
Ok(PnOfferEvaluation::WantAll)
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 1, 1024, |_| false),
Err(PnOfferEvaluationError::InvalidKey)
);
}
#[test]
fn wanted_evaluation_preserves_offer_order_and_duplicates() {
let request = encode_offer(
Value::Binary(vec![]),
Value::Array(vec![
Value::Binary(id(1).to_vec()),
Value::Binary(id(2).to_vec()),
Value::Binary(id(2).to_vec()),
Value::Binary(id(3).to_vec()),
]),
);
assert_eq!(
evaluate(&request, &[1; 16], &[2; 16], 0, 1024, |id| *id == [1; 32]),
Ok(PnOfferEvaluation::WantSome(vec![id(2), id(2), id(3)]))
);
}
#[test]
fn outcomes_map_to_admission_and_wire_types() {
assert_eq!(
PnOfferEvaluation::HaveAll.admission_response(),
PnOfferResponse::HaveAll
);
assert_eq!(
PnOfferEvaluation::WantAll.admission_response(),
PnOfferResponse::WantAll
);
let some = PnOfferEvaluation::WantSome(vec![id(7)]);
assert_eq!(some.admission_response(), PnOfferResponse::WantSome);
assert_eq!(
some.into_wire_response(),
OfferResponse::WantSome(vec![id(7).to_vec()])
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+238 -85
View File
@@ -1,19 +1,22 @@
//! LXMF Ticket system: bypass PoW with pre-shared 16-byte tokens.
//! LXMF ticket lifecycle and persistence state.
//!
//! Trusted peers may exchange tickets that bypass stamp requirements for a
//! fixed expiry window. Tickets are single-use and renewable before expiry.
//! A ticket issued to a peer is an *inbound* ticket: it validates that peer's
//! future stamps. A ticket learned from a peer is an *outbound* ticket: it is
//! used to stamp future messages to that peer. Keeping those directions
//! separate is required for Python LXMF compatibility.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::constants::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ticket {
pub token: [u8; 16],
pub destination_hash: [u8; 16],
/// Expiry timestamp (Unix epoch seconds).
pub expires: f64,
pub used: bool,
}
impl Ticket {
@@ -22,26 +25,90 @@ impl Ticket {
token,
destination_hash,
expires,
used: false,
}
}
pub fn is_valid(&self, now: f64) -> bool {
!self.used && now < self.expires
now < self.expires
}
pub fn should_renew(&self, now: f64) -> bool {
self.is_valid(now) && (self.expires - now) < TICKET_RENEW as f64
self.is_valid(now) && (self.expires - now) <= TICKET_RENEW as f64
}
pub fn use_ticket(&mut self) {
self.used = true;
/// Encode Python's native MessagePack ticket field `[expires, token]`.
pub fn encode_field(&self) -> Result<Vec<u8>, rmpv::encode::Error> {
let value = rmpv::Value::Array(vec![
rmpv::Value::F64(self.expires),
rmpv::Value::Binary(self.token.to_vec()),
]);
let mut encoded = Vec::new();
rmpv::encode::write_value(&mut encoded, &value)?;
Ok(encoded)
}
/// Decode a signed inbound Python-compatible ticket field.
pub fn decode_field(destination_hash: [u8; 16], encoded: &[u8], now: f64) -> Option<Self> {
let mut cursor = std::io::Cursor::new(encoded);
let value = rmpv::decode::read_value(&mut cursor).ok()?;
if cursor.position() != encoded.len() as u64 {
return None;
}
let values = value.as_array()?;
if values.len() != 2 {
return None;
}
let expires = values[0].as_f64()?;
let token = values[1].as_slice()?;
if !expires.is_finite() || expires <= now || token.len() != TICKET_LENGTH {
return None;
}
let mut token_array = [0u8; TICKET_LENGTH];
token_array.copy_from_slice(token);
Some(Self::new(token_array, destination_hash, expires))
}
}
/// Versioned, serializable ticket state.
///
/// Version 1 replaces the former flat `Vec<Ticket>` representation. The flat
/// form could not distinguish tickets issued to peers from tickets learned
/// from peers and therefore could not implement Python's reply semantics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TicketStoreSnapshot {
#[serde(default = "ticket_store_version")]
pub version: u8,
#[serde(default)]
pub outbound: Vec<Ticket>,
#[serde(default)]
pub inbound: Vec<Ticket>,
#[serde(default)]
pub last_deliveries: HashMap<[u8; 16], f64>,
}
const fn ticket_store_version() -> u8 {
1
}
impl Default for TicketStoreSnapshot {
fn default() -> Self {
Self {
version: ticket_store_version(),
outbound: Vec::new(),
inbound: Vec::new(),
last_deliveries: HashMap::new(),
}
}
}
#[derive(Debug, Default)]
pub struct TicketStore {
tickets: Vec<Ticket>,
/// One learned ticket per destination, matching Python's outbound map.
outbound: HashMap<[u8; 16], Ticket>,
/// Multiple locally issued tickets may overlap during renewal/grace.
inbound: Vec<Ticket>,
/// Last successful delivery of a message containing a ticket.
last_deliveries: HashMap<[u8; 16], f64>,
}
impl TicketStore {
@@ -49,45 +116,130 @@ impl TicketStore {
Self::default()
}
pub fn add(&mut self, ticket: Ticket) {
self.tickets.push(ticket);
}
pub fn find(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.tickets
.iter()
.find(|t| &t.destination_hash == destination_hash && t.is_valid(now))
}
/// Find and mark a ticket as used. Returns the token on success.
pub fn use_for(&mut self, destination_hash: &[u8; 16], now: f64) -> Option<[u8; 16]> {
for ticket in &mut self.tickets {
if &ticket.destination_hash == destination_hash && ticket.is_valid(now) {
ticket.use_ticket();
return Some(ticket.token);
}
/// Store a ticket issued locally for `destination_hash`.
pub fn add_inbound(&mut self, ticket: Ticket) {
if self.inbound.iter().any(|existing| {
existing.destination_hash == ticket.destination_hash && existing.token == ticket.token
}) {
return;
}
None
self.inbound.push(ticket);
}
/// Drop expired and used tickets (past TICKET_GRACE).
/// Store or replace the ticket learned from `destination_hash`.
pub fn remember_outbound(&mut self, ticket: Ticket) {
self.outbound.insert(ticket.destination_hash, ticket);
}
/// Return the valid ticket learned from `destination_hash`.
pub fn find_outbound(&self, destination_hash: &[u8; 16], now: f64) -> Option<&Ticket> {
self.outbound
.get(destination_hash)
.filter(|ticket| ticket.is_valid(now))
}
/// Return every valid ticket issued locally for `destination_hash`.
pub fn inbound_tokens(&self, destination_hash: &[u8; 16], now: f64) -> Vec<[u8; 16]> {
self.inbound
.iter()
.filter(|ticket| &ticket.destination_hash == destination_hash && ticket.is_valid(now))
.map(|ticket| ticket.token)
.collect()
}
/// Generate or reuse a ticket for a peer, respecting Python's delivery
/// interval and renewal window. `None` means a ticket was delivered too
/// recently and should not be included in this message.
pub fn issue_for(
&mut self,
destination_hash: [u8; 16],
expiry_secs: u64,
now: f64,
) -> Option<Ticket> {
if !self.should_issue_for(&destination_hash, now) {
return None;
}
if let Some(ticket) = self.inbound.iter().find(|ticket| {
ticket.destination_hash == destination_hash
&& ticket.expires - now > TICKET_RENEW as f64
}) {
return Some(ticket.clone());
}
let token: [u8; TICKET_LENGTH] = rand::random();
let ticket = Ticket::new(token, destination_hash, now + expiry_secs as f64);
self.inbound.push(ticket.clone());
Some(ticket)
}
pub fn should_issue_for(&self, destination_hash: &[u8; 16], now: f64) -> bool {
!self
.last_deliveries
.get(destination_hash)
.is_some_and(|last| now - *last < TICKET_INTERVAL as f64)
}
pub fn mark_ticket_delivered(&mut self, destination_hash: [u8; 16], delivered_at: f64) {
self.last_deliveries.insert(destination_hash, delivered_at);
}
/// Drop expired outbound tickets and inbound tickets after their grace
/// period. Delivery timestamps need only survive one interval.
pub fn cull(&mut self, now: f64) {
self.tickets
.retain(|t| !t.used && now < t.expires + TICKET_GRACE as f64);
self.outbound.retain(|_, ticket| ticket.is_valid(now));
self.inbound
.retain(|ticket| now < ticket.expires + TICKET_GRACE as f64);
self.last_deliveries
.retain(|_, delivered| now - *delivered < TICKET_INTERVAL as f64);
}
pub fn count_valid(&self, now: f64) -> usize {
self.tickets.iter().filter(|t| t.is_valid(now)).count()
self.outbound
.values()
.filter(|ticket| ticket.is_valid(now))
.count()
+ self
.inbound
.iter()
.filter(|ticket| ticket.is_valid(now))
.count()
}
/// Snapshot of all stored tickets (including expired / used).
pub fn all(&self) -> &[Ticket] {
&self.tickets
pub fn inbound(&self) -> &[Ticket] {
&self.inbound
}
/// Replace the entire ticket set — used when restoring from persisted state.
pub fn replace_all(&mut self, tickets: Vec<Ticket>) {
self.tickets = tickets;
pub fn snapshot(&self) -> TicketStoreSnapshot {
TicketStoreSnapshot {
version: ticket_store_version(),
outbound: self.outbound.values().cloned().collect(),
inbound: self.inbound.clone(),
last_deliveries: self.last_deliveries.clone(),
}
}
pub fn replace_snapshot(&mut self, snapshot: TicketStoreSnapshot) {
self.outbound = snapshot
.outbound
.into_iter()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = snapshot.inbound;
self.last_deliveries = snapshot.last_deliveries;
}
/// Migrate the legacy flat representation conservatively. Old Rust used
/// every entry for both directions, so retaining entries in both stores
/// preserves working stamps while all new state is direction-correct.
pub fn replace_legacy(&mut self, tickets: Vec<Ticket>) {
self.outbound = tickets
.iter()
.cloned()
.map(|ticket| (ticket.destination_hash, ticket))
.collect();
self.inbound = tickets;
self.last_deliveries.clear();
}
}
@@ -96,66 +248,67 @@ mod tests {
use super::*;
#[test]
fn test_ticket_validity() {
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(999.0));
assert!(!ticket.is_valid(1001.0));
}
#[test]
fn test_ticket_used() {
let mut ticket = Ticket::new([0xAA; 16], [0xBB; 16], 1000.0);
assert!(ticket.is_valid(500.0));
ticket.use_ticket();
assert!(!ticket.is_valid(500.0));
}
#[test]
fn test_ticket_renew() {
let expires = 2_000_000.0;
let ticket = Ticket::new([0xAA; 16], [0xBB; 16], expires);
// TICKET_RENEW is ~1 week; close to expiry should trigger, far should not.
assert!(ticket.should_renew(expires - 1.0));
assert!(!ticket.should_renew(0.0));
}
#[test]
fn test_ticket_store() {
fn direction_state_is_separate() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
store.add_inbound(Ticket::new([0x01; 16], dest, 2_000.0));
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
assert!(store.find_outbound(&dest, 1_000.0).is_none());
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.add(Ticket::new([0x02; 16], dest, 2000.0));
store.add(Ticket::new([0x03; 16], [0xCC; 16], 1500.0));
assert_eq!(store.count_valid(500.0), 3);
assert_eq!(store.count_valid(1500.0), 1);
let found = store.find(&dest, 500.0);
assert!(found.is_some());
store.remember_outbound(Ticket::new([0x02; 16], dest, 2_000.0));
assert_eq!(
store.find_outbound(&dest, 1_000.0).unwrap().token,
[0x02; 16]
);
assert_eq!(store.inbound_tokens(&dest, 1_000.0), vec![[0x01; 16]]);
}
#[test]
fn test_ticket_store_use() {
fn issuance_reuses_then_renews_and_throttles_after_delivery() {
let mut store = TicketStore::new();
let dest = [0xBB; 16];
let first = store.issue_for(dest, TICKET_EXPIRY, 1_000.0).unwrap();
let reused = store.issue_for(dest, TICKET_EXPIRY, 2_000.0).unwrap();
assert_eq!(reused.token, first.token);
store.add(Ticket::new([0x01; 16], dest, 1000.0));
store.mark_ticket_delivered(dest, 2_000.0);
assert!(store.issue_for(dest, TICKET_EXPIRY, 2_001.0).is_none());
let renewed = store
.issue_for(dest, TICKET_EXPIRY, 2_000.0 + TICKET_INTERVAL as f64)
.unwrap();
assert_eq!(renewed.token, first.token);
let token = store.use_for(&dest, 500.0);
assert_eq!(token, Some([0x01; 16]));
let token = store.use_for(&dest, 500.0);
assert!(token.is_none());
let near_expiry = first.expires - TICKET_RENEW as f64 + 1.0;
let replacement = store.issue_for(dest, TICKET_EXPIRY, near_expiry).unwrap();
assert_ne!(replacement.token, first.token);
}
#[test]
fn test_ticket_store_cull() {
fn snapshot_roundtrip_preserves_directions_and_delivery_gate() {
let mut store = TicketStore::new();
store.add(Ticket::new([0x01; 16], [0xBB; 16], 100.0));
store.add(Ticket::new([0x02; 16], [0xBB; 16], 99999.0));
let dest = [0xCC; 16];
store.add_inbound(Ticket::new([1; 16], dest, 9_999.0));
store.remember_outbound(Ticket::new([2; 16], dest, 9_999.0));
store.mark_ticket_delivered(dest, 100.0);
store.cull(100.0 + TICKET_GRACE as f64 + 1.0);
assert_eq!(store.count_valid(99999.0 - 1.0), 1);
let mut restored = TicketStore::new();
restored.replace_snapshot(store.snapshot());
assert_eq!(restored.inbound_tokens(&dest, 200.0), vec![[1; 16]]);
assert_eq!(restored.find_outbound(&dest, 200.0).unwrap().token, [2; 16]);
assert!(restored.issue_for(dest, TICKET_EXPIRY, 200.0).is_none());
}
#[test]
fn ticket_field_is_native_python_shape_and_rejects_expired_values() {
let ticket = Ticket::new([0x42; 16], [0x11; 16], 2_000.0);
let encoded = ticket.encode_field().unwrap();
let value = rmpv::decode::read_value(&mut encoded.as_slice()).unwrap();
let values = value.as_array().unwrap();
assert_eq!(values[0].as_f64(), Some(2_000.0));
assert_eq!(values[1].as_slice(), Some(&[0x42; 16][..]));
let decoded = Ticket::decode_field([0x11; 16], &encoded, 1_000.0).unwrap();
assert_eq!(decoded, ticket);
assert!(Ticket::decode_field([0x11; 16], &encoded, 2_000.0).is_none());
}
}
+5
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
@@ -23,6 +25,9 @@ base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
[dev-dependencies]
tempfile = { workspace = true }
[[bin]]
name = "lxmd-rs"
path = "src/bin/lxmd-rs.rs"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+302 -38
View File
@@ -3,6 +3,9 @@
//! Python reference: LXMF/Utilities/lxmd.py.
use lxmf_core::constants::*;
use lxmf_core::propagation_admission::{
PN_DEFAULT_MAX_INBOUND_SYNCS, PN_MIN_MAX_INBOUND_SYNCS, PnInboundAdmissionConfig,
};
use lxmf_core::router::{LxmRouter, RouterConfig, RouterConfigExt};
use rns_runtime::config::{Config, ConfigSection};
@@ -16,6 +19,7 @@ pub struct PythonLxmdConfig {
pub display_name: String,
pub peer_announce_at_start: bool,
pub peer_announce_interval: Option<i64>,
pub peer_stamp_cost: i64,
pub delivery_transfer_max_accepted_size: f64,
pub on_inbound: Option<String>,
pub enable_propagation_node: bool,
@@ -24,6 +28,9 @@ pub struct PythonLxmdConfig {
pub node_announce_at_start: bool,
pub autopeer: bool,
pub autopeer_maxdepth: Option<i64>,
pub sequential_pn_stamp_validation: bool,
pub static_peers_bypass_sequential: bool,
pub max_inbound_syncs: i64,
pub node_announce_interval: Option<i64>,
pub message_storage_limit: f64,
pub propagation_transfer_max_accepted_size: f64,
@@ -58,10 +65,13 @@ impl PythonLxmdConfig {
.to_string(),
peer_announce_at_start: get_bool_or(lxmf, "announce_at_start", false),
peer_announce_interval: get_int(lxmf, "announce_interval").map(|v| v * 60),
peer_stamp_cost: get_int(lxmf, "stamp_cost")
.map(|value| value.max(1))
.unwrap_or(12),
delivery_transfer_max_accepted_size: get_float_or_floor(
lxmf,
"delivery_transfer_max_accepted_size",
1000.0,
1.0,
0.38,
),
on_inbound: lxmf
@@ -75,6 +85,19 @@ impl PythonLxmdConfig {
node_announce_at_start: get_bool_or(propagation, "announce_at_start", false),
autopeer: get_bool_or(propagation, "autopeer", true),
autopeer_maxdepth: get_int(propagation, "autopeer_maxdepth"),
sequential_pn_stamp_validation: get_bool_or(
propagation,
"sequential_pn_stamp_validation",
true,
),
static_peers_bypass_sequential: get_bool_or(
propagation,
"static_peers_bypass_sequential",
true,
),
max_inbound_syncs: get_int(propagation, "max_inbound_syncs")
.map(|value| value.max(PN_MIN_MAX_INBOUND_SYNCS as i64))
.unwrap_or(PN_DEFAULT_MAX_INBOUND_SYNCS as i64),
node_announce_interval: get_int(propagation, "announce_interval").map(|v| v * 60),
message_storage_limit: get_float_or_floor(
propagation,
@@ -152,6 +175,9 @@ pub struct DaemonConfig {
pub max_peers: usize,
pub autopeer: bool,
pub autopeer_maxdepth: usize,
pub sequential_pn_stamp_validation: bool,
pub static_peers_bypass_sequential: bool,
pub max_inbound_syncs: usize,
pub propagation_limit_kb: usize,
pub sync_limit_kb: usize,
pub on_inbound_command: Option<String>,
@@ -161,13 +187,12 @@ pub struct DaemonConfig {
pub control_allowed: Vec<String>,
pub static_peers: Vec<String>,
pub prioritise_destinations: Vec<String>,
pub enforce_ratchets: bool,
pub enforce_stamps: bool,
pub message_storage_limit: Option<usize>,
pub from_static_only: bool,
/// Max accepted inbound delivery transfer size in KB. Python reference:
/// `delivery_transfer_max_accepted_size` in `lxmd.py`.
pub delivery_transfer_max_accepted_size: usize,
pub delivery_transfer_max_accepted_size: f64,
}
impl Default for DaemonConfig {
@@ -177,7 +202,7 @@ impl Default for DaemonConfig {
node_name: None,
announce_at_start: false,
announce_interval: None,
stamp_cost: None,
stamp_cost: Some(12),
propagation_enabled: false,
outbound_propagation_node: None,
propagation_stamp_cost: PROPAGATION_COST,
@@ -187,6 +212,9 @@ impl Default for DaemonConfig {
max_peers: MAX_PEERS,
autopeer: true,
autopeer_maxdepth: AUTOPEER_MAXDEPTH,
sequential_pn_stamp_validation: true,
static_peers_bypass_sequential: true,
max_inbound_syncs: PN_DEFAULT_MAX_INBOUND_SYNCS,
propagation_limit_kb: PROPAGATION_LIMIT,
sync_limit_kb: SYNC_LIMIT,
on_inbound_command: None,
@@ -196,11 +224,13 @@ impl Default for DaemonConfig {
control_allowed: Vec::new(),
static_peers: Vec::new(),
prioritise_destinations: Vec::new(),
enforce_ratchets: false,
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
delivery_transfer_max_accepted_size: DELIVERY_LIMIT,
// Current Python LXMF 1.1.0's standalone lxmd defaults
// direct-delivery Resource admission to 1 decimal KB when the
// setting is omitted. LXMRouter's library default is separate.
delivery_transfer_max_accepted_size: 1.0,
}
}
}
@@ -221,8 +251,6 @@ impl DaemonConfig {
autopeer_maxdepth: self.autopeer_maxdepth,
peering_cost: self.peering_cost,
max_peering_cost: self.max_peering_cost,
enforce_ratchets: self.enforce_ratchets,
enforce_stamps: self.enforce_stamps,
auth_required: self.auth_required,
message_storage_limit: self.message_storage_limit,
name: self.node_name.clone(),
@@ -232,6 +260,16 @@ impl DaemonConfig {
}
}
/// Build the long-lived inbound propagation admission policy.
pub fn to_inbound_admission_config(&self) -> PnInboundAdmissionConfig {
PnInboundAdmissionConfig {
sequential_validation: self.sequential_pn_stamp_validation,
static_sequential: !self.static_peers_bypass_sequential,
max_inbound_syncs: self.max_inbound_syncs,
from_static_only: self.from_static_only,
}
}
/// Parse from `[lxmf]`, `[propagation]`, and `[control]` sections.
pub fn from_config(config: &Config) -> Self {
let py = PythonLxmdConfig::from_config(config);
@@ -240,6 +278,7 @@ impl DaemonConfig {
node_name: py.node_name,
announce_at_start: py.peer_announce_at_start,
announce_interval: seconds_to_u64(py.peer_announce_interval),
stamp_cost: normalize_peer_stamp_cost(py.peer_stamp_cost),
propagation_enabled: py.enable_propagation_node,
propagation_stamp_cost: clamp_python_cost_to_u8(
py.propagation_stamp_cost_target,
@@ -260,6 +299,9 @@ impl DaemonConfig {
.autopeer_maxdepth
.and_then(|value| usize::try_from(value).ok())
.unwrap_or(AUTOPEER_MAXDEPTH),
sequential_pn_stamp_validation: py.sequential_pn_stamp_validation,
static_peers_bypass_sequential: py.static_peers_bypass_sequential,
max_inbound_syncs: usize::try_from(py.max_inbound_syncs).unwrap_or(usize::MAX),
propagation_limit_kb: kb_to_usize_ceil(py.propagation_transfer_max_accepted_size),
sync_limit_kb: kb_to_usize_ceil(py.propagation_sync_max_accepted_size),
on_inbound_command: py.on_inbound,
@@ -271,18 +313,10 @@ impl DaemonConfig {
prioritise_destinations: py.prioritised_lxmf_destinations,
message_storage_limit: megabytes_to_bytes(py.message_storage_limit),
from_static_only: py.from_static_only,
delivery_transfer_max_accepted_size: kb_to_usize_ceil(
py.delivery_transfer_max_accepted_size,
),
delivery_transfer_max_accepted_size: py.delivery_transfer_max_accepted_size,
..DaemonConfig::default()
};
if let Some(sec) = config.section("lxmf")
&& let Some(cost) = sec.get_uint("stamp_cost")
{
dc.stamp_cost = Some(cost as u8);
}
if let Some(sec) = config.section("propagation") {
if let Some(node) = sec.get("outbound_node") {
let trimmed = node.trim();
@@ -290,18 +324,18 @@ impl DaemonConfig {
dc.outbound_propagation_node = Some(trimmed.to_string());
}
}
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_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_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")
{
dc.propagation_limit_kb = limit as usize;
if let Some(limit) = sec.get_uint("propagation_limit") {
dc.propagation_limit_kb = limit as usize;
}
}
dc.enforce_ratchets = sec.get_bool_or("enforce_ratchets", false);
dc.enforce_stamps = sec.get_bool_or("enforce_stamps", false);
}
@@ -309,14 +343,14 @@ impl DaemonConfig {
if !dc.auth_required {
dc.auth_required = sec.get_bool_or("auth_required", false);
}
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();
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();
}
}
}
@@ -328,6 +362,13 @@ fn clamp_python_cost_to_u8(value: i64, floor: i64) -> u8 {
value.max(floor).min(u8::MAX as i64) as u8
}
/// Apply Python lxmd's signed floor, then mirror `set_inbound_stamp_cost`:
/// delivery stamp costs are valid only in `1..=254`.
fn normalize_peer_stamp_cost(value: i64) -> Option<u8> {
let cost = u8::try_from(value.max(1)).ok()?;
(cost < u8::MAX).then_some(cost)
}
fn get_float(section: Option<&ConfigSection>, key: &str) -> Option<f64> {
section.and_then(|sec| sec.get_float(key))
}
@@ -366,12 +407,12 @@ pub fn create_router_with_transport(
pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> {
use std::process::Command;
let parts: Vec<&str> = command.split_whitespace().collect();
let parts = split_command_line(command)?;
if parts.is_empty() {
return Ok(());
}
let mut cmd = Command::new(parts[0]);
let mut cmd = Command::new(&parts[0]);
for arg in &parts[1..] {
cmd.arg(arg);
}
@@ -384,16 +425,158 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
Ok(())
}
/// Parse the configured hook using the shell-like quoting supported by
/// Python's `shlex.split()`, without invoking a shell.
fn split_command_line(command: &str) -> std::io::Result<Vec<String>> {
use std::io::{Error, ErrorKind};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quote {
None,
Single,
Double,
}
let mut parts = Vec::new();
let mut current = String::new();
let mut quote = Quote::None;
let mut escaped = false;
let mut started = false;
for ch in command.chars() {
if escaped {
current.push(ch);
escaped = false;
started = true;
continue;
}
match quote {
Quote::Single => {
if ch == '\'' {
quote = Quote::None;
} else {
current.push(ch);
}
started = true;
}
Quote::Double => {
if ch == '"' {
quote = Quote::None;
} else if ch == '\\' {
escaped = true;
} else {
current.push(ch);
}
started = true;
}
Quote::None => match ch {
'\'' => {
quote = Quote::Single;
started = true;
}
'"' => {
quote = Quote::Double;
started = true;
}
'\\' => {
escaped = true;
started = true;
}
c if c.is_whitespace() => {
if started {
parts.push(std::mem::take(&mut current));
started = false;
}
}
_ => {
current.push(ch);
started = true;
}
},
}
}
if escaped || quote != Quote::None {
return Err(Error::new(
ErrorKind::InvalidInput,
"unterminated quote or escape in on_inbound command",
));
}
if started {
parts.push(current);
}
Ok(parts)
}
/// Persist a received message 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.
pub fn persist_inbound_and_execute(
message_path: &std::path::Path,
packed: &[u8],
command: Option<&str>,
) -> std::io::Result<()> {
lxmf_core::persist::write_file_atomic(message_path, packed)?;
if let Some(command) = command {
execute_on_inbound(command, &message_path.to_string_lossy())?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_inbound_parser_matches_shell_like_quoting_without_a_shell() {
assert_eq!(
split_command_line("/tmp/a\\ b --label 'two words' \"\" --quoted=\"x y\"").unwrap(),
["/tmp/a b", "--label", "two words", "", "--quoted=x y"]
);
assert!(split_command_line("hook 'unterminated").is_err());
assert!(split_command_line("hook trailing\\").is_err());
}
#[cfg(unix)]
#[test]
fn inbound_hook_observes_fully_persisted_message() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let hook = dir.path().join("hook with spaces.sh");
let message = dir.path().join("message.lxm");
let observed = dir.path().join("observed");
std::fs::write(
&hook,
"#!/bin/sh\nexpected=$1\nobserved=$2\nmessage=$3\ncmp \"$expected\" \"$message\" && printf ok > \"$observed\"\n",
)
.unwrap();
let mut permissions = std::fs::metadata(&hook).unwrap().permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&hook, permissions).unwrap();
let expected = dir.path().join("expected");
std::fs::write(&expected, b"complete payload").unwrap();
let command = format!(
"'{}' '{}' '{}'",
hook.display(),
expected.display(),
observed.display()
);
persist_inbound_and_execute(&message, b"complete payload", Some(&command)).unwrap();
assert_eq!(std::fs::read(&message).unwrap(), b"complete payload");
assert_eq!(std::fs::read(&observed).unwrap(), b"ok");
}
#[test]
fn test_default_config() {
let dc = DaemonConfig::default();
assert_eq!(dc.display_name.as_deref(), Some("Anonymous Peer"));
assert!(!dc.announce_at_start);
assert_eq!(dc.announce_interval, None);
assert_eq!(dc.stamp_cost, Some(12));
assert!(!dc.propagation_enabled);
assert_eq!(dc.propagation_stamp_cost, 16);
assert_eq!(dc.propagation_stamp_flex, 3);
@@ -402,12 +585,19 @@ mod tests {
assert_eq!(dc.max_peers, 20);
assert!(dc.autopeer);
assert_eq!(dc.autopeer_maxdepth, AUTOPEER_MAXDEPTH);
assert!(dc.sequential_pn_stamp_validation);
assert!(dc.static_peers_bypass_sequential);
assert_eq!(dc.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS);
assert_eq!(
dc.to_inbound_admission_config(),
PnInboundAdmissionConfig::default()
);
assert_eq!(dc.propagation_limit_kb, 256);
assert_eq!(dc.sync_limit_kb, 10_240);
assert!(!dc.node_announce_at_start);
assert_eq!(dc.node_announce_interval, None);
assert_eq!(dc.message_storage_limit, Some(500_000_000));
assert_eq!(dc.delivery_transfer_max_accepted_size, 1000);
assert_eq!(dc.delivery_transfer_max_accepted_size, 1.0);
assert!(!dc.from_static_only);
}
@@ -419,7 +609,8 @@ mod tests {
assert_eq!(py.display_name, "Anonymous Peer");
assert!(!py.peer_announce_at_start);
assert_eq!(py.peer_announce_interval, None);
assert_eq!(py.delivery_transfer_max_accepted_size, 1000.0);
assert_eq!(py.peer_stamp_cost, 12);
assert_eq!(py.delivery_transfer_max_accepted_size, 1.0);
assert_eq!(py.on_inbound, None);
assert!(!py.enable_propagation_node);
assert_eq!(py.node_name, None);
@@ -427,6 +618,9 @@ mod tests {
assert!(!py.node_announce_at_start);
assert!(py.autopeer);
assert_eq!(py.autopeer_maxdepth, None);
assert!(py.sequential_pn_stamp_validation);
assert!(py.static_peers_bypass_sequential);
assert_eq!(py.max_inbound_syncs, PN_DEFAULT_MAX_INBOUND_SYNCS as i64);
assert_eq!(py.node_announce_interval, None);
assert_eq!(py.message_storage_limit, 500.0);
assert_eq!(py.propagation_transfer_max_accepted_size, 256.0);
@@ -460,9 +654,13 @@ prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
control_allowed = 11111111111111111111111111111111
from_static_only = yes
max_peers = 7
sequential_pn_stamp_validation = no
static_peers_bypass_sequential = no
max_inbound_syncs = 0
[lxmf]
announce_interval = 3
stamp_cost = -9
delivery_transfer_max_accepted_size = 0.1
[logging]
@@ -473,6 +671,7 @@ loglevel = 6
assert_eq!(py.peer_announce_interval, Some(180));
assert_eq!(py.node_announce_interval, Some(120));
assert_eq!(py.peer_stamp_cost, 1);
assert_eq!(py.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(py.message_storage_limit, 0.005);
assert_eq!(py.propagation_transfer_max_accepted_size, 0.38);
@@ -491,6 +690,9 @@ loglevel = 6
["11111111111111111111111111111111"]
);
assert_eq!(py.max_peers, Some(7));
assert!(!py.sequential_pn_stamp_validation);
assert!(!py.static_peers_bypass_sequential);
assert_eq!(py.max_inbound_syncs, PN_MIN_MAX_INBOUND_SYNCS as i64);
assert!(py.from_static_only);
assert_eq!(py.target_loglevel, Some(6));
}
@@ -531,7 +733,8 @@ propagation_transfer_max_accepted_size = 12
let rc = dc.to_router_config();
assert!(!rc.propagation_enabled);
assert_eq!(rc.max_peers, 20);
assert_eq!(rc.delivery_limit_kb, 1000);
assert_eq!(rc.delivery_limit_kb, 1.0);
assert_eq!(RouterConfig::default().delivery_limit_kb, 1000.0);
assert_eq!(rc.propagation_limit_kb, 256);
assert_eq!(rc.sync_limit_kb, 10_240);
assert_eq!(rc.propagation_stamp_cost, 16);
@@ -587,6 +790,9 @@ remote_peering_cost_max = -2
max_peers = 10
autopeer = no
autopeer_maxdepth = 2
sequential_pn_stamp_validation = no
static_peers_bypass_sequential = no
max_inbound_syncs = 5
static_peers = 00112233445566778899aabbccddeeff
prioritise_destinations = 0102030405060708090a0b0c0d0e0f10
control_allowed = 11111111111111111111111111111111
@@ -597,7 +803,7 @@ from_static_only = yes
assert_eq!(dc.display_name.as_deref(), Some("TestNode"));
assert!(dc.announce_at_start);
assert_eq!(dc.announce_interval, Some(180));
assert_eq!(dc.delivery_transfer_max_accepted_size, 1);
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(dc.stamp_cost, Some(8));
assert!(dc.propagation_enabled);
assert_eq!(dc.node_name.as_deref(), Some("PropNode"));
@@ -617,6 +823,18 @@ from_static_only = yes
assert_eq!(dc.max_peers, 10);
assert!(!dc.autopeer);
assert_eq!(dc.autopeer_maxdepth, 2);
assert!(!dc.sequential_pn_stamp_validation);
assert!(!dc.static_peers_bypass_sequential);
assert_eq!(dc.max_inbound_syncs, 5);
assert_eq!(
dc.to_inbound_admission_config(),
PnInboundAdmissionConfig {
sequential_validation: false,
static_sequential: true,
max_inbound_syncs: 5,
from_static_only: true,
}
);
assert_eq!(dc.static_peers, ["00112233445566778899aabbccddeeff"]);
assert_eq!(
dc.prioritise_destinations,
@@ -626,6 +844,38 @@ from_static_only = yes
assert!(dc.from_static_only);
}
#[test]
fn delivery_stamp_cost_matches_python_floor_and_destination_range() {
for (configured, normalized, expected) in [
(-7, 1, Some(1)),
(0, 1, Some(1)),
(254, 254, Some(254)),
(255, 255, None),
(256, 256, None),
(1000, 1000, None),
] {
let input = format!("[lxmf]\nstamp_cost = {configured}\n");
let config = rns_runtime::config::Config::parse(&input).unwrap();
let py = PythonLxmdConfig::from_config(&config);
let dc = DaemonConfig::from_config(&config);
assert_eq!(py.peer_stamp_cost, normalized, "configured {configured}");
assert_eq!(dc.stamp_cost, expected, "configured {configured}");
}
}
#[test]
fn fractional_delivery_limit_survives_daemon_and_router_config() {
let config = rns_runtime::config::Config::parse(
"[lxmf]\ndelivery_transfer_max_accepted_size = 0.38\n",
)
.unwrap();
let dc = DaemonConfig::from_config(&config);
assert_eq!(dc.delivery_transfer_max_accepted_size, 0.38);
assert_eq!(dc.to_router_config().delivery_limit_kb, 0.38);
}
#[test]
fn test_parse_python_stamp_target_key_with_floor() {
let input = r#"
@@ -654,4 +904,18 @@ propagation_stamp_cost = 19
assert_eq!(dc.propagation_stamp_cost, 19);
assert_eq!(dc.to_router_config().propagation_stamp_cost, 19);
}
/// Python lxmd exposes no enforce_ratchets option; the key must parse as a no-op.
#[test]
fn test_enforce_ratchets_key_ignored_matching_python_lxmd() {
let input = r#"
[propagation]
enforce_ratchets = yes
enforce_stamps = yes
"#;
let config = rns_runtime::config::Config::parse(input).unwrap();
let dc = DaemonConfig::from_config(&config);
assert!(dc.enforce_stamps);
}
}
+13 -2
View File
@@ -94,7 +94,7 @@ pub struct Args {
#[arg(long, value_name = "PATH")]
pub identity: Option<PathBuf>,
/// Send a single message and exit: --send <dest_hash> <content>
/// Send a single message and exit: `--send <dest_hash> <content>`.
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
pub send: Option<Vec<String>>,
@@ -180,6 +180,15 @@ autopeer = yes
autopeer_maxdepth = 6
# Validate inbound propagation stamp batches sequentially by default.
# sequential_pn_stamp_validation = yes
# Let configured static peers bypass sequential validation and inbound limits.
# static_peers_bypass_sequential = yes
# Maximum concurrent inbound propagation sync transfers.
# max_inbound_syncs = 3
# message_storage_limit = 500
# propagation_message_max_accepted_size = 256
@@ -213,7 +222,9 @@ announce_at_start = no
# announce_interval = 360
delivery_transfer_max_accepted_size = 1000
# stamp_cost = 12
delivery_transfer_max_accepted_size = 1
# on_inbound = /path/to/handler
+124 -56
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";
@@ -68,50 +71,22 @@ pub async fn resolve_remote_identity_hash(
remote_destination_hash: [u8; 16],
timeout_secs: f64,
) -> Result<[u8; 16], LinkClientError> {
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
transport_tx
.send(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
let send_result = transport_tx
.send(TransportMessage::RequestPath {
destination_hash: remote_destination_hash,
})
.await;
if send_result.is_err() {
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
return Err(LinkClientError::TransportUnavailable);
}
let wait = async {
while let Some(event) = ann_rx.recv().await {
if event.destination_hash == remote_destination_hash
&& let Some(identity_hash) = event.identity_hash
{
return Ok(identity_hash);
}
let recalled = resolve_destination_on_transport(
&transport_tx,
remote_destination_hash,
DestinationResolveOptions::new(Duration::from_secs_f64(timeout_secs.max(0.0))),
)
.await;
let recalled = recalled.map_err(|error| match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("remote identity resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
let result =
match tokio::time::timeout(Duration::from_secs_f64(timeout_secs.max(0.0)), wait).await {
Ok(result) => result,
Err(_) => Err(LinkClientError::Timeout("remote identity resolution")),
};
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
result
})?;
Identity::from_public_key(&recalled.public_key)
.map(|identity| identity.hash)
.map_err(|error| LinkClientError::UnexpectedResponse(error.to_string()))
}
pub fn decode_control_response(response: &[u8]) -> ControlResponse {
@@ -123,10 +98,10 @@ pub fn decode_control_response(response: &[u8]) -> ControlResponse {
return ControlResponse::Success;
};
if let Some(code) = value.as_u64()
&& let Some(error) = peer_error_from_code(code as u8)
{
return ControlResponse::Error(error);
if let Some(code) = value.as_u64() {
if let Some(error) = peer_error_from_code(code as u8) {
return ControlResponse::Error(error);
}
}
if value.is_nil() {
@@ -193,6 +168,9 @@ pub fn encode_router_control_stats(
.as_ref()
.map(|(_, value)| Value::from(*value as u64))
.unwrap_or(Value::Nil);
let unhandled = node
.map(|node| node.unhandled_message_count(&peer.handled_messages))
.unwrap_or_else(|| peer.unhandled_messages() as usize);
let peer_map = Value::Map(vec![
(Value::String("type".into()), Value::from(peer_type)),
@@ -269,7 +247,7 @@ pub fn encode_router_control_stats(
(Value::String("incoming".into()), Value::from(peer.incoming)),
(
Value::String("unhandled".into()),
Value::from(peer.unhandled_messages() as u64),
Value::from(unhandled as u64),
),
]),
),
@@ -300,7 +278,7 @@ pub fn encode_router_control_stats(
(Value::String("uptime".into()), Value::F64(uptime)),
(
Value::String("delivery_limit".into()),
Value::from(router.config.delivery_limit_kb as u64),
Value::F64(router.config.delivery_limit_kb),
),
(
Value::String("propagation_limit".into()),
@@ -612,12 +590,10 @@ pub fn format_remote_status(
}
_ => "never synced".to_string(),
};
let name = map_str(peer, "name")
.unwrap_or("")
.trim()
.replace(['\n', '\r'], "");
let display_name = if name.len() > 45 {
format!("{}...", &name[..45])
let name =
lxmf_core::presentation::sanitize_name(map_str(peer, "name").unwrap_or(""), 46);
let display_name = if name.chars().count() > 45 {
format!("{}...", name.chars().take(45).collect::<String>())
} else {
name
};
@@ -868,6 +844,68 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[tokio::test]
async fn remote_identity_resolution_uses_recall_and_path_request_without_handlers() {
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportQuery, TransportQueryResponse,
};
let remote_destination_hash = [0x41; 16];
let remote_identity = Identity::new();
let public_key = remote_identity.get_public_key();
let expected_identity_hash = remote_identity.hash;
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("initial recall")
else {
panic!("expected initial recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.expect("return cache miss");
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::RequestPath { destination_hash })
if destination_hash == remote_destination_hash
));
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("post-request recall")
else {
panic!("expected post-request recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(
RecalledDestinationRpcEntry {
dest_hash: remote_destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
},
)))
.expect("return resolved identity");
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_remote_identity_hash(transport_tx, remote_destination_hash, 1.0)
.await
.expect("resolve remote identity");
assert_eq!(resolved, expected_identity_hash);
responder.await.expect("transport responder");
}
fn decode_value(data: &[u8]) -> Value {
rmpv::decode::read_value(&mut &data[..]).unwrap()
}
@@ -955,6 +993,34 @@ mod tests {
assert!(out.contains("4 propagation messages served to clients"));
}
#[test]
fn status_formatter_bounds_multibyte_untrusted_peer_names() {
let hostile_name = format!("{}\u{202e}\u{1f680}", "界".repeat(50));
let peer = Value::Map(vec![
(
Value::String("name".into()),
Value::String(hostile_name.into()),
),
(Value::String("alive".into()), Value::Boolean(true)),
]);
let stats = Value::Map(vec![
(
Value::String("destination_hash".into()),
Value::Binary(vec![0x01; 16]),
),
(
Value::String("peers".into()),
Value::Map(vec![(Value::Binary(vec![0x02; 16]), peer)]),
),
]);
let out = format_remote_status(&stats, false, true, 0.0);
let expected = format!("Name : {}...", "界".repeat(45));
assert!(out.contains(&expected));
assert!(!out.contains('\u{202e}'));
assert!(!out.contains('\u{1f680}'));
}
#[test]
fn stats_encoder_uses_python_compile_stats_shape() {
use lxmf_core::peer::LxmPeer;
@@ -964,6 +1030,7 @@ mod tests {
propagation_enabled: true,
..Default::default()
};
config.delivery_limit_kb = 0.38;
config.ext.message_storage_limit = Some(500_000_000);
let mut router = LxmRouter::new(config);
router.propagation_start_time = Some(1_700_000_000.0);
@@ -1022,6 +1089,7 @@ mod tests {
assert_eq!(map_u64(&stats, "static_peers"), Some(1));
assert_eq!(map_u64(&stats, "discovered_peers"), Some(0));
assert_eq!(map_u64(&stats, "total_peers"), Some(1));
assert_eq!(map_f64(&stats, "delivery_limit"), Some(0.38));
let peers = map_value(&stats, "peers").unwrap().as_map().unwrap();
let peer_stats = &peers[0].1;
+11 -2
View File
@@ -18,6 +18,7 @@ pub struct LxmdPaths {
pub propagation_store_dir: PathBuf,
pub ratchets_dir: PathBuf,
pub ratchet_ring_path: PathBuf,
pub ratchet_control_path: PathBuf,
pub received_ratchets_dir: PathBuf,
pub known_identities_path: PathBuf,
pub legacy_lxmf_dir: PathBuf,
@@ -38,6 +39,7 @@ impl LxmdPaths {
let propagation_store_dir = lxmf_storage_dir.join("messagestore");
let ratchets_dir = lxmf_storage_dir.join("ratchets");
let ratchet_ring_path = ratchets_dir.join("ring");
let ratchet_control_path = ratchets_dir.join("ring.control");
let received_ratchets_dir = ratchets_dir.join("received");
let known_identities_path = ratchets_dir.join("known_identities");
@@ -57,6 +59,7 @@ impl LxmdPaths {
propagation_store_dir,
ratchets_dir,
ratchet_ring_path,
ratchet_control_path,
received_ratchets_dir,
known_identities_path,
legacy_lxmf_dir,
@@ -333,6 +336,10 @@ mod tests {
paths.ratchet_ring_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring")
);
assert_eq!(
paths.ratchet_control_path,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/ring.control")
);
assert_eq!(
paths.received_ratchets_dir,
PathBuf::from("/tmp/lxmd-config/storage/lxmf/ratchets/received")
@@ -445,13 +452,15 @@ mod tests {
#[test]
fn delivery_announce_app_data_matches_python_msgpack() {
// Python 1.0.1: msgpack([display_name, stamp_cost, [SF_COMPRESSION]])
// — LXMRouter.py:999-1001.
assert_eq!(
hex::encode(delivery_announce_app_data(Some("Test"), Some(16))),
"92c4045465737410"
"93c40454657374109100"
);
assert_eq!(
hex::encode(delivery_announce_app_data(None, None)),
"92c0c0"
"93c0c09100"
);
}
+10 -5
View File
@@ -227,11 +227,15 @@ fn example_config_exits_before_runtime_initialisation() {
assert!(text.contains("[lxmf]"));
assert!(text.contains("display_name = Anonymous Peer"));
assert!(text.contains("announce_at_start = no"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1000"));
assert!(text.contains("# stamp_cost = 12"));
assert!(text.contains("delivery_transfer_max_accepted_size = 1"));
assert!(text.contains("[propagation]"));
assert!(text.contains("enable_node = no"));
assert!(text.contains("announce_interval = 360"));
assert!(text.contains("announce_at_start = yes"));
assert!(text.contains("# sequential_pn_stamp_validation = yes"));
assert!(text.contains("# static_peers_bypass_sequential = yes"));
assert!(text.contains("# max_inbound_syncs = 3"));
assert!(text.contains("[logging]"));
assert!(text.contains("loglevel = 4"));
assert!(!text.contains("[control]"));
@@ -285,7 +289,7 @@ fn clap_requires_send_argument() {
}
#[test]
fn status_and_peers_query_control_and_timeout_without_daemon() {
fn status_and_peers_fail_before_link_without_an_online_interface() {
let lxmf_dir = TestDir::new("lxmf");
let rns_dir = TestDir::new("rns");
write_rust_identity(&lxmf_dir.path().join("identity"));
@@ -319,12 +323,13 @@ discover_interfaces = No
assert_eq!(
output.status.code(),
Some(200),
"expected Python-compatible control timeout, got:\n{}",
"expected interface-readiness failure, got:\n{}",
combined_output(&output)
);
assert!(
combined_output(&output).contains("Getting lxmd statistics timed out, exiting now"),
"expected Python-compatible control timeout text, got:\n{}",
combined_output(&output)
.contains("No online Reticulum interface became available, exiting now"),
"expected specific interface-readiness error, got:\n{}",
combined_output(&output)
);
assert!(
+194
View File
@@ -0,0 +1,194 @@
#!/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.87"
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()
if not requirement.startswith("^"):
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\.87\.0\s*$", workflow, re.MULTILINE):
fail("release workflow does not select Rust 1.87.0")
if "ref: ${{ env.RELEASE_TAG }}" not in workflow:
fail("release workflow does not check out RELEASE_TAG")
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")
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, dependency_commit: str) -> None:
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})")
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 main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--release-tag")
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.release_tag:
check_release_tag(args.release_tag, version, dependency_commit)
print(f"source-release contract passed for rsLXMF {version}")
if __name__ == "__main__":
main()
+351
View File
@@ -0,0 +1,351 @@
#!/usr/bin/env python3
"""Validate or refresh the reviewed public-API compatibility snapshots."""
from __future__ import annotations
import argparse
from datetime import date
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 config.get("schemaVersion") != 1:
fail("unsupported api-stability schema")
return config
def validate_change_record(path: str, snapshot_commit: str) -> None:
record_path = ROOT / path
try:
record = json.loads(record_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
fail(f"cannot read snapshot change record {path}: {error}")
required = {
"schemaVersion", "snapshotSourceCommit", "capabilities", "classification",
"publicApiDiff", "semver", "deprecations", "platformEvidence",
}
if not required.issubset(record) or record.get("schemaVersion") != 1:
fail("snapshot change record is incomplete")
if record.get("snapshotSourceCommit") != snapshot_commit:
fail("snapshot change record does not match the snapshot source commit")
if not isinstance(record.get("capabilities"), list) or not record["capabilities"]:
fail("snapshot change record must name capability IDs")
diff = record.get("publicApiDiff")
if not isinstance(diff, dict) or set(diff) != {"added", "removed"}:
fail("snapshot change record must classify added and removed API lines")
if not all(isinstance(diff[key], int) and diff[key] >= 0 for key in diff):
fail("snapshot change record API counts must be non-negative integers")
if not isinstance(record.get("platformEvidence"), list) or not record["platformEvidence"]:
fail("snapshot change record must name platform evidence")
for key in ("classification", "semver", "deprecations"):
if not isinstance(record.get(key), str) or not record[key]:
fail(f"snapshot change record must name {key}")
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]]:
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")
snapshot_source = config.get("snapshotSource")
if not isinstance(snapshot_source, dict):
fail("snapshot source identity is missing")
snapshot_commit = snapshot_source.get("commit")
if not isinstance(snapshot_commit, str) or not SHA_PATTERN.fullmatch(
snapshot_commit
):
fail("snapshot source commit must be a full Git commit")
snapshot_check = subprocess.run(
["git", "cat-file", "-e", f"{snapshot_commit}^{{commit}}"], cwd=ROOT
)
if snapshot_check.returncode != 0:
fail(f"snapshot source commit {snapshot_commit} is unavailable")
snapshot_ancestor = subprocess.run(
["git", "merge-base", "--is-ancestor", snapshot_commit, "HEAD"], cwd=ROOT
)
if snapshot_ancestor.returncode != 0:
fail(f"snapshot source commit {snapshot_commit} is not an ancestor of HEAD")
change_record = snapshot_source.get("changeRecord")
if not isinstance(change_record, str) or not change_record.startswith("api-reviews/"):
fail("snapshot source must name a reviewed change record")
validate_change_record(change_record, snapshot_commit)
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")
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-baseline/"):
fail(f"{name} has an invalid snapshot path")
snapshot_path = ROOT / snapshot
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()
parser.add_argument("--metadata-only", action="store_true")
parser.add_argument("--update", action="store_true")
parser.add_argument("--snapshot-source-commit")
parser.add_argument("--change-record")
args = parser.parse_args()
if args.metadata_only and args.update:
fail("--metadata-only and --update are mutually exclusive")
config = load_config()
if args.update:
if not args.snapshot_source_commit or not args.change_record:
fail("--update requires --snapshot-source-commit and --change-record")
head = run(["git", "rev-parse", "HEAD"]).strip()
if args.snapshot_source_commit != head:
fail("snapshot source must be the clean source commit at HEAD")
if not args.change_record.startswith("api-reviews/"):
fail("change record must be stored below api-reviews/")
status = run(["git", "status", "--porcelain=v1", "--untracked-files=all"])
dirty_paths = {line[3:] for line in status.splitlines() if len(line) > 3}
if dirty_paths - {args.change_record}:
fail("snapshot source has uncommitted changes outside the review record")
config["snapshotSource"] = {
"commit": args.snapshot_source_commit,
"capturedOn": date.today().isoformat(),
"changeRecord": args.change_record,
}
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()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Reject removals from the immutable Wave C public-API compatibility floor."""
from __future__ import annotations
import json
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 main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
)
if metadata.returncode != 0:
fail("snapshot metadata or reviewed change record is invalid")
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
if not isinstance(floor, str):
fail("api-stability.json has no compatibility-floor commit")
total_added = 0
total_removed = 0
for package in ledger["packages"]:
path = package["snapshot"]
before = set(git_show(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)
if total_removed:
fail(
f"{total_removed} public API lines were removed from the Wave C floor; "
"the current policy permits additions only"
)
change_record = json.loads(
(ROOT / ledger["snapshotSource"]["changeRecord"]).read_text(encoding="utf-8")
)
if change_record["publicApiDiff"] != {
"added": total_added,
"removed": total_removed,
}:
fail("reviewed change record does not match the measured API diff")
print(f"api compatibility: additive-only (+{total_added}, -0)")
if __name__ == "__main__":
main()
+158
View File
@@ -0,0 +1,158 @@
#!/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-baseline" / "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()
parser.add_argument(
"--print",
action="store_true",
dest="print_contract",
help="print the current canonical contract for reviewed application",
)
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()