Compare commits

...
Author SHA1 Message Date
DeFiDude 4a0abec3b4 lxmd: preserve binary peer hashes in control requests 2026-09-20 00:47:32 -06:00
DeFiDude 534abbb95b build: align API fixture lock and qualified core metadata 2026-09-17 14:43:35 -06:00
DeFiDude 86d5e10230 build: pin corrected Windows socket dependency 2026-09-17 14:21:55 -06:00
DeFiDude 09948bf81c ci: pin bounded RPC fixture checkpoint 2026-09-17 13:51:01 -06:00
DeFiDude 7a851cc204 ci: qualify final core shutdown-test checkpoint 2026-09-17 12:41:36 -06:00
DeFiDude 85e725a064 build: adopt the bounded Reticulum 1.3 dependency line 2026-09-10 12:05:59 -06:00
DeFiDude 0a34047342 propagation: preserve legacy opaque blobs across reload 2026-09-09 00:52:43 -06:00
DeFiDude bb628ba8ef delivery: reject idle cancellation owners and cover Link reuse 2026-09-08 21:50:21 -06:00
DeFiDude fd69ab4fbc api: record reviewed delivery coordination additions 2026-09-08 20:03:36 -06:00
DeFiDude 8db95825c5 daemon: preserve ordered delivery receipts and exact cleanup 2026-09-08 20:00:35 -06:00
DeFiDude 7cf129f76c delivery: retain bounded protocol and cancellation ownership 2026-09-08 20:00:35 -06:00
DeFiDude d7da7f34aa ci: qualify LXMF against the current protocol source graph 2026-09-05 22:48:21 -06:00
DeFiDude e609864d88 build: synchronize existing runtime zeroize dependency in lockfile 2026-09-05 19:29:00 -06:00
DeFiDude e210e0c244 lxmd: exit cleanly during early shutdown 2026-08-26 20:55:38 -06:00
DeFiDude fc1c99d3ff docs: promote RNS 1.4.2 release baseline 2026-08-26 20:48:14 -06:00
DeFiDude e49a8b3d88 api: review link timing additions 2026-08-21 03:03:52 -06:00
DeFiDude 2ab8fdf22b link: align establishment timing with first hop 2026-08-21 00:31:18 -06:00
DeFiDude eac0feaced router: add owned persistence snapshots 2026-08-20 17:56:21 -06:00
DeFiDude a446ee21b6 release: keep maintainer policy internal 2026-08-17 17:08:36 -06:00
DeFiDude b2aab6940d api: organize compatibility evidence 2026-08-17 16:48:42 -06:00
DeFiDude d58ea18011 ci: qualify release source with full history 2026-08-17 15:54:17 -06:00
DeFiDude c0053734f5 release: prepare rsLXMF 1.2.0 2026-08-17 15:00:05 -06:00
DeFiDude 1aee9dc1ed ci: follow clean Reticulum API source 2026-08-17 12:53:34 -06:00
DeFiDude 7da6df836c api: require clean snapshot source 2026-08-17 12:52:42 -06:00
DeFiDude 84c59c87b4 ci: follow reviewed Reticulum API source 2026-08-17 12:37:03 -06:00
DeFiDude 7d0285f46d api: bind snapshots to reviewed source 2026-08-17 12:36:12 -06:00
DeFiDude c934ccc5fe api: add canonical message facade 2026-08-17 11:50:43 -06:00
DeFiDude a8f74d2aed api: enforce manifest and additive compatibility 2026-08-17 11:43:25 -06:00
DeFiDude 133b9e2f60 ci: pin qualified Reticulum API source 2026-08-17 11:42:11 -06:00
DeFiDude 80bb96f799 api: record public compatibility baseline 2026-08-17 10:23:02 -06:00
DeFiDude b8d7afce73 ci: run source contract from workspace 2026-08-17 04:06:39 -06:00
DeFiDude ca9f119cbb release: pin qualified Reticulum source 2026-08-17 02:20:13 -06:00
DeFiDude 8101523fb9 lint: adopt Rust 1.87 integer divisibility 2026-08-17 02:20:13 -06:00
DeFiDude 92ea14b485 release: raise unified MSRV to Rust 1.87 2026-08-17 01:42:44 -06:00
DeFiDude 8b641971d9 ci: pin source qualification actions 2026-08-17 00:38:58 -06:00
DeFiDude c787312b48 release: pin compatible Reticulum source 2026-08-17 00:14:20 -06:00
DeFiDude 00de17cf26 release: enforce source qualification contract 2026-08-17 00:10:25 -06:00
DeFiDude 8a6316c635 lxmd: own announce discovery subscriptions 2026-08-16 20:18:31 -06:00
DeFiDude 0bd4220db6 docs: distinguish LXMF reference baselines 2026-08-16 18:41:23 -06:00
DeFiDude 44af77dc98 lxmd: follow current Python resource policy 2026-08-16 18:34:25 -06:00
DeFiDude 42355b4f46 lxmd: restore Python resource limit default 2026-08-16 17:32:26 -06:00
DeFiDude d100e3eae5 docs: explain established Link binding 2026-08-16 15:39:49 -06:00
DeFiDude 502795c70d link: observe typed endpoint send results 2026-08-16 15:37:13 -06:00
DeFiDude a530ad77c0 tools: map Link identity send errors 2026-08-16 15:19:59 -06:00
DeFiDude f91747b1d8 docs: record Link delivery hardening 2026-08-16 15:17:11 -06:00
DeFiDude 29804534ce propagation: pin Link sessions to proof interfaces 2026-08-16 15:17:08 -06:00
DeFiDude f89b6a2811 direct: bind Links and retain reverse proofs 2026-08-16 15:17:04 -06:00
DeFiDude 094bc95662 core: add native LXMF audio fields 2026-08-15 12:48:04 -06:00
DeFiDude b40dcd37f2 delivery: reconcile backchannel outcomes and reverse resources 2026-08-14 13:49:48 -06:00
DeFiDude 681c0f5961 delivery: reduce large message allocation 2026-08-13 12:42:35 -06:00
33 changed files with 13164 additions and 900 deletions

No files matched your search

+67 -16
View File
@@ -9,7 +9,47 @@ on:
permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 49aa33db1bbe8c7d93b12c4e8fa378ba5060376e
jobs:
api-compat:
name: Public API baseline
runs-on: macos-15
timeout-minutes: 45
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: nightly-2026-08-01
targets: aarch64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: true
- name: Install API snapshot tool
run: cargo install cargo-public-api --version 0.52.0 --locked
- name: Check reviewed public API baseline
run: python3 tools/check-api-baseline.py
working-directory: rsLXMF
- name: Check manifest and feature contract
run: python3 tools/check-api-manifest.py
working-directory: rsLXMF
- name: Check additions-only compatibility floor
run: python3 tools/check-api-compatibility.py
working-directory: rsLXMF
- name: Check canonical and legacy external consumer
run: cargo check --manifest-path api/fixtures/Cargo.toml --locked
working-directory: rsLXMF
test:
name: Test (${{ matrix.os }})
timeout-minutes: 30
@@ -19,16 +59,18 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
- name: Install system deps
@@ -36,28 +78,36 @@ jobs:
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
- run: cargo test --workspace --locked
working-directory: rsLXMF
- name: Build embedding examples
run: cargo build -p lxmf-core --examples --locked
working-directory: rsLXMF
lint:
name: Lint
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
fetch-depth: 0
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 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 --all-features --locked -- -D warnings
@@ -69,22 +119,23 @@ jobs:
working-directory: rsLXMF
msrv:
name: Rust 1.85 MSRV
name: Rust 1.87 MSRV
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
path: rsLXMF
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
repository: ${{ github.repository_owner }}/rsReticulum
ref: main
ref: ${{ env.RSLXMF_RSRETICULUM_COMMIT }}
path: rsReticulum
- uses: dtolnay/rust-toolchain@1.85.0
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
with:
toolchain: 1.87.0
components: clippy
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
workspaces: rsLXMF -> target
cache-bin: false
+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.1.0
RSLXMF_RSRETICULUM_VERSION: 1.3.0
RSLXMF_RSRETICULUM_COMMIT: 49aa33db1bbe8c7d93b12c4e8fa378ba5060376e
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 "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, '-') }}
+3
View File
@@ -1,4 +1,7 @@
/target/
/api/fixtures/target/
*.swp
.DS_Store
__pycache__/
*.pyc
proptest-regressions/
+41
View File
@@ -2,6 +2,45 @@
## Unreleased
- Encode propagation-control peer addresses explicitly as binary data, avoiding
intermittent sync/unpeer failures for hashes that resemble MessagePack values.
- Adopt rsReticulum 1.3 with a patch-line (`~1.3.0`) requirement so the next
breaking core minor release is not admitted implicitly.
- Promote exact Python RNS 1.4.2 to the complete release baseline while
retaining LXMF 1.0.1 for the main corpus and live matrix; the LXMF 1.1.0
supplemental lane remains separate and RNS 1.5.0 remains deferred.
## 1.2.0 - 2026-08-17
- Added the exact-reexport `lxmf_core::message_api` facade, a compiled message
example, and canonical/legacy external-consumer coverage while retaining all
existing module paths and leaving router, delivery, propagation, wire, and
persistence behavior unchanged.
- Classified `lxmf-core` as candidate stable and `lxmf-tools` as tool internal,
with pinned CI-enforced public API snapshots and no visibility or signature
change.
- Made source releases reproducible from an existing immutable component tag:
packages are non-publishable by default and expose Rust 1.87 metadata,
release builds use the committed lockfile and exact dependency commits,
actions are commit-pinned, and CI verifies the release-source contract.
- Replaced temporary aspect-wide announce handlers in remote-control lookup
with bounded validated destination recall, and made lxmd's delivery and
propagation observers exact owned subscriptions with deterministic cleanup.
- Matched current Python LXMF 1.1.0's fresh `lxmd` direct-delivery Resource
admission default of 1 decimal KB, while keeping the reusable router's
separate 1000 KB library default and preserving explicit configured limits.
- Bound Direct-delivery, propagation-download, and propagation-sync Link
initiators to the authenticated LRPROOF ingress interface before LRRTT,
routed all established-Link traffic through ordered typed endpoints, and
made reverse delivery proofs durable before plaintext publication.
- Bounded propagation-sync transport staging, scoped Link endpoint failures
to their owning operation, and prevented Resource responses from becoming
visible when their delivery proof cannot be retained.
- Made typed Link sends fail closed on rejected transport admission, delayed
reverse plaintext and propagation responses until their proofs are reliably
admitted, and made failed graceful closes unbind before deregistration.
- Added automatic pre-sign reply-ticket issue, signature-gated inbound
learning, directional migration-safe persistence, and proof-gated delivery
accounting, with live Python restart/reply interoperability.
@@ -14,6 +53,8 @@
peer-Resource convergence coverage.
- Made one-shot remote control commands wait for a real online Reticulum
interface before opening their Link, avoiding stale-path startup loss.
- This source line targets the rsReticulum 1.2 dependency line and includes
API evolution since the alpha-stage 1.1.0 source release.
## 1.1.0 - 2026-07-26
Generated
+14 -12
View File
@@ -643,7 +643,7 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.1.0"
version = "1.2.0"
dependencies = [
"base64",
"bytes",
@@ -670,7 +670,7 @@ dependencies = [
[[package]]
name = "lxmf-tools"
version = "1.1.0"
version = "1.2.0"
dependencies = [
"base64",
"bytes",
@@ -717,9 +717,9 @@ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
dependencies = [
"libc",
"wasi",
@@ -1052,7 +1052,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"aes",
"cbc",
@@ -1070,7 +1070,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1088,7 +1088,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1096,6 +1096,7 @@ dependencies = [
"jni",
"libc",
"md-5",
"mio",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
@@ -1116,7 +1117,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1131,7 +1132,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"bzip2",
"hex",
@@ -1147,7 +1148,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1169,11 +1170,12 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "rns-transport"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"bytes",
"hex",
@@ -1192,7 +1194,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.1.0"
version = "1.3.0"
dependencies = [
"rns-crypto",
"sha2",
+12 -12
View File
@@ -6,25 +6,25 @@ members = [
]
[workspace.package]
version = "1.1.0"
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.1.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "1.1.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "1.1.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "1.1.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "1.1.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "1.1.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "1.1.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "1.1.0" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.1.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.1.0" }
lxmf-core = { path = "crates/lxmf-core", version = "1.2.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.2.0" }
# Encoding
base64 = "0.22"
+25 -5
View File
@@ -5,8 +5,9 @@
**Rust LXMF messaging and propagation for Reticulum.**
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![LXMF 1.0.1](https://img.shields.io/badge/target-LXMF%201.0.1-success.svg)](https://github.com/markqvist/LXMF)
[![Rust 1.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)
- [Rust API](api/README.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
@@ -259,6 +261,11 @@ 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 |
@@ -289,6 +296,13 @@ and, where network-backed, through `lxmd-rs --send-method`.
| 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
@@ -328,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 complete release-baseline corpus and live matrix use Python LXMF 1.0.1
with Reticulum 1.4.2. A supplementary lane checks daemon, delivery,
Resource/proof, and propagation behavior against exact LXMF 1.1.0 with the
same Reticulum 1.4.2 source. Historical vectors retain their original
provenance, and RNS 1.5.0 is intentionally deferred.
## Contributing
If the issue or contribution belongs upstream as well, start there. Python LXMF
+97
View File
@@ -0,0 +1,97 @@
# Rust API
Application code that constructs or inspects LXMF messages should use
`lxmf_core::message_api`. It re-exports the existing message, status, and
identifier types without wrapping or replacing them. The original
module-qualified paths remain supported.
The compiled `lxmf-core` `message` example demonstrates message construction,
signing, packing, and unpacking through this path.
## Stability
`lxmf-core` is candidate stable, but that classification does not make every
public implementation detail a permanent API. The message facade is the
recommended application path. Router ownership, delivery orchestration,
propagation clients and nodes, handlers, persistence representations,
admission machinery, Link-delivery state, and raw Reticulum channels remain
provisional module-qualified APIs.
`lxmf-tools` supports the `lxmd-rs` binary and is not a public library
integration target.
The message facade changes no wire fields, signatures, serialization,
delivery methods, proofs, persistence, or runtime behavior. Later reductions
to the broader module tree require a reviewed API diff, downstream migration,
and an explicit version decision.
## Delivery-owner integration
`LinkDeliveryManager::set_link_endpoint_dispatch_handle` opts Direct packet
sends into the Reticulum owner's exact local-admission receipts. Supply the
handle from the same runtime that owns the manager's transport channel.
Local FIFO residence and the subsequent measured-RTT proof wait are different
phases; neither is a recipient delivery confirmation.
Applications using responder-owned backchannels should forward the ordered
`LinkManagerAccountingEvent` packet and Resource wait observations through
`observe_backchannel_packet_wait` and `observe_backchannel_resource_wait`,
retaining the exact packet/resource identity and original timestamps.
Forward the optional exact packet-cancellation capability with its original
wait observation as well. A separate application owner can then cancel a
packet still awaiting local admission without closing the shared Link. This
cannot retract driver-admitted bytes. When a command receipt cannot be
published to its message owner, retain its exact identity for bounded cleanup;
close and drain a oneshot receiver before discarding it to fence concurrent
publication.
Adapters implementing that close-and-drain protocol can install their sender
with `set_cancellation_aware_backchannel_sender`, allowing cancellation before
the command receipt arrives to notify the adapter immediately. The existing
`set_backchannel_sender` retains legacy receipt-after-cancellation behavior.
Each pending send captures its adapter policy; replacing a sender does not
retroactively change cancellation semantics for older sends.
`message_timeout_window` exposes the finite current owner window for an outer
orphan watchdog. Externally observed Resource windows include a bounded
180-second notification allowance measured from the original protocol deadline;
this does not alter the Resource engine's timeout or delay explicit terminal
events. It is not renewed by receiving the same observation or by keepalives.
Queued messages without an active protocol owner receive no
blanket timeout exemption. Explicit rejection and cancellation are not evidence
of a failed route.
Applications that reserve inbound attachment memory can opt into
`set_inbound_resource_completion_handler`. It receives one owned completed
payload before the ordinary conclusion callback, so an application can move
its exact Link/Resource reservation into a queued payload and retain it through
processing. This synchronous callback must not block. It replaces the legacy
inbound packet-channel delivery for that Resource, without cloning the data;
applications that do not install it keep the existing completion behavior.
## Compatibility checks
The `api/` directory contains the evidence used by CI:
- `stability.json` records package tiers, source commits, snapshot hashes, and
the current review decision;
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
manifest, feature, dependency, target, and MSRV contract; and
- `fixtures/` compiles recommended and retained imports as an external
consumer.
These checks catch accidental changes, but they do not replace platform builds,
wire and persistence tests, Python interoperability, or manual review. The API
snapshot omits auto-derived, auto-trait, and blanket implementations and is not
by itself a complete SemVer verdict.
Run the checks with:
```sh
python3 tools/check-api-baseline.py
python3 tools/check-api-manifest.py
python3 tools/check-api-compatibility.py
cargo check --manifest-path api/fixtures/Cargo.toml --locked
```
Snapshot updates require a clean source commit and an explicit review recorded
in `api/stability.json`. Additions, removals, deprecations, platform impact, and
version consequences must be reviewed before accepting new evidence.
+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.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
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.3.0"
dependencies = [
"aes",
"cbc",
"ed25519-dalek",
"hkdf",
"hmac",
"rand",
"rand_core",
"sha2",
"subtle",
"thiserror",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "rns-identity"
version = "1.3.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.3.0"
dependencies = [
"hex",
"rand",
"rmpv",
"rns-crypto",
"rns-identity",
"rns-wire",
"thiserror",
"tracing",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
dependencies = [
"bzip2",
"hex",
"rmp-serde",
"rmpv",
"rns-crypto",
"rns-link",
"rns-wire",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "rns-transport"
version = "1.3.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.3.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" }
+59
View File
@@ -0,0 +1,59 @@
//! External-consumer compile contract for canonical and retained LXMF paths.
pub mod canonical {
use lxmf_core::message_api::{
AudioField, DeliveryMethod, DeliveryRepresentation, DestinationHash, IdentityHash,
LxMessage, MessageError, MessageId, MessageState, UnverifiedReason,
};
pub fn compile_surface() {
let _ = std::mem::size_of::<AudioField<'static>>();
let _ = std::mem::size_of::<DeliveryMethod>();
let _ = std::mem::size_of::<DeliveryRepresentation>();
let _ = std::mem::size_of::<DestinationHash>();
let _ = std::mem::size_of::<IdentityHash>();
let _ = std::mem::size_of::<LxMessage>();
let _ = std::mem::size_of::<MessageError>();
let _ = std::mem::size_of::<MessageId>();
let _ = std::mem::size_of::<MessageState>();
let _ = std::mem::size_of::<UnverifiedReason>();
}
}
pub mod legacy {
use lxmf_core::constants::{
DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason,
};
use lxmf_core::message::{AudioField, LxMessage, MessageError};
use lxmf_core::types::{DestinationHash, IdentityHash, MessageId};
pub fn compile_surface() {
let _ = std::mem::size_of::<AudioField<'static>>();
let _ = std::mem::size_of::<DeliveryMethod>();
let _ = std::mem::size_of::<DeliveryRepresentation>();
let _ = std::mem::size_of::<DestinationHash>();
let _ = std::mem::size_of::<IdentityHash>();
let _ = std::mem::size_of::<LxMessage>();
let _ = std::mem::size_of::<MessageError>();
let _ = std::mem::size_of::<MessageId>();
let _ = std::mem::size_of::<MessageState>();
let _ = std::mem::size_of::<UnverifiedReason>();
}
}
/// Delivery coordination remains a module-qualified opt-in API.
pub mod delivery_ownership {
use lxmf_core::link_delivery::LinkDeliveryManager;
pub fn compile_surface(manager: &mut LinkDeliveryManager) {
let _ = LinkDeliveryManager::set_link_endpoint_dispatch_handle;
let _ = LinkDeliveryManager::set_cancellation_aware_backchannel_sender;
let _ = LinkDeliveryManager::observe_backchannel_packet_wait;
let _ = LinkDeliveryManager::observe_backchannel_resource_wait;
let _ = LinkDeliveryManager::abandon_backchannel_packet;
let _ = LinkDeliveryManager::message_timeout_window;
manager.set_inbound_resource_completion_handler(|link_id, resource_id, data| {
let _: ([u8; 16], [u8; 32], Vec<u8>) = (link_id, resource_id, data);
});
}
}
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.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-link",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-protocol",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.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.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-identity",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-runtime",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [
"serial"
],
"sourceKind": "path"
},
{
"name": "rns-transport",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "path"
},
{
"name": "rns-wire",
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.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"
}
]
}
]
}
+83
View File
@@ -0,0 +1,83 @@
{
"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": "8db95825c568ace467c99d2011cefe618e1c60fc",
"capturedOn": "2026-09-08",
"review": {
"areas": [
"Exact local packet admission and proof-clock ownership",
"Finite original Resource windows and bounded external observation grace",
"Cancellation-aware backchannel adapters with legacy compatibility",
"Generation-safe cleanup, settlement and queued-message preservation",
"Owned reverse Resource completion handoff"
],
"canonicalPath": "lxmf_core::link_delivery::LinkDeliveryManager",
"retainedPaths": [
"lxmf_core::message",
"lxmf_core::constants",
"lxmf_core::types",
"lxmf_core::router",
"lxmf_core::link_delivery"
],
"excludedImplementationAreas": [
"propagation and handlers",
"serialized persistence representations",
"raw Reticulum transport channels"
],
"classification": "compatible additive opt-in provisional delivery-owner integration; existing message facade and public signatures remain unchanged",
"publicApiDiff": {
"added": 93,
"removed": 0
},
"semver": "compatible additive APIs included in version 1.2.0",
"deprecations": "none",
"wirePersistenceRuntimeImpact": "No wire-format, cryptography, message identity or persisted-layout change. Exact local Link admission precedes RTT proof timing. Resource owner windows retain original timestamps; only externally observed Resources receive a finite 180-second accounting allowance after the original protocol deadline. Cancellation-aware adapters close and drain unpublished receipts while legacy sender installation retains its previous behavior. Exact cleanup is bounded and cannot erase replacement Links or lose uncancelled queued messages; authenticated settlement remains owned after Link closure. Optional reverse Resource completion hands off the single owned payload before conclusion cleanup, without changing legacy consumers.",
"platformEvidence": [
"clean committed-source all-feature Apple ARM64 snapshot: seven added methods, zero removed; cumulative compatibility-floor diff is 93 additions and zero removals",
"564 LXMF core and 55 daemon tests passed on the final implementation checkpoint; strict all-target Clippy and core Rustdoc passed",
"independent actual-actor cancellation, captured legacy/aware policy, 256-owner reservation and replacement-Link/settlement review controls passed",
"actual encrypted Resource final-proof expiry and same-message retry produced one receiver publication; signed Link reuse/loss/recovery and completion-lease controls passed",
"default/all-feature external consumer fixtures and final working app runtime suite passed; no feature/MSRV/native-export changes",
"final clean combined host/MSRV/native/interop and artifact qualification remain separately required; focused software evidence is not physical fading-radio or mobile acceptance"
]
}
},
"packages": [
{
"name": "lxmf-core",
"manifestPath": "Cargo.toml",
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 1645,
"sha256": "65aebd34c72bb2b621d515331bba1f4d85234c448d1c7039132f24c0a95bbe4a"
},
{
"name": "lxmf-tools",
"manifestPath": "Cargo.toml",
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
}
]
}
+1 -1
View File
@@ -1,2 +1,2 @@
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
msrv = "1.85"
msrv = "1.87"
+2
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]
+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(())
}
+13
View File
@@ -65,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
+636 -73
View File
@@ -24,8 +24,12 @@ use rns_protocol::resource::{
};
use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{OutboundRequest, TransportMessage};
use tokio::sync::mpsc;
use rns_transport::messages::{
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
TransportMessage,
};
use tokio::sync::{mpsc, oneshot};
use crate::constants::*;
use crate::propagation::hex_encode;
@@ -74,6 +78,33 @@ struct SegmentRoute {
segment_index: usize,
}
struct PendingEndpointBind {
interface_id: InterfaceId,
rtt_request: OutboundRequest,
result_rx: oneshot::Receiver<LinkEndpointBindResult>,
}
enum EndpointSendSuccess {
None,
ResourceProof {
assembled: Vec<u8>,
route: Option<SegmentRoute>,
metadata: Option<Vec<u8>>,
},
}
struct PendingEndpointSend {
link_id: [u8; 16],
final_send: bool,
success: EndpointSendSuccess,
result_rx: oneshot::Receiver<LinkEndpointSendResult>,
}
struct PendingEndpointCleanup {
link_id: [u8; 16],
result_rx: oneshot::Receiver<LinkEndpointUnbindResult>,
}
pub struct PropagationClient {
transport_tx: mpsc::Sender<TransportMessage>,
event_tx: mpsc::Sender<DestinationEvent>,
@@ -81,6 +112,13 @@ pub struct PropagationClient {
outbound_propagation_node: Option<[u8; 16]>,
link: Option<Link>,
link_id: Option<[u8; 16]>,
attached_interface: Option<InterfaceId>,
endpoint_release_queued: bool,
pending_endpoint_bind: Option<PendingEndpointBind>,
pending_endpoint_sends: Vec<PendingEndpointSend>,
pending_endpoint_cleanups: Vec<PendingEndpointCleanup>,
endpoint_lifecycle_tx: mpsc::UnboundedSender<LinkEndpointLifecycleEvent>,
endpoint_lifecycle_rx: mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
status: PropagationTransferStatus,
/// Request phase whose response is currently arriving as a Resource.
receiving_for: Option<PropagationClientState>,
@@ -116,6 +154,7 @@ impl PropagationClient {
identity_key: Option<Ed25519PrivateKey>,
) -> Self {
let (event_tx, event_rx) = mpsc::channel(256);
let (endpoint_lifecycle_tx, endpoint_lifecycle_rx) = mpsc::unbounded_channel();
Self {
transport_tx,
event_tx,
@@ -123,6 +162,13 @@ impl PropagationClient {
outbound_propagation_node: None,
link: None,
link_id: None,
attached_interface: None,
endpoint_release_queued: false,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
status: PropagationTransferStatus::default(),
receiving_for: None,
identity_pub,
@@ -277,6 +323,9 @@ impl PropagationClient {
self.receiving_for = None;
self.link = Some(link);
self.link_id = Some(link_id);
self.attached_interface = None;
self.endpoint_release_queued = false;
self.pending_endpoint_bind = None;
self.started_at = Some(Instant::now());
self.max_messages = max_messages.filter(|limit| *limit > 0);
self.identified = false;
@@ -332,7 +381,183 @@ impl PropagationClient {
}
}
fn queue_link_endpoint(&mut self, request: OutboundRequest) -> bool {
self.queue_link_endpoint_with_success(request, EndpointSendSuccess::None)
}
fn queue_link_endpoint_with_success(
&mut self,
request: OutboundRequest,
success: EndpointSendSuccess,
) -> bool {
let Some(link_id) = self.link_id else {
return false;
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::SendLinkEndpoint {
link_id,
role: LinkEndpointRole::Initiator,
request,
result_tx,
}) {
return false;
}
self.pending_endpoint_sends.push(PendingEndpointSend {
link_id,
final_send: false,
success,
result_rx,
});
true
}
fn queue_link_endpoint_and_unbind(&mut self, request: OutboundRequest) -> bool {
let Some(link_id) = self.link_id else {
return false;
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::SendLinkEndpointAndUnbind {
link_id,
role: LinkEndpointRole::Initiator,
request,
result_tx,
}) {
return false;
}
self.pending_endpoint_sends.push(PendingEndpointSend {
link_id,
final_send: true,
success: EndpointSendSuccess::None,
result_rx,
});
true
}
fn queue_endpoint_cleanup(&mut self, link_id: [u8; 16]) {
let (result_tx, result_rx) = oneshot::channel();
if self.queue_transport(TransportMessage::UnbindLinkEndpoint {
link_id,
role: LinkEndpointRole::Initiator,
result_tx,
}) {
self.pending_endpoint_cleanups
.push(PendingEndpointCleanup { link_id, result_rx });
}
}
fn poll_endpoint_send_results(&mut self) {
let mut still_pending = Vec::new();
let mut endpoint_sends = std::mem::take(&mut self.pending_endpoint_sends);
for mut pending in endpoint_sends.drain(..) {
match pending.result_rx.try_recv() {
Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => {
if self.link_id == Some(pending.link_id)
&& self.status.state != PropagationClientState::Failed
{
match pending.success {
EndpointSendSuccess::None => {}
EndpointSendSuccess::ResourceProof {
assembled,
route,
metadata,
} => self.finish_completed_resource(assembled, route, metadata),
}
}
}
Ok(result) => {
tracing::warn!(
link_id = %hex::encode(pending.link_id),
?result,
final_send = pending.final_send,
"propagation client Link endpoint send rejected"
);
if self.link_id == Some(pending.link_id) {
self.status.state = PropagationClientState::Failed;
}
if pending.final_send {
self.queue_endpoint_cleanup(pending.link_id);
}
}
Err(oneshot::error::TryRecvError::Closed) => {
if self.link_id == Some(pending.link_id) {
self.status.state = PropagationClientState::Failed;
}
}
Err(oneshot::error::TryRecvError::Empty) => still_pending.push(pending),
}
}
still_pending.append(&mut self.pending_endpoint_sends);
self.pending_endpoint_sends = still_pending;
let mut cleanup_pending = Vec::new();
let mut cleanups = std::mem::take(&mut self.pending_endpoint_cleanups);
for mut pending in cleanups.drain(..) {
match pending.result_rx.try_recv() {
Ok(LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound) => {
let _ = self.queue_transport(TransportMessage::DeregisterDestination {
hash: pending.link_id,
});
}
Ok(LinkEndpointUnbindResult::RoleMismatch) => {
tracing::warn!(
link_id = %hex::encode(pending.link_id),
"refusing to deregister a propagation Link owned by the opposite role"
);
}
Err(oneshot::error::TryRecvError::Closed) => {}
Err(oneshot::error::TryRecvError::Empty) => cleanup_pending.push(pending),
}
}
self.pending_endpoint_cleanups = cleanup_pending;
}
fn poll_endpoint_control(&mut self) {
self.poll_endpoint_send_results();
while let Ok(event) = self.endpoint_lifecycle_rx.try_recv() {
if self.link_id == Some(event.binding.link_id)
&& event.binding.role == LinkEndpointRole::Initiator
{
tracing::warn!(
link_id = %hex::encode(event.binding.link_id),
interface_id = event.binding.interface_id,
reason = ?event.reason,
dropped_packets = event.dropped_packets,
"propagation client Link endpoint terminated"
);
self.attached_interface = None;
self.pending_endpoint_bind = None;
self.status.state = PropagationClientState::Failed;
}
}
let Some(mut pending) = self.pending_endpoint_bind.take() else {
return;
};
match pending.result_rx.try_recv() {
Ok(LinkEndpointBindResult::Bound | LinkEndpointBindResult::AlreadyBound) => {
self.attached_interface = Some(pending.interface_id);
if self.queue_link_endpoint(pending.rtt_request) {
self.status.state = PropagationClientState::LinkEstablished;
self.started_at = Some(Instant::now());
} else {
self.status.state = PropagationClientState::Failed;
}
}
Ok(
LinkEndpointBindResult::Conflict { .. }
| LinkEndpointBindResult::InterfaceUnavailable,
)
| Err(oneshot::error::TryRecvError::Closed) => {
self.status.state = PropagationClientState::Failed;
}
Err(oneshot::error::TryRecvError::Empty) => {
self.pending_endpoint_bind = Some(pending);
}
}
}
pub fn drain_events(&mut self, known_identities: &std::collections::HashMap<String, [u8; 64]>) {
self.poll_endpoint_control();
let mut events = Vec::new();
while let Ok(event) = self.event_rx.try_recv() {
events.push(event);
@@ -343,7 +568,9 @@ impl PropagationClient {
DestinationEvent::LinkClosed { link_id } => {
self.handle_link_closed(link_id, None);
}
DestinationEvent::InboundPacket { raw, .. } => {
DestinationEvent::InboundPacket {
raw, interface_id, ..
} => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
@@ -351,6 +578,28 @@ impl PropagationClient {
if self.link_id != Some(header.destination_hash) {
continue;
}
let is_link_proof = matches!(
header.context,
rns_wire::context::PacketContext::Lrproof
| rns_wire::context::PacketContext::None
) && (header.flags.packet_type
== rns_wire::flags::PacketType::Proof
|| header.context == rns_wire::context::PacketContext::Lrproof);
if is_link_proof {
if self.pending_endpoint_bind.is_some()
|| self.status.state != PropagationClientState::LinkEstablishing
{
continue;
}
} else if self.attached_interface != Some(interface_id) {
tracing::warn!(
link_id = %hex::encode(header.destination_hash),
interface_id,
attached_interface = ?self.attached_interface,
"rejected propagation client packet from wrong Link interface"
);
continue;
}
let data = if raw.len() > data_offset {
&raw[data_offset..]
} else {
@@ -379,7 +628,12 @@ impl PropagationClient {
if let Ok(verify_key) =
Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(data, &verify_key, &ed25519_bytes);
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
}
}
@@ -448,44 +702,53 @@ impl PropagationClient {
proof_data: &[u8],
verify_key: &Ed25519PublicKey,
ed25519_pub: &[u8; 32],
interface_id: InterfaceId,
) {
let link = match self.link.as_mut() {
Some(l) => l,
None => return,
};
match link.validate_proof(proof_data, verify_key, ed25519_pub) {
Ok(rtt_data) => {
if let Some(link_id) = self.link_id {
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
if let Ok(rtt_data) = link.validate_proof(proof_data, verify_key, ed25519_pub) {
if let Some(link_id) = self.link_id {
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
})) {
self.status.state = PropagationClientState::Failed;
return;
}
let rtt_request = OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id,
role: LinkEndpointRole::Initiator,
},
lifecycle_tx: self.endpoint_lifecycle_tx.clone(),
result_tx,
}) {
self.status.state = PropagationClientState::Failed;
return;
}
self.status.state = PropagationClientState::LinkEstablished;
self.started_at = Some(Instant::now());
}
Err(_) => {
self.status.state = PropagationClientState::Failed;
self.pending_endpoint_bind = Some(PendingEndpointBind {
interface_id,
rtt_request,
result_rx,
});
}
}
}
@@ -761,8 +1024,10 @@ impl PropagationClient {
}
}
};
self.send_resource_proof(&proof);
if !self.send_resource_proof(&proof) {
self.status.state = PropagationClientState::Failed;
return;
}
let route = self.segment_routing.remove(&resource_hash);
if let Some(link) = self.link.as_mut() {
link.untrack_resource(&resource_hash);
@@ -773,6 +1038,23 @@ impl PropagationClient {
.and_then(|transfer| transfer.resource.metadata.clone());
self.inbound_resources.remove(&resource_hash);
let Some(pending) = self.pending_endpoint_sends.last_mut() else {
self.status.state = PropagationClientState::Failed;
return;
};
pending.success = EndpointSendSuccess::ResourceProof {
assembled,
route,
metadata,
};
}
fn finish_completed_resource(
&mut self,
assembled: Vec<u8>,
route: Option<SegmentRoute>,
metadata: Option<Vec<u8>>,
) {
if let Some(route) = route {
let mut complete_payload = None;
if let Some(coord) = self.inbound_split_resources.get_mut(&route.original_hash) {
@@ -835,12 +1117,12 @@ impl PropagationClient {
}
}
fn send_resource_proof(&mut self, proof: &[u8]) {
fn send_resource_proof(&mut self, proof: &[u8]) -> bool {
self.send_link_packet(
rns_wire::context::PacketContext::ResourcePrf,
rns_wire::flags::PacketType::Proof,
proof,
);
)
}
fn send_link_packet(
@@ -848,9 +1130,9 @@ impl PropagationClient {
context: rns_wire::context::PacketContext,
packet_type: rns_wire::flags::PacketType,
payload: &[u8],
) {
) -> bool {
let Some(link_id) = self.link_id else {
return;
return false;
};
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
@@ -867,16 +1149,50 @@ impl PropagationClient {
};
let mut raw = header.pack();
raw.extend_from_slice(payload);
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
if !self.queue_link_endpoint(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
})) {
}) {
self.status.state = PropagationClientState::Failed;
false
} else if let Some(link) = self.link.as_mut() {
link.record_tx(payload.len());
true
} else {
false
}
}
fn send_final_link_packet(
&mut self,
context: rns_wire::context::PacketContext,
packet_type: rns_wire::flags::PacketType,
payload: &[u8],
) -> bool {
let Some(link_id) = self.link_id else {
return false;
};
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context,
};
let mut raw = header.pack();
raw.extend_from_slice(payload);
self.queue_link_endpoint_and_unbind(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
})
}
/// Phase 1: parse available transient IDs from the server.
fn handle_list_response(&mut self, response_data: &[u8]) {
let value: rmpv::Value = match rmpv::decode::read_value(&mut &response_data[..]) {
@@ -950,6 +1266,7 @@ impl PropagationClient {
pub fn tick(&mut self) {
self.flush_pending_transport();
self.poll_endpoint_control();
if self.status.state == PropagationClientState::Failed {
self.cleanup();
return;
@@ -981,7 +1298,7 @@ impl PropagationClient {
);
}
Some(LinkAction::SendTeardownAndClose(payload)) => {
self.send_link_packet(
self.endpoint_release_queued = self.send_final_link_packet(
rns_wire::context::PacketContext::LinkClose,
rns_wire::flags::PacketType::Data,
&payload,
@@ -1054,10 +1371,10 @@ impl PropagationClient {
};
let mut id_raw = id_header.pack();
id_raw.extend_from_slice(&identify_data);
Some(TransportMessage::Outbound(OutboundRequest {
Some(OutboundRequest {
raw: Bytes::from(id_raw),
destination_hash: link_id,
}))
})
} else {
None
}
@@ -1068,7 +1385,7 @@ impl PropagationClient {
None
};
if let Some(outbound) = outbound {
if !self.queue_transport(outbound) {
if !self.queue_link_endpoint(outbound) {
self.status.state = PropagationClientState::Failed;
}
}
@@ -1204,10 +1521,10 @@ impl PropagationClient {
rns_wire::flags::HeaderType::Header1,
);
link.update_pending_request_id(&_request_id, packet_request_id);
Some(TransportMessage::Outbound(OutboundRequest {
Some(OutboundRequest {
raw: Bytes::from(req_raw),
destination_hash: link_id,
}))
})
} else {
None
}
@@ -1217,19 +1534,19 @@ impl PropagationClient {
} else {
None
};
outbound.is_some_and(|message| self.queue_transport(message))
outbound.is_some_and(|request| self.queue_link_endpoint(request))
}
fn cleanup(&mut self) {
self.send_teardown();
let graceful_release = self.endpoint_release_queued || self.send_teardown();
if let Some(link_id) = self.link_id.take() {
if !self.queue_transport(TransportMessage::DeregisterDestination { hash: link_id }) {
tracing::warn!(
link_id = %hex::encode(link_id),
"failed to deregister propagation client Link"
);
if !graceful_release {
self.queue_endpoint_cleanup(link_id);
}
}
self.attached_interface = None;
self.endpoint_release_queued = false;
self.pending_endpoint_bind = None;
self.link = None;
self.inbound_resources.clear();
self.inbound_split_resources.clear();
@@ -1238,16 +1555,16 @@ impl PropagationClient {
self.started_at = None;
}
fn send_teardown(&mut self) {
fn send_teardown(&mut self) -> bool {
let Some(link_id) = self.link_id else {
return;
return false;
};
let teardown_data = self
.link
.as_mut()
.and_then(|link| link.teardown(CloseReason::InitiatorClosed));
if let Some(teardown_data) = teardown_data {
self.send_link_packet(
let retained = self.send_final_link_packet(
rns_wire::context::PacketContext::LinkClose,
rns_wire::flags::PacketType::Data,
&teardown_data,
@@ -1256,6 +1573,9 @@ impl PropagationClient {
link_id = hex::encode(link_id),
"propagation client link closed"
);
retained
} else {
false
}
}
@@ -1269,6 +1589,43 @@ mod tests {
use super::*;
use rns_protocol::resource::OutboundTransfer;
fn next_link_request(rx: &mut mpsc::Receiver<TransportMessage>) -> OutboundRequest {
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::Outbound(request) => return request,
TransportMessage::SendLinkEndpoint {
request, result_tx, ..
} => {
let _ = result_tx.send(LinkEndpointSendResult::Sent);
return request;
}
_ => {}
}
}
panic!("expected Link packet");
}
fn complete_client_cleanup(
client: &mut PropagationClient,
rx: &mut mpsc::Receiver<TransportMessage>,
) -> bool {
let mut saw_deregister = false;
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::UnbindLinkEndpoint { result_tx, .. } => {
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
}
TransportMessage::DeregisterDestination { .. } => saw_deregister = true,
_ => {}
}
}
client.poll_endpoint_control();
while let Ok(message) = rx.try_recv() {
saw_deregister |= matches!(message, TransportMessage::DeregisterDestination { .. });
}
saw_deregister
}
fn active_link_pair(dest_hash: [u8; 16]) -> (Link, Link) {
let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let responder_pub = responder_key.public_key();
@@ -1393,6 +1750,51 @@ mod tests {
assert!(client.pending_transport.is_empty());
}
#[test]
fn invalid_client_lrproof_allows_later_valid_binding_before_lrrtt() {
let (tx, mut rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
let node_hash = [0xB4; 16];
let (link, request_data) = Link::new_initiator(node_hash, 1);
let link_id = link.link_id;
let responder_key = Ed25519PrivateKey::generate();
let responder_public = responder_key.public_key();
let (_responder, proof) =
Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap();
client.link = Some(link);
client.link_id = Some(link_id);
client.status.state = PropagationClientState::LinkEstablishing;
client.handle_link_proof(
&[0u8; 99],
&responder_public,
&responder_public.to_bytes(),
7,
);
assert_eq!(client.state(), PropagationClientState::LinkEstablishing);
assert!(client.pending_endpoint_bind.is_none());
assert!(rx.try_recv().is_err());
client.handle_link_proof(&proof, &responder_public, &responder_public.to_bytes(), 8);
let TransportMessage::BindLinkEndpoint {
binding, result_tx, ..
} = rx.try_recv().unwrap()
else {
panic!("valid proof must bind before LRRTT");
};
assert_eq!(binding.interface_id, 8);
assert!(rx.try_recv().is_err());
result_tx.send(LinkEndpointBindResult::Bound).unwrap();
client.poll_endpoint_control();
let TransportMessage::SendLinkEndpoint { request, role, .. } = rx.try_recv().unwrap()
else {
panic!("bound endpoint must carry LRRTT");
};
assert_eq!(role, LinkEndpointRole::Initiator);
let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt);
}
#[test]
fn test_start_download_rejects_an_active_transfer() {
let (tx, mut rx) = mpsc::channel(64);
@@ -1441,10 +1843,7 @@ mod tests {
client.local_messages.insert(vec![1; 32]);
client.send_get_request();
let request = match rx.try_recv().unwrap() {
TransportMessage::Outbound(request) => request,
other => panic!("expected request packet, got {other:?}"),
};
let request = next_link_request(&mut rx);
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
let (_, _, _, request_data) = responder.handle_request(&request.raw[offset..]).unwrap();
let value = rmpv::decode::read_value(&mut &request_data[..]).unwrap();
@@ -1621,10 +2020,7 @@ mod tests {
Some(PropagationClientState::GetRequested)
);
let request = match rx.try_recv().unwrap() {
TransportMessage::Outbound(request) => request,
other => panic!("expected Resource request, got {other:?}"),
};
let request = next_link_request(&mut rx);
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
let request_data = responder.decrypt(&request.raw[offset..]).unwrap();
let first_part = sender
@@ -1644,6 +2040,104 @@ mod tests {
assert!(client.status.progress >= first_progress);
}
#[test]
fn resource_response_is_not_published_when_its_proof_cannot_be_retained() {
let (tx, mut rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
let (initiator, responder) = active_link_pair([0xE5; 16]);
client.link_id = Some(initiator.link_id);
client.link = Some(initiator);
client.attached_interface = Some(0);
client.status.state = PropagationClientState::GetRequested;
let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAB; 32])]);
let payload = crate::encode_value(&response);
let mut sender = OutboundTransfer::new_encrypted(
payload,
false,
Duration::from_millis(50),
responder.session_keys().unwrap(),
)
.unwrap();
sender.resource.flags.is_response = true;
let advertisement = match sender.tick() {
TransferAction::SendAdvertisement(data) => data,
other => panic!("expected Resource advertisement, got {other:?}"),
};
client.handle_resource_advertisement(&responder.encrypt(&advertisement).unwrap());
let request = next_link_request(&mut rx);
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
let request_data = responder.decrypt(&request.raw[offset..]).unwrap();
let parts: Vec<Vec<u8>> = sender
.handle_request(&request_data)
.into_iter()
.filter_map(|action| match action {
TransferAction::SendPart(_, data) => Some(data),
_ => None,
})
.collect();
drop(rx);
for part in parts {
client.handle_resource_part(&part);
}
assert_eq!(client.state(), PropagationClientState::Failed);
assert!(client.received_messages.is_empty());
}
#[test]
fn resource_response_is_not_published_when_transport_rejects_its_proof() {
let (tx, mut rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
let (initiator, responder) = active_link_pair([0xE6; 16]);
client.link_id = Some(initiator.link_id);
client.link = Some(initiator);
client.attached_interface = Some(0);
client.status.state = PropagationClientState::GetRequested;
let response = rmpv::Value::Array(vec![rmpv::Value::Binary(vec![0xAC; 32])]);
let mut sender = OutboundTransfer::new_encrypted(
crate::encode_value(&response),
false,
Duration::from_millis(50),
responder.session_keys().unwrap(),
)
.unwrap();
sender.resource.flags.is_response = true;
let advertisement = match sender.tick() {
TransferAction::SendAdvertisement(data) => data,
other => panic!("expected Resource advertisement, got {other:?}"),
};
client.handle_resource_advertisement(&responder.encrypt(&advertisement).unwrap());
let request = next_link_request(&mut rx);
let (_, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
let request_data = responder.decrypt(&request.raw[offset..]).unwrap();
for part in sender
.handle_request(&request_data)
.into_iter()
.filter_map(|action| match action {
TransferAction::SendPart(_, data) => Some(data),
_ => None,
})
{
client.handle_resource_part(&part);
}
let TransportMessage::SendLinkEndpoint { result_tx, .. } =
rx.try_recv().expect("Resource proof send")
else {
panic!("expected typed Resource proof send");
};
result_tx
.send(LinkEndpointSendResult::InvalidPacket)
.unwrap();
client.poll_endpoint_control();
assert_eq!(client.state(), PropagationClientState::Failed);
assert!(client.received_messages.is_empty());
assert!(client.received_ids.is_empty());
}
#[test]
fn test_handle_purge_response() {
let (tx, _rx) = mpsc::channel(16);
@@ -1704,10 +2198,47 @@ mod tests {
client.status.state = PropagationClientState::Complete;
client.tick();
let dereg = rx.try_recv();
let saw_deregister = complete_client_cleanup(&mut client, &mut rx);
assert!(saw_deregister);
}
#[test]
fn failed_final_send_unbinds_before_deregistering_client_link() {
let (tx, mut rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
let (initiator, _) = active_link_pair([0xD9; 16]);
let link_id = initiator.link_id;
client.link_id = Some(link_id);
client.link = Some(initiator);
client.status.state = PropagationClientState::ListRequested;
assert!(client.send_final_link_packet(
rns_wire::context::PacketContext::LinkClose,
rns_wire::flags::PacketType::Data,
&[0x01],
));
let TransportMessage::SendLinkEndpointAndUnbind { result_tx, .. } =
rx.try_recv().expect("final Link send")
else {
panic!("expected atomic final Link send");
};
result_tx
.send(LinkEndpointSendResult::InvalidPacket)
.unwrap();
client.poll_endpoint_control();
assert_eq!(client.state(), PropagationClientState::Failed);
let TransportMessage::UnbindLinkEndpoint { result_tx, .. } =
rx.try_recv().expect("role-safe fallback unbind")
else {
panic!("failed final send must fall back to exact-owner unbind");
};
assert!(rx.try_recv().is_err(), "deregister must wait for unbind");
result_tx.send(LinkEndpointUnbindResult::Unbound).unwrap();
client.poll_endpoint_control();
assert!(matches!(
dereg.unwrap(),
TransportMessage::DeregisterDestination { .. }
rx.try_recv().unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
));
}
@@ -1720,6 +2251,7 @@ mod tests {
let link_id = link.link_id;
client.link = Some(link);
client.link_id = Some(link_id);
client.attached_interface = Some(0);
client.status.state = PropagationClientState::ListRequested;
client.started_at = Some(Instant::now());
@@ -1745,10 +2277,8 @@ mod tests {
client.tick();
assert_eq!(client.status.state, PropagationClientState::Failed);
assert!(client.link.is_none());
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
));
let saw_deregister = complete_client_cleanup(&mut client, &mut rx);
assert!(saw_deregister);
assert!(client.acknowledge_transfer());
assert_eq!(client.status.state, PropagationClientState::Idle);
}
@@ -1762,6 +2292,7 @@ mod tests {
let link_id = link.link_id;
client.link = Some(link);
client.link_id = Some(link_id);
client.attached_interface = Some(0);
client.status.state = PropagationClientState::ListRequested;
client
@@ -1777,4 +2308,36 @@ mod tests {
assert_eq!(client.status.state, PropagationClientState::ListRequested);
assert!(client.link.is_some());
}
#[test]
fn client_rejects_authenticated_packet_from_wrong_interface_before_state_change() {
let (tx, _rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
let node_hash = [0xE6; 16];
let (link, mut responder) = active_link_pair(node_hash);
let link_id = link.link_id;
client.link = Some(link);
client.link_id = Some(link_id);
client.attached_interface = Some(4);
client.status.state = PropagationClientState::ListRequested;
let close_body = responder
.teardown(CloseReason::InitiatorClosed)
.expect("active responder teardown");
client
.event_tx
.try_send(DestinationEvent::InboundPacket {
raw: link_data_packet(
link_id,
rns_wire::context::PacketContext::LinkClose,
&close_body,
),
interface_id: 5,
metrics: Default::default(),
})
.unwrap();
client.drain_events(&std::collections::HashMap::new());
assert_eq!(client.state(), PropagationClientState::ListRequested);
assert!(client.link.as_ref().is_some_and(Link::is_active));
}
}
+142
View File
@@ -745,6 +745,17 @@ impl PropagationNode {
PropagationEntry::new_stamped(tid, message_hash, destination_hash, size, sv);
pe.stored_at = ts;
// Older app hosts persisted opaque blobs without their PN
// stamp. Their filename TID hashes the entire file, whereas
// canonical stamped storage hashes the file before its final
// 32-byte stamp. Recover that exact legacy representation so
// client /get cannot truncate ciphertext after a restart.
// This distinguishes storage format, not stamp authenticity;
// retain the existing policy for other opaque/malformed files.
if data.len() > DESTINATION_LENGTH && message_hash == tid {
pe.stamped = false;
}
if let Ok(msg) = LxMessage::unpack(&data) {
pe.message_hash = msg.hash.unwrap_or([0u8; 32]);
pe.destination_hash = msg.destination_hash;
@@ -2840,9 +2851,140 @@ mod tests {
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_array().unwrap().len(), 1);
let full_id = rns_crypto::sha::full_hash(&lxmf_data);
let get_request = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut get_buf = Vec::new();
rmpv::encode::write_value(&mut get_buf, &get_request).unwrap();
let response = reloaded
.handle_get_request(&get_buf, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(
value.as_array().unwrap()[0].as_slice().unwrap(),
lxmf_data.as_slice(),
"legacy opaque blobs have no stamp to strip after restart"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_opaque_blob_reload_preserves_bytes_and_accounting_at_minimum_lengths() {
use rmpv::Value;
// These are storage-format controls, not authenticated ciphertext or
// stamp-validation tests. Retain the existing public ingress minimum.
for stamped in [false, true] {
for len in [17, 31, 32, 33, 48, 49, 144] {
let dir = tempfile::tempdir().unwrap();
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert!(!node.accept_propagated_blob(&[0xBB; 16], 0));
assert!(!node.accept_stamped_propagated_blob(&[0xBB; 16], &[0; 32], 0));
assert_eq!(node.message_count(), 0);
let mut blob = vec![0xBB; 16];
blob.resize(len, 0xCC);
let stamp = [0x5A; 32];
let full_id = rns_crypto::sha::full_hash(&blob);
let mut stored = blob.clone();
if stamped {
stored.extend_from_slice(&stamp);
assert!(node.accept_stamped_propagated_blob(&blob, &stamp, 0));
} else {
assert!(node.accept_propagated_blob(&blob, 0));
}
assert_eq!(node.total_size(), stored.len());
let path = dir
.path()
.join(node.store.get(&full_id).unwrap().filename());
assert_eq!(std::fs::read(&path).unwrap(), stored);
drop(node);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), stored.len());
assert_eq!(node.store.get(&full_id).unwrap().stamped, stamped);
// Duplicate admission must neither replace the known format
// nor grow the byte/accounting reservation after reload.
assert!(!node.accept_propagated_blob(&blob, 0));
assert!(!node.accept_stamped_propagated_blob(&blob, &stamp, 0));
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), stored.len());
assert!(node.pending_write_ids.is_empty());
assert_eq!(node.pending_write_bytes, 0);
let get = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut request = Vec::new();
rmpv::encode::write_value(&mut request, &get).unwrap();
let response = node
.handle_get_request(&request, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
let messages = value.as_array().unwrap();
assert_eq!(messages.len(), 1);
assert_eq!(messages[0].as_slice().unwrap(), blob);
assert_eq!(
node.message_get_request(&[full_id]),
vec![(full_id, stored.clone())]
);
assert_eq!(std::fs::read(&path).unwrap(), stored);
}
}
}
#[test]
fn test_reloaded_legacy_message_keeps_original_get_bytes() {
use rmpv::Value;
let dir = tempfile::tempdir().unwrap();
let message = make_signed_message([0xBB; 16], [0xCC; 16], "legacy", "full message");
let packed = message.pack().unwrap();
let full_id = message.transient_id.or(message.hash).unwrap();
assert_ne!(full_id, rns_crypto::sha::full_hash(&packed));
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert!(node.accept_message(&message));
drop(node);
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[0xAA; 16],
dir.path().to_path_buf(),
)
.unwrap();
assert_eq!(node.message_count(), 1);
assert_eq!(node.total_size(), packed.len());
assert!(!node.store.get(&full_id).unwrap().stamped);
let get = Value::Array(vec![
Value::Array(vec![Value::Binary(full_id.to_vec())]),
Value::Array(vec![]),
]);
let mut request = Vec::new();
rmpv::encode::write_value(&mut request, &get).unwrap();
let response = node
.handle_get_request(&request, &[0xBB; 16])
.into_response();
let value: Value = rmpv::decode::read_value(&mut &response[..]).unwrap();
assert_eq!(value.as_array().unwrap()[0].as_slice().unwrap(), packed);
}
#[test]
fn test_handle_get_request_purge_phase() {
let dir = std::env::temp_dir().join("lxmf_test_get_purge");
+531 -108
View File
@@ -20,7 +20,11 @@ use rns_protocol::resource::{
MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundTransfer, ResourceError, TransferAction,
};
use rns_transport::link_messages::DestinationEvent;
use rns_transport::messages::{OutboundRequest, TransportMessage};
use rns_transport::messages::{
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
TransportMessage,
};
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::{mpsc, oneshot};
@@ -77,6 +81,23 @@ struct PreparedTransferBatch {
payload: Vec<u8>,
}
struct PendingEndpointBind {
interface_id: InterfaceId,
rtt_request: OutboundRequest,
result_rx: oneshot::Receiver<LinkEndpointBindResult>,
}
struct PendingEndpointSend {
link_id: [u8; 16],
final_send: bool,
result_rx: oneshot::Receiver<LinkEndpointSendResult>,
}
struct PendingEndpointCleanup {
link_id: [u8; 16],
result_rx: oneshot::Receiver<LinkEndpointUnbindResult>,
}
fn prepare_outbound_resource_transfers(
payload: Vec<u8>,
auto_compress: bool,
@@ -115,6 +136,12 @@ pub struct PropagationSyncTask {
pub propagation_node: Arc<Mutex<PropagationNode>>,
link: Option<Link>,
link_id: Option<[u8; 16]>,
attached_interface: Option<InterfaceId>,
pending_endpoint_bind: Option<PendingEndpointBind>,
pending_endpoint_sends: Vec<PendingEndpointSend>,
pending_endpoint_cleanups: Vec<PendingEndpointCleanup>,
endpoint_lifecycle_tx: mpsc::UnboundedSender<LinkEndpointLifecycleEvent>,
endpoint_lifecycle_rx: mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
pub state: SyncTaskState,
last_sync: Instant,
sync_interval: Duration,
@@ -150,6 +177,7 @@ pub struct PropagationSyncTask {
impl PropagationSyncTask {
pub fn new(transport_tx: mpsc::Sender<TransportMessage>, dest_hash: [u8; 16]) -> Self {
let (event_tx, event_rx) = mpsc::channel(256);
let (endpoint_lifecycle_tx, endpoint_lifecycle_rx) = mpsc::unbounded_channel();
Self {
transport_tx,
event_tx,
@@ -161,6 +189,12 @@ impl PropagationSyncTask {
))),
link: None,
link_id: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
state: SyncTaskState::Idle,
last_sync: Instant::now(),
sync_interval: Duration::from_secs(300),
@@ -201,6 +235,7 @@ impl PropagationSyncTask {
storage_path: std::path::PathBuf,
) -> std::io::Result<Self> {
let (event_tx, event_rx) = mpsc::channel(256);
let (endpoint_lifecycle_tx, endpoint_lifecycle_rx) = mpsc::unbounded_channel();
Ok(Self {
transport_tx,
event_tx,
@@ -213,6 +248,12 @@ impl PropagationSyncTask {
)?)),
link: None,
link_id: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
state: SyncTaskState::Idle,
last_sync: Instant::now(),
sync_interval: Duration::from_secs(300),
@@ -253,6 +294,7 @@ impl PropagationSyncTask {
propagation_node: Arc<Mutex<PropagationNode>>,
) -> Self {
let (event_tx, event_rx) = mpsc::channel(256);
let (endpoint_lifecycle_tx, endpoint_lifecycle_rx) = mpsc::unbounded_channel();
Self {
transport_tx,
event_tx,
@@ -261,6 +303,12 @@ impl PropagationSyncTask {
propagation_node,
link: None,
link_id: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
state: SyncTaskState::Idle,
last_sync: Instant::now(),
sync_interval: Duration::from_secs(300),
@@ -408,8 +456,14 @@ impl PropagationSyncTask {
/// Preserve protocol packet ordering while tolerating temporary pressure
/// on the bounded Reticulum transport actor mailbox. A full mailbox is a
/// retryable local condition, not packet loss.
const PENDING_TRANSPORT_LIMIT: usize = 256;
fn queue_transport(&mut self, message: TransportMessage) -> bool {
if !self.pending_transport.is_empty() {
if self.pending_transport.len() >= Self::PENDING_TRANSPORT_LIMIT {
self.state = SyncTaskState::Failed;
return false;
}
self.pending_transport.push_back(message);
return true;
}
@@ -417,6 +471,10 @@ impl PropagationSyncTask {
match self.transport_tx.try_send(message) {
Ok(()) => true,
Err(TrySendError::Full(message)) => {
if self.pending_transport.len() >= Self::PENDING_TRANSPORT_LIMIT {
self.state = SyncTaskState::Failed;
return false;
}
self.pending_transport.push_back(message);
true
}
@@ -441,6 +499,146 @@ impl PropagationSyncTask {
true
}
fn queue_link_endpoint(&mut self, request: OutboundRequest) -> bool {
let Some(link_id) = self.link_id else {
return false;
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::SendLinkEndpoint {
link_id,
role: LinkEndpointRole::Initiator,
request,
result_tx,
}) {
return false;
}
self.pending_endpoint_sends.push(PendingEndpointSend {
link_id,
final_send: false,
result_rx,
});
true
}
fn queue_endpoint_cleanup(&mut self, link_id: [u8; 16]) {
let (result_tx, result_rx) = oneshot::channel();
if self.queue_transport(TransportMessage::UnbindLinkEndpoint {
link_id,
role: LinkEndpointRole::Initiator,
result_tx,
}) {
self.pending_endpoint_cleanups
.push(PendingEndpointCleanup { link_id, result_rx });
}
}
fn poll_endpoint_send_results(&mut self) {
let mut still_pending = Vec::new();
let mut endpoint_sends = std::mem::take(&mut self.pending_endpoint_sends);
for mut pending in endpoint_sends.drain(..) {
match pending.result_rx.try_recv() {
Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => {}
Ok(result) => {
tracing::warn!(
link_id = %hex::encode(pending.link_id),
?result,
final_send = pending.final_send,
"propagation sync Link endpoint send rejected"
);
if self.link_id == Some(pending.link_id) {
self.state = SyncTaskState::Failed;
}
if pending.final_send {
self.queue_endpoint_cleanup(pending.link_id);
}
}
Err(oneshot::error::TryRecvError::Closed) => {
if self.link_id == Some(pending.link_id) {
self.state = SyncTaskState::Failed;
}
}
Err(oneshot::error::TryRecvError::Empty) => still_pending.push(pending),
}
}
self.pending_endpoint_sends = still_pending;
let mut cleanup_pending = Vec::new();
let mut cleanups = std::mem::take(&mut self.pending_endpoint_cleanups);
for mut pending in cleanups.drain(..) {
match pending.result_rx.try_recv() {
Ok(LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound) => {
let _ = self.queue_transport(TransportMessage::DeregisterDestination {
hash: pending.link_id,
});
}
Ok(LinkEndpointUnbindResult::RoleMismatch) => {
tracing::warn!(
link_id = %hex::encode(pending.link_id),
"refusing to deregister a propagation sync Link owned by the opposite role"
);
}
Err(oneshot::error::TryRecvError::Closed) => {}
Err(oneshot::error::TryRecvError::Empty) => cleanup_pending.push(pending),
}
}
self.pending_endpoint_cleanups = cleanup_pending;
}
fn poll_endpoint_control(&mut self) {
self.poll_endpoint_send_results();
while let Ok(event) = self.endpoint_lifecycle_rx.try_recv() {
if self.link_id == Some(event.binding.link_id)
&& event.binding.role == LinkEndpointRole::Initiator
{
tracing::warn!(
link_id = %hex::encode(event.binding.link_id),
interface_id = event.binding.interface_id,
reason = ?event.reason,
dropped_packets = event.dropped_packets,
"propagation sync Link endpoint terminated"
);
self.attached_interface = None;
self.pending_endpoint_bind = None;
self.state = SyncTaskState::Failed;
}
}
let Some(mut pending) = self.pending_endpoint_bind.take() else {
return;
};
match pending.result_rx.try_recv() {
Ok(LinkEndpointBindResult::Bound | LinkEndpointBindResult::AlreadyBound) => {
self.attached_interface = Some(pending.interface_id);
if !self.queue_link_endpoint(pending.rtt_request) {
self.state = SyncTaskState::Failed;
return;
}
let establishment_rate =
self.link.as_ref().and_then(|link| link.establishment_rate);
self.link_establishment_rate = establishment_rate;
if let (Some(peer), Some(link_id)) = (self.peer.as_mut(), self.link_id) {
peer.link_established(link_id, establishment_rate);
}
if !self.send_identify() {
self.state = SyncTaskState::Failed;
return;
}
self.state = SyncTaskState::Offering;
self.sync_started = Some(Instant::now());
}
Ok(
LinkEndpointBindResult::Conflict { .. }
| LinkEndpointBindResult::InterfaceUnavailable,
)
| Err(oneshot::error::TryRecvError::Closed) => {
self.state = SyncTaskState::Failed;
}
Err(oneshot::error::TryRecvError::Empty) => {
self.pending_endpoint_bind = Some(pending);
}
}
}
fn reset_attempt_accounting(&mut self) {
self.offered_count = 0;
self.outgoing_count = 0;
@@ -461,6 +659,7 @@ impl PropagationSyncTask {
///
/// `known_identities` maps dest_hash_hex -> 64-byte public key, used for link proof validation.
pub fn drain_events(&mut self, known_identities: &HashMap<String, [u8; 64]>) {
self.poll_endpoint_control();
let mut events = Vec::new();
while let Ok(event) = self.event_rx.try_recv() {
events.push(event);
@@ -471,7 +670,9 @@ impl PropagationSyncTask {
DestinationEvent::LinkClosed { link_id } => {
self.handle_link_closed(link_id, None);
}
DestinationEvent::InboundPacket { raw, .. } => {
DestinationEvent::InboundPacket {
raw, interface_id, ..
} => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
Err(_) => continue,
@@ -479,6 +680,28 @@ impl PropagationSyncTask {
if self.link_id != Some(header.destination_hash) {
continue;
}
let is_link_proof = matches!(
header.context,
rns_wire::context::PacketContext::Lrproof
| rns_wire::context::PacketContext::None
) && (header.flags.packet_type
== rns_wire::flags::PacketType::Proof
|| header.context == rns_wire::context::PacketContext::Lrproof);
if is_link_proof {
if self.pending_endpoint_bind.is_some()
|| self.state != SyncTaskState::Establishing
{
continue;
}
} else if self.attached_interface != Some(interface_id) {
tracing::warn!(
link_id = %hex::encode(header.destination_hash),
interface_id,
attached_interface = ?self.attached_interface,
"rejected propagation sync packet from wrong Link interface"
);
continue;
}
let data = if raw.len() > data_offset {
&raw[data_offset..]
} else {
@@ -502,7 +725,12 @@ impl PropagationSyncTask {
if let Ok(verify_key) =
Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(data, &verify_key, &ed25519_bytes);
self.handle_link_proof(
data,
&verify_key,
&ed25519_bytes,
interface_id,
);
}
}
}
@@ -702,57 +930,54 @@ impl PropagationSyncTask {
proof_data: &[u8],
verify_key: &Ed25519PublicKey,
ed25519_pub: &[u8; 32],
interface_id: InterfaceId,
) {
let proof_result = match self.link.as_mut() {
Some(link) => link.validate_proof(proof_data, verify_key, ed25519_pub),
None => return,
};
match proof_result {
Ok(rtt_data) => {
// RTT packet = message 3 of the link handshake.
if let Some(link_id) = self.link_id {
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
if let Ok(rtt_data) = proof_result {
// RTT packet = message 3 of the link handshake.
if let Some(link_id) = self.link_id {
let rtt_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::Lrrtt,
};
let mut rtt_raw = rtt_header.pack();
rtt_raw.extend_from_slice(&rtt_data);
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
})) {
self.state = SyncTaskState::Failed;
return;
}
// Python LXMPeer.py:530-538
let establishment_rate =
self.link.as_ref().and_then(|link| link.establishment_rate);
self.link_establishment_rate = establishment_rate;
if let Some(ref mut peer) = self.peer {
peer.link_established(link_id, establishment_rate);
}
}
if !self.send_identify() {
let rtt_request = OutboundRequest {
raw: Bytes::from(rtt_raw),
destination_hash: link_id,
};
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id,
role: LinkEndpointRole::Initiator,
},
lifecycle_tx: self.endpoint_lifecycle_tx.clone(),
result_tx,
}) {
self.state = SyncTaskState::Failed;
return;
}
self.state = SyncTaskState::Offering;
self.sync_started = Some(Instant::now());
}
Err(_) => {
self.state = SyncTaskState::Failed;
self.pending_endpoint_bind = Some(PendingEndpointBind {
interface_id,
rtt_request,
result_rx,
});
}
}
}
@@ -869,6 +1094,7 @@ impl PropagationSyncTask {
if !self.flush_pending_transport() && self.state != SyncTaskState::Idle {
self.state = SyncTaskState::Failed;
}
self.poll_endpoint_control();
// Link establishment and offer requests retain a bounded phase
// timeout. Resource transfers deliberately do not have an absolute
@@ -978,7 +1204,7 @@ impl PropagationSyncTask {
}
LinkAction::SendTeardownAndClose(teardown_data) => {
if !teardown_data.is_empty() {
self.preserve_pending_on_cleanup = self.queue_plain_link_packet(
self.preserve_pending_on_cleanup = self.queue_final_link_packet(
link_id,
&teardown_data,
rns_wire::context::PacketContext::LinkClose,
@@ -1141,10 +1367,10 @@ impl PropagationSyncTask {
rns_wire::flags::HeaderType::Header1,
);
link.update_pending_request_id(&_request_id, packet_request_id);
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
if !self.queue_link_endpoint(OutboundRequest {
raw: Bytes::from(req_raw),
destination_hash: link_id,
})) {
}) {
self.state = SyncTaskState::Failed;
return;
}
@@ -1180,6 +1406,8 @@ impl PropagationSyncTask {
self.link = Some(link);
self.link_id = Some(link_id);
self.attached_interface = None;
self.pending_endpoint_bind = None;
if !self.queue_transport(TransportMessage::RegisterDestination {
hash: link_id,
@@ -1390,10 +1618,51 @@ impl PropagationSyncTask {
};
let mut raw = header.pack();
raw.extend_from_slice(data);
self.queue_transport(TransportMessage::Outbound(OutboundRequest {
self.queue_link_endpoint(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
}))
})
}
fn queue_final_link_packet(
&mut self,
link_id: [u8; 16],
data: &[u8],
context: rns_wire::context::PacketContext,
) -> bool {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context,
};
let mut raw = header.pack();
raw.extend_from_slice(data);
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::SendLinkEndpointAndUnbind {
link_id,
role: LinkEndpointRole::Initiator,
request: OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
},
result_tx,
}) {
return false;
}
self.pending_endpoint_sends.push(PendingEndpointSend {
link_id,
final_send: true,
result_rx,
});
true
}
fn send_resource_packet(
@@ -1451,10 +1720,10 @@ impl PropagationSyncTask {
};
let mut raw = header.pack();
raw.extend_from_slice(&identify_data);
self.queue_transport(TransportMessage::Outbound(OutboundRequest {
self.queue_link_endpoint(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
}))
})
}
/// Python LXMPeer.py:540-542.
@@ -1462,18 +1731,23 @@ impl PropagationSyncTask {
// No transfer packet should survive the attempt it belongs to. The
// teardown and deregistration below form a new ordered tail. Preserve
// a teardown already emitted by Link::tick() when it closed the link.
if !self.preserve_pending_on_cleanup {
let endpoint_release_queued = self.preserve_pending_on_cleanup;
if !endpoint_release_queued {
self.pending_transport.clear();
}
self.preserve_pending_on_cleanup = false;
self.send_teardown();
let graceful_release = endpoint_release_queued || self.send_teardown();
if let Some(ref mut peer) = self.peer {
peer.link_closed();
}
if let Some(link_id) = self.link_id.take() {
let _ = self.queue_transport(TransportMessage::DeregisterDestination { hash: link_id });
if !graceful_release {
self.queue_endpoint_cleanup(link_id);
}
}
self.attached_interface = None;
self.pending_endpoint_bind = None;
self.link = None;
self.peer = None;
self.active_transfer = None;
@@ -1487,34 +1761,22 @@ impl PropagationSyncTask {
self.sync_started = None;
}
fn send_teardown(&mut self) {
fn send_teardown(&mut self) -> bool {
let Some(link_id) = self.link_id else {
return;
return false;
};
let teardown_data = self
.link
.as_mut()
.and_then(|link| link.teardown(CloseReason::InitiatorClosed));
if let Some(teardown_data) = teardown_data {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::LinkClose,
};
let mut raw = header.pack();
raw.extend_from_slice(&teardown_data);
let _ = self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: link_id,
}));
self.queue_final_link_packet(
link_id,
&teardown_data,
rns_wire::context::PacketContext::LinkClose,
)
} else {
false
}
}
@@ -1548,6 +1810,43 @@ impl PropagationSyncTask {
mod tests {
use super::*;
fn next_link_request(rx: &mut mpsc::Receiver<TransportMessage>) -> OutboundRequest {
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::Outbound(request) => return request,
TransportMessage::SendLinkEndpoint {
request, result_tx, ..
} => {
let _ = result_tx.send(LinkEndpointSendResult::Sent);
return request;
}
_ => {}
}
}
panic!("expected Link packet");
}
fn complete_sync_cleanup(
task: &mut PropagationSyncTask,
rx: &mut mpsc::Receiver<TransportMessage>,
) -> bool {
let mut saw_deregister = false;
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::UnbindLinkEndpoint { result_tx, .. } => {
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
}
TransportMessage::DeregisterDestination { .. } => saw_deregister = true,
_ => {}
}
}
task.poll_endpoint_control();
while let Ok(message) = rx.try_recv() {
saw_deregister |= matches!(message, TransportMessage::DeregisterDestination { .. });
}
saw_deregister
}
fn active_link_pair(dest_hash: [u8; 16]) -> (Link, Link) {
let responder_key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let responder_pub = responder_key.public_key();
@@ -1630,12 +1929,11 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
let resource_part = b"already-encrypted-resource-part";
task.send_resource_packet(resource_part, rns_wire::context::PacketContext::Resource);
let TransportMessage::Outbound(part_request) = rx.try_recv().unwrap() else {
panic!("expected outbound Resource packet");
};
let part_request = next_link_request(&mut rx);
let (part_header, part_offset) =
rns_wire::header::PacketHeader::unpack(&part_request.raw).unwrap();
assert_eq!(
@@ -1646,9 +1944,7 @@ mod tests {
let advertisement = b"resource-advertisement";
task.send_resource_packet(advertisement, rns_wire::context::PacketContext::ResourceAdv);
let TransportMessage::Outbound(adv_request) = rx.try_recv().unwrap() else {
panic!("expected outbound Resource advertisement");
};
let adv_request = next_link_request(&mut rx);
let (adv_header, adv_offset) =
rns_wire::header::PacketHeader::unpack(&adv_request.raw).unwrap();
assert_eq!(
@@ -1705,6 +2001,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.state = SyncTaskState::Transferring;
let mut stale_request = request.clone();
@@ -1728,9 +2025,7 @@ mod tests {
task.drain_events(&HashMap::new());
let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else {
panic!("expected requested Resource part");
};
let response = next_link_request(&mut rx);
let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap();
assert_eq!(header.context, rns_wire::context::PacketContext::Resource);
assert_eq!(&response.raw[offset..], expected_part);
@@ -1767,6 +2062,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.state = SyncTaskState::Transferring;
deliver_encrypted_resource_control(
@@ -1778,9 +2074,7 @@ mod tests {
task.drain_events(&HashMap::new());
let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else {
panic!("expected Resource hashmap update");
};
let response = next_link_request(&mut rx);
let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap();
assert_eq!(
header.context,
@@ -1814,6 +2108,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.active_transfer_ids = vec![[0x66; 32]];
task.state = SyncTaskState::Transferring;
@@ -1826,9 +2121,7 @@ mod tests {
task.drain_events(&HashMap::new());
let TransportMessage::Outbound(response) = rx.try_recv().unwrap() else {
panic!("expected initiator Resource cancel");
};
let response = next_link_request(&mut rx);
let (header, offset) = rns_wire::header::PacketHeader::unpack(&response.raw).unwrap();
assert_eq!(
header.context,
@@ -1864,6 +2157,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.active_transfer_ids = vec![[0x77; 32]];
task.state = SyncTaskState::Transferring;
@@ -2140,6 +2434,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link = Some(initiator);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.state = SyncTaskState::Transferring;
task.sync_started = Some(Instant::now() - Duration::from_secs(600));
@@ -2148,9 +2443,7 @@ mod tests {
task.tick();
assert_eq!(task.state, SyncTaskState::Transferring);
let TransportMessage::Outbound(advertisement) = rx.try_recv().unwrap() else {
panic!("expected Resource advertisement");
};
let advertisement = next_link_request(&mut rx);
let (header, _) = rns_wire::header::PacketHeader::unpack(&advertisement.raw).unwrap();
assert_eq!(
header.context,
@@ -2174,6 +2467,7 @@ mod tests {
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link = Some(initiator);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
task.active_transfer = Some(transfer);
task.state = SyncTaskState::Transferring;
@@ -2184,9 +2478,7 @@ mod tests {
task.tick();
let TransportMessage::Outbound(retry) = rx.try_recv().unwrap() else {
panic!("expected retried Resource advertisement");
};
let retry = next_link_request(&mut rx);
let (header, _) = rns_wire::header::PacketHeader::unpack(&retry.raw).unwrap();
assert_eq!(
header.context,
@@ -2221,6 +2513,106 @@ mod tests {
assert!(task.pending_transport.is_empty());
}
#[test]
fn propagation_sync_staging_is_finite_fifo_and_overflow_fails_only_task() {
let (tx, _rx) = mpsc::channel(1);
tx.try_send(TransportMessage::DeregisterDestination { hash: [0; 16] })
.unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.state = SyncTaskState::Offering;
for index in 0..PropagationSyncTask::PENDING_TRANSPORT_LIMIT {
assert!(
task.queue_transport(TransportMessage::DeregisterDestination {
hash: [(index & 0xff) as u8; 16],
})
);
}
let first_hash = match task.pending_transport.front().unwrap() {
TransportMessage::DeregisterDestination { hash } => *hash,
_ => unreachable!(),
};
assert!(
!task.queue_transport(TransportMessage::DeregisterDestination { hash: [0xFF; 16] })
);
assert_eq!(task.pending_transport.len(), 256);
assert_eq!(first_hash, [0; 16]);
assert_eq!(task.state, SyncTaskState::Failed);
}
#[test]
fn invalid_sync_lrproof_allows_later_valid_interface_binding() {
let (tx, mut rx) = mpsc::channel(64);
let node_hash = [0xB5; 16];
let (link, request_data) = Link::new_initiator(node_hash, 1);
let responder_key = Ed25519PrivateKey::generate();
let responder_public = responder_key.public_key();
let (_responder, proof) =
Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.node_dest_hash = Some(node_hash);
task.link_id = Some(link.link_id);
task.link = Some(link);
task.peer = Some(LxmPeer::new(node_hash));
task.state = SyncTaskState::Establishing;
task.handle_link_proof(
&[0u8; 99],
&responder_public,
&responder_public.to_bytes(),
11,
);
assert_eq!(task.state, SyncTaskState::Establishing);
assert!(task.pending_endpoint_bind.is_none());
assert!(rx.try_recv().is_err());
task.handle_link_proof(&proof, &responder_public, &responder_public.to_bytes(), 12);
let TransportMessage::BindLinkEndpoint { binding, .. } = rx.try_recv().unwrap() else {
panic!("valid proof must bind before post-proof traffic");
};
assert_eq!(binding.interface_id, 12);
assert!(rx.try_recv().is_err());
}
#[test]
fn propagation_sync_rejects_wrong_interface_before_decrypt_or_state_change() {
let (tx, _rx) = mpsc::channel(8);
let (initiator, responder) = active_link_pair([0x48; 16]);
let link_id = initiator.link_id;
let mut transfers = prepare_outbound_resource_transfers(
b"wrong interface cancel".to_vec(),
false,
Duration::from_millis(500),
initiator.session_keys().unwrap(),
)
.unwrap();
let transfer = transfers.pop_front().unwrap();
let resource_hash = transfer.resource.resource_hash;
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(4);
task.active_transfer = Some(transfer);
task.active_transfer_ids = vec![[0x77; 32]];
task.state = SyncTaskState::Transferring;
let encrypted = responder.encrypt(&resource_hash).unwrap();
task.event_tx
.try_send(DestinationEvent::InboundPacket {
raw: link_data_packet(
link_id,
rns_wire::context::PacketContext::ResourceRcl,
&encrypted,
),
interface_id: 5,
metrics: Default::default(),
})
.unwrap();
task.drain_events(&HashMap::new());
assert_eq!(task.state, SyncTaskState::Transferring);
assert!(task.active_transfer.is_some());
}
#[test]
fn test_cleanup_deregisters() {
let (tx, mut rx) = mpsc::channel(64);
@@ -2245,11 +2637,34 @@ mod tests {
task.state = SyncTaskState::Complete;
task.tick();
let dereg = rx.try_recv();
assert!(matches!(
dereg.unwrap(),
TransportMessage::DeregisterDestination { .. }
let saw_deregister = complete_sync_cleanup(&mut task, &mut rx);
assert!(saw_deregister);
}
#[test]
fn rejected_endpoint_send_fails_the_sync_owner() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let link_id = [0xD8; 16];
task.link_id = Some(link_id);
task.state = SyncTaskState::Offering;
assert!(task.queue_plain_link_packet(
link_id,
&[0x01],
rns_wire::context::PacketContext::Keepalive,
));
let TransportMessage::SendLinkEndpoint { result_tx, .. } =
rx.try_recv().expect("sync Link packet")
else {
panic!("expected typed sync Link send");
};
result_tx
.send(LinkEndpointSendResult::RoleMismatch)
.unwrap();
task.poll_endpoint_control();
assert_eq!(task.state, SyncTaskState::Failed);
}
#[test]
@@ -2262,6 +2677,7 @@ mod tests {
task.set_node(node_hash);
task.link = Some(link);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
task.state = SyncTaskState::AwaitingResponse;
task.sync_started = Some(Instant::now());
let mut peer = LxmPeer::new(node_hash);
@@ -2289,10 +2705,8 @@ mod tests {
task.tick();
assert_eq!(task.state, SyncTaskState::Idle);
assert!(task.link.is_none());
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
));
let saw_deregister = complete_sync_cleanup(&mut task, &mut rx);
assert!(saw_deregister);
}
#[test]
@@ -2305,6 +2719,7 @@ mod tests {
task.set_node(node_hash);
task.link = Some(link);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
task.state = SyncTaskState::AwaitingResponse;
task.event_tx
@@ -2923,13 +3338,21 @@ mod tests {
assert!(task.accept_message(&message));
task.offer_policy = Some(OutboundOfferPolicy::unrestricted(node_hash));
task.handle_link_proof(&proof_data, &responder_pub, &responder_pub.to_bytes());
task.handle_link_proof(&proof_data, &responder_pub, &responder_pub.to_bytes(), 0);
let bind = rx.try_recv().expect("endpoint bind");
let TransportMessage::BindLinkEndpoint { result_tx, .. } = bind else {
panic!("expected endpoint bind");
};
result_tx.send(LinkEndpointBindResult::Bound).unwrap();
task.poll_endpoint_control();
task.send_offer_request();
let mut contexts = Vec::new();
while let Ok(TransportMessage::Outbound(request)) = rx.try_recv() {
let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
contexts.push(header.context);
while let Ok(message) = rx.try_recv() {
if let TransportMessage::SendLinkEndpoint { request, .. } = message {
let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
contexts.push(header.context);
}
}
assert_eq!(
contexts,
+145 -22
View File
@@ -20,7 +20,7 @@ use crate::peer::{LxmPeer, OutboundOfferPolicy};
use crate::propagation::PropagationStore;
use crate::propagation_client::PropagationTransferStatus;
use crate::stamper;
use crate::ticket::{Ticket, TicketStore};
use crate::ticket::{Ticket, TicketStore, TicketStoreSnapshot};
use crate::types::PropagationTransientId;
/// Router configuration.
@@ -352,6 +352,37 @@ pub struct StampCostEntry {
pub recorded_at: f64,
}
/// Owned, coherent snapshot of the router state written by [`LxmRouter::save_state`].
///
/// Creating the snapshot only clones in-memory state. The caller can therefore
/// release any lock that protects the router before calling [`Self::save_state`],
/// keeping filesystem I/O out of the router's critical section.
#[derive(Debug, Clone)]
pub struct RouterStateSnapshot {
outbound_stamp_costs: HashMap<[u8; 16], StampCostEntry>,
tickets: TicketStoreSnapshot,
local_deliveries: HashMap<PropagationTransientId, f64>,
locally_processed: HashMap<PropagationTransientId, f64>,
node_stats: crate::persist::PersistedNodeStats,
}
impl RouterStateSnapshot {
/// Persist this owned snapshot using the router's MessagePack layout.
///
/// Each file is written atomically via rename, matching
/// [`LxmRouter::save_state`].
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, &self.tickets)?;
persist::save_local_deliveries(state_dir, &self.local_deliveries)?;
persist::save_locally_processed(state_dir, &self.locally_processed)?;
persist::save_node_stats(state_dir, &self.node_stats)?;
Ok(())
}
}
impl LxmRouter {
pub fn new(config: RouterConfig) -> Self {
Self {
@@ -1129,25 +1160,29 @@ impl LxmRouter {
Ok(())
}
/// Persist runtime state to `state_dir` using MessagePack. Safe to call
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
use crate::persist;
persist::save_stamp_costs(state_dir, &self.outbound_stamp_costs)?;
persist::save_tickets(state_dir, &self.ticket_store.snapshot())?;
persist::save_local_deliveries(state_dir, self.propagation_store.locally_delivered_ids())?;
persist::save_locally_processed(state_dir, self.propagation_store.locally_processed_ids())?;
persist::save_node_stats(
state_dir,
&persist::PersistedNodeStats {
/// Clone all runtime state written by [`Self::save_state`] into one owned
/// value. Embedders can take this snapshot while holding the router lock,
/// release the lock, and perform persistence through
/// [`RouterStateSnapshot::save_state`].
pub fn state_snapshot(&self) -> RouterStateSnapshot {
RouterStateSnapshot {
outbound_stamp_costs: self.outbound_stamp_costs.clone(),
tickets: self.ticket_store.snapshot(),
local_deliveries: self.propagation_store.locally_delivered_ids().clone(),
locally_processed: self.propagation_store.locally_processed_ids().clone(),
node_stats: crate::persist::PersistedNodeStats {
client_propagation_messages_received: self.client_propagation_messages_received,
client_propagation_messages_served: self.client_propagation_messages_served,
unpeered_propagation_incoming: self.unpeered_propagation_incoming,
unpeered_propagation_rx_bytes: self.unpeered_propagation_rx_bytes,
},
)?;
Ok(())
}
}
/// Persist runtime state to `state_dir` using MessagePack. Safe to call
/// periodically; each file is written atomically via rename.
pub fn save_state(&self, state_dir: &std::path::Path) -> std::io::Result<()> {
self.state_snapshot().save_state(state_dir)
}
/// Return peer destination hashes that are due for sync and mark each as
@@ -1978,15 +2013,19 @@ impl LxmRouter {
let mut raw = header.pack();
raw.extend_from_slice(&packet_payload);
if transport_tx
let dispatched = transport_tx
.try_send(rns_transport::messages::TransportMessage::Outbound(
rns_transport::messages::OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest_hash,
},
))
.is_ok()
&& message.state == MessageState::Sending
.is_ok();
if dispatched
&& matches!(
message.state,
MessageState::Sending | MessageState::Sent
)
{
message.mark_sent();
message.progress = 1.0;
@@ -2070,16 +2109,20 @@ impl LxmRouter {
fn run_periodic_jobs(&mut self) {
// Job cadences match the Python LXMRouter jobloop.
if self.processing_count % JOB_TRANSIENT_INTERVAL == 0 {
if self.processing_count.is_multiple_of(JOB_TRANSIENT_INTERVAL) {
self.propagation_store.clean_transient_caches(now_f64());
}
if self.processing_count % JOB_STORE_INTERVAL == 0 && self.config.propagation_enabled {
if self.processing_count.is_multiple_of(JOB_STORE_INTERVAL)
&& self.config.propagation_enabled
{
self.cull_propagation();
}
if self.processing_count % JOB_PEERSYNC_INTERVAL == 0 {
if self.processing_count.is_multiple_of(JOB_PEERSYNC_INTERVAL) {
self.clean_throttled_peers();
}
if self.processing_count % JOB_ROTATE_INTERVAL == 0 && self.config.propagation_enabled {
if self.processing_count.is_multiple_of(JOB_ROTATE_INTERVAL)
&& self.config.propagation_enabled
{
self.rotate_peers();
}
}
@@ -3043,6 +3086,82 @@ mod tests {
assert_eq!(r2.unpeered_propagation_rx_bytes, 13);
}
#[test]
fn test_state_snapshot_is_an_owned_coherent_copy() {
let dest = [0xA1; 16];
let transient = [0xB2; 32];
let mut router = LxmRouter::new(RouterConfig::default());
router.set_stamp_cost(dest, 8);
router.remember_ticket(dest, [0xC3; 16], 4_102_444_800.0);
router.propagation_store.mark_locally_delivered(transient);
router.propagation_store.mark_locally_processed(transient);
router.client_propagation_messages_received = 10;
router.client_propagation_messages_served = 11;
router.unpeered_propagation_incoming = 12;
router.unpeered_propagation_rx_bytes = 13;
let snapshot = router.state_snapshot();
// Mutating every persisted router dataset after capture must not alter
// the snapshot that a background persistence task owns.
router.set_stamp_cost(dest, 42);
router.remember_ticket(dest, [0xD4; 16], 4_102_444_800.0);
router
.propagation_store
.replace_locally_delivered(HashMap::new());
router
.propagation_store
.replace_locally_processed(HashMap::new());
router.client_propagation_messages_received = 20;
router.client_propagation_messages_served = 21;
router.unpeered_propagation_incoming = 22;
router.unpeered_propagation_rx_bytes = 23;
assert_eq!(snapshot.outbound_stamp_costs[&dest].cost, 8);
assert_eq!(snapshot.tickets.outbound.len(), 1);
assert_eq!(snapshot.tickets.outbound[0].token, [0xC3; 16]);
assert!(snapshot.local_deliveries.contains_key(&transient));
assert!(snapshot.locally_processed.contains_key(&transient));
assert_eq!(snapshot.node_stats.client_propagation_messages_received, 10);
assert_eq!(snapshot.node_stats.client_propagation_messages_served, 11);
assert_eq!(snapshot.node_stats.unpeered_propagation_incoming, 12);
assert_eq!(snapshot.node_stats.unpeered_propagation_rx_bytes, 13);
}
#[test]
fn test_state_snapshot_persists_after_router_is_dropped() {
let tmp = tempfile::TempDir::new().unwrap();
let dest = [0xA5; 16];
let transient = [0xB6; 32];
let snapshot = {
let mut router = LxmRouter::new(RouterConfig::default());
router.set_stamp_cost(dest, 9);
router.remember_ticket(dest, [0xC7; 16], 4_102_444_800.0);
router.propagation_store.mark_locally_delivered(transient);
router.propagation_store.mark_locally_processed(transient);
router.client_propagation_messages_received = 30;
router.client_propagation_messages_served = 31;
router.unpeered_propagation_incoming = 32;
router.unpeered_propagation_rx_bytes = 33;
router.state_snapshot()
};
snapshot.save_state(tmp.path()).unwrap();
let mut restored = LxmRouter::new(RouterConfig::default());
restored.load_state(tmp.path()).unwrap();
assert_eq!(restored.outbound_stamp_costs[&dest].cost, 9);
assert_eq!(restored.get_outbound_ticket(&dest), Some([0xC7; 16]));
assert!(restored.propagation_store.is_locally_delivered(&transient));
assert!(restored.propagation_store.is_locally_processed(&transient));
assert_eq!(restored.client_propagation_messages_received, 30);
assert_eq!(restored.client_propagation_messages_served, 31);
assert_eq!(restored.unpeered_propagation_incoming, 32);
assert_eq!(restored.unpeered_propagation_rx_bytes, 33);
}
/// T1-10: persisted dedup timestamps are the REAL first-seen times —
/// restored on load (not reset to save-time), so age-based expiry is
/// stable across arbitrarily many save/load cycles.
@@ -3643,6 +3762,10 @@ mod tests {
let received = rx.try_recv();
assert!(received.is_ok(), "expected outbound packet from tick()");
assert!(
router.pending_outbound.is_empty(),
"a successful fire-and-forget tick must not requeue the sent packet"
);
}
#[test]
+2
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
+394 -39
View File
@@ -62,9 +62,8 @@ use rns_runtime::link_manager::{
LinkManagerAccountingEvent, LinkManagerCommand, LinkResourceConclusion, LinkResourceDirection,
LinkResourceEvent,
};
use rns_transport::messages::{
AnnounceHandlerEvent, TransportMessage, TransportQuery, TransportQueryResponse,
};
use rns_runtime::reticulum::{AnnounceSubscription, AnnounceSubscriptionError, ReticulumHandle};
use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse};
use self::lxmd_pn::{
PnInboundRuntime, PnValidationJob, PnValidationOutcome, PnValidationToken, logical_resource_id,
@@ -870,6 +869,46 @@ fn direct_reusable_link_state(
}
}
async fn forward_backchannel_receipt(
mut runtime_rx: tokio::sync::oneshot::Receiver<
Result<
rns_runtime::link_manager::LinkPayloadSendReceipt,
rns_runtime::link_manager::LinkSendError,
>,
>,
mut owner_tx: tokio::sync::oneshot::Sender<
Result<BackchannelSendReceipt, BackchannelSendError>,
>,
abandon_tx: mpsc::Sender<BackchannelSendReceipt>,
) {
let result = tokio::select! {
biased;
result = &mut runtime_rx => Some(result),
_ = owner_tx.closed() => None,
_ = tokio::time::sleep(std::time::Duration::from_secs(10)) => None,
};
let Some(result) = result else {
// close preserves an already-published value and rejects future sends.
// The runtime cancels exact admission if its receipt publication fails.
runtime_rx.close();
if let Ok(Ok(receipt)) = runtime_rx.try_recv() {
let _ = abandon_tx
.send(backchannel_receipt_from_runtime(receipt))
.await;
}
let _ = owner_tx.send(Err(BackchannelSendError::TransportUnavailable));
return;
};
let result = match result {
Ok(Ok(receipt)) => Ok(backchannel_receipt_from_runtime(receipt)),
Ok(Err(error)) => Err(backchannel_error_from_runtime(error)),
Err(_) => Err(BackchannelSendError::TransportUnavailable),
};
if let Err(Ok(receipt)) = owner_tx.send(result) {
let _ = abandon_tx.send(receipt).await;
}
}
fn backchannel_receipt_from_runtime(
receipt: rns_runtime::link_manager::LinkPayloadSendReceipt,
) -> BackchannelSendReceipt {
@@ -902,6 +941,10 @@ fn backchannel_error_from_runtime(
rns_runtime::link_manager::LinkSendError::NoSessionKeys => {
BackchannelSendError::NoSessionKeys
}
err @ (rns_runtime::link_manager::LinkSendError::IdentityUnavailable
| rns_runtime::link_manager::LinkSendError::IdentificationUnavailable) => {
BackchannelSendError::Other(err.to_string())
}
rns_runtime::link_manager::LinkSendError::TransportUnavailable => {
BackchannelSendError::TransportUnavailable
}
@@ -1176,12 +1219,19 @@ struct LxmdRunner {
mpsc::UnboundedReceiver<rns_runtime::link_manager::DestinationDeliveryProof>,
opportunistic_in_flight: HashMap<[u8; 32], PendingOpportunisticDelivery>,
backchannel_command_rx: Option<mpsc::Receiver<BackchannelSendCommand>>,
backchannel_abandon_tx: mpsc::Sender<BackchannelSendReceipt>,
backchannel_abandon_rx: mpsc::Receiver<BackchannelSendReceipt>,
pending_backchannel_abandon: Option<BackchannelSendReceipt>,
backchannel_bridge_slots: Arc<tokio::sync::Semaphore>,
pending_backchannel_resource_cancellations:
VecDeque<lxmf_core::link_delivery::BackchannelResourceCancelRequest>,
last_delivery_failure: Option<String>,
propagation_sync: Option<lxmf_core::propagation_sync::PropagationSyncTask>,
propagation_client: Option<lxmf_core::propagation_client::PropagationClient>,
propagation_node: Option<Arc<Mutex<PropagationNode>>>,
propagation_admission: Option<Arc<Mutex<PnInboundRuntime>>>,
prop_link_command_tx: Option<mpsc::Sender<rns_runtime::link_manager::LinkManagerCommand>>,
endpoint_dispatch: Option<rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle>,
transport_tx: mpsc::Sender<TransportMessage>,
pending_runtime_transport: VecDeque<TransportMessage>,
required_announces: AnnounceMailbox,
@@ -1221,7 +1271,7 @@ struct LxmdRunner {
peer_sync_cursor: Option<[u8; 16]>,
/// Non-link inbound packets; still encrypted, need destination-level decrypt.
inbound_raw_rx: mpsc::Receiver<Vec<u8>>,
announce_rx: mpsc::Receiver<AnnounceHandlerEvent>,
announce_subscriptions: Vec<AnnounceSubscription>,
last_peer_announce: f64,
last_node_announce: f64,
last_propagation_check: f64,
@@ -1235,6 +1285,47 @@ struct LxmdRunner {
}
impl LxmdRunner {
async fn install_announce_subscriptions(
&mut self,
rns_handle: &ReticulumHandle,
) -> Result<(), AnnounceSubscriptionError> {
self.close_announce_subscriptions().await;
let mut subscriptions = Vec::with_capacity(2);
for aspect in [DELIVERY_APP_NAME, "lxmf.propagation"] {
match rns_handle
.subscribe_announces_with_capacity(Some(aspect.to_string()), true, 256)
.await
{
Ok(subscription) => subscriptions.push(subscription),
Err(error) => {
for subscription in &mut subscriptions {
let _ = subscription.close().await;
}
return Err(error);
}
}
}
self.announce_subscriptions = subscriptions;
Ok(())
}
async fn close_announce_subscriptions(&mut self) {
for subscription in &mut self.announce_subscriptions {
let dropped_events = subscription.dropped_events();
if dropped_events > 0 {
tracing::warn!(
dropped_events,
"lxmd announce subscription omitted events under backpressure"
);
}
if let Err(error) = subscription.close().await {
tracing::warn!(%error, "failed to close lxmd announce subscription");
}
}
self.announce_subscriptions.clear();
}
fn queue_router_message(&mut self, message: LxMessage, operation: &'static str) -> bool {
match self.router.try_send(message) {
Ok(()) => true,
@@ -1249,6 +1340,9 @@ impl LxmdRunner {
config: DaemonConfig,
config_dir: &Path,
transport_tx: mpsc::Sender<TransportMessage>,
endpoint_dispatch: Option<
rns_transport::link_endpoint_dispatch::LinkEndpointDispatchHandle,
>,
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
let paths = LxmdPaths::new(config_dir);
std::fs::create_dir_all(&paths.config_dir)?;
@@ -1339,6 +1433,7 @@ impl LxmdRunner {
// LinkManager handles link handshakes (ECDH), keepalive, identification,
// and resource transfers; it forwards plaintext application data here.
let (delivery_tx, delivery_rx) = mpsc::channel(256);
let (backchannel_abandon_tx, backchannel_abandon_rx) = mpsc::channel(256);
let (link_packet_tx, link_packet_rx) = mpsc::unbounded_channel::<(Vec<u8>, [u8; 16])>();
let (delivery_accounting_tx, delivery_accounting_rx) =
mpsc::unbounded_channel::<LinkManagerAccountingEvent>();
@@ -1390,6 +1485,9 @@ impl LxmdRunner {
DELIVERY_APP_NAME,
signing_key,
);
if let Some(handle) = &endpoint_dispatch {
link_mgr.set_link_endpoint_dispatch_handle(handle.clone());
}
link_mgr.set_link_packet_channel(link_packet_tx);
link_mgr.set_accounting_event_channel(delivery_accounting_tx);
link_mgr.set_resource_event_channel(delivery_resource_event_tx);
@@ -1528,6 +1626,9 @@ impl LxmdRunner {
"lxmf.propagation",
Some(prop_signing_key),
);
if let Some(handle) = &endpoint_dispatch {
prop_link_mgr.set_link_endpoint_dispatch_handle(handle.clone());
}
prop_link_mgr.set_link_packet_channel(prop_link_packet_tx);
prop_link_mgr.set_accounting_event_channel(prop_accounting_tx);
prop_link_mgr.set_resource_strategy(rns_runtime::prelude::ResourceStrategy::AcceptApp);
@@ -1684,6 +1785,9 @@ impl LxmdRunner {
CONTROL_APP_NAME,
Some(control_signing_key),
);
if let Some(handle) = &endpoint_dispatch {
control_link_mgr.set_link_endpoint_dispatch_handle(handle.clone());
}
let control_link_identities = control_link_mgr.link_identities_handle();
let stats_path_hash =
rns_crypto::sha::truncated_hash(lxmf_core::constants::STATS_GET_PATH.as_bytes());
@@ -1781,26 +1885,6 @@ impl LxmdRunner {
None
};
let (announce_tx, announce_rx) = mpsc::channel(256);
queue_required_transport(
&transport_tx,
TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(DELIVERY_APP_NAME.to_string()),
receive_path_responses: true,
callback_tx: announce_tx.clone(),
},
"delivery announce-handler registration",
)?;
queue_required_transport(
&transport_tx,
TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some("lxmf.propagation".to_string()),
receive_path_responses: true,
callback_tx: announce_tx,
},
"propagation announce-handler registration",
)?;
let messages_dir = paths.messages_dir.clone();
std::fs::create_dir_all(&messages_dir)?;
@@ -1830,12 +1914,18 @@ impl LxmdRunner {
destination_delivery_proof_rx,
opportunistic_in_flight: HashMap::new(),
backchannel_command_rx: None,
backchannel_abandon_tx,
backchannel_abandon_rx,
pending_backchannel_abandon: None,
backchannel_bridge_slots: Arc::new(tokio::sync::Semaphore::new(256)),
pending_backchannel_resource_cancellations: VecDeque::new(),
last_delivery_failure: None,
propagation_sync: None,
propagation_client: None,
propagation_node: None,
propagation_admission,
prop_link_command_tx,
endpoint_dispatch,
transport_tx: transport_tx.clone(),
pending_runtime_transport: VecDeque::new(),
required_announces,
@@ -1859,7 +1949,7 @@ impl LxmdRunner {
pending_peer_syncs: HashSet::new(),
peer_sync_cursor: None,
inbound_raw_rx,
announce_rx,
announce_subscriptions: Vec::new(),
last_peer_announce: 0.0,
last_node_announce: 0.0,
last_propagation_check: 0.0,
@@ -2371,12 +2461,77 @@ impl LxmdRunner {
}
fn drain_core_backchannel_send_commands(&mut self) {
while let Some(receipt) = self
.pending_backchannel_abandon
.take()
.or_else(|| self.backchannel_abandon_rx.try_recv().ok())
{
match receipt {
BackchannelSendReceipt::Packet {
link_id,
packet_hash,
} => {
if let Some(ld) = &mut self.link_delivery {
if !ld.abandon_backchannel_packet(link_id, packet_hash) {
self.pending_backchannel_abandon =
Some(BackchannelSendReceipt::Packet {
link_id,
packet_hash,
});
break;
}
}
}
BackchannelSendReceipt::Resource {
link_id,
resource_hash,
} => {
self.pending_backchannel_resource_cancellations.push_back(
lxmf_core::link_delivery::BackchannelResourceCancelRequest {
link_id,
resource_hash,
},
);
}
}
}
if let Some(ld) = &mut self.link_delivery {
self.pending_backchannel_resource_cancellations
.extend(ld.take_backchannel_resource_cancellations());
}
while let Some(request) = self.pending_backchannel_resource_cancellations.front() {
let command = LinkManagerCommand::CancelLinkResource {
link_id: request.link_id,
resource_id: request.resource_hash,
direction: LinkResourceDirection::Outbound,
result_tx: None,
};
match self.link_command_tx.try_send(command) {
Ok(()) => {
self.pending_backchannel_resource_cancellations.pop_front();
}
Err(mpsc::error::TrySendError::Full(_)) => break,
Err(mpsc::error::TrySendError::Closed(_)) => {
self.pending_backchannel_resource_cancellations.clear();
break;
}
}
}
let Some(rx) = self.backchannel_command_rx.as_mut() else {
return;
};
let command_tx = self.link_command_tx.clone();
while let Ok(command) = rx.try_recv() {
if command.result_tx.is_closed() {
continue;
}
let Ok(bridge_slot) = self.backchannel_bridge_slots.clone().try_acquire_owned() else {
let _ = command
.result_tx
.send(Err(BackchannelSendError::TransportUnavailable));
continue;
};
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
let link_id = command.link_id;
let link_command = rns_runtime::link_manager::LinkManagerCommand::SendLinkPayload {
@@ -2387,13 +2542,10 @@ impl LxmdRunner {
};
match command_tx.try_send(link_command) {
Ok(()) => {
let abandon_tx = self.backchannel_abandon_tx.clone();
tokio::spawn(async move {
let result = match result_rx.await {
Ok(Ok(receipt)) => Ok(backchannel_receipt_from_runtime(receipt)),
Ok(Err(err)) => Err(backchannel_error_from_runtime(err)),
Err(_) => Err(BackchannelSendError::TransportUnavailable),
};
let _ = command.result_tx.send(result);
let _bridge_slot = bridge_slot;
forward_backchannel_receipt(result_rx, command.result_tx, abandon_tx).await;
});
}
Err(err) => {
@@ -2825,6 +2977,7 @@ impl LxmdRunner {
self.handle_link_delivery_result(result);
}
}
self.drain_core_backchannel_send_commands();
self.drive_propagation_sync();
@@ -2998,7 +3151,13 @@ impl LxmdRunner {
let mut seen = Vec::new();
let delivery_name_hash = rns_identity::name_hash::name_hash(DELIVERY_APP_NAME);
let propagation_name_hash = rns_identity::name_hash::name_hash("lxmf.propagation");
while let Ok(event) = self.announce_rx.try_recv() {
let mut events = Vec::new();
for subscription in &mut self.announce_subscriptions {
while let Ok(event) = subscription.events().try_recv() {
events.push(event);
}
}
for event in events {
seen.push(event.destination_hash);
let dest_hex = hex::encode(event.destination_hash);
tracing::info!(
@@ -3304,6 +3463,68 @@ impl LxmdRunner {
fn handle_delivery_accounting_event(&mut self, event: LinkManagerAccountingEvent) {
match event {
LinkManagerAccountingEvent::OutboundPacketWait {
receipt,
started_at,
timeout,
awaiting_admission,
cancellation,
} => {
if let Some(ld) = &mut self.link_delivery {
ld.observe_backchannel_packet_wait(
receipt.link_id,
receipt.packet_hash,
started_at,
timeout,
awaiting_admission,
cancellation,
);
}
}
LinkManagerAccountingEvent::OutboundResourceWait {
link_id,
resource_id,
started_at,
timeout,
} => {
if let Some(ld) = &mut self.link_delivery {
ld.observe_backchannel_resource_wait(link_id, resource_id, started_at, timeout);
}
}
LinkManagerAccountingEvent::ResourceEvent(LinkResourceEvent::Concluded {
link_id,
resource_id,
direction: LinkResourceDirection::Outbound,
conclusion,
}) => {
let result = self.link_delivery.as_mut().and_then(|ld| match conclusion {
LinkResourceConclusion::Complete => {
ld.handle_backchannel_resource_proof(link_id, resource_id)
}
LinkResourceConclusion::Rejected => ld.handle_backchannel_resource_conclusion(
link_id,
resource_id,
lxmf_core::link_delivery::BackchannelResourceConclusion::Rejected,
"resource rejected",
),
LinkResourceConclusion::Failed(reason) => ld
.handle_backchannel_resource_conclusion(
link_id,
resource_id,
lxmf_core::link_delivery::BackchannelResourceConclusion::Failed,
reason,
),
LinkResourceConclusion::Cancelled => ld.handle_backchannel_resource_conclusion(
link_id,
resource_id,
lxmf_core::link_delivery::BackchannelResourceConclusion::Failed,
"resource cancelled",
),
});
if let Some(result) = result {
self.handle_link_delivery_result(result);
}
}
LinkManagerAccountingEvent::ResourceEvent(event) => {
if let Some(event) = delivery_resource_event_from_runtime(event) {
self.router.handle_inbound_resource_event(event);
@@ -4322,11 +4543,15 @@ impl LxmdRunner {
fn ensure_link_delivery(&mut self) {
if self.link_delivery.is_none() {
self.link_delivery = Some(lxmf_core::link_delivery::LinkDeliveryManager::new(
let mut delivery = lxmf_core::link_delivery::LinkDeliveryManager::new(
self.transport_tx.clone(),
Some(self.identity.get_public_key()),
self.identity.get_signing_key(),
));
);
if let Some(handle) = &self.endpoint_dispatch {
delivery.set_link_endpoint_dispatch_handle(handle.clone());
}
self.link_delivery = Some(delivery);
}
self.ensure_backchannel_sender();
}
@@ -4338,7 +4563,7 @@ impl LxmdRunner {
let (tx, rx) = mpsc::channel(256);
if let Some(ref mut ld) = self.link_delivery {
ld.set_backchannel_sender(tx);
ld.set_cancellation_aware_backchannel_sender(tx);
self.backchannel_command_rx = Some(rx);
}
}
@@ -4682,13 +4907,26 @@ pub(crate) async fn main() {
}
}
let mut runner = match LxmdRunner::new(daemon_config.clone(), &config_dir, transport_tx) {
let mut runner = match LxmdRunner::new(
daemon_config.clone(),
&config_dir,
transport_tx,
Some(rns_handle.link_endpoint_dispatch_handle()),
) {
Ok(r) => r,
Err(e) => {
tracing::error!("Failed to initialize LXMF daemon: {e}");
std::process::exit(1);
}
};
if let Err(error) = runner.install_announce_subscriptions(&rns_handle).await {
if shutdown.is_triggered() {
tracing::info!("Startup announce cancelled by shutdown");
return;
}
tracing::error!(%error, "failed to install lxmd announce subscriptions");
std::process::exit(1);
}
runner.apply_config();
@@ -5081,6 +5319,7 @@ pub(crate) async fn main() {
}
tracing::info!("LXMF Daemon shutting down");
runner.close_announce_subscriptions().await;
for task in std::mem::take(&mut runner.prop_store_write_tasks) {
if let Err(error) = task.await {
tracing::warn!(%error, "propagation store write task failed during shutdown");
@@ -5105,6 +5344,111 @@ pub(crate) async fn main() {
mod tests {
use super::*;
#[tokio::test]
async fn backchannel_accounting_retains_exact_windows_and_resource_cancellation() {
use rns_crypto::ed25519::Ed25519PrivateKey;
use std::time::{Duration, Instant};
let unique = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let temp = std::env::temp_dir().join(format!(
"lxmd-backchannel-accounting-{}-{unique}",
std::process::id()
));
let (tx, _rx) = mpsc::channel(64);
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx, None).unwrap();
runner.ensure_link_delivery();
let (send_tx, mut send_rx) = mpsc::channel(8);
runner
.link_delivery
.as_mut()
.unwrap()
.set_backchannel_sender(send_tx);
let link_id = [0x61; 16];
let dest = [0x62; 16];
let resource_hash = [0x63; 32];
let mut message = LxMessage::new(
dest,
[0x64; 16],
"accounting",
"bounded",
DeliveryMethod::Direct,
);
message.sign(&Ed25519PrivateKey::generate()).unwrap();
let hash = message.hash.unwrap();
let ld = runner.link_delivery.as_mut().unwrap();
ld.register_backchannel(dest, link_id);
ld.start_backchannel_delivery(message, dest).unwrap();
send_rx
.try_recv()
.unwrap()
.result_tx
.send(Ok(BackchannelSendReceipt::Resource {
link_id,
resource_hash,
}))
.unwrap();
assert!(ld.tick().is_empty());
let original = Instant::now() - Duration::from_secs(400);
runner.handle_delivery_accounting_event(LinkManagerAccountingEvent::OutboundResourceWait {
link_id,
resource_id: resource_hash,
started_at: original,
timeout: Duration::from_secs(800),
});
let ld = runner.link_delivery.as_mut().unwrap();
assert_eq!(
ld.message_timeout_window(hash),
Some((original, Duration::from_secs(980)))
);
assert!(ld.tick().is_empty());
assert!(ld.cancel_delivery_by_message_hash(hash));
let (command_tx, mut command_rx) = mpsc::channel(1);
command_tx
.try_send(LinkManagerCommand::CancelLinkResource {
link_id: [0; 16],
resource_id: [0; 32],
direction: LinkResourceDirection::Outbound,
result_tx: None,
})
.unwrap();
runner.link_command_tx = command_tx;
runner.drain_core_backchannel_send_commands();
assert_eq!(runner.pending_backchannel_resource_cancellations.len(), 1);
command_rx.try_recv().unwrap();
runner.drain_core_backchannel_send_commands();
assert!(
matches!(command_rx.try_recv(), Ok(LinkManagerCommand::CancelLinkResource {
link_id: observed_link, resource_id, direction: LinkResourceDirection::Outbound, ..
}) if observed_link == link_id && resource_id == resource_hash)
);
runner.drain_core_backchannel_send_commands();
assert!(runner.pending_backchannel_resource_cancellations.is_empty());
assert!(command_rx.try_recv().is_err());
// A late terminal is reconciled as already cancelled, not retried or
// published a second time by the daemon's second notification path.
runner.handle_delivery_accounting_event(LinkManagerAccountingEvent::ResourceEvent(
LinkResourceEvent::Concluded {
link_id,
resource_id: resource_hash,
direction: LinkResourceDirection::Outbound,
conclusion: LinkResourceConclusion::Rejected,
},
));
assert_eq!(runner.link_delivery.as_ref().unwrap().pending_count(), 0);
assert!(
runner
.link_delivery
.as_ref()
.unwrap()
.message_timeout_window(hash)
.is_none()
);
drop(runner);
let _ = std::fs::remove_dir_all(temp);
}
#[test]
fn propagation_download_auth_uses_live_allowed_identity_set() {
let allowed = [0x11; 16];
@@ -5417,6 +5761,17 @@ mod tests {
assert!(accepts_delivery_resource(1_000, default_limit));
assert!(!accepts_delivery_resource(1_001, default_limit));
let explicit_limit = rns_runtime::config::Config::parse(
"[lxmf]\ndelivery_transfer_max_accepted_size = 1000\n",
)
.map(|config| DaemonConfig::from_config(&config))
.unwrap()
.delivery_transfer_max_accepted_size;
assert_eq!(explicit_limit, 1000.0);
assert!(accepts_delivery_resource(4_114, explicit_limit));
assert!(accepts_delivery_resource(1_000_000, explicit_limit));
assert!(!accepts_delivery_resource(1_000_001, explicit_limit));
assert!(accepts_delivery_resource(380, 0.38));
assert!(!accepts_delivery_resource(381, 0.38));
@@ -5443,7 +5798,7 @@ mod tests {
enforce_stamps,
..Default::default()
};
let mut runner = LxmdRunner::new(config, &temp, tx).expect("runner");
let mut runner = LxmdRunner::new(config, &temp, tx, None).expect("runner");
let raw = runner.create_announce_packet().expect("delivery announce");
let (_, announce) = unpack_announce(&raw);
let (_, stamp_cost) = lxmf_core::handlers::parse_announce_app_data(
@@ -5688,7 +6043,7 @@ mod tests {
stamp_cost: Some(8),
..Default::default()
};
let mut runner = LxmdRunner::new(config, &temp, tx).expect("runner");
let mut runner = LxmdRunner::new(config, &temp, tx, None).expect("runner");
let dest = [0xAB; 16];
assert_ne!(dest, runner.lxmf_dest_hash);
@@ -5738,7 +6093,7 @@ mod tests {
std::process::id()
));
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx).expect("runner");
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx, None).expect("runner");
let deliveries = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&deliveries);
+3 -3
View File
@@ -227,9 +227,9 @@ impl Default for DaemonConfig {
enforce_stamps: false,
message_storage_limit: Some(500_000_000),
from_static_only: false,
// Current Python lxmd 1.1.0 deliberately narrows the standalone
// daemon default to 1 decimal KB. The reusable RouterConfig keeps
// its 1000 KB library default, matching Python LXMRouter.
// Current Python LXMF 1.1.0's standalone lxmd defaults
// direct-delivery Resource admission to 1 decimal KB when the
// setting is omitted. LXMRouter's library default is separate.
delivery_transfer_max_accepted_size: 1.0,
}
}
+126 -45
View File
@@ -10,8 +10,11 @@ use lxmf_core::propagation_node::PropagationNode;
use lxmf_core::router::LxmRouter;
use rmpv::Value;
use rns_identity::identity::Identity;
use rns_runtime::destination_resolver::{
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
};
use rns_runtime::link_client::{LinkClient, LinkClientError};
use rns_transport::messages::{AnnounceHandlerEvent, TransportMessage};
use rns_transport::messages::TransportMessage;
use tokio::sync::mpsc;
pub const CONTROL_APP_NAME: &str = "lxmf.propagation.control";
@@ -42,6 +45,7 @@ impl ControlCommandKind {
}
}
/// Query propagation control with a raw peer hash, or no payload for status.
pub async fn query_control(
transport_tx: tokio::sync::mpsc::Sender<rns_transport::messages::TransportMessage>,
identity: Identity,
@@ -56,62 +60,46 @@ pub async fn query_control(
target_identity_hash,
CONTROL_APP_NAME,
path,
payload,
encode_control_payload(payload),
0,
Duration::from_secs_f64(timeout_secs.max(0.0)),
)
.await
}
fn encode_control_payload(payload: Vec<u8>) -> Vec<u8> {
// LinkClient accepts an encoded MessagePack value. Raw hash bytes can
// themselves form a complete value (e.g. 0xaf followed by 15 bytes), so
// letting Link infer the type can truncate or reinterpret a peer address.
// Python sends a bytes object for sync/unpeer and None for status.
encode_value(&if payload.is_empty() {
Value::Nil
} else {
Value::Binary(payload)
})
}
pub async fn resolve_remote_identity_hash(
transport_tx: mpsc::Sender<TransportMessage>,
remote_destination_hash: [u8; 16],
timeout_secs: f64,
) -> Result<[u8; 16], LinkClientError> {
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
transport_tx
.send(TransportMessage::RegisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
receive_path_responses: true,
callback_tx: ann_tx,
})
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
let send_result = transport_tx
.send(TransportMessage::RequestPath {
destination_hash: remote_destination_hash,
})
.await;
if send_result.is_err() {
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
return Err(LinkClientError::TransportUnavailable);
}
let wait = async {
while let Some(event) = ann_rx.recv().await {
if event.destination_hash == remote_destination_hash {
if let Some(identity_hash) = event.identity_hash {
return Ok(identity_hash);
}
}
let recalled = resolve_destination_on_transport(
&transport_tx,
remote_destination_hash,
DestinationResolveOptions::new(Duration::from_secs_f64(timeout_secs.max(0.0))),
)
.await;
let recalled = recalled.map_err(|error| match error {
DestinationResolveError::Timeout => LinkClientError::Timeout("remote identity resolution"),
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
DestinationResolveError::UnexpectedResponse(operation) => {
LinkClientError::UnexpectedResponse(operation.to_string())
}
Err(LinkClientError::PubkeyNotDiscovered)
};
let result =
match tokio::time::timeout(Duration::from_secs_f64(timeout_secs.max(0.0)), wait).await {
Ok(result) => result,
Err(_) => Err(LinkClientError::Timeout("remote identity resolution")),
};
let _ = transport_tx.try_send(TransportMessage::DeregisterAnnounceHandler {
aspect_filter: Some(PROPAGATION_APP_NAME.to_string()),
});
result
})?;
Identity::from_public_key(&recalled.public_key)
.map(|identity| identity.hash)
.map_err(|error| LinkClientError::UnexpectedResponse(error.to_string()))
}
pub fn decode_control_response(response: &[u8]) -> ControlResponse {
@@ -869,6 +857,99 @@ fn encode_value(value: &Value) -> Vec<u8> {
mod tests {
use super::*;
#[test]
fn control_payload_preserves_every_peer_hash_prefix_as_binary() {
for prefix in 0..=u8::MAX {
let mut hash = vec![0x41; 16];
hash[0] = prefix;
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash),
"peer prefix {prefix:#04x} must not select a MessagePack type"
);
}
for hash in [
hex::decode("af55b3f0e0b336fdfdbe263c12a688e0").unwrap(),
[vec![0xc4, 14], vec![0x41; 14]].concat(),
[vec![0x9f], vec![0; 15]].concat(),
] {
assert_eq!(
decode_value(&encode_control_payload(hash.clone())),
Value::Binary(hash)
);
}
}
#[test]
fn empty_control_payload_matches_python_status_nil() {
assert_eq!(
decode_value(&encode_control_payload(Vec::new())),
Value::Nil
);
}
#[tokio::test]
async fn remote_identity_resolution_uses_recall_and_path_request_without_handlers() {
use rns_transport::messages::{
RecalledDestinationRpcEntry, TransportQuery, TransportQueryResponse,
};
let remote_destination_hash = [0x41; 16];
let remote_identity = Identity::new();
let public_key = remote_identity.get_public_key();
let expected_identity_hash = remote_identity.hash;
let (transport_tx, mut transport_rx) = mpsc::channel(8);
let responder = tokio::spawn(async move {
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("initial recall")
else {
panic!("expected initial recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(None))
.expect("return cache miss");
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::RequestPath { destination_hash })
if destination_hash == remote_destination_hash
));
let TransportMessage::Rpc { query, response_tx } =
transport_rx.recv().await.expect("post-request recall")
else {
panic!("expected post-request recall");
};
assert!(matches!(
query,
TransportQuery::RecallDestination { dest } if dest == remote_destination_hash
));
response_tx
.send(TransportQueryResponse::RecalledDestination(Some(
RecalledDestinationRpcEntry {
dest_hash: remote_destination_hash,
public_key,
app_data: None,
ratchet: None,
hops: 2,
timestamp: 1.0,
},
)))
.expect("return resolved identity");
assert!(transport_rx.try_recv().is_err());
});
let resolved = resolve_remote_identity_hash(transport_tx, remote_destination_hash, 1.0)
.await
.expect("resolve remote identity");
assert_eq!(resolved, expected_identity_hash);
responder.await.expect("transport responder");
}
fn decode_value(data: &[u8]) -> Value {
rmpv::decode::read_value(&mut &data[..]).unwrap()
}
+196
View File
@@ -0,0 +1,196 @@
#!/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()
# The project permits breaking core APIs in a minor release; caret ranges
# would silently admit the next incompatible minor line.
if not re.fullmatch(r"~\d+\.\d+\.\d+", requirement):
fail(f"unexpected rsReticulum compatibility requirement {requirement!r}")
return str(versions.pop()), requirement.removeprefix("~")
def check_workflow_actions() -> None:
workflows = ROOT / ".github/workflows"
for workflow_path in sorted([*workflows.glob("*.yml"), *workflows.glob("*.yaml")]):
workflow = workflow_path.read_text()
action_uses = re.findall(
r"^\s*(?:-\s+)?uses:\s+([^\s#]+)", workflow, re.MULTILINE
)
for action in action_uses:
if action.startswith("./"):
continue
if "@" not in action or not SHA_PATTERN.fullmatch(
action.rsplit("@", 1)[1]
):
fail(
f"workflow action is not pinned to a commit "
f"({workflow_path.name}): {action}"
)
def check_release_workflow(reticulum_version: str) -> str:
workflow = (ROOT / ".github/workflows/release.yml").read_text()
if not re.search(r"^\s*toolchain:\s*1\.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()
+354
View File
@@ -0,0 +1,354 @@
#!/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_snapshot_review(record: object) -> None:
if not isinstance(record, dict):
fail("snapshot review is missing")
required = {
"areas",
"canonicalPath",
"classification",
"publicApiDiff",
"semver",
"deprecations",
"wirePersistenceRuntimeImpact",
"platformEvidence",
}
if not required.issubset(record):
fail("snapshot review is incomplete")
if not isinstance(record.get("areas"), list) or not record["areas"]:
fail("snapshot review must name the affected API areas")
if not all(isinstance(area, str) and area for area in record["areas"]):
fail("snapshot review API areas must be non-empty strings")
diff = record.get("publicApiDiff")
if not isinstance(diff, dict) or set(diff) != {"added", "removed"}:
fail("snapshot review must classify added and removed API lines")
if not all(isinstance(diff[key], int) and diff[key] >= 0 for key in diff):
fail("snapshot review API counts must be non-negative integers")
if not isinstance(record.get("platformEvidence"), list) or not record["platformEvidence"]:
fail("snapshot review must name platform evidence")
for key in (
"canonicalPath",
"classification",
"semver",
"deprecations",
"wirePersistenceRuntimeImpact",
):
if not isinstance(record.get(key), str) or not record[key]:
fail(f"snapshot review 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")
validate_snapshot_review(snapshot_source.get("review"))
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/snapshots/"):
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")
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:
fail("--update requires --snapshot-source-commit")
head = run(["git", "rev-parse", "HEAD"]).strip()
if args.snapshot_source_commit != head:
fail("snapshot source must be the clean source commit at HEAD")
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 - {"api/stability.json"}:
fail("snapshot source has uncommitted changes outside api/stability.json")
snapshot_source = config.get("snapshotSource")
if not isinstance(snapshot_source, dict):
fail("snapshot source identity is missing")
snapshot_source["commit"] = args.snapshot_source_commit
snapshot_source["capturedOn"] = date.today().isoformat()
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()
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Reject removals from the reviewed 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 load_floor_ledger(commit: str) -> dict[str, object]:
for path in ("api/stability.json", "api-stability.json"):
result = subprocess.run(
["git", "show", f"{commit}:{path}"],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode == 0:
return json.loads(result.stdout)
fail(f"cannot read API ledger at compatibility floor {commit}")
def main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
)
if metadata.returncode != 0:
fail("snapshot metadata or review 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")
floor_ledger = load_floor_ledger(floor)
floor_snapshots = {
package["name"]: package["snapshot"] for package in floor_ledger["packages"]
}
total_added = 0
total_removed = 0
for package in ledger["packages"]:
path = package["snapshot"]
floor_path = floor_snapshots.get(package["name"])
if not isinstance(floor_path, str):
fail(f"{package['name']} is absent from the compatibility floor")
before = set(git_show(floor, floor_path).splitlines())
after = set((ROOT / path).read_text(encoding="utf-8").splitlines())
added = sorted(after - before)
removed = sorted(before - after)
total_added += len(added)
total_removed += len(removed)
print(f"{package['name']}: +{len(added)} -{len(removed)}")
if removed:
for line in removed:
print(f"- {line}", file=sys.stderr)
if total_removed:
fail(
f"{total_removed} public API lines were removed from the compatibility floor; "
"the current policy permits additions only"
)
review = ledger["snapshotSource"]["review"]
if review["publicApiDiff"] != {
"added": total_added,
"removed": total_removed,
}:
fail("snapshot review 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" / "snapshots" / "manifest-contract.json"
def fail(message: str) -> None:
print(f"api manifest contract: {message}", file=sys.stderr)
raise SystemExit(1)
def metadata(manifest_path: str) -> dict[str, object]:
result = subprocess.run(
[
"cargo",
"metadata",
"--format-version",
"1",
"--no-deps",
"--manifest-path",
manifest_path,
],
cwd=ROOT,
capture_output=True,
text=True,
)
if result.returncode != 0:
if result.stderr:
print(result.stderr, file=sys.stderr, end="")
fail(f"cargo metadata failed for {manifest_path}")
return json.loads(result.stdout)
def dependency_contract(dependency: dict[str, object]) -> dict[str, object]:
source = dependency.get("source")
return {
"name": dependency["name"],
"rename": dependency.get("rename"),
"kind": dependency.get("kind"),
"target": dependency.get("target"),
"requirement": dependency["req"],
"optional": dependency["optional"],
"defaultFeatures": dependency["uses_default_features"],
"features": sorted(dependency["features"]),
"sourceKind": "registry" if source else "path",
}
def package_contract(package: dict[str, object]) -> dict[str, object]:
targets = []
for target in package["targets"]:
if "lib" not in target["kind"]:
continue
targets.append(
{
"name": target["name"],
"kind": sorted(target["kind"]),
"crateTypes": sorted(target["crate_types"]),
"requiredFeatures": sorted(target.get("required-features", [])),
}
)
dependencies = [
dependency_contract(dependency)
for dependency in package["dependencies"]
if dependency.get("kind") != "dev"
]
dependencies.sort(
key=lambda item: (
str(item["kind"]),
str(item["target"]),
str(item["rename"]),
str(item["name"]),
)
)
return {
"name": package["name"],
"version": package["version"],
"rustVersion": package.get("rust_version"),
"edition": package["edition"],
"features": {
name: sorted(values)
for name, values in sorted(package["features"].items())
},
"targets": sorted(targets, key=lambda item: str(item["name"])),
"dependencies": dependencies,
}
def render_contract() -> str:
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
manifests = sorted({entry["manifestPath"] for entry in ledger["packages"]})
recorded_names = {entry["name"] for entry in ledger["packages"]}
packages: list[dict[str, object]] = []
for manifest in manifests:
for package in metadata(manifest)["packages"]:
if package["name"] in recorded_names:
packages.append(package_contract(package))
actual_names = {entry["name"] for entry in packages}
if actual_names != recorded_names:
fail(
f"package inventory differs: expected={sorted(recorded_names)}, "
f"actual={sorted(actual_names)}"
)
contract = {
"schemaVersion": 1,
"scope": "library Cargo manifests, public features, targets, and non-dev dependencies",
"packages": sorted(packages, key=lambda item: str(item["name"])),
}
return json.dumps(contract, indent=2) + "\n"
def main() -> None:
parser = argparse.ArgumentParser()
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()