mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
799e946ac9 | ||
|
|
6a425e8d5a | ||
|
|
032c3fd6d3 | ||
|
|
1ff0134979 | ||
|
|
1a0a74ad06 | ||
|
|
5275fbb402 | ||
|
|
0f8731bb5b | ||
|
|
6bbac52ea0 | ||
|
|
cac8151fd8 | ||
|
|
f64b4d22d9 | ||
|
|
5edb8f22f5 | ||
|
|
d4183434fc | ||
|
|
3ce9909f78 | ||
|
|
56c7a6e5d8 | ||
|
|
49aa33db1b | ||
|
|
bdbb6e9f63 | ||
|
|
8be3725a35 | ||
|
|
306eaa8a18 | ||
|
|
6abe1f3d4a | ||
|
|
92b91d6ba3 | ||
|
|
25c69c6f37 | ||
|
|
0279d2475a | ||
|
|
a7515f3f5a | ||
|
|
61f9573bc1 | ||
|
|
c64f0d238a | ||
|
|
3e56135fd8 | ||
|
|
70fe70fbbe | ||
|
|
9122eba38c | ||
|
|
23045c6a0f | ||
|
|
f3518ff7c1 | ||
|
|
e209c8789c | ||
|
|
edc3964823 | ||
|
|
a90f7e1ec7 | ||
|
|
ca729453e0 | ||
|
|
62e144ed27 | ||
|
|
9bc7ee5ff9 | ||
|
|
bd3c1d61ba | ||
|
|
1af490682f | ||
|
|
f6523fd5c5 | ||
|
|
555bb33fdf | ||
|
|
9f65990536 | ||
|
|
8f1d650614 | ||
|
|
67b60362aa | ||
|
|
9a18435b75 | ||
|
|
795058e5bf | ||
|
|
c0fa43664b | ||
|
|
3b3eb29c16 | ||
|
|
6f2a6e8759 | ||
|
|
7ffefa5b8c | ||
|
|
5b6b5eb951 | ||
|
|
8fac96aed8 | ||
|
|
199eeb43cb | ||
|
|
d3c28b1247 | ||
|
|
1d27e8140b | ||
|
|
6705e9804f | ||
|
|
ef4b54b0a5 | ||
|
|
340291f234 | ||
|
|
45bbe47506 | ||
|
|
041cfbed91 | ||
|
|
8b7e20d5bf | ||
|
|
61f625e6ed | ||
|
|
b4c0358beb | ||
|
|
02e1b3f090 | ||
|
|
a1639cc065 | ||
|
|
e0889f7188 | ||
|
|
dc6bc4ee82 | ||
|
|
4a924ce281 | ||
|
|
ab53670f98 | ||
|
|
31472d9251 | ||
|
|
51763a97dc | ||
|
|
cfb7253f99 | ||
|
|
c9b210a52b | ||
|
|
47dbbf1feb | ||
|
|
b927f26ca6 | ||
|
|
092cf5ac30 | ||
|
|
ccf2f11419 | ||
|
|
d9a1024a16 | ||
|
|
bd8c2d8264 | ||
|
|
b3bcd2b886 | ||
|
|
31c5269695 | ||
|
|
9300253cee | ||
|
|
0aeb4f02c9 | ||
|
|
f66047e2a2 | ||
|
|
3c527bd5cf | ||
|
|
2252b83470 | ||
|
|
1d38688b8f | ||
|
|
0049231139 | ||
|
|
d1b5659169 | ||
|
|
2fd604b4aa | ||
|
|
a9d26472d0 | ||
|
|
e43fefbc54 | ||
|
|
e19944f6c1 | ||
|
|
921eac40c2 | ||
|
|
f7ae0274c3 | ||
|
|
fbc2f1938b |
No files matched your search
+46
-11
@@ -10,6 +10,34 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
api-compat:
|
||||
name: Public API baseline
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: nightly-2026-08-01
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
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
|
||||
- name: Check manifest and feature contract
|
||||
run: python3 tools/check-api-manifest.py
|
||||
- name: Check additions-only compatibility floor
|
||||
run: python3 tools/check-api-compatibility.py
|
||||
- name: Check canonical and legacy external consumer
|
||||
run: |
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
|
||||
|
||||
test:
|
||||
name: Test (${{ matrix.os }})
|
||||
timeout-minutes: 30
|
||||
@@ -19,9 +47,11 @@ jobs:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
@@ -31,8 +61,7 @@ jobs:
|
||||
run: cargo test --workspace --locked
|
||||
- name: Build application examples
|
||||
run: cargo build -p rns-runtime --examples --locked
|
||||
- name: Test BLE interface features (Linux/macOS)
|
||||
if: runner.os != 'Windows'
|
||||
- name: Test BLE interface features
|
||||
run: cargo test -p rns-interface --features ble --locked
|
||||
|
||||
lint:
|
||||
@@ -40,12 +69,17 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy, rustfmt
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Check source-release contract
|
||||
run: python3 scripts/ci/check_source_release_contract.py
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
- name: Check public API documentation
|
||||
@@ -55,15 +89,16 @@ jobs:
|
||||
- run: cargo check --workspace --no-default-features --locked
|
||||
|
||||
msrv:
|
||||
name: Rust 1.85 MSRV
|
||||
name: Rust 1.89 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@1.85.0
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps
|
||||
|
||||
@@ -7,20 +7,55 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: "Release tag to create or update"
|
||||
description: "Version tag (also used for untagged qualification)"
|
||||
required: true
|
||||
qualify_only:
|
||||
description: "Build and verify archives without publishing or creating a tag"
|
||||
type: boolean
|
||||
default: true
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
env:
|
||||
SOURCE_REF: ${{ github.sha }}
|
||||
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
|
||||
PACKAGE_ROOT: rsReticulum
|
||||
RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Verify release source
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
- shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
QUALIFY_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.qualify_only }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git rev-parse HEAD)" = "${SOURCE_REF}"
|
||||
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SOURCE_REF}&event=push&per_page=100" \
|
||||
--jq '.workflow_runs | any(.head_sha == env.SOURCE_REF and .conclusion == "success")' | grep -qx true
|
||||
if [[ "${QUALIFY_ONLY}" == "true" ]]; then
|
||||
python3 scripts/ci/check_source_release_contract.py --candidate-tag "${RELEASE_TAG}"
|
||||
else
|
||||
python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.artifact_suffix }}
|
||||
needs: verify
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -39,22 +74,29 @@ jobs:
|
||||
env:
|
||||
ARCHIVE_NAME: rsReticulum-${{ 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 }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
- name: Build release binaries
|
||||
run: cargo build -p rns-tools --release --bins
|
||||
run: cargo build -p rns-tools --release --bins --locked
|
||||
- name: Stage archive contents
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for bin in ${RETICULUM_BINS}; do
|
||||
suffix=""
|
||||
if [[ "${RUNNER_OS}" == "Windows" ]]; then suffix=".exe"; fi
|
||||
"target/release/${bin}${suffix}" --version
|
||||
done
|
||||
mkdir -p "dist/${PACKAGE_ROOT}/bin"
|
||||
for bin in ${RETICULUM_BINS}; do
|
||||
if [[ "${RUNNER_OS}" == "Windows" ]]; then
|
||||
@@ -63,7 +105,10 @@ jobs:
|
||||
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
|
||||
fi
|
||||
done
|
||||
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
|
||||
# Read blobs directly so Windows checkout line endings cannot alter the package.
|
||||
for doc in README.md LICENSE CHANGELOG.md; do
|
||||
git show "HEAD:${doc}" > "dist/${PACKAGE_ROOT}/${doc}"
|
||||
done
|
||||
- name: Create tar archive
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
@@ -72,7 +117,7 @@ jobs:
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
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: |
|
||||
@@ -80,22 +125,46 @@ jobs:
|
||||
*.zip
|
||||
if-no-files-found: error
|
||||
|
||||
package:
|
||||
name: Verify release archives
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
with:
|
||||
pattern: rsReticulum-*
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Verify archive inventory and generate checksums
|
||||
run: python3 scripts/ci/check_release_archives.py --tag "${RELEASE_TAG}" --directory release-assets
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: verified-release-assets
|
||||
path: release-assets/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
name: Publish GitHub release
|
||||
needs: build
|
||||
if: github.event_name == 'push' || !inputs.qualify_only
|
||||
needs: package
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v7
|
||||
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
with:
|
||||
name: verified-release-assets
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Generate checksums
|
||||
working-directory: release-assets
|
||||
run: sha256sum * > SHA256SUMS
|
||||
- uses: softprops/action-gh-release@v3
|
||||
- uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
tag_name: ${{ env.RELEASE_TAG }}
|
||||
name: ${{ env.RELEASE_TAG }}
|
||||
body: ""
|
||||
generate_release_notes: false
|
||||
append_body: false
|
||||
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
|
||||
files: release-assets/*
|
||||
@@ -7,3 +7,6 @@ __pycache__/
|
||||
/rust_artifacts/
|
||||
proptest-regressions/
|
||||
/tools/*
|
||||
!/tools/check-api-manifest.py
|
||||
!/tools/check-api-compatibility.py
|
||||
/api/fixtures/target/
|
||||
@@ -2,6 +2,64 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.3.0 - 2026-10-12
|
||||
|
||||
### Added
|
||||
|
||||
- Added Link bind-readiness polling so applications can start sending as soon as the transport is ready.
|
||||
|
||||
### Fixed and improved
|
||||
|
||||
- Represent unknown discovery latitude, longitude, and height independently as `None` instead of zero, accept Python nil coordinates, and preserve presence through configuration, storage, and `rnstatus-rs`.
|
||||
- Register and own the interface-discovery destination, advance publication intervals only after driver admission, and preserve pending announcements across bounded backpressure and reconnect.
|
||||
- Keep learned mesh announcements out of ordinary RNode control/data backlogs until the final writer can send them, while preserving same-radio relay and announce pacing.
|
||||
- Retain refused local announcements and attached path answers under bounded ownership tied to the exact interface generation.
|
||||
- Preserve multiple recursive-discovery requesters, slow-radio deadlines, interface replacement safety, and hidden-peer same-radio responses without letting one cancellation affect another requester.
|
||||
- Updated btleplug to 0.13.4, including upstream Windows discovery and reconnect fixes. Windows can try an explicitly configured RNode MAC or an eligible remembered BLE Peer absent from scan results, with bounded GATT setup, existing backoff, and signed peer identity checks.
|
||||
- Installed desktop BLE notification receivers before subscribing and limited packet fragments to the negotiated ATT payload.
|
||||
- Improved Bluetooth Peer packet sizing and flow control, including Apple write handling and queued sends.
|
||||
- Fixed a remotely triggerable Link panic when a peer reported an infinite, NaN, negative, or oversized RTT. Peer RTTs follow Python's handling and saturate at the 720-second stale window; initiators ignore LRRTT as Python does.
|
||||
- Require the corrected Windows socket backend so spawned helper processes cannot keep network listeners alive after the owning runtime shuts down.
|
||||
- Match Python RNS 1.4.2 Channel receive-window admission by dropping sequence numbers more than 48 slots ahead until a retry falls inside the window.
|
||||
- Report the bundled `rnsh` compatibility level as 0.3.0 and the `rnsd-rs` interactive compatibility level as RNS 1.4.2.
|
||||
|
||||
### Build and compatibility
|
||||
|
||||
- Discovery coordinates now use `Option<f64>`, and recursive discovery exposes detached observations and exact requester cancellation instead of public mutable state. Both source-breaking changes are covered by the [1.3 migration guide](api/migrations/1.3.md).
|
||||
- Project minor versions may include breaking APIs. Select `~1.3.0` or an exact reviewed source revision when adopting this release line.
|
||||
- Raised the full Rust workspace minimum compiler to Rust 1.89. Apple native BLE bindings declare their required features explicitly; Android consumers must use btleplug's matching 0.13.4 Java bridge and JNI 0.22 initialization.
|
||||
- Promote exact Python RNS 1.4.2 to the complete release baseline, including live interoperability, source oracles, utility vectors, and corpus provenance. RNS 1.5.0 remains deferred.
|
||||
|
||||
## 1.2.0 - 2026-08-17
|
||||
|
||||
- Designated the existing `rns_runtime::prelude` and compiled examples as the
|
||||
canonical application spine while retaining every module-qualified path,
|
||||
and added external-consumer, manifest/feature, and additions-only API
|
||||
compatibility gates without changing runtime behavior or public signatures.
|
||||
- Classified every library package and added pinned, CI-enforced public API
|
||||
snapshots so compatibility drift is reviewed before any boundary change;
|
||||
no visibility or signature changed in this baseline.
|
||||
- Made source releases reproducible from an existing immutable component tag:
|
||||
packages are non-publishable by default, release builds use the committed
|
||||
lockfile and Rust 1.87.0, actions are commit-pinned, and CI verifies the
|
||||
manifest, changelog, tag, and checkout contract.
|
||||
- Isolate exact announce subscriptions from legacy aspect-wide deregistration,
|
||||
and resolve finite destination identities through validated recall plus
|
||||
deadline-bounded path discovery instead of temporary announce handlers.
|
||||
- Distinguished the Reticulum 1.3.8 compatibility-floor corpus from the
|
||||
current 1.4.2 behavior reference instead of presenting the old oracle as the
|
||||
newest upstream target.
|
||||
- Enforce role-specific Link packet proofs: initiators sign with the transient
|
||||
LINKREQUEST key, responders sign with the destination identity, and external
|
||||
identity backends no longer fall back to an unrelated key.
|
||||
- Ignore unauthenticated invalid LRPROOF candidates without closing a pending
|
||||
initiator, allowing the authentic proof to win an interface race.
|
||||
- Bind every locally owned established Link endpoint to its validated
|
||||
interface and role, with fail-closed routing, bounded ordered control egress,
|
||||
terminal interface-loss notification, and bounded best-effort realtime
|
||||
egress. Typed send rejection closes only the exact owner, while final
|
||||
LINKCLOSE and temporary-destination cleanup drain atomically in order.
|
||||
Initial LINKREQUEST discovery remains path-routed or broadcast.
|
||||
- Forward authenticated non-Link packet delivery proofs from `LinkManager` to
|
||||
owning applications through a lossless completion channel.
|
||||
- Retain and retry destination announcements, including path responses, when
|
||||
@@ -11,6 +69,8 @@
|
||||
discovery.
|
||||
- Keep completed `rncp` Links alive for Python's receiver-side Resource
|
||||
conclusion callback before sending the authenticated teardown.
|
||||
- This source line includes application and runtime API evolution since 1.1.0;
|
||||
downstream integrations should qualify against the 1.2 dependency line.
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
|
||||
Generated
+283
-219
File diff suppressed because it is too large.
Load diff
+11
-11
@@ -14,10 +14,10 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.1.0"
|
||||
version = "1.3.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
rust-version = "1.89"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Crypto
|
||||
@@ -80,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.1.0", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.1.0", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.1.0" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.1.0" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.1.0" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.1.0" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.1.0" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.1.0" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.1.0" }
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "~1.3.0", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "~1.3.0", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "~1.3.0" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "~1.3.0" }
|
||||
rns-link = { path = "crates/rns-link", version = "~1.3.0" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "~1.3.0" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "~1.3.0" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "~1.3.0" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.3.0" }
|
||||
@@ -6,8 +6,8 @@
|
||||
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](#feature-status)
|
||||
|
||||
[Reticulum Manual](https://reticulum.network/manual/) |
|
||||
@@ -29,6 +29,7 @@ rsReticulum can live beside other Reticulum tools on `PATH` without worry.
|
||||
## Contents
|
||||
|
||||
- [Build It](#build-it)
|
||||
- [Rust API](api/README.md)
|
||||
- [Tool Usage](#tool-usage)
|
||||
- [Configuration](#configuration)
|
||||
- [Interface Support](#interface-support)
|
||||
@@ -50,7 +51,7 @@ Build the tools:
|
||||
|
||||
```bash
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Linux, Raspberry Pi, and VPS Hosts
|
||||
@@ -80,7 +81,7 @@ sudo pacman -S --needed base-devel pkgconf
|
||||
|
||||
```bash
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Windows
|
||||
@@ -92,7 +93,7 @@ Build from PowerShell:
|
||||
|
||||
```powershell
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
After the build, use the commands below with `./target/release/<tool>` on
|
||||
@@ -150,7 +151,7 @@ intentional.
|
||||
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
|
||||
dump/backup, and trusted-key storage.
|
||||
|
||||
`rnid-rs` tracks the Reticulum 1.3.8 identity utility surface for normal
|
||||
`rnid-rs` tracks the Reticulum 1.4.2 identity utility surface for normal
|
||||
software identities: public/private import and export, destination hashing,
|
||||
`.pub` public identity files, and signed `.rsg` signature files. The
|
||||
hardware-backed `rnid-rs hw` path is a Rust extension behind the `hardware`
|
||||
@@ -174,7 +175,7 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -X -w mgmt.rid
|
||||
rnid-rs -m <public_identity_data> -w peer.pub
|
||||
rnid-rs -M <private_identity_data> -X -w restored_identity
|
||||
|
||||
# Sign and validate. New signatures are Reticulum 1.3.8 .rsg envelopes.
|
||||
# Sign and validate. New signatures are Reticulum 1.4.2-compatible .rsg envelopes.
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
|
||||
rnid-rs -V message.txt.rsg
|
||||
rnid-rs -i <signer_hash> -N -V message.txt.rsg
|
||||
@@ -186,7 +187,7 @@ rnid-rs -i ~/.rsReticulum/identities/mgmt -d message.txt.rfe
|
||||
|
||||
Use `--raw -s <file>` only when a workflow intentionally needs the legacy raw
|
||||
64-byte signature form. Normal `rnid-rs -s <file>` produces a `.rsg` file that
|
||||
embeds the signer metadata needed for 1.3.8 validation.
|
||||
embeds the signer metadata needed for current and retained compatibility.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -255,15 +256,32 @@ instance_control_port = 37433
|
||||
| Weave | Partial: interface driver implemented, not yet config-wired in the runtime. |
|
||||
| Bluetooth Classic RFCOMM | Not implemented. |
|
||||
|
||||
## Established Link Routing
|
||||
|
||||
An initial Link Request uses normal Reticulum path discovery and may be
|
||||
broadcast when no path is known. Once the responder accepts that request and
|
||||
the initiator validates its proof, each local Link endpoint is bound to the
|
||||
exact interface and role selected by the handshake. Later Link packets,
|
||||
Channels, Resources, proofs, keepalives, and teardown never fall back to a
|
||||
different path or interface; loss of the selected interface closes that Link.
|
||||
|
||||
Reliable Link control uses a bounded ordered queue, while realtime media has a
|
||||
separate bounded best-effort path that cannot overtake retained control
|
||||
traffic. Initiator packet proofs use the temporary signing key advertised in
|
||||
the Link Request, and responder packet proofs use the accepting destination
|
||||
identity.
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
Most daemon and utility flows are implemented for the public `*-rs` tools:
|
||||
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
|
||||
`rnsh-rs`, and `rnodeconf-rs`.
|
||||
|
||||
The current compatibility target is Reticulum 1.3.8 where the matching Rust
|
||||
surface is implemented and tested. `rnid-rs` has explicit 1.3.8 coverage for
|
||||
the normal identity utility flow.
|
||||
The release baseline is Reticulum 1.4.2. The complete byte-exact corpus,
|
||||
utility vectors, source-truth oracles, and live Python interoperability matrix
|
||||
are pinned to its exact source commit. Historical 1.3.8 audits and fixtures
|
||||
retain their original provenance as backward-compatibility evidence. RNS 1.5.0
|
||||
is intentionally deferred and is not a current support claim.
|
||||
|
||||
Known gaps and intentional limits:
|
||||
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
# Rust API
|
||||
|
||||
Application code should begin with `rns_runtime::prelude`. It collects the
|
||||
runtime handle and the commonly used identity, destination, packet, Link,
|
||||
request, Channel, Resource, interface, and shutdown types without wrapping or
|
||||
replacing them. Existing module-qualified imports remain supported.
|
||||
|
||||
The examples in `crates/rns-runtime/examples/` are compiled as part of CI and
|
||||
show complete flows for runtime startup, Destinations, announces, receipts,
|
||||
Links, requests, Channels, Buffer streams, Resources, and RNode observation.
|
||||
|
||||
```rust
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), ReticulumError> {
|
||||
let runtime = init(
|
||||
None,
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let identity = Identity::new();
|
||||
// Use `runtime` and `identity` to create application Destinations.
|
||||
|
||||
runtime.shutdown_and_wait().await;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Finite destination discovery uses `resolve_destination_on_transport` with one
|
||||
deadline and validated identity recall. Long-lived announce observation uses
|
||||
`ReticulumHandle::subscribe_announces`; the returned `AnnounceSubscription`
|
||||
owns exactly one registration. Finite lookups do not install or remove
|
||||
announce handlers.
|
||||
|
||||
## Explicit shared-instance ownership
|
||||
|
||||
Applications that require authenticated shared control can opt into
|
||||
`reticulum::init_with_policy` and `shared_instance::InstancePolicy`:
|
||||
|
||||
- `Configured` retains the normal config-driven automatic owner/client behavior.
|
||||
- `Standalone` owns local interfaces without exposing shared IPC.
|
||||
- `SharedOwner` binds both configured shared endpoints or fails; it never joins
|
||||
another owner. `SharedOwnerAt(endpoint)` selects them in memory without
|
||||
rewriting the configuration file.
|
||||
- `SharedClient(credentials)` requires the selected packet endpoint and
|
||||
authenticated interface-status RPC before becoming ready. It reauthenticates
|
||||
on reconnect and never falls back to local interfaces.
|
||||
|
||||
`SharedInstanceEndpoint::Tcp` is loopback-only. Explicit Unix endpoints use
|
||||
Linux/Android abstract instance names. Keys are opaque HMAC bytes, supplied via
|
||||
`SharedInstanceCredentials::new`; its debug representation redacts the key.
|
||||
`credentials.test().await` checks availability without starting a runtime.
|
||||
|
||||
Observe reconnect/authentication state through `shared_instance_state()` and
|
||||
typed control failures through `query_control_result()`. Client runtimes reject
|
||||
dynamic local interface spawns. Non-fatal configured-interface startup failures
|
||||
are available through `startup_interface_failures()`; other interfaces can
|
||||
remain usable.
|
||||
|
||||
Upstream packet IPC is unauthenticated: successful RPC authenticates the control
|
||||
endpoint, not the identity of the packet socket. Selecting a trustworthy matching
|
||||
pair remains the application's responsibility. These policies do not move
|
||||
AutoInterface's interoperable UDP ports or alter Reticulum wire formats.
|
||||
|
||||
## Stability
|
||||
|
||||
The 1.3 line changes the six discovery coordinate fields to `Option<f64>` so
|
||||
unknown values remain distinct from real zero. It also replaces publicly mutable
|
||||
recursive discovery state with detached observations and exact requester
|
||||
cancellation. See the [1.3 migration guide](migrations/1.3.md) for both changes
|
||||
and their source, wire, and storage behavior. Normal runtime lookup/recovery
|
||||
APIs remain unchanged. Project minor releases can include breaking API changes;
|
||||
select an explicit compatible dependency line or reviewed immutable source pin.
|
||||
|
||||
Applications that own retry policy can obtain
|
||||
`ReticulumHandle::path_recovery_handle()` (also available from the application
|
||||
prelude). `try_recover(destination, Some(failed_link_id))` requests an atomic
|
||||
comparison with the route actually used by that locally originated Link. Only
|
||||
the unchanged route can be invalidated; fresh routes on the same interface are
|
||||
not suppressed. `None` requests bounded discovery without route invalidation.
|
||||
The 64-operation admission queue reports backpressure; callers retain ownership
|
||||
and bound their reply wait. Discovery is coalesced per destination, and the
|
||||
result is not proof of radio transmission or delivery. Old or unobserved Link
|
||||
attempts cannot delete routes. Shared clients only affect their own local
|
||||
transport state and use normal packet IPC for discovery.
|
||||
|
||||
`try_recover_packet(destination, packet_hash)` provides the same comparison for
|
||||
an atomically tracked local `SendPacket` attempt. Packet and Link ownership are
|
||||
separate; failures cannot consume another kind of attempt. Packet receipt
|
||||
windows can use `rns_wire::receipt::receipt_timeout_for_route`, also used by the
|
||||
runtime's automatic packet receipt policy.
|
||||
|
||||
`try_invalidate_packet(destination, packet_hash)` and
|
||||
`try_invalidate_link(destination, link_id)` perform only the exact
|
||||
failed-attempt route comparison and invalidation, without starting a new path
|
||||
request. A shared-client application can use this result to sequence its own
|
||||
authenticated owner recovery before ordinary discovery. This does not make
|
||||
legacy Python's destination-only owner reset an atomic route comparison or
|
||||
cancel other callers' pre-existing discovery.
|
||||
|
||||
### Established-Link delivery clocks
|
||||
|
||||
Advanced Link owners can obtain `ReticulumHandle::link_endpoint_dispatch_handle()`.
|
||||
Its opt-in bind receipt publishes an opaque token for one exact endpoint
|
||||
generation. `token.try_send(request, deadline)` retains the ordinary packet in
|
||||
the existing ordered endpoint FIFO until driver/local-peer admission, local
|
||||
expiry, cancellation, or an exact terminal failure. The deadline includes
|
||||
mailbox wait and is limited to 120 seconds. `Sent` contains the original local
|
||||
dispatch time and packet hash; it is not physical transmission or delivery.
|
||||
Dropping an unread bind receipt retires only its unpublished binding; published
|
||||
bindings still require the normal explicit cleanup.
|
||||
|
||||
`LinkEndpointDispatchBindReceipt::poll_ready` registers a task waker without
|
||||
publishing the binding. It retains a ready result until `try_recv` or awaiting
|
||||
consumes it; cancellation between readiness and consumption still retires the
|
||||
unpublished endpoint. This supports event-driven delivery owners without
|
||||
changing existing periodic consumers or proof timing.
|
||||
|
||||
`try_send_cancellable` additionally returns an exact cancellation capability.
|
||||
It requests removal while the packet is still awaiting local admission; it
|
||||
cannot recall bytes already admitted to a driver or affect another binding.
|
||||
The actor's final pre-admission check is the concurrent cancellation boundary.
|
||||
|
||||
`LinkManager::set_link_endpoint_dispatch_handle` enables these observations for
|
||||
ordinary packet sends. Legacy mailbox `Queued` still means only FIFO acceptance.
|
||||
`Link::packet_proof_timeout()` provides the measured-RTT proof budget, distinct
|
||||
from local queue residence. The accounting stream's outbound wait events retain
|
||||
the owner's original start time and finite timeout; delayed consumers must not
|
||||
restart those clocks. `OutboundTransfer::timeout_window()` similarly describes
|
||||
the current bounded Resource phase. Only genuine protocol progress renews it.
|
||||
|
||||
The application prelude is the recommended integration path, but the workspace
|
||||
is not yet a blanket stability promise for every public Rust item.
|
||||
|
||||
- `rns-identity`, `rns-link`, `rns-protocol`, and `rns-interface` are candidate
|
||||
stable.
|
||||
- `rns-crypto`, `rns-wire`, and `rns-transport` are provisional low-level
|
||||
packages.
|
||||
- `rns-runtime` is provisional because it contains both the application
|
||||
prelude and lower-level actor, RPC, manager, and command APIs.
|
||||
- `rns-ratkey` is experimental, and the `rns-tools` library target supports the
|
||||
repository's binaries rather than a public library integration.
|
||||
|
||||
Low-level actor, mailbox, RPC, transport-table, concrete-driver, and Link
|
||||
endpoint ownership APIs remain available for compatibility. They should not be
|
||||
treated as stable merely because they are publicly reachable.
|
||||
|
||||
## Compatibility checks
|
||||
|
||||
The `api/` directory contains the evidence used by CI:
|
||||
|
||||
- `stability.json` records package tiers, compatibility baselines, and snapshot
|
||||
hashes;
|
||||
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
|
||||
manifest, feature, dependency, target, and MSRV contract; and
|
||||
- `fixtures/` compiles recommended and retained import paths as an external
|
||||
consumer.
|
||||
|
||||
These checks catch accidental changes, but they do not replace platform builds,
|
||||
protocol interoperability tests, or manual review. In particular, 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
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
|
||||
```
|
||||
|
||||
After reviewing an API change, run
|
||||
`python3 tools/check-api-baseline.py --update` and commit the source and snapshot
|
||||
changes together. CI compares snapshots with the current source; compatibility
|
||||
checks retain the historical baseline.
|
||||
Generated
+2171
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "rns-application-api-fixture"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
all = ["rns-runtime/ble", "rns-runtime/rnode-tcp", "rns-runtime/serial"]
|
||||
|
||||
[dependencies]
|
||||
rns-transport = { path = "../../crates/rns-transport" }
|
||||
rns-runtime = { path = "../../crates/rns-runtime", default-features = false }
|
||||
@@ -0,0 +1,165 @@
|
||||
//! External-consumer compile contract for canonical and retained Reticulum paths.
|
||||
|
||||
/// Advanced actor ownership uses detached discovery snapshots, never map edits.
|
||||
pub mod recursive_discovery {
|
||||
use rns_transport::actor::{DiscoveryPathRequest, TransportActor};
|
||||
use rns_transport::messages::InterfaceId;
|
||||
use rns_transport::path_discovery::{DiscoveryAdmission, DiscoveryError};
|
||||
|
||||
pub fn request(
|
||||
actor: &mut TransportActor,
|
||||
destination: [u8; 16],
|
||||
interface: InterfaceId,
|
||||
) -> Result<DiscoveryAdmission, DiscoveryError> {
|
||||
actor.request_recursive_discovery(destination, interface)
|
||||
}
|
||||
|
||||
pub fn observe_and_cancel(actor: &mut TransportActor, destination: &[u8; 16]) {
|
||||
if let Some(snapshot) = actor.discovery_path_request(destination) {
|
||||
let _: DiscoveryPathRequest = snapshot.clone(); // retained import
|
||||
let _ = (snapshot.destination_hash(), snapshot.deadline());
|
||||
for requester in snapshot.requesters() {
|
||||
let _ = (requester.interface_id(), requester.destination_hash());
|
||||
actor.cancel_discovery_requester(requester);
|
||||
}
|
||||
}
|
||||
let _ = actor.discovery_path_requests();
|
||||
}
|
||||
}
|
||||
|
||||
pub mod canonical {
|
||||
use rns_runtime::prelude::{
|
||||
AnnounceSubscription, DestinationResolveError, DestinationResolveOptions,
|
||||
LinkSessionHandle, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
|
||||
resolve_destination_on_transport,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let _ = resolve_destination_on_transport;
|
||||
let _ = std::mem::size_of::<DestinationResolveOptions>();
|
||||
let _ = std::mem::size_of::<DestinationResolveError>();
|
||||
let _ = std::mem::size_of::<ReticulumHandle>();
|
||||
let _ = std::mem::size_of::<RecalledDestination>();
|
||||
let _ = std::mem::size_of::<AnnounceSubscription>();
|
||||
let _ = std::mem::size_of::<PacketReceiptHandle>();
|
||||
let _ = std::mem::size_of::<LinkSessionHandle>();
|
||||
let _ = ReticulumHandle::path_recovery_handle;
|
||||
let _ = ReticulumHandle::link_endpoint_dispatch_handle;
|
||||
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_packet;
|
||||
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_link;
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryHandle>();
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryOutcome>();
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryError>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Advanced ownership remains opt-in and module-qualified.
|
||||
pub mod delivery_ownership {
|
||||
use rns_runtime::link_manager::{LinkManager, LinkManagerAccountingEvent};
|
||||
use rns_runtime::prelude::ReticulumHandle;
|
||||
|
||||
pub fn install_dispatch(runtime: &ReticulumHandle, manager: &mut LinkManager) {
|
||||
manager.set_link_endpoint_dispatch_handle(runtime.link_endpoint_dispatch_handle());
|
||||
}
|
||||
|
||||
pub fn observe_wait(event: &LinkManagerAccountingEvent) {
|
||||
match event {
|
||||
LinkManagerAccountingEvent::OutboundPacketWait {
|
||||
receipt,
|
||||
started_at,
|
||||
timeout,
|
||||
awaiting_admission,
|
||||
cancellation,
|
||||
} => {
|
||||
let _ = (
|
||||
receipt.link_id,
|
||||
receipt.packet_hash,
|
||||
started_at,
|
||||
timeout,
|
||||
awaiting_admission,
|
||||
cancellation,
|
||||
);
|
||||
}
|
||||
LinkManagerAccountingEvent::OutboundResourceWait {
|
||||
link_id,
|
||||
resource_id,
|
||||
started_at,
|
||||
timeout,
|
||||
} => {
|
||||
let _ = (link_id, resource_id, started_at, timeout);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod legacy {
|
||||
use rns_runtime::destination_resolver::{
|
||||
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
|
||||
};
|
||||
use rns_runtime::link_session::LinkSessionHandle;
|
||||
use rns_runtime::reticulum::{
|
||||
AnnounceSubscription, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let _ = resolve_destination_on_transport;
|
||||
let _ = std::mem::size_of::<DestinationResolveOptions>();
|
||||
let _ = std::mem::size_of::<DestinationResolveError>();
|
||||
let _ = std::mem::size_of::<ReticulumHandle>();
|
||||
let _ = std::mem::size_of::<RecalledDestination>();
|
||||
let _ = std::mem::size_of::<AnnounceSubscription>();
|
||||
let _ = std::mem::size_of::<PacketReceiptHandle>();
|
||||
let _ = std::mem::size_of::<LinkSessionHandle>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Strict application ownership is additive; legacy imports above remain valid.
|
||||
pub mod shared_ownership {
|
||||
use rns_runtime::shared_instance::{
|
||||
InstancePolicy, SharedInstanceCredentials, SharedInstanceEndpoint,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let endpoint = SharedInstanceEndpoint::Tcp {
|
||||
packet_port: 37428,
|
||||
control_port: 37429,
|
||||
};
|
||||
let credentials = SharedInstanceCredentials::new(endpoint.clone(), vec![1; 17]).unwrap();
|
||||
let _ = InstancePolicy::SharedClient(credentials);
|
||||
let _ = InstancePolicy::SharedOwnerAt(endpoint);
|
||||
let _ = rns_runtime::reticulum::init_with_policy;
|
||||
let _ = rns_runtime::reticulum::ReticulumHandle::shared_instance_state;
|
||||
let _ = rns_runtime::reticulum::ReticulumHandle::startup_interface_failures;
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1.4 discovery API distinguishes unknown components from true zeros.
|
||||
pub mod nullable_discovery {
|
||||
use rns_transport::discovery::DiscoveryInterfaceConfig;
|
||||
use rns_transport::discovery::app_data::DiscoveryInfo;
|
||||
|
||||
pub fn literal() -> DiscoveryInfo {
|
||||
DiscoveryInfo {
|
||||
name: "coordinate-fixture".into(),
|
||||
interface_type: "BackboneInterface".into(),
|
||||
latitude: Some(0.0),
|
||||
longitude: Some(0.0),
|
||||
height: None,
|
||||
..DiscoveryInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configured() -> DiscoveryInterfaceConfig {
|
||||
let mut config =
|
||||
DiscoveryInterfaceConfig::backbone("relay".into(), "127.0.0.1".into(), 4965);
|
||||
config.latitude = Some(0.0);
|
||||
config.longitude = None;
|
||||
config.height = Some(0.0);
|
||||
config
|
||||
}
|
||||
|
||||
pub fn read(info: &DiscoveryInfo) -> [Option<f64>; 3] {
|
||||
[info.latitude, info.longitude, info.height]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# Migrating to rsReticulum 1.3
|
||||
|
||||
Version 1.3 combines two discovery API changes since the published 1.2 release:
|
||||
owned recursive discovery operations and independently optional interface
|
||||
coordinates. Both changes belong to this release.
|
||||
|
||||
This project's version convention permits breaking Rust APIs in a minor release.
|
||||
Version 1.3 is not source-compatible with direct mutation of the 1.2 discovery
|
||||
map. Cargo's default caret requirement `"1.2"` permits 1.3; use an explicit
|
||||
compatible line (for example `"~1.3.0"`) or an exact reviewed Git revision.
|
||||
Existing external dependency requirements cannot be changed retroactively.
|
||||
Packet, signature, RPC, and AutoInterface port formats remain unchanged.
|
||||
|
||||
Normal applications keep runtime `request_path`, finite destination resolution
|
||||
and `PathRecoveryHandle`. They do not need this advanced actor API.
|
||||
|
||||
## Advanced synchronous actor owners
|
||||
|
||||
| Before | Supported replacement |
|
||||
| --- | --- |
|
||||
| Read `actor.discovery_path_requests[&destination]` | `actor.discovery_path_request(&destination)` returns an optional detached snapshot |
|
||||
| Iterate the public map | `actor.discovery_path_requests()` returns snapshots sorted by destination |
|
||||
| Read one `requesting_interface` | Iterate `snapshot.requesters()` and read each token's `interface_id()` |
|
||||
| Read `timeout` | `snapshot.deadline()` is the original absolute Unix-seconds expiry |
|
||||
| Insert a record to participate in recursive discovery | `actor.request_recursive_discovery(destination, interface)` validates admission and starts/joins the one bounded search |
|
||||
| Remove/edit a record to cancel one requester | `actor.cancel_discovery_requester(token)` removes only that registration |
|
||||
| Copy/extend a deadline | Clone a snapshot for observation; callers cannot renew an existing operation |
|
||||
|
||||
`actor::DiscoveryPathRequest` remains an import path, re-exporting the type in
|
||||
`path_discovery`. Its public fields and `Copy` contract are removed deliberately.
|
||||
The old single-requester shape could silently discard other registrations when
|
||||
edited. Keeping a mutable compatibility mirror would retain that defect.
|
||||
|
||||
One operation admits at most 64 distinct requester channel generations; the
|
||||
actor admits at most 1,024 destinations. Repeated joins of the same registration
|
||||
return the same token without a new fanout or deadline. Requester identity is an
|
||||
interface generation, not a count of individual people sharing one radio.
|
||||
|
||||
Snapshots are not live views. A removed first requester disappears from new
|
||||
snapshots while other requesters remain. Offline but still registered/open
|
||||
requesters may remain waiting; no response is sent while they are offline.
|
||||
Expiry and interface replacement are checked without requiring a prior tick.
|
||||
|
||||
Tokens are opaque and actor/operation/registration-specific. Cloning or dropping
|
||||
one does not change ownership. Cancellation is explicit and cannot act on a new
|
||||
operation, a cancelled-and-rejoined requester, another actor, or a replacement
|
||||
channel that reused the numeric ID. Cancelling the last waiter removes related
|
||||
unadmitted search bytes; cancellation cannot recall transmitted bytes.
|
||||
|
||||
The advanced request API requires transport forwarding, an unknown nonlocal
|
||||
destination, and an available normal interface with eligible discovery policy.
|
||||
Typed errors distinguish policy, availability and capacity failures. It uses
|
||||
normal ingress/egress limits and a new wire tag only for a newly started search.
|
||||
`DiscoveryAdmission::started()` is local ownership/fanout intent, not a radio or
|
||||
delivery receipt. Driver backpressure and network loss still require normal
|
||||
caller policy. Normal runtime lookups should not use recursive actor control.
|
||||
|
||||
Use the compiled external fixture's `recursive_discovery` module as an example.
|
||||
No shared IPC/JNI or application UI is added by this change. Package stability
|
||||
classifications remain provisional; the compatibility gate records exactly the
|
||||
approved removals and continues rejecting unrelated API loss.
|
||||
|
||||
## Interface discovery coordinates
|
||||
|
||||
The six public `latitude`, `longitude`, and `height` fields in `DiscoveryInfo`
|
||||
and `DiscoveryInterfaceConfig` change from `f64` to `Option<f64>`, including the
|
||||
re-export of `DiscoveryInterfaceConfig` from `rns_transport::discovery`.
|
||||
|
||||
Unknown coordinates are `None`; known coordinates, including zero, are `Some`.
|
||||
The components are independent, so a known latitude and longitude do not imply
|
||||
a known height. `Default` and discovery convenience constructors leave them
|
||||
unknown. Update struct literals and assignments accordingly:
|
||||
|
||||
```rust,ignore
|
||||
// Before
|
||||
config.latitude = 0.0;
|
||||
config.longitude = -105.0;
|
||||
config.height = 0.0;
|
||||
|
||||
// After: latitude is genuinely zero; height is unknown.
|
||||
config.latitude = Some(0.0);
|
||||
config.longitude = Some(-105.0);
|
||||
config.height = None;
|
||||
```
|
||||
|
||||
Consumers should match the options or use `if let Some(value)` when displaying
|
||||
or using a component. Do not use `unwrap_or(0.0)` to turn an unknown location
|
||||
into a real map position. This change does not add new coordinate range rules.
|
||||
|
||||
## Wire, configuration, and storage
|
||||
|
||||
The discovery map retains its existing keys. An unknown component is encoded
|
||||
as MessagePack `nil`, matching Python Reticulum; a known component remains a
|
||||
number. Missing configuration leaves a component unknown, while an explicit
|
||||
zero remains known. Existing configuration key precedence and units are retained.
|
||||
No new wire protocol version or storage directory is required.
|
||||
|
||||
The Rust decoder continues accepting integer coordinates and missing coordinate
|
||||
keys as a leniency: integers become `Some`, and missing values become `None`.
|
||||
Those forms are not a claim of strict Python validation parity. Valid Python
|
||||
`nil`, partial-coordinate, and floating-point records are supported.
|
||||
|
||||
Existing numeric discovery records remain numeric on disk reload. Old stored
|
||||
zero cannot reveal whether it was deliberately configured or produced by the
|
||||
previous defaulting behavior, so it is preserved as `Some(0.0)`. A fresh valid
|
||||
announcement can replace it. Records containing `nil` or absent location keys
|
||||
load as `None`. Downgrading to older Rust versions loses this distinction:
|
||||
those versions coerce stored unknown components to zero.
|
||||
|
||||
`rnstatus-rs` represents unknown components as JSON `null`; text output uses
|
||||
presence instead of treating zero as absent. This does not change an embedding
|
||||
application's separate map display or location-sharing policy.
|
||||
|
||||
The historical API compatibility floor is retained. The exact removal ledger
|
||||
contains three recursive-ownership paths and nine coordinate paths for six
|
||||
fields because three are also re-exported. No unrelated removals are authorized.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
pub mod rns_crypto
|
||||
pub mod rns_crypto::aes_cbc
|
||||
pub enum rns_crypto::aes_cbc::AesCbcError
|
||||
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
|
||||
pub rns_crypto::aes_cbc::AesCbcError::EncryptionFailed
|
||||
pub rns_crypto::aes_cbc::AesCbcError::InvalidIvLength(usize)
|
||||
pub rns_crypto::aes_cbc::AesCbcError::InvalidKeyLength(usize)
|
||||
pub rns_crypto::aes_cbc::AesCbcError::NotBlockAligned
|
||||
pub fn rns_crypto::aes_cbc::decrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
|
||||
pub fn rns_crypto::aes_cbc::encrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
|
||||
pub mod rns_crypto::ed25519
|
||||
pub enum rns_crypto::ed25519::Ed25519Error
|
||||
pub rns_crypto::ed25519::Ed25519Error::InvalidPublicKey
|
||||
pub rns_crypto::ed25519::Ed25519Error::InvalidSignature
|
||||
pub rns_crypto::ed25519::Ed25519Error::VerificationFailed
|
||||
pub struct rns_crypto::ed25519::Ed25519PrivateKey
|
||||
impl rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::generate() -> Self
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::public_key(&self) -> rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::sign(&self, &[u8]) -> [u8; 64]
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::to_bytes(&self) -> [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::zeroize(&mut self)
|
||||
pub struct rns_crypto::ed25519::Ed25519PublicKey
|
||||
impl rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&[u8; 32]) -> core::result::Result<Self, rns_crypto::ed25519::Ed25519Error>
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::to_bytes(&self) -> [u8; 32]
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::verify(&self, &[u8], &[u8; 64]) -> core::result::Result<(), rns_crypto::ed25519::Ed25519Error>
|
||||
pub mod rns_crypto::hkdf
|
||||
pub enum rns_crypto::hkdf::HkdfError
|
||||
pub rns_crypto::hkdf::HkdfError::ExpansionFailed
|
||||
pub rns_crypto::hkdf::HkdfError::OutputTooLong(usize)
|
||||
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<[u8; 64], rns_crypto::hkdf::HkdfError>
|
||||
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::hkdf::HkdfError>
|
||||
pub mod rns_crypto::hmac
|
||||
pub fn rns_crypto::hmac::hmac_sha256(&[u8], &[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::hmac::hmac_verify(&[u8], &[u8], &[u8; 32]) -> bool
|
||||
pub mod rns_crypto::pkcs7
|
||||
pub enum rns_crypto::pkcs7::Pkcs7Error
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::EmptyInput
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::InconsistentPadding
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::InvalidPaddingValue(u8)
|
||||
pub fn rns_crypto::pkcs7::pad(&[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_crypto::pkcs7::unpad(&[u8]) -> core::result::Result<&[u8], rns_crypto::pkcs7::Pkcs7Error>
|
||||
pub mod rns_crypto::random
|
||||
pub fn rns_crypto::random::random_16() -> [u8; 16]
|
||||
pub fn rns_crypto::random::random_32() -> [u8; 32]
|
||||
pub fn rns_crypto::random::random_bytes(usize) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_crypto::sha
|
||||
pub fn rns_crypto::sha::full_hash(&[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::sha::name_hash(&str) -> [u8; 10]
|
||||
pub fn rns_crypto::sha::sha256(&[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::sha::sha512(&[u8]) -> [u8; 64]
|
||||
pub fn rns_crypto::sha::truncated_hash(&[u8]) -> [u8; 16]
|
||||
pub mod rns_crypto::token
|
||||
pub enum rns_crypto::token::TokenError
|
||||
pub rns_crypto::token::TokenError::AuthenticationFailed
|
||||
pub rns_crypto::token::TokenError::DecryptionFailed
|
||||
pub rns_crypto::token::TokenError::EncryptionFailed
|
||||
pub rns_crypto::token::TokenError::InvalidKeyLength(usize)
|
||||
pub rns_crypto::token::TokenError::TooShort
|
||||
pub const rns_crypto::token::AES128_BLOCKSIZE: usize
|
||||
pub const rns_crypto::token::AES256_BLOCKSIZE: usize
|
||||
pub const rns_crypto::token::DERIVED_KEY_LENGTH_LEGACY: usize
|
||||
pub const rns_crypto::token::KEY_LENGTH: usize
|
||||
pub const rns_crypto::token::LEGACY_KEY_LENGTH: usize
|
||||
pub const rns_crypto::token::TOKEN_OVERHEAD: usize
|
||||
pub fn rns_crypto::token::decrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
|
||||
pub fn rns_crypto::token::encrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
|
||||
pub fn rns_crypto::token::generate_key() -> zeroize::Zeroizing<alloc::vec::Vec<u8>>
|
||||
pub mod rns_crypto::x25519
|
||||
pub struct rns_crypto::x25519::X25519PrivateKey
|
||||
impl rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::exchange(&self, &rns_crypto::x25519::X25519PublicKey) -> [u8; 32]
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::generate() -> Self
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::public_key(&self) -> rns_crypto::x25519::X25519PublicKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::to_bytes(&self) -> [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::zeroize(&mut self)
|
||||
pub struct rns_crypto::x25519::X25519PublicKey
|
||||
impl rns_crypto::x25519::X25519PublicKey
|
||||
pub fn rns_crypto::x25519::X25519PublicKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::x25519::X25519PublicKey::to_bytes(&self) -> [u8; 32]
|
||||
pub const rns_crypto::TOKEN_OVERHEAD: usize
|
||||
pub fn rns_crypto::hex_encode(&[u8]) -> alloc::string::String
|
||||
@@ -0,0 +1,374 @@
|
||||
pub mod rns_identity
|
||||
pub mod rns_identity::announce
|
||||
pub enum rns_identity::announce::AnnounceError
|
||||
pub rns_identity::announce::AnnounceError::HashCollision
|
||||
pub rns_identity::announce::AnnounceError::HashMismatch
|
||||
pub rns_identity::announce::AnnounceError::InvalidPublicKey
|
||||
pub rns_identity::announce::AnnounceError::InvalidWireTime(u64)
|
||||
pub rns_identity::announce::AnnounceError::NoPrivateKey
|
||||
pub rns_identity::announce::AnnounceError::SignatureInvalid
|
||||
pub rns_identity::announce::AnnounceError::TooShort(usize)
|
||||
pub struct rns_identity::announce::AnnounceData
|
||||
pub rns_identity::announce::AnnounceData::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_identity::announce::AnnounceData::name_hash: [u8; 10]
|
||||
pub rns_identity::announce::AnnounceData::public_key: [u8; 64]
|
||||
pub rns_identity::announce::AnnounceData::random_hash: [u8; 10]
|
||||
pub rns_identity::announce::AnnounceData::ratchet: core::option::Option<[u8; 32]>
|
||||
pub rns_identity::announce::AnnounceData::signature: [u8; 64]
|
||||
impl rns_identity::announce::AnnounceData
|
||||
pub fn rns_identity::announce::AnnounceData::create(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::create_at(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, u64) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::announce::AnnounceData::unpack(&[u8], bool) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate_destination_binding(&self, &[u8; 16], &rns_identity::identity::Identity, core::option::Option<&[u8; 64]>) -> core::result::Result<(), rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate_with_known_key(&self, &[u8; 16], core::option::Option<&[u8; 64]>) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::verify_signature(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub const rns_identity::announce::ANNOUNCE_TIME_MAX: u64
|
||||
pub mod rns_identity::announce_state
|
||||
pub struct rns_identity::announce_state::RatchetControlState
|
||||
impl rns_identity::announce_state::RatchetControlState
|
||||
pub fn rns_identity::announce_state::RatchetControlState::anchor_rotation_if_unknown(&mut self, u64)
|
||||
pub fn rns_identity::announce_state::RatchetControlState::destination_hash(&self) -> [u8; 16]
|
||||
pub fn rns_identity::announce_state::RatchetControlState::identity_hash(&self) -> [u8; 16]
|
||||
pub fn rns_identity::announce_state::RatchetControlState::last_announce_wire(&self) -> core::option::Option<u64>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::last_rotation_wall(&self) -> core::option::Option<u64>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::load_verified(&std::path::Path, &rns_identity::identity::Identity, [u8; 16]) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::new([u8; 16], [u8; 16]) -> Self
|
||||
pub fn rns_identity::announce_state::RatchetControlState::prepare_announce(&self, u64) -> core::io::error::Result<core::option::Option<Self>>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::rotation_due(&self, u64, u64) -> bool
|
||||
pub fn rns_identity::announce_state::RatchetControlState::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::with_rotation_at(&self, u64) -> Self
|
||||
pub mod rns_identity::destination
|
||||
#[repr(u8)] pub enum rns_identity::destination::AllowPolicy
|
||||
pub rns_identity::destination::AllowPolicy::AllowAll = 1
|
||||
pub rns_identity::destination::AllowPolicy::AllowList = 2
|
||||
pub rns_identity::destination::AllowPolicy::AllowNone = 0
|
||||
pub enum rns_identity::destination::DefaultAppData
|
||||
pub rns_identity::destination::DefaultAppData::Dynamic(alloc::boxed::Box<(dyn core::ops::function::Fn() -> core::option::Option<alloc::vec::Vec<u8>> + core::marker::Send + core::marker::Sync)>)
|
||||
pub rns_identity::destination::DefaultAppData::Static(alloc::vec::Vec<u8>)
|
||||
#[repr(u8)] pub enum rns_identity::destination::DestType
|
||||
pub rns_identity::destination::DestType::Group = 1
|
||||
pub rns_identity::destination::DestType::Link = 3
|
||||
pub rns_identity::destination::DestType::Plain = 2
|
||||
pub rns_identity::destination::DestType::Single = 0
|
||||
pub enum rns_identity::destination::DestinationError
|
||||
pub rns_identity::destination::DestinationError::DecryptionFailed
|
||||
pub rns_identity::destination::DestinationError::EncryptionUnavailable
|
||||
pub rns_identity::destination::DestinationError::Identity(rns_identity::identity::IdentityError)
|
||||
pub rns_identity::destination::DestinationError::IdentityMismatch
|
||||
pub rns_identity::destination::DestinationError::InvalidAnnounceTime(f64)
|
||||
pub rns_identity::destination::DestinationError::InvalidGroupKeyLength(usize)
|
||||
pub rns_identity::destination::DestinationError::InvalidNameComponent(alloc::string::String)
|
||||
pub rns_identity::destination::DestinationError::MissingIdentity
|
||||
pub rns_identity::destination::DestinationError::NotGroup
|
||||
pub rns_identity::destination::DestinationError::NotInbound
|
||||
pub rns_identity::destination::DestinationError::NotSingle
|
||||
pub rns_identity::destination::DestinationError::OutboundMissingIdentity
|
||||
pub rns_identity::destination::DestinationError::PlainWithIdentity
|
||||
pub rns_identity::destination::DestinationError::ProveNotSingle
|
||||
pub rns_identity::destination::DestinationError::SigningUnavailable
|
||||
pub enum rns_identity::destination::DestinationPacketError
|
||||
pub rns_identity::destination::DestinationPacketError::Destination(rns_identity::destination::DestinationError)
|
||||
pub rns_identity::destination::DestinationPacketError::LinkRuntimeRequired
|
||||
pub rns_identity::destination::DestinationPacketError::LrproofRequiresLink
|
||||
pub rns_identity::destination::DestinationPacketError::MissingIdentity
|
||||
pub rns_identity::destination::DestinationPacketError::MissingTransportId
|
||||
pub rns_identity::destination::DestinationPacketError::Packet(rns_wire::packet::PacketError)
|
||||
pub enum rns_identity::destination::Direction
|
||||
pub rns_identity::destination::Direction::In
|
||||
pub rns_identity::destination::Direction::Out
|
||||
#[repr(u8)] pub enum rns_identity::destination::ProofStrategy
|
||||
pub rns_identity::destination::ProofStrategy::ProveAll = 35
|
||||
pub rns_identity::destination::ProofStrategy::ProveApp = 34
|
||||
pub rns_identity::destination::ProofStrategy::ProveNone = 33
|
||||
pub struct rns_identity::destination::AnnounceTime
|
||||
pub rns_identity::destination::AnnounceTime::cache: f64
|
||||
pub rns_identity::destination::AnnounceTime::wire: u64
|
||||
impl rns_identity::destination::AnnounceTime
|
||||
pub fn rns_identity::destination::AnnounceTime::new(u64, f64) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub struct rns_identity::destination::Destination
|
||||
pub rns_identity::destination::Destination::accept_link_requests: bool
|
||||
pub rns_identity::destination::Destination::app_name: alloc::string::String
|
||||
pub rns_identity::destination::Destination::dest_type: rns_identity::destination::DestType
|
||||
pub rns_identity::destination::Destination::direction: rns_identity::destination::Direction
|
||||
pub rns_identity::destination::Destination::hash: [u8; 16]
|
||||
pub rns_identity::destination::Destination::identity_hash: core::option::Option<[u8; 16]>
|
||||
pub rns_identity::destination::Destination::links: alloc::vec::Vec<[u8; 16]>
|
||||
pub rns_identity::destination::Destination::local_ratchet_pub: core::option::Option<[u8; 32]>
|
||||
pub rns_identity::destination::Destination::name: alloc::string::String
|
||||
pub rns_identity::destination::Destination::name_hash: [u8; 10]
|
||||
pub rns_identity::destination::Destination::only_validate_signature: bool
|
||||
pub rns_identity::destination::Destination::proof_strategy: rns_identity::destination::ProofStrategy
|
||||
pub rns_identity::destination::Destination::ratchets_enabled: bool
|
||||
pub rns_identity::destination::Destination::ratchets_enforced: bool
|
||||
pub rns_identity::destination::Destination::remote_ratchet_pub: core::option::Option<[u8; 32]>
|
||||
impl rns_identity::destination::Destination
|
||||
pub const rns_identity::destination::Destination::PR_TAG_WINDOW: f64
|
||||
pub const rns_identity::destination::Destination::RATCHET_COUNT: usize
|
||||
pub const rns_identity::destination::Destination::RATCHET_INTERVAL: u64
|
||||
pub fn rns_identity::destination::Destination::accepts_links(&self) -> bool
|
||||
pub fn rns_identity::destination::Destination::announce_packet(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, f64) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::announce_packet_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::app_and_aspects_from_name(&str) -> (&str, alloc::vec::Vec<&str>)
|
||||
pub fn rns_identity::destination::Destination::auto_identity(&self) -> core::option::Option<&rns_identity::identity::Identity>
|
||||
pub fn rns_identity::destination::Destination::cached_path_response_packet(&mut self, &[u8], f64) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::check_request_allowed(&self, &[u8; 16], core::option::Option<&[u8; 16]>) -> bool
|
||||
pub fn rns_identity::destination::Destination::clear_default_app_data(&mut self)
|
||||
pub fn rns_identity::destination::Destination::compute_hash(&[u8; 10], core::option::Option<&[u8; 16]>) -> [u8; 16]
|
||||
pub fn rns_identity::destination::Destination::create_announce(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, f64) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::create_announce_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt_with_ratchet_id(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt_with_ratchets(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::deregister_request_handler(&mut self, &str) -> bool
|
||||
pub fn rns_identity::destination::Destination::disable_ratchets(&mut self)
|
||||
pub fn rns_identity::destination::Destination::enable_ratchets(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::encrypt(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::expand_name(core::option::Option<&rns_identity::identity::Identity>, &str, &[&str]) -> core::result::Result<alloc::string::String, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::generate_group_key(&mut self) -> core::result::Result<(), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::get_ratchet_for_announce(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::destination::Destination::get_request_handler(&self, &[u8; 16]) -> core::option::Option<&rns_identity::destination::RequestHandler>
|
||||
pub fn rns_identity::destination::Destination::group_key(&self) -> core::result::Result<&[u8], rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::hash_from_name_and_identity(&str, core::option::Option<&[u8; 16]>) -> [u8; 16]
|
||||
pub fn rns_identity::destination::Destination::hex_hash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::destination::Destination::hexhash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::destination::Destination::incoming_link_request(&mut self, [u8; 16]) -> bool
|
||||
pub fn rns_identity::destination::Destination::link_count(&self) -> usize
|
||||
pub fn rns_identity::destination::Destination::load_group_key(&mut self, &[u8]) -> core::result::Result<(), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::new(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::new_with_aspects(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str, &[&str]) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::on_link_established(&self, [u8; 16])
|
||||
pub fn rns_identity::destination::Destination::pack_packet(&self, &[u8], core::option::Option<&rns_identity::identity::Identity>, core::option::Option<&[u8; 32]>, rns_identity::destination::DestinationPacketOptions) -> core::result::Result<rns_identity::destination::PackedDestinationPacket, rns_identity::destination::DestinationPacketError>
|
||||
pub fn rns_identity::destination::Destination::prove(&self, &[u8], &rns_identity::identity::Identity, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::ratchets_active(&self) -> bool
|
||||
pub fn rns_identity::destination::Destination::receive(&self, u8, &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::receive_packet(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::receive_packet_with_ratchets(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::register_request_handler(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool) -> bool
|
||||
pub fn rns_identity::destination::Destination::remove_link(&mut self, &[u8; 16])
|
||||
pub fn rns_identity::destination::Destination::resolve_app_data(&self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_identity::destination::Destination::set_accepts_links(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::set_default_app_data(&mut self, rns_identity::destination::DefaultAppData)
|
||||
pub fn rns_identity::destination::Destination::set_group_key(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_identity::destination::Destination::set_link_established_callback(&mut self, rns_identity::destination::LinkEstablishedCallback)
|
||||
pub fn rns_identity::destination::Destination::set_local_ratchet(&mut self, [u8; 32])
|
||||
pub fn rns_identity::destination::Destination::set_only_validate_signature(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::set_packet_callback(&mut self, rns_identity::destination::PacketCallback)
|
||||
pub fn rns_identity::destination::Destination::set_proof_requested_callback(&mut self, rns_identity::destination::ProofRequestedCallback)
|
||||
pub fn rns_identity::destination::Destination::set_proof_strategy(&mut self, rns_identity::destination::ProofStrategy)
|
||||
pub fn rns_identity::destination::Destination::set_remote_ratchet(&mut self, [u8; 32])
|
||||
pub fn rns_identity::destination::Destination::should_prove(&self, &[u8]) -> bool
|
||||
pub fn rns_identity::destination::Destination::sign(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<[u8; 64], rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::take_auto_identity(&mut self) -> core::option::Option<rns_identity::identity::Identity>
|
||||
impl core::fmt::Display for rns_identity::destination::Destination
|
||||
pub fn rns_identity::destination::Destination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_identity::destination::DestinationPacketOptions
|
||||
pub rns_identity::destination::DestinationPacketOptions::context: rns_wire::context::PacketContext
|
||||
pub rns_identity::destination::DestinationPacketOptions::context_flag: bool
|
||||
pub rns_identity::destination::DestinationPacketOptions::header_type: rns_wire::flags::HeaderType
|
||||
pub rns_identity::destination::DestinationPacketOptions::packet_type: rns_wire::flags::PacketType
|
||||
pub rns_identity::destination::DestinationPacketOptions::transport_id: core::option::Option<[u8; 16]>
|
||||
pub rns_identity::destination::DestinationPacketOptions::transport_type: rns_wire::flags::TransportType
|
||||
impl core::default::Default for rns_identity::destination::DestinationPacketOptions
|
||||
pub fn rns_identity::destination::DestinationPacketOptions::default() -> Self
|
||||
pub struct rns_identity::destination::PackedDestinationPacket
|
||||
pub rns_identity::destination::PackedDestinationPacket::packet: rns_wire::packet::Packet
|
||||
pub rns_identity::destination::PackedDestinationPacket::ratchet_id: core::option::Option<[u8; 10]>
|
||||
pub struct rns_identity::destination::RequestHandler
|
||||
pub rns_identity::destination::RequestHandler::allow: rns_identity::destination::AllowPolicy
|
||||
pub rns_identity::destination::RequestHandler::allowed_list: alloc::vec::Vec<[u8; 16]>
|
||||
pub rns_identity::destination::RequestHandler::auto_compress: bool
|
||||
pub rns_identity::destination::RequestHandler::path: alloc::string::String
|
||||
pub const rns_identity::destination::GROUP_KEY_LENGTH: usize
|
||||
pub const rns_identity::destination::PR_TAG_WINDOW: f64
|
||||
pub type rns_identity::destination::LinkEstablishedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn([u8; 16]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_identity::destination::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8], &[u8]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_identity::destination::ProofRequestedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) -> bool + core::marker::Send + core::marker::Sync)>
|
||||
pub mod rns_identity::identity
|
||||
pub enum rns_identity::identity::IdentityError
|
||||
pub rns_identity::identity::IdentityError::DecryptionFailed
|
||||
pub rns_identity::identity::IdentityError::Ed25519(rns_crypto::ed25519::Ed25519Error)
|
||||
pub rns_identity::identity::IdentityError::InvalidPrivateKeyLength(usize)
|
||||
pub rns_identity::identity::IdentityError::InvalidPublicKeyLength(usize)
|
||||
pub rns_identity::identity::IdentityError::Io(core::io::error::Error)
|
||||
pub rns_identity::identity::IdentityError::VerificationFailed
|
||||
pub struct rns_identity::identity::DecryptionResult
|
||||
pub rns_identity::identity::DecryptionResult::plaintext: alloc::vec::Vec<u8>
|
||||
pub rns_identity::identity::DecryptionResult::ratchet_id: core::option::Option<[u8; 10]>
|
||||
pub struct rns_identity::identity::Identity
|
||||
pub rns_identity::identity::Identity::hash: [u8; 16]
|
||||
impl rns_identity::identity::Identity
|
||||
pub const rns_identity::identity::Identity::CURVE: &'static str
|
||||
pub const rns_identity::identity::Identity::HASH_LENGTH_BITS: usize
|
||||
pub const rns_identity::identity::Identity::KEY_SIZE_BITS: usize
|
||||
pub const rns_identity::identity::Identity::RATCHETSIZE: usize
|
||||
pub const rns_identity::identity::Identity::RATCHET_SIZE_BITS: usize
|
||||
pub fn rns_identity::identity::Identity::decrypt(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::decrypt_with_ratchet_id(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::encrypt(&self, &[u8], core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_backend(&[u8], alloc::sync::Arc<dyn rns_identity::identity::LocalKeyBackend>) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_file(&std::path::Path) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_private_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_public_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::get_private_key(&self) -> core::option::Option<zeroize::Zeroizing<[u8; 64]>>
|
||||
pub fn rns_identity::identity::Identity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_identity::identity::Identity::get_signing_key(&self) -> core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>
|
||||
pub fn rns_identity::identity::Identity::has_backend(&self) -> bool
|
||||
pub fn rns_identity::identity::Identity::has_private_key(&self) -> bool
|
||||
pub fn rns_identity::identity::Identity::hexhash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::identity::Identity::lock(&self)
|
||||
pub fn rns_identity::identity::Identity::new() -> Self
|
||||
pub fn rns_identity::identity::Identity::prove(&self, &[u8], bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::pub_to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::ratchet_id(&[u8; 32]) -> [u8; 10]
|
||||
pub fn rns_identity::identity::Identity::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_identity::identity::Identity::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
impl core::clone::Clone for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::clone(&self) -> Self
|
||||
impl core::default::Default for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::default() -> Self
|
||||
impl core::fmt::Display for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub const rns_identity::identity::CURVE: &str
|
||||
pub const rns_identity::identity::DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_identity::identity::HASH_LENGTH_BITS: usize
|
||||
pub const rns_identity::identity::IDENTITY_OVERHEAD: usize
|
||||
pub const rns_identity::identity::KEY_SIZE_BITS: usize
|
||||
pub const rns_identity::identity::RATCHETSIZE: usize
|
||||
pub const rns_identity::identity::RATCHET_ID_LENGTH: usize
|
||||
pub const rns_identity::identity::RATCHET_SIZE_BITS: usize
|
||||
pub trait rns_identity::identity::LocalKeyBackend: core::marker::Send + core::marker::Sync
|
||||
pub fn rns_identity::identity::LocalKeyBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::identity::LocalKeyBackend::lock(&self)
|
||||
pub fn rns_identity::identity::LocalKeyBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub mod rns_identity::ifac
|
||||
pub enum rns_identity::ifac::IfacError
|
||||
pub rns_identity::ifac::IfacError::HkdfFailed(rns_crypto::hkdf::HkdfError)
|
||||
pub rns_identity::ifac::IfacError::InvalidSalt
|
||||
pub const rns_identity::ifac::IFAC_SALT: &str
|
||||
pub fn rns_identity::ifac::derive_ifac_identity(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<(rns_identity::identity::Identity, [u8; 64], [u8; 64]), rns_identity::ifac::IfacError>
|
||||
pub fn rns_identity::ifac::derive_ifac_key(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<[u8; 64], rns_identity::ifac::IfacError>
|
||||
pub fn rns_identity::ifac::split_ifac_key(&[u8; 64]) -> (&[u8], &[u8])
|
||||
pub mod rns_identity::known_destinations
|
||||
pub struct rns_identity::known_destinations::KnownDestination
|
||||
pub rns_identity::known_destinations::KnownDestination::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_identity::known_destinations::KnownDestination::packet_hash: [u8; 32]
|
||||
pub rns_identity::known_destinations::KnownDestination::public_key: [u8; 64]
|
||||
pub rns_identity::known_destinations::KnownDestination::retained: bool
|
||||
pub rns_identity::known_destinations::KnownDestination::timestamp: f64
|
||||
pub struct rns_identity::known_destinations::KnownDestinations
|
||||
impl rns_identity::known_destinations::KnownDestinations
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::cleanup(&mut self, f64, f64, impl core::ops::function::Fn(&[u8; 16]) -> bool) -> alloc::vec::Vec<[u8; 16]>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::contains(&self, &[u8; 16]) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::get(&self, &[u8; 16]) -> core::option::Option<&rns_identity::known_destinations::KnownDestination>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::is_empty(&self) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::is_known_or_registered(&self, &[u8; 16], &std::collections::hash::set::HashSet<[u8; 16]>) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::len(&self) -> usize
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::load(&std::path::Path) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::merge(&mut self, &rns_identity::known_destinations::KnownDestinations)
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::new() -> Self
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::recall_app_data(&self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::recall_by_identity(&self, &[u8; 16]) -> core::option::Option<(&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::remember(&mut self, [u8; 16], f64, [u8; 32], [u8; 64], core::option::Option<alloc::vec::Vec<u8>>)
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_identity::known_destinations::KnownDestination>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::retain(&mut self, &[u8; 16])
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::retain_identity(&mut self, &[u8; 16]) -> usize
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::save(&self, &std::path::Path) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::unretain(&mut self, &[u8; 16])
|
||||
impl core::default::Default for rns_identity::known_destinations::KnownDestinations
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::default() -> Self
|
||||
pub mod rns_identity::name_hash
|
||||
pub fn rns_identity::name_hash::name_hash(&str) -> [u8; 10]
|
||||
pub mod rns_identity::persistence
|
||||
pub fn rns_identity::persistence::atomic_write(&std::path::Path, &[u8]) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub mod rns_identity::ratchet
|
||||
pub enum rns_identity::ratchet::RatchetRingFormat
|
||||
pub rns_identity::ratchet::RatchetRingFormat::Canonical
|
||||
pub rns_identity::ratchet::RatchetRingFormat::LegacyRust
|
||||
pub struct rns_identity::ratchet::LoadedRatchetRing
|
||||
impl rns_identity::ratchet::LoadedRatchetRing
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::format(&self) -> rns_identity::ratchet::RatchetRingFormat
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::into_ring(self) -> rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub struct rns_identity::ratchet::PersistentRatchetRing
|
||||
impl rns_identity::ratchet::PersistentRatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::is_empty(&self) -> bool
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::len(&self) -> usize
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::open(impl core::convert::AsRef<std::path::Path>, &rns_identity::identity::Identity) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::path(&self) -> &std::path::Path
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::private_keys(&self) -> &[[u8; 32]]
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
|
||||
impl core::fmt::Debug for rns_identity::ratchet::PersistentRatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_identity::ratchet::PreparedRatchetRotation
|
||||
impl rns_identity::ratchet::PreparedRatchetRotation
|
||||
pub fn rns_identity::ratchet::PreparedRatchetRotation::public_key(&self) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::PreparedRatchetRotation::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub struct rns_identity::ratchet::RatchetRing
|
||||
impl rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::anchor_rotation_at(&mut self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::commit_prepared_rotation(&mut self, rns_identity::ratchet::PreparedRatchetRotation) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::RatchetRing::is_empty(&self) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::last_rotation(&self) -> f64
|
||||
pub fn rns_identity::ratchet::RatchetRing::len(&self) -> usize
|
||||
pub fn rns_identity::ratchet::RatchetRing::load(&std::path::Path) -> core::io::error::Result<(Self, [u8; 64])>
|
||||
pub fn rns_identity::ratchet::RatchetRing::load_verified(&std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<rns_identity::ratchet::LoadedRatchetRing>
|
||||
pub fn rns_identity::ratchet::RatchetRing::needs_rotation(&self) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::needs_rotation_at(&self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::new() -> Self
|
||||
pub fn rns_identity::ratchet::RatchetRing::prepare_rotation_at(&self, f64) -> rns_identity::ratchet::PreparedRatchetRotation
|
||||
pub fn rns_identity::ratchet::RatchetRing::private_keys(&self) -> &[[u8; 32]]
|
||||
pub fn rns_identity::ratchet::RatchetRing::ratchet_interval(&self) -> u64
|
||||
pub fn rns_identity::ratchet::RatchetRing::retained_ratchets(&self) -> usize
|
||||
pub fn rns_identity::ratchet::RatchetRing::rotate(&mut self) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::rotate_at(&mut self, f64) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::save(&self, &std::path::Path, &[u8; 64]) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::RatchetRing::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::RatchetRing::set_ratchet_interval(&mut self, u64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::set_retained_ratchets(&mut self, usize) -> bool
|
||||
impl core::default::Default for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::zeroize(&mut self)
|
||||
pub struct rns_identity::ratchet::ReceivedRatchet
|
||||
pub rns_identity::ratchet::ReceivedRatchet::ratchet_pub: [u8; 32]
|
||||
pub rns_identity::ratchet::ReceivedRatchet::received_at: f64
|
||||
impl rns_identity::ratchet::ReceivedRatchet
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired(&self) -> bool
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired_at(&self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::load(&std::path::Path) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::new([u8; 32]) -> Self
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::new_at([u8; 32], f64) -> Self
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::ratchet_id(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::save(&self, &std::path::Path) -> core::io::error::Result<()>
|
||||
pub struct rns_identity::ratchet::ReceivedRatchetStore
|
||||
impl rns_identity::ratchet::ReceivedRatchetStore
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::clean_expired(&mut self)
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::current_ratchet_id(&mut self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::get(&mut self, &[u8; 16]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::get_at(&mut self, &[u8; 16], f64) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::is_empty(&self) -> bool
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::len(&self) -> usize
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::new() -> Self
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::remember(&mut self, [u8; 16], [u8; 32])
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::remember_at(&mut self, [u8; 16], [u8; 32], f64)
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::with_storage(std::path::PathBuf) -> Self
|
||||
impl core::default::Default for rns_identity::ratchet::ReceivedRatchetStore
|
||||
pub fn rns_identity::ratchet::ReceivedRatchetStore::default() -> Self
|
||||
pub fn rns_identity::ratchet::clean_received_ratchets_dir(&std::path::Path) -> usize
|
||||
pub fn rns_identity::ratchet::get_ratchet_id(&[u8; 32]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::ratchet::purge_expired_ratchets_in_memory<K: core::cmp::Eq + core::hash::Hash>(&mut std::collections::hash::map::HashMap<K, rns_identity::ratchet::ReceivedRatchet>) -> usize
|
||||
pub fn rns_identity::ratchet::ratchet_public_bytes(&[u8; 32]) -> [u8; 32]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,359 @@
|
||||
pub mod rns_link
|
||||
pub mod rns_link::constants
|
||||
pub const rns_link::constants::ACCEPT_ALL: u8
|
||||
pub const rns_link::constants::ACCEPT_APP: u8
|
||||
pub const rns_link::constants::ACCEPT_NONE: u8
|
||||
pub const rns_link::constants::AES128_DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_link::constants::AES256_DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_link::constants::DEFAULT_MODE: u8
|
||||
pub const rns_link::constants::DESTINATION_CLOSED: u8
|
||||
pub const rns_link::constants::ECPUBSIZE: usize
|
||||
pub const rns_link::constants::ENABLED_MODES: &[u8]
|
||||
pub const rns_link::constants::ESTABLISHMENT_TIMEOUT_PER_HOP: f64
|
||||
pub const rns_link::constants::INITIATOR_CLOSED: u8
|
||||
pub const rns_link::constants::KEEPALIVE_DEFAULT: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MAX: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MAX_RTT: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MIN: f64
|
||||
pub const rns_link::constants::KEEPALIVE_REQUEST: u8
|
||||
pub const rns_link::constants::KEEPALIVE_RESPONSE: u8
|
||||
pub const rns_link::constants::KEEPALIVE_TIMEOUT_FACTOR: f64
|
||||
pub const rns_link::constants::KEYSIZE: usize
|
||||
pub const rns_link::constants::LINK_MTU_SIZE: usize
|
||||
pub const rns_link::constants::MODE_AES128_CBC: u8
|
||||
pub const rns_link::constants::MODE_AES256_CBC: u8
|
||||
pub const rns_link::constants::MODE_AES256_GCM: u8
|
||||
pub const rns_link::constants::MODE_BYTEMASK: u32
|
||||
pub const rns_link::constants::MODE_OTP_RESERVED: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_1: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_2: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_3: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_4: u8
|
||||
pub const rns_link::constants::MTU_BYTEMASK: u32
|
||||
pub const rns_link::constants::RESPONSE_MAX_GRACE_TIME: f64
|
||||
pub const rns_link::constants::STALE_FACTOR: f64
|
||||
pub const rns_link::constants::STALE_GRACE: f64
|
||||
pub const rns_link::constants::STALE_TIME_DEFAULT: f64
|
||||
pub const rns_link::constants::TIMEOUT: u8
|
||||
pub const rns_link::constants::TRAFFIC_TIMEOUT_FACTOR: f64
|
||||
pub const rns_link::constants::TRAFFIC_TIMEOUT_FLOOR_MS: u64
|
||||
pub const rns_link::constants::WATCHDOG_MAX_SLEEP: f64
|
||||
pub mod rns_link::encryption
|
||||
pub enum rns_link::encryption::LinkCryptoError
|
||||
pub rns_link::encryption::LinkCryptoError::DecryptionFailed
|
||||
pub rns_link::encryption::LinkCryptoError::EncryptionFailed
|
||||
pub fn rns_link::encryption::link_decrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::encryption::link_encrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub mod rns_link::handshake
|
||||
pub enum rns_link::handshake::HandshakeError
|
||||
pub rns_link::handshake::HandshakeError::InvalidLength(usize)
|
||||
pub rns_link::handshake::HandshakeError::InvalidSignature
|
||||
pub rns_link::handshake::HandshakeError::KeyDerivation(rns_link::key_derivation::LinkKeyError)
|
||||
pub rns_link::handshake::HandshakeError::TooShort
|
||||
pub rns_link::handshake::HandshakeError::UnsupportedMode(u8)
|
||||
pub struct rns_link::handshake::EphemeralKeys
|
||||
pub rns_link::handshake::EphemeralKeys::ed25519_prv: rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub rns_link::handshake::EphemeralKeys::ed25519_pub: rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub rns_link::handshake::EphemeralKeys::x25519_prv: rns_crypto::x25519::X25519PrivateKey
|
||||
pub rns_link::handshake::EphemeralKeys::x25519_pub: rns_crypto::x25519::X25519PublicKey
|
||||
impl rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::generate() -> Self
|
||||
impl core::ops::drop::Drop for rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::zeroize(&mut self)
|
||||
pub struct rns_link::handshake::LinkProofData
|
||||
pub rns_link::handshake::LinkProofData::responder_x25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkProofData::signalling: rns_link::mtu_discovery::SignallingData
|
||||
pub rns_link::handshake::LinkProofData::signature: [u8; 64]
|
||||
impl rns_link::handshake::LinkProofData
|
||||
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self
|
||||
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_link::mtu_discovery::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::handshake::LinkProofData::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_link::handshake::LinkProofData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::handshake::LinkProofData::validate(&self, &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 16], &[u8; 32]) -> bool
|
||||
pub struct rns_link::handshake::LinkRequestData
|
||||
pub rns_link::handshake::LinkRequestData::peer_ed25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkRequestData::peer_x25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkRequestData::signalling: rns_link::mtu_discovery::SignallingData
|
||||
impl rns_link::handshake::LinkRequestData
|
||||
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_link::mtu_discovery::SignallingData) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_link::handshake::LinkRequestData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::handshake::compute_link_id(&[u8; 16], &[u8]) -> [u8; 16]
|
||||
pub fn rns_link::handshake::compute_link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub fn rns_link::handshake::perform_handshake(&rns_crypto::x25519::X25519PrivateKey, &[u8; 32], &[u8; 16], u8) -> core::result::Result<rns_link::key_derivation::LinkKeys, rns_link::key_derivation::LinkKeyError>
|
||||
pub mod rns_link::keepalive
|
||||
pub struct rns_link::keepalive::KeepaliveState
|
||||
pub rns_link::keepalive::KeepaliveState::activated_at: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::is_initiator: bool
|
||||
pub rns_link::keepalive::KeepaliveState::keepalive_interval: core::time::Duration
|
||||
pub rns_link::keepalive::KeepaliveState::last_data: std::time::Instant
|
||||
pub rns_link::keepalive::KeepaliveState::last_inbound: std::time::Instant
|
||||
pub rns_link::keepalive::KeepaliveState::last_keepalive_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::last_outbound: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::last_proof: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::stale_time: core::time::Duration
|
||||
impl rns_link::keepalive::KeepaliveState
|
||||
pub fn rns_link::keepalive::KeepaliveState::is_stale(&self) -> bool
|
||||
pub fn rns_link::keepalive::KeepaliveState::mark_activated(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::mark_keepalive_sent(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::new(bool) -> Self
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_data(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_inbound(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_outbound(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_proof(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::should_send_keepalive(&self) -> bool
|
||||
pub fn rns_link::keepalive::KeepaliveState::since_inbound(&self) -> core::time::Duration
|
||||
pub fn rns_link::keepalive::KeepaliveState::stale_grace_timeout(&self, core::time::Duration) -> core::time::Duration
|
||||
pub fn rns_link::keepalive::KeepaliveState::update_from_rtt(&mut self, core::time::Duration)
|
||||
pub mod rns_link::key_derivation
|
||||
pub enum rns_link::key_derivation::LinkKeyError
|
||||
pub rns_link::key_derivation::LinkKeyError::HkdfFailed
|
||||
pub rns_link::key_derivation::LinkKeyError::UnsupportedMode(u8)
|
||||
pub struct rns_link::key_derivation::LinkKeys
|
||||
pub rns_link::key_derivation::LinkKeys::encryption_key: alloc::vec::Vec<u8>
|
||||
pub rns_link::key_derivation::LinkKeys::signing_key: alloc::vec::Vec<u8>
|
||||
impl rns_link::key_derivation::LinkKeys
|
||||
pub fn rns_link::key_derivation::LinkKeys::derive(&rns_crypto::x25519::X25519PrivateKey, &rns_crypto::x25519::X25519PublicKey, &[u8; 16], u8) -> core::result::Result<Self, rns_link::key_derivation::LinkKeyError>
|
||||
impl core::ops::drop::Drop for rns_link::key_derivation::LinkKeys
|
||||
pub fn rns_link::key_derivation::LinkKeys::drop(&mut self)
|
||||
pub mod rns_link::link
|
||||
pub enum rns_link::link::CloseReason
|
||||
pub rns_link::link::CloseReason::DestinationClosed
|
||||
pub rns_link::link::CloseReason::InitiatorClosed
|
||||
pub rns_link::link::CloseReason::Timeout
|
||||
pub enum rns_link::link::LinkAction
|
||||
pub rns_link::link::LinkAction::Closed(rns_link::link::CloseReason)
|
||||
pub rns_link::link::LinkAction::None
|
||||
pub rns_link::link::LinkAction::SendKeepalive
|
||||
pub rns_link::link::LinkAction::SendTeardownAndClose(alloc::vec::Vec<u8>)
|
||||
pub rns_link::link::LinkAction::TransitionedToStale
|
||||
pub enum rns_link::link::LinkRole
|
||||
pub rns_link::link::LinkRole::Initiator
|
||||
pub rns_link::link::LinkRole::Responder
|
||||
pub enum rns_link::link::LinkState
|
||||
pub rns_link::link::LinkState::Active = 2
|
||||
pub rns_link::link::LinkState::Closed = 4
|
||||
pub rns_link::link::LinkState::Handshake = 1
|
||||
pub rns_link::link::LinkState::Pending = 0
|
||||
pub rns_link::link::LinkState::Stale = 3
|
||||
pub enum rns_link::link::OutboundResourceState
|
||||
pub rns_link::link::OutboundResourceState::AwaitingProof
|
||||
pub rns_link::link::OutboundResourceState::Complete
|
||||
pub rns_link::link::OutboundResourceState::Failed
|
||||
pub rns_link::link::OutboundResourceState::Transferring
|
||||
pub enum rns_link::link::PacketProofError
|
||||
pub rns_link::link::PacketProofError::HashMismatch
|
||||
pub rns_link::link::PacketProofError::InvalidSignature
|
||||
pub rns_link::link::PacketProofError::InvalidState(rns_link::link::LinkState)
|
||||
pub rns_link::link::PacketProofError::MalformedProof
|
||||
pub rns_link::link::PacketProofError::PeerKeyUnavailable
|
||||
pub rns_link::link::PacketProofError::SignerUnavailable
|
||||
pub rns_link::link::PacketProofError::WrongRole
|
||||
pub enum rns_link::link::RequestSendMode
|
||||
pub rns_link::link::RequestSendMode::Packet(alloc::vec::Vec<u8>)
|
||||
pub rns_link::link::RequestSendMode::Resource(alloc::vec::Vec<u8>)
|
||||
pub enum rns_link::link::ResourceAcceptance
|
||||
pub rns_link::link::ResourceAcceptance::Accept
|
||||
pub rns_link::link::ResourceAcceptance::AskApp
|
||||
pub rns_link::link::ResourceAcceptance::Reject
|
||||
pub enum rns_link::link::ResourceStrategy
|
||||
pub rns_link::link::ResourceStrategy::AcceptAll
|
||||
pub rns_link::link::ResourceStrategy::AcceptApp
|
||||
pub rns_link::link::ResourceStrategy::AcceptNone
|
||||
pub struct rns_link::link::Link
|
||||
pub rns_link::link::Link::activated_at: core::option::Option<std::time::Instant>
|
||||
pub rns_link::link::Link::destination_hash: [u8; 16]
|
||||
pub rns_link::link::Link::establishment_cost: usize
|
||||
pub rns_link::link::Link::establishment_rate: core::option::Option<f64>
|
||||
pub rns_link::link::Link::establishment_timeout: core::time::Duration
|
||||
pub rns_link::link::Link::expected_hops: core::option::Option<u8>
|
||||
pub rns_link::link::Link::expected_rate: core::option::Option<f64>
|
||||
pub rns_link::link::Link::has_channel: bool
|
||||
pub rns_link::link::Link::identified: bool
|
||||
pub rns_link::link::Link::incoming_resource_count: usize
|
||||
pub rns_link::link::Link::incoming_resources: alloc::vec::Vec<[u8; 32]>
|
||||
pub rns_link::link::Link::is_initiator: bool
|
||||
pub rns_link::link::Link::keepalive: rns_link::keepalive::KeepaliveState
|
||||
pub rns_link::link::Link::link_closed_callback: core::option::Option<rns_link::link::LinkCallback>
|
||||
pub rns_link::link::Link::link_established_callback: core::option::Option<rns_link::link::LinkCallback>
|
||||
pub rns_link::link::Link::link_id: [u8; 16]
|
||||
pub rns_link::link::Link::mdu: usize
|
||||
pub rns_link::link::Link::mode: u8
|
||||
pub rns_link::link::Link::mtu: u32
|
||||
pub rns_link::link::Link::outgoing_resource_states: alloc::vec::Vec<rns_link::link::OutboundResourceState>
|
||||
pub rns_link::link::Link::outgoing_resources: alloc::vec::Vec<[u8; 32]>
|
||||
pub rns_link::link::Link::packet_callback: core::option::Option<rns_link::link::PacketCallback>
|
||||
pub rns_link::link::Link::pending_requests: alloc::vec::Vec<rns_link::request::RequestReceipt>
|
||||
pub rns_link::link::Link::q: core::option::Option<f64>
|
||||
pub rns_link::link::Link::remote_identified_callback: core::option::Option<rns_link::link::RemoteIdentifiedCallback>
|
||||
pub rns_link::link::Link::request_time: std::time::Instant
|
||||
pub rns_link::link::Link::resource_callback: core::option::Option<rns_link::link::ResourceCallback>
|
||||
pub rns_link::link::Link::resource_strategy: rns_link::link::ResourceStrategy
|
||||
pub rns_link::link::Link::rssi: core::option::Option<f64>
|
||||
pub rns_link::link::Link::rtt: core::option::Option<core::time::Duration>
|
||||
pub rns_link::link::Link::rx_bytes: u64
|
||||
pub rns_link::link::Link::rx_count: u64
|
||||
pub rns_link::link::Link::snr: core::option::Option<f64>
|
||||
pub rns_link::link::Link::stale_since: core::option::Option<std::time::Instant>
|
||||
pub rns_link::link::Link::state: rns_link::link::LinkState
|
||||
pub rns_link::link::Link::teardown_reason: core::option::Option<rns_link::link::CloseReason>
|
||||
pub rns_link::link::Link::tx_bytes: u64
|
||||
pub rns_link::link::Link::tx_count: u64
|
||||
impl rns_link::link::Link
|
||||
pub fn rns_link::link::Link::add_establishment_cost(&mut self, usize)
|
||||
pub fn rns_link::link::Link::age(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_link::link::Link::classify_request(&self, alloc::vec::Vec<u8>) -> rns_link::link::RequestSendMode
|
||||
pub fn rns_link::link::Link::create_response(&self, &[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::create_rtt_packet(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::decrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::default_request_timeout(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::deliver_response_data(&mut self, &[u8; 16], alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_link::link::Link::encrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::extend_establishment_timeout(&mut self, f64)
|
||||
pub fn rns_link::link::Link::fail_pending_request(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::get_age(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_establishment_rate(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_expected_rate(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_mdu(&self) -> core::option::Option<usize>
|
||||
pub const fn rns_link::link::Link::get_mode(&self) -> u8
|
||||
pub fn rns_link::link::Link::get_mtu(&self) -> core::option::Option<u32>
|
||||
pub fn rns_link::link::Link::get_q(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_rssi(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_snr(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::handle_identification(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_request(&self, &[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_response(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_response_plaintext(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::has_keys(&self) -> bool
|
||||
pub fn rns_link::link::Link::identify(&self, &[u8; 64], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::identify_with<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::link::Link::identify_with_fallible<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::inactive_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::is_active(&self) -> bool
|
||||
pub fn rns_link::link::Link::mark_channel_created(&mut self)
|
||||
pub fn rns_link::link::Link::mark_closed(&mut self, rns_link::link::CloseReason)
|
||||
pub fn rns_link::link::Link::mark_request_resource_sending(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::mark_request_resource_sent(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::new_initiator([u8; 16], u8) -> (Self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::link::Link::new_responder(&[u8], &rns_crypto::ed25519::Ed25519PrivateKey, [u8; 16], u8) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::link::Link::new_responder_with<F>(&[u8], &[u8; 32], [u8; 16], u8, F) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::no_data_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::no_inbound_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::no_outbound_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::pack_response(&[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::packet_proof_timeout(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::parse_request(&[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::parse_response_plaintext(&[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::phy_stats(&self) -> (core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::phy_stats_snapshot(&self) -> rns_link::link::LinkPhyStats
|
||||
pub fn rns_link::link::Link::phy_stats_tracking_enabled(&self) -> bool
|
||||
pub fn rns_link::link::Link::prepare_request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet(&self, &[u8; 32], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::link::Link::prove_packet_with_fallible<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::prove_packet_with_link_key(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet_with_local_signer(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError>
|
||||
pub fn rns_link::link::Link::prove_responder_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::ready_for_new_resource(&self) -> bool
|
||||
pub fn rns_link::link::Link::receive_rtt_packet(&mut self, &[u8]) -> core::result::Result<(), rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::link::Link::receive_teardown(&mut self, &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::record_inbound(&mut self)
|
||||
pub fn rns_link::link::Link::record_rx(&mut self, usize)
|
||||
pub fn rns_link::link::Link::record_tx(&mut self, usize)
|
||||
pub fn rns_link::link::Link::record_tx_keepalive(&mut self, usize)
|
||||
pub fn rns_link::link::Link::register_incoming_resource(&mut self)
|
||||
pub fn rns_link::link::Link::register_outgoing_resource(&mut self)
|
||||
pub fn rns_link::link::Link::remote_identity(&self) -> core::option::Option<&[u8; 64]>
|
||||
pub fn rns_link::link::Link::request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::request_str(&mut self, &str, &str, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::resource_concluded(&mut self, usize, f64, bool)
|
||||
pub fn rns_link::link::Link::role(&self) -> rns_link::link::LinkRole
|
||||
pub fn rns_link::link::Link::rtt_secs(&self) -> f64
|
||||
pub fn rns_link::link::Link::session_keys(&self) -> core::option::Option<rns_link::key_derivation::LinkKeys>
|
||||
pub fn rns_link::link::Link::set_link_closed_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_link_established_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_packet_callback(&mut self, impl core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_remote_identified_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_resource_callback(&mut self, impl core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_resource_strategy(&mut self, rns_link::link::ResourceStrategy)
|
||||
pub fn rns_link::link::Link::set_signing_key(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey)
|
||||
pub fn rns_link::link::Link::should_accept_resource(&self) -> rns_link::link::ResourceAcceptance
|
||||
pub fn rns_link::link::Link::should_respond_to_keepalive(&self) -> bool
|
||||
pub fn rns_link::link::Link::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::teardown(&mut self, rns_link::link::CloseReason) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_link::link::Link::tick(&mut self) -> rns_link::link::LinkAction
|
||||
pub fn rns_link::link::Link::track_incoming_resource(&mut self, [u8; 32])
|
||||
pub fn rns_link::link::Link::track_outgoing_resource(&mut self, [u8; 32])
|
||||
pub fn rns_link::link::Link::track_phy_stats(&mut self, bool)
|
||||
pub fn rns_link::link::Link::traffic_stats(&self) -> (u64, u64, u64, u64)
|
||||
pub fn rns_link::link::Link::untrack_resource(&mut self, &[u8; 32])
|
||||
pub fn rns_link::link::Link::update_outgoing_resource_state(&mut self, usize, rns_link::link::OutboundResourceState)
|
||||
pub fn rns_link::link::Link::update_pending_request_id(&mut self, &[u8; 16], [u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::update_phy_stats(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::update_phy_stats_force(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::update_rtt_from_packet(&mut self, &[u8]) -> core::result::Result<core::time::Duration, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::validate(&self, &[u8], &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::validate_packet_proof(&self, &[u8; 32], &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::validate_peer_packet_proof(&self, &[u8; 32], &[u8]) -> core::result::Result<(), rns_link::link::PacketProofError>
|
||||
pub fn rns_link::link::Link::validate_proof(&mut self, &[u8], &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::handshake::HandshakeError>
|
||||
pub struct rns_link::link::LinkPhyStats
|
||||
pub rns_link::link::LinkPhyStats::q: core::option::Option<f64>
|
||||
pub rns_link::link::LinkPhyStats::rssi: core::option::Option<f64>
|
||||
pub rns_link::link::LinkPhyStats::snr: core::option::Option<f64>
|
||||
pub type rns_link::link::LinkCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::ParsedRequestData = ([u8; 16], [u8; 16], f64, alloc::vec::Vec<u8>)
|
||||
pub type rns_link::link::RemoteIdentifiedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::ResourceCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync)>
|
||||
pub mod rns_link::mtu_discovery
|
||||
pub struct rns_link::mtu_discovery::SignallingData
|
||||
pub rns_link::mtu_discovery::SignallingData::mode: u8
|
||||
pub rns_link::mtu_discovery::SignallingData::mtu: u32
|
||||
impl rns_link::mtu_discovery::SignallingData
|
||||
pub fn rns_link::mtu_discovery::SignallingData::new(u8, u32) -> Self
|
||||
pub fn rns_link::mtu_discovery::SignallingData::pack(&self) -> [u8; 3]
|
||||
pub fn rns_link::mtu_discovery::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
|
||||
pub mod rns_link::request
|
||||
pub enum rns_link::request::RequestState
|
||||
pub rns_link::request::RequestState::Delivered
|
||||
pub rns_link::request::RequestState::Failed
|
||||
pub rns_link::request::RequestState::Receiving
|
||||
pub rns_link::request::RequestState::ResponseReceived
|
||||
pub rns_link::request::RequestState::SendingResource
|
||||
pub rns_link::request::RequestState::Sent
|
||||
pub struct rns_link::request::RequestCallbacks
|
||||
pub rns_link::request::RequestCallbacks::failed: core::option::Option<rns_link::request::RequestCallback>
|
||||
pub rns_link::request::RequestCallbacks::progress: core::option::Option<rns_link::request::ProgressCallback>
|
||||
pub rns_link::request::RequestCallbacks::response: core::option::Option<rns_link::request::RequestCallback>
|
||||
pub struct rns_link::request::RequestReceipt
|
||||
pub rns_link::request::RequestReceipt::callbacks: rns_link::request::RequestCallbacks
|
||||
pub rns_link::request::RequestReceipt::link_id: [u8; 16]
|
||||
pub rns_link::request::RequestReceipt::progress: f32
|
||||
pub rns_link::request::RequestReceipt::request_id: [u8; 32]
|
||||
pub rns_link::request::RequestReceipt::response: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_link::request::RequestReceipt::rtt: core::option::Option<core::time::Duration>
|
||||
pub rns_link::request::RequestReceipt::sent_at: std::time::Instant
|
||||
pub rns_link::request::RequestReceipt::state: rns_link::request::RequestState
|
||||
pub rns_link::request::RequestReceipt::timeout: core::time::Duration
|
||||
impl rns_link::request::RequestReceipt
|
||||
pub fn rns_link::request::RequestReceipt::check_timeout(&mut self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::concluded(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::deliver(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::request::RequestReceipt::fail(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::get_progress(&self) -> f32
|
||||
pub fn rns_link::request::RequestReceipt::get_response_time(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_link::request::RequestReceipt::is_pending(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::is_timed_out(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::mark_delivered(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_failed(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_resource_sending(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_resource_sent(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::new([u8; 32], [u8; 16], core::time::Duration) -> Self
|
||||
pub fn rns_link::request::RequestReceipt::receive_response(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::request::RequestReceipt::set_failed_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::set_progress_callback(&mut self, impl core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::set_response_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::update_progress(&mut self, f32)
|
||||
pub type rns_link::request::ProgressCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::request::RequestCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send)>
|
||||
@@ -0,0 +1,624 @@
|
||||
pub mod rns_protocol
|
||||
pub mod rns_protocol::buffer
|
||||
pub enum rns_protocol::buffer::BufferError
|
||||
pub rns_protocol::buffer::BufferError::WriterClosed
|
||||
pub struct rns_protocol::buffer::ChannelBuffer
|
||||
impl rns_protocol::buffer::ChannelBuffer
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::available(&self) -> usize
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::close_writer(&mut self) -> rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::drain_and_close_writer(&mut self) -> rns_protocol::buffer::DrainClose
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::feed_reader(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::is_done(&self) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::is_writer_closed(&self) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::new(u16, usize) -> Self
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::stream_id(&self) -> u16
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
|
||||
pub struct rns_protocol::buffer::DrainClose
|
||||
pub rns_protocol::buffer::DrainClose::eof_message: rns_protocol::stream_data::StreamDataMessage
|
||||
pub struct rns_protocol::buffer::StreamReader
|
||||
impl rns_protocol::buffer::StreamReader
|
||||
pub fn rns_protocol::buffer::StreamReader::available(&self) -> usize
|
||||
pub fn rns_protocol::buffer::StreamReader::feed(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::is_done(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::is_eof(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::new(u16) -> Self
|
||||
pub fn rns_protocol::buffer::StreamReader::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::StreamReader::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub struct rns_protocol::buffer::StreamWriter
|
||||
impl rns_protocol::buffer::StreamWriter
|
||||
pub fn rns_protocol::buffer::StreamWriter::close(&mut self) -> rns_protocol::buffer::DrainClose
|
||||
pub fn rns_protocol::buffer::StreamWriter::close_simple(&mut self) -> rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::buffer::StreamWriter::is_closed(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamWriter::new(u16, usize) -> Self
|
||||
pub fn rns_protocol::buffer::StreamWriter::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
|
||||
pub const rns_protocol::buffer::COMPRESSION_TRIES: usize
|
||||
pub const rns_protocol::buffer::MAX_CHUNK_LEN: usize
|
||||
pub mod rns_protocol::channel
|
||||
pub enum rns_protocol::channel::ChannelError
|
||||
pub rns_protocol::channel::ChannelError::ChannelClosed
|
||||
pub rns_protocol::channel::ChannelError::InvalidEnvelope
|
||||
pub rns_protocol::channel::ChannelError::InvalidMessageType(u16)
|
||||
pub rns_protocol::channel::ChannelError::MaxRetriesExceeded
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge::actual: usize
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge::max: usize
|
||||
pub rns_protocol::channel::ChannelError::NotReady
|
||||
pub rns_protocol::channel::ChannelError::UnknownMessageType(u16)
|
||||
pub struct rns_protocol::channel::Channel
|
||||
pub rns_protocol::channel::Channel::active: bool
|
||||
pub rns_protocol::channel::Channel::window: rns_protocol::channel::ChannelWindow
|
||||
impl rns_protocol::channel::Channel
|
||||
pub fn rns_protocol::channel::Channel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
|
||||
pub fn rns_protocol::channel::Channel::channel_mdu(usize) -> usize
|
||||
pub fn rns_protocol::channel::Channel::clear_message_handlers(&mut self)
|
||||
pub fn rns_protocol::channel::Channel::compute_timeout(&self, usize) -> f64
|
||||
pub fn rns_protocol::channel::Channel::delivered(&mut self, u16, f64)
|
||||
pub fn rns_protocol::channel::Channel::is_drained(&self) -> bool
|
||||
pub fn rns_protocol::channel::Channel::is_ready_to_send(&self) -> bool
|
||||
pub fn rns_protocol::channel::Channel::new(f64) -> Self
|
||||
pub fn rns_protocol::channel::Channel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_protocol::channel::Channel::outstanding_count(&self) -> usize
|
||||
pub fn rns_protocol::channel::Channel::receive(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::register_system_type(&mut self, u16)
|
||||
pub fn rns_protocol::channel::Channel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
|
||||
pub fn rns_protocol::channel::Channel::send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<(u16, alloc::vec::Vec<u8>), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::shutdown(&mut self)
|
||||
pub fn rns_protocol::channel::Channel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::Channel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::update_rtt(&mut self, f64)
|
||||
pub struct rns_protocol::channel::ChannelWindow
|
||||
pub rns_protocol::channel::ChannelWindow::fast_rate_rounds: usize
|
||||
pub rns_protocol::channel::ChannelWindow::medium_rate_rounds: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_flexibility: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_max: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_min: usize
|
||||
impl rns_protocol::channel::ChannelWindow
|
||||
pub fn rns_protocol::channel::ChannelWindow::grow(&mut self, f64)
|
||||
pub fn rns_protocol::channel::ChannelWindow::new(f64) -> Self
|
||||
pub fn rns_protocol::channel::ChannelWindow::shrink(&mut self)
|
||||
pub struct rns_protocol::channel::Envelope
|
||||
pub rns_protocol::channel::Envelope::msg_type: u16
|
||||
pub rns_protocol::channel::Envelope::packed: bool
|
||||
pub rns_protocol::channel::Envelope::raw: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::channel::Envelope::sequence: u16
|
||||
pub rns_protocol::channel::Envelope::state: rns_protocol::channel_message::MessageState
|
||||
pub rns_protocol::channel::Envelope::tries: usize
|
||||
impl rns_protocol::channel::Envelope
|
||||
pub fn rns_protocol::channel::Envelope::pack(&dyn rns_protocol::channel_message::MessageBase, u16) -> Self
|
||||
pub fn rns_protocol::channel::Envelope::payload(&self) -> &[u8]
|
||||
pub fn rns_protocol::channel::Envelope::unpack(&[u8]) -> core::result::Result<Self, rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::channel::HandlerId(_)
|
||||
pub struct rns_protocol::channel::LinkChannel
|
||||
impl rns_protocol::channel::LinkChannel
|
||||
pub fn rns_protocol::channel::LinkChannel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
|
||||
pub fn rns_protocol::channel::LinkChannel::clear_message_handlers(&mut self)
|
||||
pub fn rns_protocol::channel::LinkChannel::delivered(&mut self, u16, f64)
|
||||
pub fn rns_protocol::channel::LinkChannel::delivered_by_packet_hash(&mut self, &[u8; 32], f64) -> core::option::Option<u16>
|
||||
pub fn rns_protocol::channel::LinkChannel::is_active(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::is_drained(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::is_ready_to_send(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::link_id(&self) -> &[u8; 16]
|
||||
pub fn rns_protocol::channel::LinkChannel::mdu(&self) -> usize
|
||||
pub fn rns_protocol::channel::LinkChannel::new([u8; 16], f64) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_encrypted([u8; 16], f64, rns_link::key_derivation::LinkKeys) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_encrypted_with_mdu([u8; 16], f64, usize, rns_link::key_derivation::LinkKeys) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_with_mdu([u8; 16], f64, usize) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_protocol::channel::LinkChannel::outstanding_count(&self) -> usize
|
||||
pub fn rns_protocol::channel::LinkChannel::prepare_send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::prepare_send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<rns_protocol::channel::PreparedChannelData, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::receive_data(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::register_system_type(&mut self, u16)
|
||||
pub fn rns_protocol::channel::LinkChannel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::shutdown(&mut self)
|
||||
pub fn rns_protocol::channel::LinkChannel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::LinkChannel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::track_outbound_packet_hash(&mut self, [u8; 32], u16)
|
||||
pub fn rns_protocol::channel::LinkChannel::update_rtt(&mut self, f64)
|
||||
pub struct rns_protocol::channel::PreparedChannelData
|
||||
pub rns_protocol::channel::PreparedChannelData::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::channel::PreparedChannelData::sequence: u16
|
||||
pub const rns_protocol::channel::ENVELOPE_HEADER_SIZE: usize
|
||||
pub const rns_protocol::channel::FAST_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::channel::MAX_TRIES: usize
|
||||
pub const rns_protocol::channel::MIN_TIMEOUT_BASE: f64
|
||||
pub const rns_protocol::channel::RTT_FAST: f64
|
||||
pub const rns_protocol::channel::RTT_MEDIUM: f64
|
||||
pub const rns_protocol::channel::RTT_SLOW: f64
|
||||
pub const rns_protocol::channel::SEQ_MAX: u16
|
||||
pub const rns_protocol::channel::SEQ_MODULUS: u32
|
||||
pub const rns_protocol::channel::WINDOW_FLEXIBILITY: usize
|
||||
pub const rns_protocol::channel::WINDOW_INITIAL: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_FAST: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_MEDIUM: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_SLOW: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_FAST: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_MEDIUM: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_SLOW: usize
|
||||
pub type rns_protocol::channel::MessageCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(u16, &[u8]) -> bool + core::marker::Send)>
|
||||
pub mod rns_protocol::channel_message
|
||||
pub enum rns_protocol::channel_message::ChannelMessageError
|
||||
pub rns_protocol::channel_message::ChannelMessageError::InvalidType
|
||||
pub rns_protocol::channel_message::ChannelMessageError::TooShort
|
||||
pub rns_protocol::channel_message::ChannelMessageError::UnpackFailed
|
||||
pub enum rns_protocol::channel_message::MessageState
|
||||
pub rns_protocol::channel_message::MessageState::Delivered
|
||||
pub rns_protocol::channel_message::MessageState::Failed
|
||||
pub rns_protocol::channel_message::MessageState::New
|
||||
pub rns_protocol::channel_message::MessageState::Sent
|
||||
pub const rns_protocol::channel_message::SMT_STREAM_DATA: u16
|
||||
pub const rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN: u16
|
||||
pub trait rns_protocol::channel_message::MessageBase: core::marker::Send
|
||||
pub fn rns_protocol::channel_message::MessageBase::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::channel_message::MessageBase::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::channel_message::MessageBase::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
|
||||
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub mod rns_protocol::compression
|
||||
pub enum rns_protocol::compression::CompressionError
|
||||
pub rns_protocol::compression::CompressionError::CompressFailed
|
||||
pub rns_protocol::compression::CompressionError::DecompressFailed
|
||||
pub rns_protocol::compression::CompressionError::DecompressedTooLarge
|
||||
pub const rns_protocol::compression::AUTO_COMPRESS_MAX_SIZE: usize
|
||||
pub fn rns_protocol::compression::bz2_compress(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
|
||||
pub fn rns_protocol::compression::bz2_decompress(&[u8], usize) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
|
||||
pub fn rns_protocol::compression::try_compress(&[u8]) -> (alloc::vec::Vec<u8>, bool)
|
||||
pub mod rns_protocol::resource
|
||||
pub enum rns_protocol::resource::CancelType
|
||||
pub rns_protocol::resource::CancelType::Icl
|
||||
pub rns_protocol::resource::CancelType::Rcl
|
||||
pub enum rns_protocol::resource::ResourceError
|
||||
pub rns_protocol::resource::ResourceError::Corrupt
|
||||
pub rns_protocol::resource::ResourceError::DecompressionFailed
|
||||
pub rns_protocol::resource::ResourceError::DecryptFailed
|
||||
pub rns_protocol::resource::ResourceError::DuplicateSegment
|
||||
pub rns_protocol::resource::ResourceError::HashMismatch
|
||||
pub rns_protocol::resource::ResourceError::Incomplete
|
||||
pub rns_protocol::resource::ResourceError::InvalidAdvertisement
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata::available: usize
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata::declared: usize
|
||||
pub rns_protocol::resource::ResourceError::MapHashCollision
|
||||
pub rns_protocol::resource::ResourceError::MetadataTooLarge
|
||||
pub rns_protocol::resource::ResourceError::TooLarge
|
||||
#[repr(u8)] pub enum rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::ResourceState::Advertised = 2
|
||||
pub rns_protocol::resource::ResourceState::Assembling = 5
|
||||
pub rns_protocol::resource::ResourceState::AwaitingProof = 4
|
||||
pub rns_protocol::resource::ResourceState::Complete = 6
|
||||
pub rns_protocol::resource::ResourceState::Corrupt = 8
|
||||
pub rns_protocol::resource::ResourceState::Failed = 7
|
||||
pub rns_protocol::resource::ResourceState::None = 0
|
||||
pub rns_protocol::resource::ResourceState::Queued = 1
|
||||
pub rns_protocol::resource::ResourceState::Rejected = 9
|
||||
pub rns_protocol::resource::ResourceState::Transferring = 3
|
||||
pub enum rns_protocol::resource::TransferAction
|
||||
pub rns_protocol::resource::TransferAction::Complete
|
||||
pub rns_protocol::resource::TransferAction::Failed(alloc::string::String)
|
||||
pub rns_protocol::resource::TransferAction::None
|
||||
pub rns_protocol::resource::TransferAction::SendAdvertisement(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendCancel(rns_protocol::resource::CancelType, [u8; 32])
|
||||
pub rns_protocol::resource::TransferAction::SendHmu(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendPart(usize, alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendProof(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendRequest(alloc::vec::Vec<u8>)
|
||||
pub struct rns_protocol::resource::InboundResource
|
||||
pub rns_protocol::resource::InboundResource::consecutive_completed: usize
|
||||
pub rns_protocol::resource::InboundResource::data_size: usize
|
||||
pub rns_protocol::resource::InboundResource::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::InboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
|
||||
pub rns_protocol::resource::InboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::InboundResource::parts: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::InboundResource::random_hash: [u8; 4]
|
||||
pub rns_protocol::resource::InboundResource::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource::InboundResource::sdu: usize
|
||||
pub rns_protocol::resource::InboundResource::state: rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::InboundResource::total_parts: usize
|
||||
pub rns_protocol::resource::InboundResource::total_size: usize
|
||||
pub rns_protocol::resource::InboundResource::window: rns_protocol::resource::WindowState
|
||||
impl rns_protocol::resource::InboundResource
|
||||
pub fn rns_protocol::resource::InboundResource::assemble(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundResource::generate_proof(&self, &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource::InboundResource::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::InboundResource::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::InboundResource::new(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::InboundResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::InboundResource::received_count(&self) -> usize
|
||||
pub fn rns_protocol::resource::InboundResource::with_sdu(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::option::Option<usize>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::InboundTransfer
|
||||
pub rns_protocol::resource::InboundTransfer::accepted: bool
|
||||
pub rns_protocol::resource::InboundTransfer::eifr: core::option::Option<f64>
|
||||
pub rns_protocol::resource::InboundTransfer::hashmap_height: usize
|
||||
pub rns_protocol::resource::InboundTransfer::last_activity: std::time::Instant
|
||||
pub rns_protocol::resource::InboundTransfer::outstanding_parts: usize
|
||||
pub rns_protocol::resource::InboundTransfer::part_timeout_factor: f64
|
||||
pub rns_protocol::resource::InboundTransfer::parts_since_hmu: usize
|
||||
pub rns_protocol::resource::InboundTransfer::previous_eifr: core::option::Option<f64>
|
||||
pub rns_protocol::resource::InboundTransfer::req_data_rtt_rate: f64
|
||||
pub rns_protocol::resource::InboundTransfer::req_resp: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::InboundTransfer::req_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::InboundTransfer::resource: rns_protocol::resource::InboundResource
|
||||
pub rns_protocol::resource::InboundTransfer::retries_left: usize
|
||||
pub rns_protocol::resource::InboundTransfer::rtt: core::time::Duration
|
||||
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes: usize
|
||||
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes_at_part_req: usize
|
||||
pub rns_protocol::resource::InboundTransfer::started_at: std::time::Instant
|
||||
pub rns_protocol::resource::InboundTransfer::waiting_for_hmu: bool
|
||||
impl rns_protocol::resource::InboundTransfer
|
||||
pub fn rns_protocol::resource::InboundTransfer::cancel(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::complete(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(alloc::vec::Vec<u8>, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundTransfer::create_hmu(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource::InboundTransfer::from_advertisement(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundTransfer::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::InboundTransfer::hashmap_update(&mut self, usize, &[u8]) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::InboundTransfer::receive_part(&mut self, alloc::vec::Vec<u8>) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::request_next(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::seed_previous_eifr(&mut self, f64)
|
||||
pub fn rns_protocol::resource::InboundTransfer::update_eifr(&mut self)
|
||||
pub struct rns_protocol::resource::LazyMultiSegmentOutbound
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::data_size: usize
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::total_segments: usize
|
||||
impl rns_protocol::resource::LazyMultiSegmentOutbound
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::next_segment(&mut self, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<core::option::Option<rns_protocol::resource::OutboundResource>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::remaining_segments(&self) -> usize
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::LinkResource
|
||||
pub rns_protocol::resource::LinkResource::inbound: core::option::Option<rns_protocol::resource::InboundResource>
|
||||
pub rns_protocol::resource::LinkResource::link_id: [u8; 16]
|
||||
pub rns_protocol::resource::LinkResource::outbound: core::option::Option<rns_protocol::resource::OutboundResource>
|
||||
pub rns_protocol::resource::LinkResource::session_keys: core::option::Option<rns_link::key_derivation::LinkKeys>
|
||||
impl rns_protocol::resource::LinkResource
|
||||
pub fn rns_protocol::resource::LinkResource::assemble(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::new_inbound([u8; 16], usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::new_outbound([u8; 16], alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::new_outbound_encrypted([u8; 16], alloc::vec::Vec<u8>, bool, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::next_part(&self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::resource::LinkResource::num_parts(&self) -> usize
|
||||
pub fn rns_protocol::resource::LinkResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::LinkResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub struct rns_protocol::resource::MultiSegmentInbound
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_segments: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::MultiSegmentInbound::segments: alloc::vec::Vec<core::option::Option<rns_protocol::resource::InboundResource>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::total_segments: usize
|
||||
impl rns_protocol::resource::MultiSegmentInbound
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::assemble_segment(&mut self, usize, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::assembled_count(&self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::new(usize, [u8; 32]) -> Self
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::reassemble(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_metadata(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment(&mut self, usize, rns_protocol::resource::InboundResource)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment_data(&mut self, usize, alloc::vec::Vec<u8>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::MultiSegmentOutbound
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::segments: alloc::vec::Vec<rns_protocol::resource::OutboundResource>
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::total_segments: usize
|
||||
impl rns_protocol::resource::MultiSegmentOutbound
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::cancel_all(&mut self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment(&self, usize) -> core::option::Option<&rns_protocol::resource::OutboundResource>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment_mut(&mut self, usize) -> core::option::Option<&mut rns_protocol::resource::OutboundResource>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::num_segments(&self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::with_encrypt(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::OutboundResource
|
||||
pub rns_protocol::resource::OutboundResource::advertisement_data_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource::OutboundResource::expected_proof: [u8; 32]
|
||||
pub rns_protocol::resource::OutboundResource::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::OutboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
|
||||
pub rns_protocol::resource::OutboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::metadata_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::original_hash: core::option::Option<[u8; 32]>
|
||||
pub rns_protocol::resource::OutboundResource::parts: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::random_hash: [u8; 4]
|
||||
pub rns_protocol::resource::OutboundResource::request_id: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource::OutboundResource::retries: usize
|
||||
pub rns_protocol::resource::OutboundResource::sdu: usize
|
||||
pub rns_protocol::resource::OutboundResource::segment_index: usize
|
||||
pub rns_protocol::resource::OutboundResource::state: rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::OutboundResource::total_segments: usize
|
||||
pub rns_protocol::resource::OutboundResource::total_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::window: rns_protocol::resource::WindowState
|
||||
impl rns_protocol::resource::OutboundResource
|
||||
pub fn rns_protocol::resource::OutboundResource::get_part(&self, usize) -> core::option::Option<&[u8]>
|
||||
pub fn rns_protocol::resource::OutboundResource::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::OutboundResource::handle_hmu(&mut self, &[u8]) -> alloc::vec::Vec<usize>
|
||||
pub fn rns_protocol::resource::OutboundResource::new(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundResource::num_parts(&self) -> usize
|
||||
pub fn rns_protocol::resource::OutboundResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub fn rns_protocol::resource::OutboundResource::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<usize>, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::OutboundTransfer
|
||||
pub rns_protocol::resource::OutboundTransfer::advertised: bool
|
||||
pub rns_protocol::resource::OutboundTransfer::awaiting_hmu: bool
|
||||
pub rns_protocol::resource::OutboundTransfer::confirmed_parts: alloc::vec::Vec<bool>
|
||||
pub rns_protocol::resource::OutboundTransfer::cursor: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::last_part_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::OutboundTransfer::receiver_min_consecutive_height: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::resource: rns_protocol::resource::OutboundResource
|
||||
pub rns_protocol::resource::OutboundTransfer::retries: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::rtt: core::time::Duration
|
||||
pub rns_protocol::resource::OutboundTransfer::sent_parts: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::started_at: std::time::Instant
|
||||
pub rns_protocol::resource::OutboundTransfer::window_cursor: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::window_max_sent: usize
|
||||
impl rns_protocol::resource::OutboundTransfer
|
||||
pub fn rns_protocol::resource::OutboundTransfer::all_confirmed(&self) -> bool
|
||||
pub fn rns_protocol::resource::OutboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::OutboundTransfer::from_prebuilt(rns_protocol::resource::OutboundResource, core::time::Duration) -> Self
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_hmu(&mut self, &[u8])
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_proof(&mut self, &[u8]) -> bool
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_request(&mut self, &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_request_packet(&mut self, [u8; 32], &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::new(alloc::vec::Vec<u8>, bool, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::new_encrypted(alloc::vec::Vec<u8>, bool, core::time::Duration, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::OutboundTransfer::tick(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::OutboundTransfer::timeout_window(&self) -> core::option::Option<(std::time::Instant, core::time::Duration)>
|
||||
pub struct rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::ResourceFlags::compressed: bool
|
||||
pub rns_protocol::resource::ResourceFlags::encrypted: bool
|
||||
pub rns_protocol::resource::ResourceFlags::has_metadata: bool
|
||||
pub rns_protocol::resource::ResourceFlags::is_request: bool
|
||||
pub rns_protocol::resource::ResourceFlags::is_response: bool
|
||||
pub rns_protocol::resource::ResourceFlags::split: bool
|
||||
impl rns_protocol::resource::ResourceFlags
|
||||
pub fn rns_protocol::resource::ResourceFlags::from_byte(u8) -> Self
|
||||
pub fn rns_protocol::resource::ResourceFlags::to_byte(&self) -> u8
|
||||
pub struct rns_protocol::resource::WindowState
|
||||
pub rns_protocol::resource::WindowState::fast_rate_rounds: usize
|
||||
pub rns_protocol::resource::WindowState::very_slow_rate_rounds: usize
|
||||
pub rns_protocol::resource::WindowState::window: usize
|
||||
pub rns_protocol::resource::WindowState::window_max: usize
|
||||
pub rns_protocol::resource::WindowState::window_min: usize
|
||||
impl rns_protocol::resource::WindowState
|
||||
pub fn rns_protocol::resource::WindowState::grow(&mut self, usize)
|
||||
pub fn rns_protocol::resource::WindowState::new() -> Self
|
||||
pub fn rns_protocol::resource::WindowState::shrink(&mut self)
|
||||
impl core::default::Default for rns_protocol::resource::WindowState
|
||||
pub fn rns_protocol::resource::WindowState::default() -> Self
|
||||
pub const rns_protocol::resource::EIFR_COLD_START_BYTES: usize
|
||||
pub const rns_protocol::resource::FAST_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::resource::HASHMAP_IS_EXHAUSTED: u8
|
||||
pub const rns_protocol::resource::HASHMAP_IS_NOT_EXHAUSTED: u8
|
||||
pub const rns_protocol::resource::HMU_WAIT_FACTOR: f64
|
||||
pub const rns_protocol::resource::MAPHASH_LEN: usize
|
||||
pub const rns_protocol::resource::MAX_ADV_RETRIES: usize
|
||||
pub const rns_protocol::resource::MAX_EFFICIENT_SIZE: usize
|
||||
pub const rns_protocol::resource::MAX_RESOURCE_SIZE: usize
|
||||
pub const rns_protocol::resource::MAX_RETRIES: usize
|
||||
pub const rns_protocol::resource::MAX_SEGMENTS: usize
|
||||
pub const rns_protocol::resource::METADATA_MAX_SIZE: usize
|
||||
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR: f64
|
||||
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR_AFTER_RTT: f64
|
||||
pub const rns_protocol::resource::PER_RETRY_DELAY: f64
|
||||
pub const rns_protocol::resource::PROCESSING_GRACE: f64
|
||||
pub const rns_protocol::resource::PROOF_TIMEOUT_FACTOR: f64
|
||||
pub const rns_protocol::resource::RANDOM_HASH_SIZE: usize
|
||||
pub const rns_protocol::resource::RATE_FAST: usize
|
||||
pub const rns_protocol::resource::RATE_VERY_SLOW: usize
|
||||
pub const rns_protocol::resource::RETRY_GRACE_TIME: f64
|
||||
pub const rns_protocol::resource::SDU: usize
|
||||
pub const rns_protocol::resource::SENDER_GRACE_TIME: f64
|
||||
pub const rns_protocol::resource::VERY_SLOW_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::resource::WATCHDOG_MAX_SLEEP: f64
|
||||
pub const rns_protocol::resource::WINDOW_FLEXIBILITY: usize
|
||||
pub const rns_protocol::resource::WINDOW_INITIAL: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_FAST: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_SLOW: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_VERY_SLOW: usize
|
||||
pub const rns_protocol::resource::WINDOW_MIN: usize
|
||||
pub fn rns_protocol::resource::compute_expected_proof(&[u8], &[u8; 32]) -> [u8; 32]
|
||||
pub fn rns_protocol::resource::compute_resource_hash(&[u8], &[u8]) -> [u8; 32]
|
||||
pub fn rns_protocol::resource::get_map_hash(&[u8], &[u8]) -> [u8; 4]
|
||||
pub fn rns_protocol::resource::parse_hashmap_update(&[u8]) -> core::result::Result<([u8; 32], usize, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
|
||||
pub type rns_protocol::resource::ResourceDecryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError> + 'a)
|
||||
pub type rns_protocol::resource::ResourceEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> alloc::vec::Vec<u8> + 'a)
|
||||
pub mod rns_protocol::resource_adv
|
||||
pub struct rns_protocol::resource_adv::ResourceAdvertisement
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::data_size: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::hashmap: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::metadata_size: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::num_parts: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::random_hash: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::request_id: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::segment_index: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::total_segments: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::transfer_size: usize
|
||||
impl rns_protocol::resource_adv::ResourceAdvertisement
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::get_map_hashes(&self) -> alloc::vec::Vec<[u8; 4]>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::new(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize) -> Self
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::unpack(&[u8]) -> core::result::Result<Self, alloc::string::String>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::with_metadata_size(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize, usize) -> Self
|
||||
pub const rns_protocol::resource_adv::OVERHEAD: usize
|
||||
pub fn rns_protocol::resource_adv::collision_guard_size(usize) -> usize
|
||||
pub fn rns_protocol::resource_adv::hashmap_max_len(usize) -> usize
|
||||
pub mod rns_protocol::rnsh
|
||||
pub enum rns_protocol::rnsh::RnshCodecError
|
||||
pub rns_protocol::rnsh::RnshCodecError::Decode(alloc::string::String)
|
||||
pub rns_protocol::rnsh::RnshCodecError::Encode(alloc::string::String)
|
||||
pub rns_protocol::rnsh::RnshCodecError::InvalidShape(&'static str)
|
||||
pub rns_protocol::rnsh::RnshCodecError::InvalidUtf8
|
||||
pub rns_protocol::rnsh::RnshCodecError::StreamData
|
||||
pub rns_protocol::rnsh::RnshCodecError::UnknownMessageType(u16)
|
||||
pub enum rns_protocol::rnsh::RnshMessage
|
||||
pub rns_protocol::rnsh::RnshMessage::CommandExited(rns_protocol::rnsh::CommandExitedMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::Error(rns_protocol::rnsh::ErrorMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::ExecuteCommand(rns_protocol::rnsh::ExecuteCommandMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::Noop(rns_protocol::rnsh::NoopMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::StreamData(rns_protocol::rnsh::RnshStreamDataMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::VersionInfo(rns_protocol::rnsh::VersionInfoMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::WindowSize(rns_protocol::rnsh::WindowSizeMessage)
|
||||
impl rns_protocol::rnsh::RnshMessage
|
||||
pub fn rns_protocol::rnsh::RnshMessage::decode(u16, &[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
pub fn rns_protocol::rnsh::RnshMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub struct rns_protocol::rnsh::CommandExitedMessage
|
||||
pub rns_protocol::rnsh::CommandExitedMessage::return_code: i64
|
||||
impl rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::new(i64) -> Self
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::ErrorMessage
|
||||
pub rns_protocol::rnsh::ErrorMessage::data: core::option::Option<rmpv::Value>
|
||||
pub rns_protocol::rnsh::ErrorMessage::fatal: bool
|
||||
pub rns_protocol::rnsh::ErrorMessage::msg: core::option::Option<alloc::string::String>
|
||||
impl rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::new(core::option::Option<alloc::string::String>, bool, core::option::Option<rmpv::Value>) -> Self
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::cmdline: core::option::Option<alloc::vec::Vec<alloc::string::String>>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::cols: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::hpix: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stderr: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdin: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdout: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::rows: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::tcflags: core::option::Option<rmpv::Value>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::term: core::option::Option<alloc::string::String>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::vpix: core::option::Option<u32>
|
||||
impl rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::new(core::option::Option<alloc::vec::Vec<alloc::string::String>>, bool, bool, bool, core::option::Option<rmpv::Value>, core::option::Option<alloc::string::String>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::NoopMessage
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
|
||||
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::compressed: bool
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::eof: bool
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::stream_id: u16
|
||||
impl rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl core::default::Default for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::default() -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::VersionInfoMessage
|
||||
pub rns_protocol::rnsh::VersionInfoMessage::protocol_version: u64
|
||||
pub rns_protocol::rnsh::VersionInfoMessage::sw_version: alloc::string::String
|
||||
impl rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::new(impl core::convert::Into<alloc::string::String>) -> Self
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl core::default::Default for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::default() -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::WindowSizeMessage
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::cols: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::hpix: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::rows: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::vpix: core::option::Option<u32>
|
||||
impl rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::new(core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub const rns_protocol::rnsh::MESSAGE_TYPES: [u16; 7]
|
||||
pub const rns_protocol::rnsh::MSG_MAGIC: u8
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_COMMAND_EXITED: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_ERROR: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_EXECUTE_COMMAND: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_NOOP: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_STREAM_DATA: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_VERSION_INFO: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_WINDOW_SIZE: u16
|
||||
pub const rns_protocol::rnsh::PROTOCOL_VERSION: u64
|
||||
pub const rns_protocol::rnsh::STREAM_DATA_OVERHEAD: usize
|
||||
pub const rns_protocol::rnsh::STREAM_ID_MAX: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDERR: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDIN: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDOUT: u16
|
||||
pub const fn rns_protocol::rnsh::make_msg_type(u8) -> u16
|
||||
pub mod rns_protocol::stream_data
|
||||
pub struct rns_protocol::stream_data::StreamDataMessage
|
||||
pub rns_protocol::stream_data::StreamDataMessage::compressed: bool
|
||||
pub rns_protocol::stream_data::StreamDataMessage::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::stream_data::StreamDataMessage::eof: bool
|
||||
pub rns_protocol::stream_data::StreamDataMessage::stream_id: u16
|
||||
impl rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub const rns_protocol::stream_data::OVERHEAD: usize
|
||||
pub const rns_protocol::stream_data::STREAM_ID_MAX: u16
|
||||
@@ -0,0 +1,618 @@
|
||||
pub mod rns_ratkey
|
||||
pub mod rns_ratkey::apdu
|
||||
pub const rns_ratkey::apdu::ALG_ECCP256: u8
|
||||
pub const rns_ratkey::apdu::ALG_ECCP384: u8
|
||||
pub const rns_ratkey::apdu::ALG_ED25519: u8
|
||||
pub const rns_ratkey::apdu::ALG_X25519: u8
|
||||
pub const rns_ratkey::apdu::INS_ATTEST: u8
|
||||
pub const rns_ratkey::apdu::INS_CHANGE_REFERENCE: u8
|
||||
pub const rns_ratkey::apdu::INS_GENERAL_AUTHENTICATE: u8
|
||||
pub const rns_ratkey::apdu::INS_GENERATE_ASYMMETRIC: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_DATA: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_METADATA: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_SERIAL: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_VERSION: u8
|
||||
pub const rns_ratkey::apdu::INS_IMPORT_KEY: u8
|
||||
pub const rns_ratkey::apdu::INS_RESET_PIV: u8
|
||||
pub const rns_ratkey::apdu::INS_RESET_RETRY: u8
|
||||
pub const rns_ratkey::apdu::INS_SELECT: u8
|
||||
pub const rns_ratkey::apdu::INS_VERIFY: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES128: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES192: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES256: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_TDES: u8
|
||||
pub const rns_ratkey::apdu::OBJ_ID_9A: &[u8]
|
||||
pub const rns_ratkey::apdu::OBJ_ID_9D: &[u8]
|
||||
pub const rns_ratkey::apdu::OBJ_ID_F9: &[u8]
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_ALWAYS: u8
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_NEVER: u8
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_ONCE: u8
|
||||
pub const rns_ratkey::apdu::PIV_AID: &[u8]
|
||||
pub const rns_ratkey::apdu::SLOT_ATTESTATION: u8
|
||||
pub const rns_ratkey::apdu::SLOT_AUTHENTICATION: u8
|
||||
pub const rns_ratkey::apdu::SLOT_CARD_AUTH: u8
|
||||
pub const rns_ratkey::apdu::SLOT_CARD_MANAGEMENT: u8
|
||||
pub const rns_ratkey::apdu::SLOT_KEY_MANAGEMENT: u8
|
||||
pub const rns_ratkey::apdu::SLOT_SIGNATURE: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_ALWAYS: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_CACHED: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_NEVER: u8
|
||||
pub fn rns_ratkey::apdu::attest_key(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::auth_witness_request(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::auth_witness_response(u8, &[u8], &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::change_pin(&str, &str) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::check_response(&[u8]) -> core::result::Result<&[u8], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::ecdh_x25519(u8, &[u8; 32]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::generate_key(u8, u8, core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_data(u8) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::apdu::get_metadata(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_serial() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_version() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::import_ed25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::import_x25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::parse_auth_response(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_auth_witness(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_certificate_object(&[u8]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::apdu::parse_ecdh_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_generate_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_metadata_algorithm(&[u8]) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_metadata_public_key(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_serial_response(&[u8]) -> core::result::Result<u32, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_sign_response(&[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_version_response(&[u8]) -> core::result::Result<(u8, u8, u8), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::reset_piv() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::reset_retry(&str, &str) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::select_piv() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::sign_ed25519(u8, &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::slot_to_object_id(u8) -> core::option::Option<&'static [u8]>
|
||||
pub fn rns_ratkey::apdu::verify_pin(&str) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_ratkey::attestation
|
||||
pub struct rns_ratkey::attestation::AttestationInfo
|
||||
pub rns_ratkey::attestation::AttestationInfo::attestation_cert_der: alloc::vec::Vec<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::device_cert_der: alloc::vec::Vec<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::firmware_version: core::option::Option<(u8, u8, u8)>
|
||||
pub rns_ratkey::attestation::AttestationInfo::form_factor: core::option::Option<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::pin_policy: core::option::Option<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::serial_number: core::option::Option<u32>
|
||||
pub rns_ratkey::attestation::AttestationInfo::touch_policy: core::option::Option<u8>
|
||||
pub struct rns_ratkey::attestation::AttestationVerification
|
||||
pub rns_ratkey::attestation::AttestationVerification::chain_verified: bool
|
||||
pub rns_ratkey::attestation::AttestationVerification::description: alloc::string::String
|
||||
pub rns_ratkey::attestation::AttestationVerification::info: rns_ratkey::attestation::AttestationInfo
|
||||
pub rns_ratkey::attestation::AttestationVerification::metadata_extracted: bool
|
||||
pub rns_ratkey::attestation::AttestationVerification::root_ca: alloc::string::String
|
||||
pub rns_ratkey::attestation::AttestationVerification::verified: bool
|
||||
pub const rns_ratkey::attestation::OID_FIRMWARE_VERSION: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_FORM_FACTOR: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_SERIAL_NUMBER: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_USAGE_POLICY: &[u8]
|
||||
pub const rns_ratkey::attestation::YUBICO_ATTESTATION_ROOT_1_PEM: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_LEGACY_ROOT_SHA256: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_NEW_ROOT_SHA256: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str
|
||||
pub fn rns_ratkey::attestation::pem_to_der(&str) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::attestation::supports_attestation(&str) -> bool
|
||||
pub fn rns_ratkey::attestation::verify_attestation(&[u8], &[u8]) -> core::result::Result<rns_ratkey::attestation::AttestationVerification, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::backend
|
||||
pub struct rns_ratkey::backend::HardwareBackend
|
||||
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
|
||||
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
|
||||
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_ratkey::backend::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::detect
|
||||
pub enum rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::detect::DeviceType::Nitrokey3
|
||||
pub rns_ratkey::detect::DeviceType::Unknown
|
||||
pub rns_ratkey::detect::DeviceType::YubiKey5
|
||||
impl rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::detect::DeviceType::as_str(&self) -> &'static str
|
||||
pub struct rns_ratkey::detect::DeviceInfo
|
||||
pub rns_ratkey::detect::DeviceInfo::device_type: alloc::string::String
|
||||
pub rns_ratkey::detect::DeviceInfo::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::detect::DeviceInfo::has_encryption_key: bool
|
||||
pub rns_ratkey::detect::DeviceInfo::has_signing_key: bool
|
||||
pub rns_ratkey::detect::DeviceInfo::reader_name: alloc::string::String
|
||||
pub rns_ratkey::detect::DeviceInfo::serial: core::option::Option<u32>
|
||||
pub fn rns_ratkey::detect::detect_device_type(&str) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::detect::detect_devices() -> core::result::Result<alloc::vec::Vec<rns_ratkey::detect::DeviceInfo>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::detect::list_readers() -> core::result::Result<alloc::vec::Vec<alloc::string::String>, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::error
|
||||
pub enum rns_ratkey::error::RatkeyError
|
||||
pub rns_ratkey::error::RatkeyError::Apdu
|
||||
pub rns_ratkey::error::RatkeyError::Apdu::sw1: u8
|
||||
pub rns_ratkey::error::RatkeyError::Apdu::sw2: u8
|
||||
pub rns_ratkey::error::RatkeyError::Disconnected
|
||||
pub rns_ratkey::error::RatkeyError::EcdhFailed(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::EmptySlot
|
||||
pub rns_ratkey::error::RatkeyError::EmptySlot::slot: u8
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion::found: alloc::string::String
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion::required: alloc::string::String
|
||||
pub rns_ratkey::error::RatkeyError::InvalidHwid(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::Io(core::io::error::Error)
|
||||
pub rns_ratkey::error::RatkeyError::KeyMismatch
|
||||
pub rns_ratkey::error::RatkeyError::ManagementAuthFailed
|
||||
pub rns_ratkey::error::RatkeyError::NoDevice
|
||||
pub rns_ratkey::error::RatkeyError::Pcsc(pcsc::Error)
|
||||
pub rns_ratkey::error::RatkeyError::PinFailed
|
||||
pub rns_ratkey::error::RatkeyError::PinFailed::remaining: u8
|
||||
pub rns_ratkey::error::RatkeyError::PinLocked
|
||||
pub rns_ratkey::error::RatkeyError::PinRequired
|
||||
pub rns_ratkey::error::RatkeyError::PukFailed
|
||||
pub rns_ratkey::error::RatkeyError::PukFailed::remaining: u8
|
||||
pub rns_ratkey::error::RatkeyError::PukLocked
|
||||
pub rns_ratkey::error::RatkeyError::ResetRequiresBlockedPinAndPuk
|
||||
pub rns_ratkey::error::RatkeyError::SigningFailed(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::SlotOccupied
|
||||
pub rns_ratkey::error::RatkeyError::SlotOccupied::slot: u8
|
||||
pub rns_ratkey::error::RatkeyError::TouchRequired
|
||||
pub rns_ratkey::error::RatkeyError::UnsupportedDevice(alloc::string::String)
|
||||
pub mod rns_ratkey::hardware
|
||||
pub struct rns_ratkey::hardware::HardwareIdentity
|
||||
pub rns_ratkey::hardware::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::hardware::HardwareIdentity::identity: rns_identity::identity::Identity
|
||||
impl rns_ratkey::hardware::HardwareIdentity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
|
||||
pub trait rns_ratkey::hardware::IdentityBackend
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::hwid
|
||||
pub struct rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::hwid::HwidApp::app_hash: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::hwid::HwidAttestation::ed25519_cert: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidAttestation::verified: bool
|
||||
pub rns_ratkey::hwid::HwidAttestation::x25519_cert: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::hwid::HwidBackup::backup_serial: core::option::Option<u32>
|
||||
pub rns_ratkey::hwid::HwidBackup::encrypted_backup_hash: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::hwid::HwidBackup::tier: u8
|
||||
pub struct rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::hwid::HwidConfig::app: rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::hwid::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::hwid::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::hwid::HwidConfig::device: rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::hwid::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::hwid::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::hwid::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::hwid::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
|
||||
impl rns_ratkey::hwid::HwidConfig
|
||||
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
|
||||
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
|
||||
pub struct rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::hwid::HwidDevice::device_type: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidDevice::firmware: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidDevice::serial: u32
|
||||
pub struct rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::hwid::HwidIdentity::created_at: u64
|
||||
pub rns_ratkey::hwid::HwidIdentity::hash: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidIdentity::nickname: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::hwid::HwidKeys::ed25519_pub: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidKeys::x25519_pub: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::hwid::HwidPolicy::pin_cache_timeout: u64
|
||||
pub rns_ratkey::hwid::HwidPolicy::touch_encryption: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidPolicy::touch_signing: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidSlots
|
||||
pub rns_ratkey::hwid::HwidSlots::encryption: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidSlots::signing: alloc::string::String
|
||||
pub mod rns_ratkey::mgmt
|
||||
pub fn rns_ratkey::mgmt::block_len(u8) -> core::option::Option<usize>
|
||||
pub fn rns_ratkey::mgmt::ecb_decrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mgmt::ecb_encrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mgmt::key_len(u8) -> core::option::Option<usize>
|
||||
pub mod rns_ratkey::mock
|
||||
pub enum rns_ratkey::mock::MockOperation
|
||||
pub rns_ratkey::mock::MockOperation::EcdhX25519
|
||||
pub rns_ratkey::mock::MockOperation::EcdhX25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::GenerateEd25519
|
||||
pub rns_ratkey::mock::MockOperation::GenerateEd25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::GenerateX25519
|
||||
pub rns_ratkey::mock::MockOperation::GenerateX25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::PinUnblock
|
||||
pub rns_ratkey::mock::MockOperation::PinUnblock::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::PinVerify
|
||||
pub rns_ratkey::mock::MockOperation::PinVerify::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::ReadPublicKey
|
||||
pub rns_ratkey::mock::MockOperation::ReadPublicKey::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::ResetPiv
|
||||
pub rns_ratkey::mock::MockOperation::ResetPiv::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519::data_len: usize
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519::slot: u8
|
||||
pub enum rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::mock::TouchPolicy::Always
|
||||
pub rns_ratkey::mock::TouchPolicy::Cached
|
||||
pub rns_ratkey::mock::TouchPolicy::Never
|
||||
pub struct rns_ratkey::mock::MockPivSession
|
||||
pub rns_ratkey::mock::MockPivSession::device_type: alloc::string::String
|
||||
pub rns_ratkey::mock::MockPivSession::firmware: alloc::string::String
|
||||
pub rns_ratkey::mock::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
|
||||
pub rns_ratkey::mock::MockPivSession::serial: u32
|
||||
impl rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
|
||||
impl core::default::Default for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub const rns_ratkey::mock::SLOT_9A: u8
|
||||
pub const rns_ratkey::mock::SLOT_9D: u8
|
||||
pub mod rns_ratkey::pin
|
||||
pub struct rns_ratkey::pin::PinCache
|
||||
impl rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
|
||||
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
|
||||
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
|
||||
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
|
||||
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
|
||||
pub mod rns_ratkey::provision
|
||||
pub struct rns_ratkey::provision::ProvisionConfig
|
||||
pub rns_ratkey::provision::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::provision::ProvisionConfig::nickname: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionConfig::pin: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::provision::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
|
||||
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
|
||||
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
|
||||
pub struct rns_ratkey::provision::ProvisionResult
|
||||
pub rns_ratkey::provision::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::provision::ProvisionResult::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::provision::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::provision::ProvisionResult::identity_hash: [u8; 16]
|
||||
pub rns_ratkey::provision::ProvisionResult::identity_hash_hex: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionResult::x25519_pub: [u8; 32]
|
||||
pub fn rns_ratkey::provision::compute_identity_hash(&[u8; 32], &[u8; 32]) -> [u8; 16]
|
||||
pub fn rns_ratkey::provision::import_recoverable_identity<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_hardware_only<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_mock(&mut rns_ratkey::mock::MockPivSession, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_recoverable<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<(rns_ratkey::provision::ProvisionResult, alloc::string::String), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::read_existing<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::restore<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::seed
|
||||
pub struct rns_ratkey::seed::DerivedIdentity
|
||||
pub rns_ratkey::seed::DerivedIdentity::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::ed25519_seed: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::x25519_pub: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::x25519_secret: [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_ratkey::seed::DerivedIdentity
|
||||
pub fn rns_ratkey::seed::DerivedIdentity::drop(&mut self)
|
||||
pub fn rns_ratkey::seed::derive_identity(&str) -> core::result::Result<rns_ratkey::seed::DerivedIdentity, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::seed::generate_mnemonic() -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::seed::validate_mnemonic(&str) -> bool
|
||||
pub mod rns_ratkey::session
|
||||
pub struct rns_ratkey::session::DeviceMeta
|
||||
pub rns_ratkey::session::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::session::DeviceMeta::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::session::DeviceMeta::serial: core::option::Option<u32>
|
||||
pub struct rns_ratkey::session::PivSession<T: rns_ratkey::transport::PivTransport>
|
||||
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub type rns_ratkey::session::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub mod rns_ratkey::transport
|
||||
pub struct rns_ratkey::transport::PcscTransport
|
||||
impl rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub trait rns_ratkey::transport::PivTransport
|
||||
pub fn rns_ratkey::transport::PivTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::transport::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub enum rns_ratkey::RatkeyError
|
||||
pub rns_ratkey::RatkeyError::Apdu
|
||||
pub rns_ratkey::RatkeyError::Apdu::sw1: u8
|
||||
pub rns_ratkey::RatkeyError::Apdu::sw2: u8
|
||||
pub rns_ratkey::RatkeyError::Disconnected
|
||||
pub rns_ratkey::RatkeyError::EcdhFailed(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::EmptySlot
|
||||
pub rns_ratkey::RatkeyError::EmptySlot::slot: u8
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion::found: alloc::string::String
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion::required: alloc::string::String
|
||||
pub rns_ratkey::RatkeyError::InvalidHwid(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::Io(core::io::error::Error)
|
||||
pub rns_ratkey::RatkeyError::KeyMismatch
|
||||
pub rns_ratkey::RatkeyError::ManagementAuthFailed
|
||||
pub rns_ratkey::RatkeyError::NoDevice
|
||||
pub rns_ratkey::RatkeyError::Pcsc(pcsc::Error)
|
||||
pub rns_ratkey::RatkeyError::PinFailed
|
||||
pub rns_ratkey::RatkeyError::PinFailed::remaining: u8
|
||||
pub rns_ratkey::RatkeyError::PinLocked
|
||||
pub rns_ratkey::RatkeyError::PinRequired
|
||||
pub rns_ratkey::RatkeyError::PukFailed
|
||||
pub rns_ratkey::RatkeyError::PukFailed::remaining: u8
|
||||
pub rns_ratkey::RatkeyError::PukLocked
|
||||
pub rns_ratkey::RatkeyError::ResetRequiresBlockedPinAndPuk
|
||||
pub rns_ratkey::RatkeyError::SigningFailed(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::SlotOccupied
|
||||
pub rns_ratkey::RatkeyError::SlotOccupied::slot: u8
|
||||
pub rns_ratkey::RatkeyError::TouchRequired
|
||||
pub rns_ratkey::RatkeyError::UnsupportedDevice(alloc::string::String)
|
||||
pub struct rns_ratkey::DeviceMeta
|
||||
pub rns_ratkey::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::DeviceMeta::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::DeviceMeta::serial: core::option::Option<u32>
|
||||
pub struct rns_ratkey::HardwareBackend
|
||||
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
|
||||
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
|
||||
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub struct rns_ratkey::HardwareIdentity
|
||||
pub rns_ratkey::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::HardwareIdentity::identity: rns_identity::identity::Identity
|
||||
impl rns_ratkey::hardware::HardwareIdentity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
|
||||
pub struct rns_ratkey::HwidConfig
|
||||
pub rns_ratkey::HwidConfig::app: rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::HwidConfig::device: rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
|
||||
impl rns_ratkey::hwid::HwidConfig
|
||||
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
|
||||
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
|
||||
pub struct rns_ratkey::MockPivSession
|
||||
pub rns_ratkey::MockPivSession::device_type: alloc::string::String
|
||||
pub rns_ratkey::MockPivSession::firmware: alloc::string::String
|
||||
pub rns_ratkey::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
|
||||
pub rns_ratkey::MockPivSession::serial: u32
|
||||
impl rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
|
||||
impl core::default::Default for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::PcscTransport
|
||||
impl rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::PinCache
|
||||
impl rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
|
||||
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
|
||||
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
|
||||
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
|
||||
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
|
||||
pub struct rns_ratkey::PivSession<T: rns_ratkey::transport::PivTransport>
|
||||
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::ProvisionConfig
|
||||
pub rns_ratkey::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::ProvisionConfig::nickname: alloc::string::String
|
||||
pub rns_ratkey::ProvisionConfig::pin: alloc::string::String
|
||||
pub rns_ratkey::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
|
||||
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
|
||||
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
|
||||
pub struct rns_ratkey::ProvisionResult
|
||||
pub rns_ratkey::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::ProvisionResult::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::ProvisionResult::identity_hash: [u8; 16]
|
||||
pub rns_ratkey::ProvisionResult::identity_hash_hex: alloc::string::String
|
||||
pub rns_ratkey::ProvisionResult::x25519_pub: [u8; 32]
|
||||
pub trait rns_ratkey::IdentityBackend
|
||||
pub fn rns_ratkey::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub trait rns_ratkey::PivTransport
|
||||
pub fn rns_ratkey::PivTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
|
||||
pub type rns_ratkey::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
pub mod rns_tools
|
||||
pub mod rns_tools::format
|
||||
pub fn rns_tools::format::hex_rep(&[u8]) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_frequency(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_hex_rep(&[u8]) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_size(u64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_speed(u64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_time(f64) -> alloc::string::String
|
||||
pub mod rns_tools::hash
|
||||
pub fn rns_tools::hash::format_dest_hash(&[u8; 16]) -> alloc::string::String
|
||||
pub fn rns_tools::hash::parse_dest_hash(&str) -> core::result::Result<[u8; 16], alloc::string::String>
|
||||
pub const rns_tools::RETICULUM_COMPAT_VERSION: &str
|
||||
pub const rns_tools::RS_RETICULUM_VERSION: &str
|
||||
pub fn rns_tools::config_log_timestamps(&std::path::Path) -> bool
|
||||
pub fn rns_tools::init_tracing<W>(tracing_core::metadata::Level, bool, bool, W) where W: for<'a> tracing_subscriber::fmt::writer::MakeWriter<'a> + core::marker::Send + core::marker::Sync + 'static
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,370 @@
|
||||
pub mod rns_wire
|
||||
pub mod rns_wire::constants
|
||||
pub const rns_wire::constants::AES128_BLOCKSIZE: usize
|
||||
pub const rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT: f64
|
||||
pub const rns_wire::constants::ENCRYPTED_MDU: usize
|
||||
pub const rns_wire::constants::EXPL_LENGTH: usize
|
||||
pub const rns_wire::constants::HASHLENGTH: usize
|
||||
pub const rns_wire::constants::HEADER_MAXSIZE: usize
|
||||
pub const rns_wire::constants::HEADER_MINSIZE: usize
|
||||
pub const rns_wire::constants::IMPL_LENGTH: usize
|
||||
pub const rns_wire::constants::KEYSIZE: usize
|
||||
pub const rns_wire::constants::LINK_MDU: usize
|
||||
pub const rns_wire::constants::MDU: usize
|
||||
pub const rns_wire::constants::MTU: usize
|
||||
pub const rns_wire::constants::NAME_HASH_LENGTH: usize
|
||||
pub const rns_wire::constants::PLAIN_MDU: usize
|
||||
pub const rns_wire::constants::RATCHETSIZE: usize
|
||||
pub const rns_wire::constants::RATCHET_COUNT: usize
|
||||
pub const rns_wire::constants::RATCHET_EXPIRY: u64
|
||||
pub const rns_wire::constants::RATCHET_INTERVAL: u64
|
||||
pub const rns_wire::constants::SIGLENGTH: usize
|
||||
pub const rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU: usize
|
||||
pub const rns_wire::constants::TOKEN_OVERHEAD: usize
|
||||
pub const rns_wire::constants::TRUNCATED_HASHLENGTH: usize
|
||||
pub mod rns_wire::context
|
||||
pub enum rns_wire::context::PacketContext
|
||||
pub rns_wire::context::PacketContext::CacheRequest
|
||||
pub rns_wire::context::PacketContext::Channel
|
||||
pub rns_wire::context::PacketContext::Command
|
||||
pub rns_wire::context::PacketContext::CommandStatus
|
||||
pub rns_wire::context::PacketContext::Keepalive
|
||||
pub rns_wire::context::PacketContext::LinkClose
|
||||
pub rns_wire::context::PacketContext::LinkIdentify
|
||||
pub rns_wire::context::PacketContext::LinkProof
|
||||
pub rns_wire::context::PacketContext::Lrproof
|
||||
pub rns_wire::context::PacketContext::Lrrtt
|
||||
pub rns_wire::context::PacketContext::None
|
||||
pub rns_wire::context::PacketContext::PathResponse
|
||||
pub rns_wire::context::PacketContext::Request
|
||||
pub rns_wire::context::PacketContext::Resource
|
||||
pub rns_wire::context::PacketContext::ResourceAdv
|
||||
pub rns_wire::context::PacketContext::ResourceHmu
|
||||
pub rns_wire::context::PacketContext::ResourceIcl
|
||||
pub rns_wire::context::PacketContext::ResourcePrf
|
||||
pub rns_wire::context::PacketContext::ResourceRcl
|
||||
pub rns_wire::context::PacketContext::ResourceReq
|
||||
pub rns_wire::context::PacketContext::Response
|
||||
pub rns_wire::context::PacketContext::Unknown(u8)
|
||||
impl rns_wire::context::PacketContext
|
||||
pub fn rns_wire::context::PacketContext::from_byte(u8) -> Self
|
||||
pub fn rns_wire::context::PacketContext::is_plaintext_context(self) -> bool
|
||||
pub fn rns_wire::context::PacketContext::to_byte(self) -> u8
|
||||
pub mod rns_wire::flags
|
||||
#[repr(u8)] pub enum rns_wire::flags::DestinationType
|
||||
pub rns_wire::flags::DestinationType::Group = 1
|
||||
pub rns_wire::flags::DestinationType::Link = 3
|
||||
pub rns_wire::flags::DestinationType::Plain = 2
|
||||
pub rns_wire::flags::DestinationType::Single = 0
|
||||
#[repr(u8)] pub enum rns_wire::flags::HeaderType
|
||||
pub rns_wire::flags::HeaderType::Header1 = 0
|
||||
pub rns_wire::flags::HeaderType::Header2 = 1
|
||||
#[repr(u8)] pub enum rns_wire::flags::PacketType
|
||||
pub rns_wire::flags::PacketType::Announce = 1
|
||||
pub rns_wire::flags::PacketType::Data = 0
|
||||
pub rns_wire::flags::PacketType::LinkRequest = 2
|
||||
pub rns_wire::flags::PacketType::Proof = 3
|
||||
#[repr(u8)] pub enum rns_wire::flags::TransportType
|
||||
pub rns_wire::flags::TransportType::Broadcast = 0
|
||||
pub rns_wire::flags::TransportType::Transport = 1
|
||||
pub struct rns_wire::flags::PacketFlags
|
||||
pub rns_wire::flags::PacketFlags::context_flag: bool
|
||||
pub rns_wire::flags::PacketFlags::destination_type: rns_wire::flags::DestinationType
|
||||
pub rns_wire::flags::PacketFlags::header_type: rns_wire::flags::HeaderType
|
||||
pub rns_wire::flags::PacketFlags::packet_type: rns_wire::flags::PacketType
|
||||
pub rns_wire::flags::PacketFlags::transport_type: rns_wire::flags::TransportType
|
||||
impl rns_wire::flags::PacketFlags
|
||||
pub fn rns_wire::flags::PacketFlags::pack(&self) -> u8
|
||||
pub fn rns_wire::flags::PacketFlags::unpack(u8) -> core::option::Option<Self>
|
||||
pub mod rns_wire::hash
|
||||
pub fn rns_wire::hash::get_hashable_part(&[u8], rns_wire::flags::HeaderType) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_wire::hash::link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub fn rns_wire::hash::packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 32]
|
||||
pub fn rns_wire::hash::packet_hash_pair(&[u8], rns_wire::flags::HeaderType) -> ([u8; 32], [u8; 16])
|
||||
pub fn rns_wire::hash::truncated_packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub mod rns_wire::header
|
||||
pub enum rns_wire::header::HeaderError
|
||||
pub rns_wire::header::HeaderError::TooShort(usize)
|
||||
pub struct rns_wire::header::PacketHeader
|
||||
pub rns_wire::header::PacketHeader::context: rns_wire::context::PacketContext
|
||||
pub rns_wire::header::PacketHeader::destination_hash: [u8; 16]
|
||||
pub rns_wire::header::PacketHeader::flags: rns_wire::flags::PacketFlags
|
||||
pub rns_wire::header::PacketHeader::hops: u8
|
||||
pub rns_wire::header::PacketHeader::transport_id: core::option::Option<[u8; 16]>
|
||||
impl rns_wire::header::PacketHeader
|
||||
pub fn rns_wire::header::PacketHeader::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_wire::header::PacketHeader::size(&self) -> usize
|
||||
pub fn rns_wire::header::PacketHeader::unpack(&[u8]) -> core::result::Result<(Self, usize), rns_wire::header::HeaderError>
|
||||
pub mod rns_wire::packet
|
||||
pub enum rns_wire::packet::PacketError
|
||||
pub rns_wire::packet::PacketError::ExceedsMtu(usize)
|
||||
pub rns_wire::packet::PacketError::Header(rns_wire::header::HeaderError)
|
||||
pub rns_wire::packet::PacketError::TooShort
|
||||
pub struct rns_wire::packet::Packet
|
||||
pub rns_wire::packet::Packet::header: rns_wire::header::PacketHeader
|
||||
pub rns_wire::packet::Packet::packet_hash: [u8; 32]
|
||||
pub rns_wire::packet::Packet::raw: alloc::vec::Vec<u8>
|
||||
pub rns_wire::packet::Packet::truncated_hash: [u8; 16]
|
||||
impl rns_wire::packet::Packet
|
||||
pub fn rns_wire::packet::Packet::data(&self) -> &[u8]
|
||||
pub fn rns_wire::packet::Packet::from_raw(&[u8]) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub fn rns_wire::packet::Packet::from_raw_owned(alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub fn rns_wire::packet::Packet::increment_hops(&mut self)
|
||||
pub fn rns_wire::packet::Packet::new(rns_wire::header::PacketHeader, alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub mod rns_wire::proof
|
||||
pub enum rns_wire::proof::ProofData
|
||||
pub rns_wire::proof::ProofData::Explicit
|
||||
pub rns_wire::proof::ProofData::Explicit::packet_hash: [u8; 32]
|
||||
pub rns_wire::proof::ProofData::Explicit::signature: [u8; 64]
|
||||
pub rns_wire::proof::ProofData::Implicit
|
||||
pub rns_wire::proof::ProofData::Implicit::signature: [u8; 64]
|
||||
impl rns_wire::proof::ProofData
|
||||
pub fn rns_wire::proof::ProofData::from_bytes(&[u8]) -> core::option::Option<Self>
|
||||
pub fn rns_wire::proof::ProofData::signature(&self) -> &[u8; 64]
|
||||
pub fn rns_wire::proof::ProofData::to_bytes(&self) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_wire::receipt
|
||||
#[repr(u8)] pub enum rns_wire::receipt::ReceiptStatus
|
||||
pub rns_wire::receipt::ReceiptStatus::Culled = 255
|
||||
pub rns_wire::receipt::ReceiptStatus::Delivered = 2
|
||||
pub rns_wire::receipt::ReceiptStatus::Failed = 0
|
||||
pub rns_wire::receipt::ReceiptStatus::Receiving = 6
|
||||
pub rns_wire::receipt::ReceiptStatus::Sent = 1
|
||||
pub struct rns_wire::receipt::PacketReceipt
|
||||
pub rns_wire::receipt::PacketReceipt::callbacks: rns_wire::receipt::ReceiptCallbacks
|
||||
pub rns_wire::receipt::PacketReceipt::concluded_at: core::option::Option<std::time::Instant>
|
||||
pub rns_wire::receipt::PacketReceipt::destination_hash: core::option::Option<[u8; 16]>
|
||||
pub rns_wire::receipt::PacketReceipt::destination_public_key: core::option::Option<[u8; 64]>
|
||||
pub rns_wire::receipt::PacketReceipt::hash: [u8; 32]
|
||||
pub rns_wire::receipt::PacketReceipt::sent_at: std::time::Instant
|
||||
pub rns_wire::receipt::PacketReceipt::status: rns_wire::receipt::ReceiptStatus
|
||||
pub rns_wire::receipt::PacketReceipt::timeout: core::option::Option<core::time::Duration>
|
||||
pub rns_wire::receipt::PacketReceipt::truncated_hash: [u8; 16]
|
||||
impl rns_wire::receipt::PacketReceipt
|
||||
pub fn rns_wire::receipt::PacketReceipt::check_timeout(&mut self) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::cull(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::deliver(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::fail(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::get_rtt(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_wire::receipt::PacketReceipt::is_timed_out(&self) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::new([u8; 32], [u8; 16], core::option::Option<core::time::Duration>) -> Self
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_delivery_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_destination_identity(&mut self, [u8; 16], core::option::Option<[u8; 64]>)
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_timeout_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_wire::receipt::PacketReceipt::validate_proof<F>(&mut self, &[u8], F) -> bool where F: core::ops::function::FnOnce(&[u8], &[u8]) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::validate_proof_from_destination(&mut self, &[u8]) -> bool
|
||||
pub struct rns_wire::receipt::ReceiptCallbacks
|
||||
pub rns_wire::receipt::ReceiptCallbacks::delivery: core::option::Option<rns_wire::receipt::ReceiptCallback>
|
||||
pub rns_wire::receipt::ReceiptCallbacks::timeout: core::option::Option<rns_wire::receipt::ReceiptCallback>
|
||||
pub const rns_wire::receipt::EXPL_LENGTH: usize
|
||||
pub const rns_wire::receipt::IMPL_LENGTH: usize
|
||||
pub fn rns_wire::receipt::receipt_timeout_for_route(core::time::Duration, u8) -> core::time::Duration
|
||||
pub type rns_wire::receipt::ReceiptCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send)>
|
||||
pub mod rns_wire::types
|
||||
#[repr(transparent)] pub struct rns_wire::types::DestHash(_)
|
||||
impl rns_wire::types::DestHash
|
||||
pub const rns_wire::types::DestHash::LEN: usize
|
||||
pub const fn rns_wire::types::DestHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::DestHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::DestHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::DestHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::DestHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::DestHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::DestHash
|
||||
pub type rns_wire::types::DestHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::DestHash::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::FullHash(_)
|
||||
impl rns_wire::types::FullHash
|
||||
pub const rns_wire::types::FullHash::LEN: usize
|
||||
pub const fn rns_wire::types::FullHash::as_bytes(&self) -> &[u8; 32]
|
||||
pub fn rns_wire::types::FullHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::FullHash::into_bytes(self) -> [u8; 32]
|
||||
pub const fn rns_wire::types::FullHash::new([u8; 32]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::borrow(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::from(&[u8; 32]) -> Self
|
||||
impl core::convert::From<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::from([u8; 32]) -> Self
|
||||
impl core::convert::From<rns_wire::types::FullHash> for [u8; 32]
|
||||
pub fn [u8; 32]::from(rns_wire::types::FullHash) -> [u8; 32]
|
||||
impl core::fmt::Debug for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::FullHash
|
||||
pub type rns_wire::types::FullHash::Target = [u8; 32]
|
||||
pub fn rns_wire::types::FullHash::deref(&self) -> &[u8; 32]
|
||||
#[repr(transparent)] pub struct rns_wire::types::IdentityHash(_)
|
||||
impl rns_wire::types::IdentityHash
|
||||
pub const rns_wire::types::IdentityHash::LEN: usize
|
||||
pub const fn rns_wire::types::IdentityHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::IdentityHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::IdentityHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::IdentityHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::IdentityHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::IdentityHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::IdentityHash
|
||||
pub type rns_wire::types::IdentityHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::IdentityHash::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::LinkId(_)
|
||||
impl rns_wire::types::LinkId
|
||||
pub const rns_wire::types::LinkId::LEN: usize
|
||||
pub const fn rns_wire::types::LinkId::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::LinkId::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::LinkId::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::LinkId::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::LinkId> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::LinkId) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::LinkId
|
||||
pub type rns_wire::types::LinkId::Target = [u8; 16]
|
||||
pub fn rns_wire::types::LinkId::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::MessageHash(_)
|
||||
impl rns_wire::types::MessageHash
|
||||
pub const rns_wire::types::MessageHash::LEN: usize
|
||||
pub const fn rns_wire::types::MessageHash::as_bytes(&self) -> &[u8; 32]
|
||||
pub fn rns_wire::types::MessageHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::MessageHash::into_bytes(self) -> [u8; 32]
|
||||
pub const fn rns_wire::types::MessageHash::new([u8; 32]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::borrow(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::from(&[u8; 32]) -> Self
|
||||
impl core::convert::From<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::from([u8; 32]) -> Self
|
||||
impl core::convert::From<rns_wire::types::MessageHash> for [u8; 32]
|
||||
pub fn [u8; 32]::from(rns_wire::types::MessageHash) -> [u8; 32]
|
||||
impl core::fmt::Debug for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::MessageHash
|
||||
pub type rns_wire::types::MessageHash::Target = [u8; 32]
|
||||
pub fn rns_wire::types::MessageHash::deref(&self) -> &[u8; 32]
|
||||
#[repr(transparent)] pub struct rns_wire::types::NameHash(_)
|
||||
impl rns_wire::types::NameHash
|
||||
pub const rns_wire::types::NameHash::LEN: usize
|
||||
pub const fn rns_wire::types::NameHash::as_bytes(&self) -> &[u8; 10]
|
||||
pub fn rns_wire::types::NameHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::NameHash::into_bytes(self) -> [u8; 10]
|
||||
pub const fn rns_wire::types::NameHash::new([u8; 10]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::borrow(&self) -> &[u8; 10]
|
||||
impl core::convert::AsRef<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8; 10]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::from(&[u8; 10]) -> Self
|
||||
impl core::convert::From<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::from([u8; 10]) -> Self
|
||||
impl core::convert::From<rns_wire::types::NameHash> for [u8; 10]
|
||||
pub fn [u8; 10]::from(rns_wire::types::NameHash) -> [u8; 10]
|
||||
impl core::fmt::Debug for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::NameHash
|
||||
pub type rns_wire::types::NameHash::Target = [u8; 10]
|
||||
pub fn rns_wire::types::NameHash::deref(&self) -> &[u8; 10]
|
||||
#[repr(transparent)] pub struct rns_wire::types::TransportId(_)
|
||||
impl rns_wire::types::TransportId
|
||||
pub const rns_wire::types::TransportId::LEN: usize
|
||||
pub const fn rns_wire::types::TransportId::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::TransportId::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::TransportId::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::TransportId::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::TransportId> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::TransportId) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::TransportId
|
||||
pub type rns_wire::types::TransportId::Target = [u8; 16]
|
||||
pub fn rns_wire::types::TransportId::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::TruncatedHash(_)
|
||||
impl rns_wire::types::TruncatedHash
|
||||
pub const rns_wire::types::TruncatedHash::LEN: usize
|
||||
pub const fn rns_wire::types::TruncatedHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::TruncatedHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::TruncatedHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::TruncatedHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::TruncatedHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::TruncatedHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::TruncatedHash
|
||||
pub type rns_wire::types::TruncatedHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::TruncatedHash::deref(&self) -> &[u8; 16]
|
||||
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"tool": {
|
||||
"name": "cargo-public-api",
|
||||
"version": "0.52.0",
|
||||
"rustdocToolchain": "nightly-2026-08-01",
|
||||
"target": "aarch64-apple-darwin",
|
||||
"arguments": [
|
||||
"--all-features",
|
||||
"-sss"
|
||||
]
|
||||
},
|
||||
"baseline": {
|
||||
"commit": "47dbbf1febc0a9d3259f179a0512d9b56bb2320d"
|
||||
},
|
||||
"compatibilityFloor": {
|
||||
"evidenceCommit": "c9b210a52b139ac9754b46c5c2639c4113e7ae53",
|
||||
"sourceCommit": "47dbbf1febc0a9d3259f179a0512d9b56bb2320d"
|
||||
},
|
||||
"packages": [
|
||||
{
|
||||
"name": "rns-crypto",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-crypto.txt",
|
||||
"itemCount": 91,
|
||||
"sha256": "4d1e3c0a13e48a84f2510c6586024b3d8f5781b367459bc17d714ca485f1aa63"
|
||||
},
|
||||
{
|
||||
"name": "rns-wire",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-wire.txt",
|
||||
"itemCount": 370,
|
||||
"sha256": "7ce9011e531c1642912512d9d975b8a7def0bb41f691b6b16177eddecf5bef6d"
|
||||
},
|
||||
{
|
||||
"name": "rns-identity",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-identity.txt",
|
||||
"itemCount": 374,
|
||||
"sha256": "f2b692070a3fa1a2cc98edbb40bc75d205daadfa9da9d9994ee194e8436e00c9"
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-transport.txt",
|
||||
"itemCount": 1702,
|
||||
"sha256": "30f20b408ac255e1f005e25e79e4999d813ebc6b4f1a501bf573de58db0e25ab"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-link.txt",
|
||||
"itemCount": 359,
|
||||
"sha256": "59d2f211857314e044bf31e5b78e4460483411c9b26c08904f8996295b189984"
|
||||
},
|
||||
{
|
||||
"name": "rns-protocol",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-protocol.txt",
|
||||
"itemCount": 624,
|
||||
"sha256": "9fd1968c43d3a80b5da65416f43a805e3bfd3420c91acc8ad63a7a3ca58b359c"
|
||||
},
|
||||
{
|
||||
"name": "rns-interface",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-interface.txt",
|
||||
"itemCount": 1406,
|
||||
"sha256": "b097f01fc5eac53ed0ce5b6150c47c12f69fb63072ac31789a3995167123af3a"
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-runtime.txt",
|
||||
"itemCount": 2063,
|
||||
"sha256": "ca162e9ddb542f0daf5817ac26d32be80346d36bdadd70673bf2cdc2535e4e29"
|
||||
},
|
||||
{
|
||||
"name": "rns-tools",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "tool-internal",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-tools.txt",
|
||||
"itemCount": 15,
|
||||
"sha256": "662566afbf8a21928529a33dcec4a23b0a4686e9b2d94a7721b111738a5b4a6b"
|
||||
},
|
||||
{
|
||||
"name": "rns-ratkey",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-ratkey.txt",
|
||||
"itemCount": 618,
|
||||
"sha256": "f2ab796d37f18d7d5d7a515e4b6c28900f6f1c214aec4142fed069275793fdfd"
|
||||
}
|
||||
],
|
||||
"approvedBreakingChanges": {
|
||||
"releaseLine": "1.3",
|
||||
"migrationGuide": "api/migrations/1.3.md",
|
||||
"removed": {
|
||||
"rns-transport": [
|
||||
"pub rns_transport::actor::DiscoveryPathRequest::requesting_interface: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::actor::DiscoveryPathRequest::timeout: f64",
|
||||
"pub rns_transport::actor::TransportActor::discovery_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::actor::DiscoveryPathRequest>",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::height: f64",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::latitude: f64",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::longitude: f64",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::height: f64",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::latitude: f64",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::longitude: f64",
|
||||
"pub rns_transport::discovery::app_data::DiscoveryInfo::height: f64",
|
||||
"pub rns_transport::discovery::app_data::DiscoveryInfo::latitude: f64",
|
||||
"pub rns_transport::discovery::app_data::DiscoveryInfo::longitude: f64"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
|
||||
msrv = "1.85"
|
||||
msrv = "1.89"
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-crypto"
|
||||
description = "Cryptographic primitives for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -10,11 +10,10 @@ use thiserror::Error;
|
||||
|
||||
const AES_BLOCK_SIZE: usize = 16;
|
||||
|
||||
/// Rust 1.85-compatible block alignment check. Newer Clippy suggests
|
||||
/// `usize::is_multiple_of`, but that API is not available on our MSRV.
|
||||
/// Block alignment check kept explicit at this cryptographic boundary.
|
||||
#[inline]
|
||||
pub(crate) fn is_nonzero_block_aligned(len: usize) -> bool {
|
||||
len != 0 && len % AES_BLOCK_SIZE == 0
|
||||
len != 0 && len.is_multiple_of(AES_BLOCK_SIZE)
|
||||
}
|
||||
|
||||
/// Errors surfaced by [`encrypt`] and [`decrypt`].
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-identity"
|
||||
description = "Identity, Destination, and Announce system for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -289,15 +289,15 @@ impl AnnounceData {
|
||||
|
||||
// First-seen key binding: a valid signature on a different public key
|
||||
// for an already-known destination hash implies a collision attack.
|
||||
if let Some(known_key) = known_public_key {
|
||||
if known_key != &self.public_key {
|
||||
tracing::error!(
|
||||
dest = hex::encode(packet_dest_hash),
|
||||
"announce has valid signature and destination hash, but public key \
|
||||
if let Some(known_key) = known_public_key
|
||||
&& known_key != &self.public_key
|
||||
{
|
||||
tracing::error!(
|
||||
dest = hex::encode(packet_dest_hash),
|
||||
"announce has valid signature and destination hash, but public key \
|
||||
differs from already known key — possible hash collision attack, rejecting"
|
||||
);
|
||||
return Err(AnnounceError::HashCollision);
|
||||
}
|
||||
);
|
||||
return Err(AnnounceError::HashCollision);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -852,10 +852,10 @@ impl Destination {
|
||||
|
||||
let plaintext = self.decrypt_with_ratchets(data, identity, ratchet_keys)?;
|
||||
|
||||
if packet_type == 0x00 {
|
||||
if let Some(ref cb) = self.packet_callback {
|
||||
cb(&plaintext, raw_packet);
|
||||
}
|
||||
if packet_type == 0x00
|
||||
&& let Some(ref cb) = self.packet_callback
|
||||
{
|
||||
cb(&plaintext, raw_packet);
|
||||
}
|
||||
|
||||
Ok(Some(plaintext))
|
||||
@@ -968,10 +968,10 @@ impl Destination {
|
||||
self.path_responses
|
||||
.retain(|_, v| time.cache <= v.timestamp + PR_TAG_WINDOW);
|
||||
|
||||
if let Some(tag_bytes) = tag {
|
||||
if let Some(cached) = self.path_responses.get(tag_bytes) {
|
||||
return Ok((cached.announce_data.clone(), cached.has_ratchet));
|
||||
}
|
||||
if let Some(tag_bytes) = tag
|
||||
&& let Some(cached) = self.path_responses.get(tag_bytes)
|
||||
{
|
||||
return Ok((cached.announce_data.clone(), cached.has_ratchet));
|
||||
}
|
||||
|
||||
let effective_app_data = app_data
|
||||
|
||||
@@ -357,15 +357,13 @@ impl Identity {
|
||||
let mut shared = ratchet_prv.exchange(&peer_pub);
|
||||
let derived_result = derive_key_64(&shared, &self.hash);
|
||||
shared.zeroize();
|
||||
if let Ok(derived) = derived_result {
|
||||
if let Ok(plaintext) = token::decrypt(ct, &derived) {
|
||||
return Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: Some(Self::ratchet_id(
|
||||
&ratchet_prv.public_key().to_bytes(),
|
||||
)),
|
||||
});
|
||||
}
|
||||
if let Ok(derived) = derived_result
|
||||
&& let Ok(plaintext) = token::decrypt(ct, &derived)
|
||||
{
|
||||
return Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: Some(Self::ratchet_id(&ratchet_prv.public_key().to_bytes())),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
|
||||
}
|
||||
|
||||
fn hex_decode(s: &str) -> Option<Vec<u8>> {
|
||||
if s.len() % 2 != 0 {
|
||||
if !s.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
(0..s.len())
|
||||
|
||||
@@ -150,10 +150,10 @@ fn atomic_write_inner(
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
if let Ok(d) = fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
if let Some(dir) = path.parent()
|
||||
&& let Ok(d) = fs::File::open(dir)
|
||||
{
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -763,10 +763,10 @@ impl ReceivedRatchetStore {
|
||||
/// Record a ratchet with an explicit local receive time. Re-inserting the
|
||||
/// same key remains a no-op and therefore cannot extend its lifetime.
|
||||
pub fn remember_at(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32], received_at: f64) {
|
||||
if let Some(existing) = self.entries.get(&dest_hash) {
|
||||
if existing.ratchet_pub == ratchet_pub {
|
||||
return;
|
||||
}
|
||||
if let Some(existing) = self.entries.get(&dest_hash)
|
||||
&& existing.ratchet_pub == ratchet_pub
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let received = ReceivedRatchet::new_at(ratchet_pub, received_at);
|
||||
@@ -793,28 +793,28 @@ impl ReceivedRatchetStore {
|
||||
}
|
||||
|
||||
pub fn get_at(&mut self, dest_hash: &[u8; 16], now: f64) -> Option<[u8; 32]> {
|
||||
if !self.entries.contains_key(dest_hash) {
|
||||
if let Some(ref dir) = self.storage_dir {
|
||||
let hexhash = hex::encode(dest_hash);
|
||||
let path = dir.join(&hexhash);
|
||||
if path.exists() {
|
||||
match ReceivedRatchet::load(&path) {
|
||||
Ok(ratchet) => {
|
||||
if !ratchet.is_expired_at(now) {
|
||||
self.entries.insert(*dest_hash, ratchet);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
dest = hexhash,
|
||||
error = %e,
|
||||
"failed to load ratchet from disk"
|
||||
);
|
||||
if !self.entries.contains_key(dest_hash)
|
||||
&& let Some(ref dir) = self.storage_dir
|
||||
{
|
||||
let hexhash = hex::encode(dest_hash);
|
||||
let path = dir.join(&hexhash);
|
||||
if path.exists() {
|
||||
match ReceivedRatchet::load(&path) {
|
||||
Ok(ratchet) => {
|
||||
if !ratchet.is_expired_at(now) {
|
||||
self.entries.insert(*dest_hash, ratchet);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
dest = hexhash,
|
||||
error = %e,
|
||||
"failed to load ratchet from disk"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-interface"
|
||||
description = "Network interface trait and implementations for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -28,7 +29,7 @@ tracing = { workspace = true }
|
||||
socket2 = { workspace = true }
|
||||
if-addrs = { workspace = true }
|
||||
serialport = { workspace = true, optional = true }
|
||||
btleplug = { version = "0.11", optional = true }
|
||||
btleplug = { version = "=0.13.4", optional = true }
|
||||
futures = { version = "0.3", optional = true }
|
||||
uuid = { version = "1", optional = true }
|
||||
rand = { workspace = true }
|
||||
@@ -38,15 +39,15 @@ hex = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
|
||||
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
|
||||
# Version pinned to match btleplug's internal objc2 version so the shared
|
||||
# runtime types stay binary-compatible. objc2-core-bluetooth gives us
|
||||
# These native owners do not exchange Objective-C types with btleplug. Keep
|
||||
# their binding generation and required features explicit. objc2-core-bluetooth gives us
|
||||
# linked-symbol access to NSString constants (CBCentralManagerScanOption*,
|
||||
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
|
||||
# values, which Apple is free to change.
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
objc2 = "0.5"
|
||||
objc2-foundation = "0.2"
|
||||
objc2-core-bluetooth = "0.2"
|
||||
objc2-foundation = { version = "0.2", features = ["NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
@@ -76,6 +77,11 @@ bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
|
||||
# unavailable event so embedding UIs can direct users to an MSIX build for
|
||||
# discoverability.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Resolution floor for Tokio's socket backend: older Mio lets child processes
|
||||
# inherit sockets and keep shared/network listeners alive after shutdown.
|
||||
# 1.2.3 includes the no-inheritance fix and its Wine compatibility follow-up.
|
||||
# https://github.com/tokio-rs/mio/pull/1946
|
||||
mio = { version = "1.2.3", default-features = false }
|
||||
windows = { version = "0.58", features = [
|
||||
"Devices_Bluetooth",
|
||||
"Devices_Bluetooth_Advertisement",
|
||||
|
||||
@@ -9,11 +9,11 @@ use bytes::Bytes;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use crate::android_usb_lifecycle::{
|
||||
OwnedUsbIo, UsbConnectionCleanup, UsbConnectionLifecycle, UsbDeviceCandidate,
|
||||
UsbDeviceResolutionError, UsbDeviceSelector, UsbInboundOutcome, UsbInboundState, UsbIoEvent,
|
||||
UsbLeaseTable, UsbRNodeCapabilityAdmission, UsbRNodeCapabilityStartupError,
|
||||
OwnedUsbIo, UsbApplicationQueue, UsbConnectionCleanup, UsbConnectionLifecycle,
|
||||
UsbDeviceCandidate, UsbDeviceResolutionError, UsbDeviceSelector, UsbInboundOutcome,
|
||||
UsbInboundState, UsbIoEvent, UsbLeaseTable, UsbRNodeCapabilityStartupError,
|
||||
UsbReadDrainOutcome, UsbReadResult, UsbReaderBackend, UsbShutdownReport, UsbTransferError,
|
||||
UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk,
|
||||
UsbTxGate, UsbTxPumpExit, UsbWriterBackend, drain_usb_reader_tail, forward_usb_read_chunk,
|
||||
resolve_usb_device, run_usb_rnode_capability_startup, run_usb_rnode_startup, run_usb_tx_pump,
|
||||
spawn_owned_usb_io,
|
||||
};
|
||||
@@ -23,7 +23,8 @@ use crate::rnode::{
|
||||
self, RNodeDriverShutdown, RNodeRuntimeReason, RNodeSpawnError, RNodeStartupOptions,
|
||||
RNodeTransportClass, SpawnedRNodeInterface,
|
||||
};
|
||||
use crate::rnode_protocol::RNodeProtocolTarget;
|
||||
use crate::rnode_capabilities::RNodeRadioAdmission;
|
||||
use crate::rnode_protocol::{RNodeProtocolState, RNodeProtocolTarget};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceError, InterfaceHandle, InterfaceId, InterfaceMode,
|
||||
};
|
||||
@@ -1439,7 +1440,8 @@ async fn shutdown_failed_android_usb_startup(
|
||||
|
||||
struct AndroidUsbGeneration {
|
||||
usb: OwnedUsbIo<JniUsbConnectionOwner>,
|
||||
protocol_state: Option<UsbRNodeCapabilityAdmission>,
|
||||
protocol_state: RNodeProtocolState,
|
||||
admission: Option<RNodeRadioAdmission>,
|
||||
selector: UsbDeviceSelector,
|
||||
}
|
||||
|
||||
@@ -1458,7 +1460,7 @@ async fn start_android_usb_generation(
|
||||
let (mut usb, _worker_online) = open_usb_serial(&device_name, config.baud_rate).await?;
|
||||
let rnode_cfg = rnode_config_from_android_usb_config(config);
|
||||
let init_bytes = rnode::build_init_sequence(&rnode_cfg);
|
||||
let protocol_state = if options.requires_capability_admission() {
|
||||
let (protocol_state, admission) = if options.requires_capability_admission() {
|
||||
match run_usb_rnode_capability_startup(
|
||||
&mut usb,
|
||||
rnode::RNodeRadioSettings::from(&rnode_cfg),
|
||||
@@ -1469,7 +1471,7 @@ async fn start_android_usb_generation(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(admission) => Some(admission),
|
||||
Ok(admission) => (admission.protocol_state, Some(admission.admission)),
|
||||
Err(error) => {
|
||||
let init_may_have_started =
|
||||
matches!(&error, UsbRNodeCapabilityStartupError::Initialise(_));
|
||||
@@ -1513,31 +1515,42 @@ async fn start_android_usb_generation(
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if let Err(error) = run_usb_rnode_startup(
|
||||
&usb.writer,
|
||||
rnode::build_detect_sequence(),
|
||||
init_bytes,
|
||||
USB_STARTUP_ACK_DEADLINE,
|
||||
)
|
||||
.await
|
||||
{
|
||||
// The legacy startup helper can enqueue part of the initialisation
|
||||
// sequence before reporting failure. Always attempt the terminal
|
||||
// detach here so a retry does not inherit an active radio session.
|
||||
let cleanup = shutdown_failed_android_usb_startup(usb, true).await;
|
||||
let cleanup = cleanup
|
||||
.map(|cleanup| format!("; cleanup: {cleanup}"))
|
||||
.unwrap_or_default();
|
||||
return Err(RNodeSpawnError::Interface(InterfaceError::SendFailed(
|
||||
format!("Android USB RNode startup failed: {error}{cleanup}"),
|
||||
)));
|
||||
} else {
|
||||
None
|
||||
match run_usb_rnode_startup(
|
||||
&mut usb,
|
||||
RNodeProtocolTarget::new(
|
||||
config.frequency,
|
||||
config.bandwidth,
|
||||
config.spreading_factor,
|
||||
config.coding_rate,
|
||||
config.tx_power,
|
||||
),
|
||||
rnode::build_detect_sequence(),
|
||||
init_bytes,
|
||||
USB_STARTUP_ACK_DEADLINE,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(protocol) => (protocol, None),
|
||||
Err(error) => {
|
||||
// The legacy startup helper can enqueue part of the initialisation
|
||||
// sequence before reporting failure. Always attempt the terminal
|
||||
// detach here so a retry does not inherit an active radio session.
|
||||
let cleanup = shutdown_failed_android_usb_startup(usb, true).await;
|
||||
let cleanup = cleanup
|
||||
.map(|cleanup| format!("; cleanup: {cleanup}"))
|
||||
.unwrap_or_default();
|
||||
return Err(RNodeSpawnError::Interface(InterfaceError::SendFailed(
|
||||
format!("Android USB RNode startup failed: {error}{cleanup}"),
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(AndroidUsbGeneration {
|
||||
usb,
|
||||
protocol_state,
|
||||
admission,
|
||||
selector,
|
||||
})
|
||||
}
|
||||
@@ -1591,14 +1604,6 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
let initial_generation = start_android_usb_generation(&config, options).await?;
|
||||
|
||||
let name = config.name.clone();
|
||||
let protocol_target = RNodeProtocolTarget::new(
|
||||
config.frequency,
|
||||
config.bandwidth,
|
||||
config.spreading_factor,
|
||||
config.coding_rate,
|
||||
config.tx_power,
|
||||
);
|
||||
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let beacon = config
|
||||
@@ -1621,7 +1626,10 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
// Match the serial and BLE RNode application queue. The queue is logical
|
||||
// interface state and survives physical Android USB reconnects.
|
||||
let (tx, app_rx) = mpsc::channel::<Bytes>(256);
|
||||
let app_rx = Arc::new(tokio::sync::Mutex::new(app_rx));
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
let app_rx = Arc::new(tokio::sync::Mutex::new(
|
||||
UsbApplicationQueue::new(app_rx).with_background(background),
|
||||
));
|
||||
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
|
||||
let (snapshot_publisher, driver) = rnode::new_rnode_driver_observation_with_shutdown(
|
||||
RNodeTransportClass::Usb,
|
||||
@@ -1634,7 +1642,7 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
let read_name = name.clone();
|
||||
let txb = shared_txb.clone();
|
||||
let rxb = shared_rxb.clone();
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let online_task = online.clone();
|
||||
let mut reconnect_config = config.clone();
|
||||
reconnect_config.apply_selector(initial_generation.selector.clone());
|
||||
@@ -1703,26 +1711,22 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
let AndroidUsbGeneration {
|
||||
mut usb,
|
||||
protocol_state,
|
||||
admission,
|
||||
selector,
|
||||
} = generation;
|
||||
reconnect_config.apply_selector(selector);
|
||||
let mut publisher = snapshot_publisher
|
||||
.take()
|
||||
.expect("Android USB generation publisher missing");
|
||||
let mut inbound = match protocol_state {
|
||||
Some(UsbRNodeCapabilityAdmission {
|
||||
protocol_state,
|
||||
admission,
|
||||
}) => {
|
||||
publisher.capability_connection_established(&protocol_state, admission);
|
||||
UsbInboundState::projected_with_protocol_state(protocol_state, publisher)
|
||||
}
|
||||
None => {
|
||||
publisher.connection_established();
|
||||
UsbInboundState::projected(protocol_target, publisher)
|
||||
}
|
||||
};
|
||||
online_task.store(true, Ordering::SeqCst);
|
||||
if let Some(admission) = admission {
|
||||
publisher.capability_connection_established(&protocol_state, admission);
|
||||
} else {
|
||||
publisher.connection_established();
|
||||
}
|
||||
let mut inbound =
|
||||
UsbInboundState::projected_with_protocol_state(protocol_state, publisher);
|
||||
let gate = UsbTxGate::new(reconnect_config.flow_control, online_task.clone());
|
||||
inbound.attach_tx_gate(gate.clone());
|
||||
|
||||
let (tx_pump_stop_tx, tx_pump_stop_rx) = tokio::sync::oneshot::channel();
|
||||
let (tx_pump_exit_tx, mut tx_pump_exit_rx) = tokio::sync::oneshot::channel();
|
||||
@@ -1730,10 +1734,17 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
let pump_txb = txb.clone();
|
||||
let pump_rx = app_rx.clone();
|
||||
let pump_beacon = beacon.clone();
|
||||
let pump_gate = gate.clone();
|
||||
let mut tx_pump = tokio::spawn(async move {
|
||||
let exit =
|
||||
run_usb_tx_pump(pump_rx, pump_writer, pump_txb, pump_beacon, tx_pump_stop_rx)
|
||||
.await;
|
||||
let exit = run_usb_tx_pump(
|
||||
pump_rx,
|
||||
pump_writer,
|
||||
pump_txb,
|
||||
pump_beacon,
|
||||
pump_gate,
|
||||
tx_pump_stop_rx,
|
||||
)
|
||||
.await;
|
||||
let _ = tx_pump_exit_tx.send(exit);
|
||||
});
|
||||
let mut stop_requested = false;
|
||||
@@ -1761,10 +1772,14 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
tracing::warn!(
|
||||
name = %read_name,
|
||||
error = %error,
|
||||
"Android USB packet could not be queued"
|
||||
"Android USB packet write did not complete"
|
||||
);
|
||||
drain_reader_tail = true;
|
||||
}
|
||||
Ok(UsbTxPumpExit::ReadinessTimedOut) => {
|
||||
tracing::warn!(name = %read_name,
|
||||
"Android USB fresh protocol readiness timed out");
|
||||
}
|
||||
Ok(UsbTxPumpExit::ApplicationClosed) => {
|
||||
terminal_reason = RNodeRuntimeReason::TransportConsumerClosed;
|
||||
}
|
||||
@@ -1803,14 +1818,41 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
break;
|
||||
}
|
||||
Some(UsbIoEvent::Read(bytes)) => {
|
||||
match forward_usb_read_chunk(
|
||||
let forwarding = forward_usb_read_chunk(
|
||||
&mut inbound,
|
||||
&bytes,
|
||||
id,
|
||||
rxb.as_ref(),
|
||||
&transport_tx,
|
||||
&mut stop_rx,
|
||||
).await {
|
||||
);
|
||||
// Transport backpressure must not conceal a
|
||||
// failed/timed-out writer or prevent its owner
|
||||
// from reaching bounded physical cleanup.
|
||||
// The pump owns the current generation's
|
||||
// readiness-episode deadline, including a new
|
||||
// Ready -> notReady transition after idle.
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
pump = &mut tx_pump_exit_rx => {
|
||||
match pump {
|
||||
Ok(UsbTxPumpExit::ApplicationClosed) => {
|
||||
terminal_reason = RNodeRuntimeReason::TransportConsumerClosed;
|
||||
}
|
||||
Ok(UsbTxPumpExit::StopRequested) => {
|
||||
stop_requested = true;
|
||||
terminal_reason = RNodeRuntimeReason::StopRequested;
|
||||
}
|
||||
Ok(UsbTxPumpExit::ReadinessTimedOut) => {}
|
||||
Ok(UsbTxPumpExit::WriterRejected(_)) | Err(_) => {
|
||||
drain_reader_tail = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
outcome = forwarding => outcome,
|
||||
};
|
||||
match outcome {
|
||||
UsbInboundOutcome::Complete => {}
|
||||
UsbInboundOutcome::StopRequested => {
|
||||
stop_requested = true;
|
||||
@@ -1835,6 +1877,9 @@ pub async fn spawn_android_usb_rnode_interface_with_driver_and_options(
|
||||
}
|
||||
}
|
||||
|
||||
// Close the operational gate before any drain/detach work. Late
|
||||
// frames from this generation may update diagnostics, not reopen TX.
|
||||
gate.close();
|
||||
let _ = tx_pump_stop_tx.send(());
|
||||
if tokio::time::timeout(USB_WORKER_JOIN_DEADLINE, &mut tx_pump)
|
||||
.await
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,7 @@
|
||||
//! Beacons go to a multicast group derived from `SHA-256(group_id)` every
|
||||
//! ~1.6 s; data flows over unicast UDP. Peers age out after 22 s of silence.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
@@ -161,10 +161,10 @@ impl std::fmt::Display for McastAddrType {
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum AutoInterfaceEvent {
|
||||
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this is the
|
||||
/// canonical signal for missing `com.apple.developer.networking.multicast`
|
||||
/// entitlement (free dev team can't sign it). On Linux it usually means
|
||||
/// the interface vanished between enumeration and join.
|
||||
/// `IPV6_JOIN_GROUP` was rejected by the OS. On Apple this can indicate a
|
||||
/// missing `com.apple.developer.networking.multicast` entitlement or Local
|
||||
/// Network authorization that has not been granted yet. On Linux it
|
||||
/// usually means the interface vanished between enumeration and join.
|
||||
JoinFailed {
|
||||
interface_name: String,
|
||||
ifname: String,
|
||||
@@ -579,10 +579,10 @@ fn iface_passes_filters(
|
||||
if ignored_devices.iter().any(|n| n == iface_name) {
|
||||
return false;
|
||||
}
|
||||
if let Some(allowed) = devices {
|
||||
if !allowed.iter().any(|n| n == iface_name) {
|
||||
return false;
|
||||
}
|
||||
if let Some(allowed) = devices
|
||||
&& !allowed.iter().any(|n| n == iface_name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -623,19 +623,19 @@ fn get_link_local_addrs(
|
||||
if !iface_passes_filters(&iface.name, devices, ignored_devices) {
|
||||
continue;
|
||||
}
|
||||
if let std::net::IpAddr::V6(addr) = iface.addr.ip() {
|
||||
if (addr.segments()[0] & 0xffc0) == 0xfe80 {
|
||||
let scope_id = iface_scope_id(&iface);
|
||||
if scope_id == 0 {
|
||||
tracing::warn!(
|
||||
iface = %iface.name,
|
||||
addr = %addr,
|
||||
"skipping link-local: could not resolve scope id (would send on wrong NIC)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
result.push((iface.name.clone(), addr, scope_id));
|
||||
if let std::net::IpAddr::V6(addr) = iface.addr.ip()
|
||||
&& (addr.segments()[0] & 0xffc0) == 0xfe80
|
||||
{
|
||||
let scope_id = iface_scope_id(&iface);
|
||||
if scope_id == 0 {
|
||||
tracing::warn!(
|
||||
iface = %iface.name,
|
||||
addr = %addr,
|
||||
"skipping link-local: could not resolve scope id (would send on wrong NIC)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
result.push((iface.name.clone(), addr, scope_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1021,6 +1021,17 @@ fn hex_prefix(bytes: &[u8], n: usize) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
fn multicast_join_candidates(
|
||||
link_locals: &[(String, Ipv6Addr, u32)],
|
||||
joined_memberships: &HashSet<(String, u32)>,
|
||||
) -> Vec<(String, Ipv6Addr, u32)> {
|
||||
link_locals
|
||||
.iter()
|
||||
.filter(|(ifname, _, scope_id)| !joined_memberships.contains(&(ifname.clone(), *scope_id)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Spawn the auto-discovery interface.
|
||||
pub async fn spawn_auto_interface(
|
||||
config: AutoInterfaceConfig,
|
||||
@@ -1070,6 +1081,8 @@ pub async fn spawn_auto_interface(
|
||||
})?);
|
||||
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
|
||||
|
||||
let mut joined_memberships: HashSet<(String, u32)> = HashSet::new();
|
||||
let mut reported_join_failures: HashSet<(String, u32)> = HashSet::new();
|
||||
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
|
||||
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
|
||||
tracing::warn!(
|
||||
@@ -1080,28 +1093,33 @@ pub async fn spawn_auto_interface(
|
||||
"failed to set IPv6 multicast outbound interface"
|
||||
);
|
||||
}
|
||||
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
|
||||
// PermissionDenied (EPERM/EACCES, Windows ERROR_ACCESS_DENIED) on
|
||||
// Apple platforms is the canonical signal that the multicast
|
||||
// networking entitlement isn't provisioned. Surfaced as an event
|
||||
// so UIs can show pending Apple approval.
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
tracing::warn!(
|
||||
iface = %iface_name,
|
||||
error = %e,
|
||||
"multicast join denied by OS — entitlement / firewall / capability missing"
|
||||
);
|
||||
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
|
||||
interface_name: config.name.clone(),
|
||||
ifname: iface_name.clone(),
|
||||
reason: format!("os_permission_denied: {e}"),
|
||||
});
|
||||
} else {
|
||||
tracing::debug!(
|
||||
iface = %iface_name,
|
||||
error = %e,
|
||||
"failed to join multicast group"
|
||||
);
|
||||
match disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
|
||||
Ok(()) => {
|
||||
joined_memberships.insert((iface_name.clone(), *scope_id));
|
||||
}
|
||||
Err(e) => {
|
||||
// iOS can reject the first operation while Local Network
|
||||
// authorization is being resolved. Keep the interface alive;
|
||||
// the jobs task retries missing memberships periodically.
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
reported_join_failures.insert((iface_name.clone(), *scope_id));
|
||||
tracing::warn!(
|
||||
iface = %iface_name,
|
||||
error = %e,
|
||||
"multicast join denied by OS — permission, entitlement, firewall, or capability missing"
|
||||
);
|
||||
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
|
||||
interface_name: config.name.clone(),
|
||||
ifname: iface_name.clone(),
|
||||
reason: format!("os_permission_denied: {e}"),
|
||||
});
|
||||
} else {
|
||||
tracing::debug!(
|
||||
iface = %iface_name,
|
||||
error = %e,
|
||||
"failed to join multicast group"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1509,7 +1527,9 @@ pub async fn spawn_auto_interface(
|
||||
"AutoInterface link-local set changed"
|
||||
);
|
||||
}
|
||||
for (ifname, addr, scope_id) in &added {
|
||||
let join_candidates = multicast_join_candidates(&new_set, &joined_memberships);
|
||||
for (ifname, addr, scope_id) in &join_candidates {
|
||||
let membership = (ifname.clone(), *scope_id);
|
||||
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
|
||||
tracing::warn!(
|
||||
iface = %jobs_iface_name,
|
||||
@@ -1522,32 +1542,50 @@ pub async fn spawn_auto_interface(
|
||||
);
|
||||
}
|
||||
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
|
||||
Ok(()) => tracing::info!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
addr = %addr,
|
||||
scope_id,
|
||||
"AutoInterface joined multicast on new NIC"
|
||||
),
|
||||
Ok(()) => {
|
||||
joined_memberships.insert(membership.clone());
|
||||
reported_join_failures.remove(&membership);
|
||||
tracing::info!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
addr = %addr,
|
||||
scope_id,
|
||||
"AutoInterface joined multicast on NIC"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
let first_report = reported_join_failures.insert(membership);
|
||||
if first_report && e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
dispatch_auto_event(AutoInterfaceEvent::JoinFailed {
|
||||
interface_name: jobs_iface_name.clone(),
|
||||
ifname: ifname.clone(),
|
||||
reason: format!("os_permission_denied: {e}"),
|
||||
});
|
||||
}
|
||||
tracing::warn!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
error = %e,
|
||||
"AutoInterface multicast join failed on new NIC"
|
||||
);
|
||||
if first_report {
|
||||
tracing::warn!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
error = %e,
|
||||
"AutoInterface multicast join failed; will retry"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
iface = %jobs_iface_name,
|
||||
nic = %ifname,
|
||||
error = %e,
|
||||
"AutoInterface multicast join retry failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (ifname, _addr, scope_id) in &removed {
|
||||
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
|
||||
let membership = (ifname.clone(), *scope_id);
|
||||
if joined_memberships.remove(&membership) {
|
||||
let _ = jobs_disc_sock.leave_multicast_v6(&jobs_mcast, *scope_id);
|
||||
}
|
||||
reported_join_failures.remove(&membership);
|
||||
jobs_echoes.lock().await.remove(ifname);
|
||||
carrier_state.remove(ifname);
|
||||
}
|
||||
@@ -1765,6 +1803,26 @@ mod tests {
|
||||
assert_eq!(group.segments()[7], 0x31e1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multicast_join_candidates_retries_unchanged_missing_membership() {
|
||||
let en0_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
|
||||
let en1_addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
|
||||
let link_locals = vec![
|
||||
("en0".to_string(), en0_addr, 4),
|
||||
("en1".to_string(), en1_addr, 7),
|
||||
];
|
||||
let joined = HashSet::from([("en0".to_string(), 4)]);
|
||||
|
||||
assert_eq!(
|
||||
multicast_join_candidates(&link_locals, &joined),
|
||||
vec![("en1".to_string(), en1_addr, 7)]
|
||||
);
|
||||
assert_eq!(
|
||||
multicast_join_candidates(&link_locals, &HashSet::new()),
|
||||
link_locals
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_multicast_address_all_scopes() {
|
||||
// High u16 = 0xff_T_S; bytes 2-13 of SHA-256("reticulum") fill the body.
|
||||
|
||||
@@ -190,9 +190,6 @@ pub fn build_ax25_kiss_init(config: &AX25KISSConfig) -> Vec<u8> {
|
||||
#[cfg(feature = "serial")]
|
||||
const AX25_READ_TIMEOUT_MS: u64 = 100;
|
||||
|
||||
#[cfg(feature = "serial")]
|
||||
const FLOW_CONTROL_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
/// Parse `"CALL-SSID"` or `"CALL"`; uppercased call, SSID defaults to 0.
|
||||
pub fn parse_callsign_ssid(input: &str) -> Result<(String, u8), String> {
|
||||
let (call_part, ssid) = if let Some(idx) = input.rfind('-') {
|
||||
@@ -264,6 +261,7 @@ pub async fn spawn_ax25kiss_interface(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
@@ -295,31 +293,46 @@ pub async fn spawn_ax25kiss_interface(
|
||||
let txb_w = shared_txb.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
while let Some(data) = rx.recv().await {
|
||||
loop {
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let background_packet = if rx.is_empty() {
|
||||
background.try_start_when(rns_transport::now_f64(), || {
|
||||
!flow_control
|
||||
|| ready_w
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_ok()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data = if let Some(packet) = &background_packet {
|
||||
packet.raw().clone()
|
||||
} else {
|
||||
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => continue,
|
||||
}
|
||||
};
|
||||
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
|
||||
if flow_control {
|
||||
let start = std::time::Instant::now();
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
if flow_control && background_packet.is_none() {
|
||||
while ready_w
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
if start.elapsed() > Duration::from_secs(FLOW_CONTROL_TIMEOUT_SECS) {
|
||||
tracing::warn!("AX.25 KISS flow control timeout, unlocking");
|
||||
ready_w.store(true, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let framed =
|
||||
frame_ax25_kiss(&data, &dst_call_bytes, dst_ssid, &src_call_bytes, src_ssid);
|
||||
|
||||
if flow_control {
|
||||
ready_w.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
match crate::serial_io::blocking_write_all(port_w, framed).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
|
||||
@@ -1182,7 +1182,7 @@ mod tests {
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
|
||||
|
||||
for index in 0..=policy.grace {
|
||||
let listener = if index % 2 == 0 {
|
||||
let listener = if index.is_multiple_of(2) {
|
||||
&first_listener
|
||||
} else {
|
||||
&second_listener
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Exact-channel optional lane shared by the built-in final writers.
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
use bytes::Bytes;
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
pub(crate) use rns_transport::background_egress::BackgroundAnnounceReceiver;
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
use tokio::sync::mpsc;
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
pub(crate) fn register(
|
||||
tx: &mpsc::Sender<Bytes>,
|
||||
) -> Result<BackgroundAnnounceReceiver, crate::traits::InterfaceError> {
|
||||
BackgroundAnnounceReceiver::register(tx).map_err(|error| {
|
||||
crate::traits::InterfaceError::SendFailed(format!(
|
||||
"background announce registration failed: {error:?}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scheduled_actor(
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
) -> (
|
||||
tokio::task::JoinHandle<()>,
|
||||
mpsc::Sender<rns_transport::messages::TransportMessage>,
|
||||
Bytes,
|
||||
) {
|
||||
scheduled_actor_with_backlog(tx, 1)
|
||||
}
|
||||
|
||||
/// A saturated scheduler uses a sub-clock-resolution cap interval so every
|
||||
/// explicit actor tick is a due window. Writer readiness remains independent.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scheduled_actor_with_backlog(
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
count: usize,
|
||||
) -> (
|
||||
tokio::task::JoinHandle<()>,
|
||||
mpsc::Sender<rns_transport::messages::TransportMessage>,
|
||||
Bytes,
|
||||
) {
|
||||
use rns_transport::{
|
||||
actor::TransportActor,
|
||||
constants::{InterfaceDirection, InterfaceMode},
|
||||
messages::{InterfaceEntry, QueuedAnnounce},
|
||||
};
|
||||
let (mut actor, control) = TransportActor::new();
|
||||
let bitrate = if count > 1 { u64::MAX } else { 500 };
|
||||
let mut entry = InterfaceEntry::new(
|
||||
"radio with no name heuristic".into(),
|
||||
InterfaceMode::Full,
|
||||
InterfaceDirection::bidirectional(),
|
||||
bitrate,
|
||||
500,
|
||||
tx,
|
||||
);
|
||||
let identity = rns_identity::identity::Identity::new();
|
||||
let mut first = Bytes::new();
|
||||
for index in 0..count {
|
||||
let app = format!("test.background.{index}");
|
||||
let dest = rns_identity::destination::Destination::hash_from_name_and_identity(
|
||||
&app,
|
||||
Some(&identity.hash),
|
||||
);
|
||||
let announce =
|
||||
rns_identity::announce::AnnounceData::create(&identity, &app, None, None).unwrap();
|
||||
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::Single,
|
||||
packet_type: rns_wire::flags::PacketType::Announce,
|
||||
},
|
||||
hops: 1,
|
||||
transport_id: None,
|
||||
destination_hash: dest,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend(announce.pack());
|
||||
let raw = Bytes::from(raw);
|
||||
if index == 0 {
|
||||
first = raw.clone();
|
||||
}
|
||||
entry.announce_queue.push(QueuedAnnounce {
|
||||
destination_hash: dest,
|
||||
time: rns_transport::now_f64(),
|
||||
hops: 1,
|
||||
raw,
|
||||
});
|
||||
actor.local_destinations.insert(dest);
|
||||
}
|
||||
actor.interfaces.insert(1, entry);
|
||||
(tokio::spawn(actor.run()), control, first)
|
||||
}
|
||||
@@ -256,16 +256,16 @@ pub async fn teardown_central() -> Result<(), String> {
|
||||
}
|
||||
|
||||
fn finalize_stop() {
|
||||
if let Some(lock) = POWERED_ON_TX.get() {
|
||||
if let Ok(mut g) = lock.lock() {
|
||||
*g = None;
|
||||
}
|
||||
if let Some(lock) = POWERED_ON_TX.get()
|
||||
&& let Ok(mut g) = lock.lock()
|
||||
{
|
||||
*g = None;
|
||||
}
|
||||
// Drop the discovery sender so receivers don't hang on recv.
|
||||
if let Some(lock) = DISCOVERY_TX.get() {
|
||||
if let Ok(mut g) = lock.lock() {
|
||||
*g = None;
|
||||
}
|
||||
if let Some(lock) = DISCOVERY_TX.get()
|
||||
&& let Ok(mut g) = lock.lock()
|
||||
{
|
||||
*g = None;
|
||||
}
|
||||
apply_event(CentralEvent::ScanStopped);
|
||||
apply_event(CentralEvent::Reset);
|
||||
@@ -566,13 +566,11 @@ fn get_delegate_class() -> &'static AnyClass {
|
||||
|
||||
// No sender means stop_scan raced us between the radio event
|
||||
// and this callback — drop silently.
|
||||
if let Some(lock) = DISCOVERY_TX.get() {
|
||||
if let Ok(g) = lock.lock() {
|
||||
if let Some(tx) = g.as_ref() {
|
||||
if let Some(lock) = DISCOVERY_TX.get()
|
||||
&& let Ok(g) = lock.lock()
|
||||
&& let Some(tx) = g.as_ref() {
|
||||
let _ = tx.send(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Connection-state callbacks share this delegate (one delegate per
|
||||
|
||||
@@ -7,10 +7,11 @@
|
||||
|
||||
#![cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
|
||||
use crate::ble_tx_queue::PacketQueue;
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_foundation::NSString;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -33,10 +34,6 @@ pub const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
const DISCOVERED_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Sized to absorb an LXMF fragment burst (~40 × 244B) without unbounded
|
||||
/// growth on a stuck peer. FIFO drop-oldest.
|
||||
const PENDING_WRITE_CAP: usize = 128;
|
||||
|
||||
struct SendPtr(*mut AnyObject);
|
||||
unsafe impl Send for SendPtr {}
|
||||
unsafe impl Sync for SendPtr {}
|
||||
@@ -66,9 +63,6 @@ static ONLINE_FLAGS: OnceLock<Mutex<HashMap<String, Arc<AtomicBool>>>> = OnceLoc
|
||||
/// transient RPA-rotation drops from genuine peer failures.
|
||||
static LAST_DISCONNECT_REASON: OnceLock<Mutex<HashMap<String, DisconnectReason>>> = OnceLock::new();
|
||||
|
||||
/// Drained by `peripheralIsReadyToSendWriteWithoutResponse:`.
|
||||
static PENDING_WRITE: OnceLock<Mutex<HashMap<String, VecDeque<Vec<u8>>>>> = OnceLock::new();
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DisconnectReason {
|
||||
/// `CBErrorPeripheralConnectionTimeout` — almost always an iPhone /
|
||||
@@ -121,10 +115,6 @@ fn last_disconnect_reason() -> &'static Mutex<HashMap<String, DisconnectReason>>
|
||||
LAST_DISCONNECT_REASON.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
fn pending_write() -> &'static Mutex<HashMap<String, VecDeque<Vec<u8>>>> {
|
||||
PENDING_WRITE.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
pub fn take_last_disconnect_reason(address: &str) -> Option<DisconnectReason> {
|
||||
last_disconnect_reason()
|
||||
.lock()
|
||||
@@ -144,6 +134,7 @@ pub struct ConnectedPeer {
|
||||
delegate: SendPtr,
|
||||
rx_char: SendPtr,
|
||||
tx_char: SendPtr,
|
||||
pending_write: Mutex<PacketQueue>,
|
||||
}
|
||||
|
||||
impl Drop for ConnectedPeer {
|
||||
@@ -152,8 +143,13 @@ impl Drop for ConnectedPeer {
|
||||
// Clear the (weakly-retained) delegate first so a late callback
|
||||
// can't fire into freed memory after the release below.
|
||||
if !self.peripheral.0.is_null() {
|
||||
let _: () =
|
||||
msg_send![self.peripheral.0, setDelegate: std::ptr::null::<AnyObject>()];
|
||||
// A retired write task can outlive reconnect. Do not detach
|
||||
// a replacement delegate on the same peripheral object.
|
||||
let current: *mut AnyObject = msg_send![self.peripheral.0, delegate];
|
||||
if current == self.delegate.0 {
|
||||
let _: () =
|
||||
msg_send![self.peripheral.0, setDelegate: std::ptr::null::<AnyObject>()];
|
||||
}
|
||||
}
|
||||
for p in [
|
||||
&self.delegate,
|
||||
@@ -400,6 +396,7 @@ pub async fn connect_peer(
|
||||
delegate,
|
||||
rx_char,
|
||||
tx_char,
|
||||
pending_write: Mutex::new(PacketQueue::default()),
|
||||
});
|
||||
{
|
||||
let mut g = connected_peers().lock().expect("connected_peers lock");
|
||||
@@ -408,88 +405,53 @@ pub async fn connect_peer(
|
||||
Ok(peer)
|
||||
}
|
||||
|
||||
/// Queues into [`PENDING_WRITE`] when `canSendWriteWithoutResponse` is
|
||||
/// false — without queueing, fragmented LXMF messages silently lose every
|
||||
/// fragment past the first on a loaded radio.
|
||||
/// Queue a single already-fragmented value. Full queues refuse the new value;
|
||||
/// accepted values are never evicted. Packet producers should use the internal
|
||||
/// complete-packet admission path so overload cannot admit a partial packet.
|
||||
pub fn write_peer(address: &str, data: &[u8]) -> Result<(), String> {
|
||||
let peer = {
|
||||
let g = connected_peers().lock().expect("connected_peers lock");
|
||||
g.get(address).cloned()
|
||||
};
|
||||
let peer = peer.ok_or_else(|| format!("peer {address} not connected"))?;
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return Err(format!("peer {address} marked offline"));
|
||||
let peer = connected_peers()
|
||||
.lock()
|
||||
.expect("connected_peers lock")
|
||||
.get(address)
|
||||
.cloned()
|
||||
.ok_or_else(|| "peer not connected".to_string())?;
|
||||
if enqueue_packet(&peer, vec![data.to_vec()])? {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("native write queue full".into())
|
||||
}
|
||||
|
||||
// Always enqueue, then drain, so every fragment leaves through the single
|
||||
// FIFO path. Issuing directly on a "ready" radio would let a later
|
||||
// fragment jump ahead of ones already queued from when it was busy, and
|
||||
// the receiver would misparse the out-of-order envelope as a raw packet.
|
||||
{
|
||||
let mut g = pending_write().lock().expect("pending_write lock");
|
||||
let q = g.entry(address.to_owned()).or_default();
|
||||
if q.len() >= PENDING_WRITE_CAP {
|
||||
q.pop_front();
|
||||
tracing::warn!(
|
||||
target: "ble_trace",
|
||||
step = "central.write_overflow_drop",
|
||||
peer = %address,
|
||||
cap = PENDING_WRITE_CAP,
|
||||
"Apple BLE central: pending-write ring overflowed, dropping oldest"
|
||||
);
|
||||
}
|
||||
q.push_back(data.to_vec());
|
||||
}
|
||||
unsafe { drain_pending_writes(address) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drains queued writes in FIFO order while the radio can accept them. Holds
|
||||
/// the pending-write lock across the whole loop so a concurrent drain (or a
|
||||
/// [`write_peer`] enqueue) can't interleave and reorder fragments — an
|
||||
/// out-of-order envelope makes the receiver misparse the frame as a raw packet.
|
||||
unsafe fn drain_pending_writes(address: &str) {
|
||||
let peer = {
|
||||
let g = connected_peers().lock().expect("connected_peers lock");
|
||||
match g.get(address) {
|
||||
Some(p) => p.clone(),
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
pub(crate) fn write_packet(peer: &Arc<ConnectedPeer>, data: &[u8]) -> Result<bool, String> {
|
||||
enqueue_packet(peer, crate::ble_peer::fragment_packet(data, peer.write_mtu))
|
||||
}
|
||||
|
||||
fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, String> {
|
||||
let mut q = peer.pending_write.lock().expect("pending_write lock");
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return;
|
||||
return Err("peer offline".into());
|
||||
}
|
||||
let mut drained = 0usize;
|
||||
let mut g = pending_write().lock().expect("pending_write lock");
|
||||
let Some(q) = g.get_mut(address) else {
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
// Peek before popping: leave the fragment queued if the radio can't
|
||||
// take it, so ordering is preserved for the next drain.
|
||||
if q.front().is_none() {
|
||||
break;
|
||||
if frames.iter().any(|frame| frame.len() > peer.write_mtu) {
|
||||
return Err("frame exceeds native value limit".into());
|
||||
}
|
||||
let admitted = q.enqueue(frames);
|
||||
drain_peer_queue(peer, &mut q);
|
||||
q.report("apple_central", peer.write_mtu);
|
||||
Ok(admitted)
|
||||
}
|
||||
|
||||
fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
break;
|
||||
return false;
|
||||
}
|
||||
let Some(data) = q.pop_front() else {
|
||||
break;
|
||||
};
|
||||
unsafe { issue_write(&peer, &data) };
|
||||
drained += 1;
|
||||
}
|
||||
drop(g);
|
||||
if drained > 0 {
|
||||
tracing::debug!(
|
||||
target: "ble_trace",
|
||||
step = "central.write_drained",
|
||||
peer = %address,
|
||||
drained,
|
||||
"Apple BLE central: pending writes drained"
|
||||
);
|
||||
}
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
}
|
||||
|
||||
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be
|
||||
@@ -498,7 +460,7 @@ unsafe fn drain_pending_writes(address: &str) {
|
||||
/// # Safety
|
||||
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
|
||||
/// pointers.
|
||||
unsafe fn issue_write(peer: &Arc<ConnectedPeer>, data: &[u8]) {
|
||||
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
|
||||
unsafe {
|
||||
let nsdata = nsdata_from_slice(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
@@ -519,8 +481,8 @@ pub fn disconnect_peer(address: &str) {
|
||||
return;
|
||||
};
|
||||
peer.online.store(false, Ordering::SeqCst);
|
||||
if let Ok(mut g) = pending_write().lock() {
|
||||
g.remove(address);
|
||||
if let Ok(mut q) = peer.pending_write.lock() {
|
||||
*q = PacketQueue::default();
|
||||
}
|
||||
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
|
||||
unsafe {
|
||||
@@ -646,12 +608,16 @@ pub unsafe fn adopt_restored_peer(
|
||||
let peer = Arc::new(ConnectedPeer {
|
||||
address: address.clone(),
|
||||
protocol,
|
||||
write_mtu: 244,
|
||||
write_mtu: unsafe {
|
||||
let value: usize = msg_send![peripheral, maximumWriteValueLengthForType: 1usize];
|
||||
value.clamp(20, crate::ble_peer::TARGET_MTU as usize)
|
||||
},
|
||||
online,
|
||||
peripheral: SendPtr(peripheral),
|
||||
delegate,
|
||||
rx_char,
|
||||
tx_char,
|
||||
pending_write: Mutex::new(PacketQueue::default()),
|
||||
});
|
||||
{
|
||||
let mut g = connected_peers().lock().expect("connected_peers lock");
|
||||
@@ -671,9 +637,13 @@ pub unsafe fn adopt_restored_peer(
|
||||
/// UIBackgroundMode + restore-identifier; this just logs inventory.
|
||||
pub fn on_app_will_resign_active() {
|
||||
let connected = connected_peers().lock().map(|g| g.len()).unwrap_or(0);
|
||||
let pending = pending_write()
|
||||
let pending = connected_peers()
|
||||
.lock()
|
||||
.map(|g| g.values().map(|q| q.len()).sum::<usize>())
|
||||
.map(|g| {
|
||||
g.values()
|
||||
.map(|p| p.pending_write.lock().map(|q| q.len()).unwrap_or(0))
|
||||
.sum::<usize>()
|
||||
})
|
||||
.unwrap_or(0);
|
||||
tracing::info!(
|
||||
target: "ble_trace",
|
||||
@@ -684,7 +654,7 @@ pub fn on_app_will_resign_active() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Prune discovered pointers older than [`DISCOVERED_TTL`] — after a long
|
||||
/// Prune discovered pointers older than the discovery TTL — after a long
|
||||
/// background those are RPA-rotated ghosts.
|
||||
pub fn on_app_did_become_active() {
|
||||
prune_discovered();
|
||||
@@ -762,10 +732,10 @@ pub fn on_did_disconnect(address: &str, err: Option<String>) {
|
||||
if let Some(peer) = removed {
|
||||
peer.online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
if let Ok(mut g) = online_flags().lock() {
|
||||
if let Some(flag) = g.remove(address) {
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
if let Ok(mut g) = online_flags().lock()
|
||||
&& let Some(flag) = g.remove(address)
|
||||
{
|
||||
flag.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
let classified = classify_disconnect_reason(err.as_deref());
|
||||
@@ -971,7 +941,18 @@ fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
if address.is_empty() {
|
||||
return;
|
||||
}
|
||||
unsafe { drain_pending_writes(&address) };
|
||||
let peer = connected_peers()
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|g| g.get(&address).cloned());
|
||||
if let Some(peer) = peer {
|
||||
// Old delegates cannot drain a replacement connection's queue.
|
||||
if peer.peripheral.0 != peripheral || peer.delegate.0 != _this {
|
||||
return;
|
||||
}
|
||||
let mut q = peer.pending_write.lock().expect("pending_write lock");
|
||||
drain_peer_queue(&peer, &mut q);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Private bounds for desktop GATT setup and Windows address resolution.
|
||||
|
||||
use std::{fmt::Display, future::Future, time::Duration};
|
||||
|
||||
const OPERATION_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
pub(super) async fn operation<T, E: Display>(
|
||||
label: &str,
|
||||
future: impl Future<Output = Result<T, E>>,
|
||||
) -> Result<T, String> {
|
||||
tokio::time::timeout(OPERATION_TIMEOUT, future)
|
||||
.await
|
||||
.map_err(|_| format!("{label}: timed out"))?
|
||||
.map_err(|error| format!("{label}: {error}"))
|
||||
}
|
||||
|
||||
/// Cancels an in-flight setup when its interface generation ends. The caller
|
||||
/// retains the peripheral in the teardown registry until cleanup completes.
|
||||
pub(super) async fn while_current<T>(
|
||||
future: impl Future<Output = Result<T, String>>,
|
||||
current: impl Fn() -> bool,
|
||||
) -> Result<T, String> {
|
||||
tokio::pin!(future);
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(50));
|
||||
loop {
|
||||
if !current() {
|
||||
return Err("BLE connection cancelled".into());
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = tick.tick() => {},
|
||||
result = &mut future => {
|
||||
return if current() { result } else { Err("BLE connection cancelled".into()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) fn known_address(value: &str) -> Option<btleplug::api::BDAddr> {
|
||||
let address: btleplug::api::BDAddr = value.parse().ok()?;
|
||||
// Neither sentinel can identify an explicitly selected device.
|
||||
(!matches!(
|
||||
address.to_string().as_str(),
|
||||
"00:00:00:00:00:00" | "FF:FF:FF:FF:FF:FF"
|
||||
))
|
||||
.then_some(address)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) async fn resolve_address<T, E: Display, F: Future<Output = Result<T, E>>>(
|
||||
cached: Option<T>,
|
||||
address: &str,
|
||||
add: impl FnOnce(btleplug::api::BDAddr) -> F,
|
||||
) -> Result<T, String> {
|
||||
if let Some(peripheral) = cached {
|
||||
return Ok(peripheral);
|
||||
}
|
||||
let address = known_address(address).ok_or("No valid configured BLE address")?;
|
||||
operation("Resolve BLE address", add(address)).await
|
||||
}
|
||||
|
||||
/// Keep the existing desktop ceiling; only shrink writes when the negotiated
|
||||
/// ATT MTU requires it. Unknown/invalid MTUs use BLE's mandatory baseline.
|
||||
pub(super) fn write_payload(mtu: u16) -> usize {
|
||||
if mtu < 23 {
|
||||
20
|
||||
} else {
|
||||
usize::from(mtu - 3).min(182)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_device_does_not_attempt_address_creation() {
|
||||
let result = resolve_address(Some(7), "platform-id", |_| async {
|
||||
panic!("must not add a cached peripheral");
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<_, String>(8)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result, Ok(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_explicit_addresses_can_create_peripherals() {
|
||||
for invalid in [
|
||||
"",
|
||||
"RNode One",
|
||||
"1234",
|
||||
"00:00:00:00:00:00",
|
||||
"FF:FF:FF:FF:FF:FF",
|
||||
"AE34CD04-9854-4E64-8870-D58631FBBCC4",
|
||||
] {
|
||||
assert!(
|
||||
resolve_address::<(), String, _>(None, invalid, |_| async {
|
||||
panic!("invalid target reached the platform");
|
||||
#[allow(unreachable_code)]
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resolve_address(None, "aa:bb:cc:dd:ee:01", |address| async move {
|
||||
Ok::<_, String>(address.to_string())
|
||||
})
|
||||
.await
|
||||
.unwrap(),
|
||||
"AA:BB:CC:DD:EE:01"
|
||||
);
|
||||
assert!(
|
||||
resolve_address::<(), _, _>(None, "AA:BB:CC:DD:EE:01", |_| async {
|
||||
Err("adapter unavailable")
|
||||
})
|
||||
.await
|
||||
.unwrap_err()
|
||||
.contains("adapter unavailable")
|
||||
);
|
||||
}
|
||||
|
||||
struct DropFlag(Arc<AtomicBool>);
|
||||
impl Drop for DropFlag {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unavailable_device_is_bounded_and_releases_pending_work() {
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let guard = DropFlag(dropped.clone());
|
||||
let result = resolve_address::<(), String, _>(None, "AA:BB:CC:DD:EE:01", |_| async move {
|
||||
let _guard = guard;
|
||||
std::future::pending().await
|
||||
})
|
||||
.await;
|
||||
assert!(result.unwrap_err().contains("timed out"));
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn generation_change_cancels_pending_setup_before_timeout() {
|
||||
let active = Arc::new(AtomicBool::new(true));
|
||||
let stop = active.clone();
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let guard = DropFlag(dropped.clone());
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(75)).await;
|
||||
stop.store(false, Ordering::SeqCst);
|
||||
});
|
||||
let start = tokio::time::Instant::now();
|
||||
let result: Result<(), String> = while_current(
|
||||
async move {
|
||||
let _guard = guard;
|
||||
std::future::pending().await
|
||||
},
|
||||
|| active.load(Ordering::SeqCst),
|
||||
)
|
||||
.await;
|
||||
assert!(result.unwrap_err().contains("cancelled"));
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiated_mtu_never_exceeds_existing_write_ceiling() {
|
||||
for (mtu, expected) in [
|
||||
(0, 20),
|
||||
(22, 20),
|
||||
(23, 20),
|
||||
(100, 97),
|
||||
(185, 182),
|
||||
(247, 182),
|
||||
] {
|
||||
assert_eq!(write_payload(mtu), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+2839
-1235
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,354 @@
|
||||
//! Pure connection-generation ownership for the btleplug RNode transport.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{Stream, StreamExt};
|
||||
|
||||
const STOP_POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub(super) struct BleGenerationId(u64);
|
||||
|
||||
impl BleGenerationId {
|
||||
pub(super) fn next(&mut self) -> Self {
|
||||
self.0 = self.0.wrapping_add(1).max(1);
|
||||
*self
|
||||
}
|
||||
|
||||
pub(super) const fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) enum BleOperationStage {
|
||||
Connect,
|
||||
ConnectedCheck,
|
||||
Discovery,
|
||||
#[cfg_attr(
|
||||
not(any(
|
||||
target_os = "ios",
|
||||
target_os = "macos",
|
||||
target_os = "windows",
|
||||
target_os = "android"
|
||||
)),
|
||||
allow(dead_code)
|
||||
)]
|
||||
PairingRead,
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "ios", target_os = "macos", test)),
|
||||
allow(dead_code)
|
||||
)]
|
||||
PairingSubscribe,
|
||||
Subscribe,
|
||||
NotificationAcquisition,
|
||||
Detect,
|
||||
Capability,
|
||||
Configure,
|
||||
ActiveWrite,
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
impl BleOperationStage {
|
||||
pub(super) const fn deadline(self) -> Duration {
|
||||
match self {
|
||||
Self::PairingRead | Self::PairingSubscribe => Duration::from_secs(60),
|
||||
Self::ActiveWrite => Duration::from_secs(5),
|
||||
Self::Disconnect => Duration::from_secs(3),
|
||||
Self::Connect
|
||||
| Self::ConnectedCheck
|
||||
| Self::Discovery
|
||||
| Self::Subscribe
|
||||
| Self::NotificationAcquisition
|
||||
| Self::Detect
|
||||
| Self::Capability
|
||||
| Self::Configure => Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for BleOperationStage {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::Connect => "connect",
|
||||
Self::ConnectedCheck => "connected check",
|
||||
Self::Discovery => "service discovery",
|
||||
Self::PairingRead => "pairing read",
|
||||
Self::PairingSubscribe => "pairing notification subscribe",
|
||||
Self::Subscribe => "notification subscribe",
|
||||
Self::NotificationAcquisition => "notification acquisition",
|
||||
Self::Detect => "detect write",
|
||||
Self::Capability => "capability write",
|
||||
Self::Configure => "radio configuration write",
|
||||
Self::ActiveWrite => "application write",
|
||||
Self::Disconnect => "disconnect",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(super) enum BleGenerationExit {
|
||||
TargetDisconnected {
|
||||
stage: BleOperationStage,
|
||||
},
|
||||
DeadlineElapsed {
|
||||
stage: BleOperationStage,
|
||||
},
|
||||
StopRequested {
|
||||
stage: BleOperationStage,
|
||||
},
|
||||
EventStreamEnded {
|
||||
stage: BleOperationStage,
|
||||
},
|
||||
StageFailed {
|
||||
stage: BleOperationStage,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for BleGenerationExit {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::TargetDisconnected { stage } => {
|
||||
write!(formatter, "target disconnected during {stage}")
|
||||
}
|
||||
Self::DeadlineElapsed { stage } => write!(formatter, "{stage} timed out"),
|
||||
Self::StopRequested { stage } => write!(formatter, "stop requested during {stage}"),
|
||||
Self::EventStreamEnded { stage } => {
|
||||
write!(formatter, "adapter event stream ended during {stage}")
|
||||
}
|
||||
Self::StageFailed { stage, reason } => write!(formatter, "{stage}: {reason}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one platform future while the exact connection generation continues to
|
||||
/// own target-disconnect and stop observation. Unrelated central events are
|
||||
/// consumed but never end the operation.
|
||||
pub(super) async fn run_generation_operation<T, E, F, S, I, P>(
|
||||
stage: BleOperationStage,
|
||||
future: F,
|
||||
events: &mut S,
|
||||
running: &AtomicBool,
|
||||
is_target_disconnect: P,
|
||||
) -> Result<T, BleGenerationExit>
|
||||
where
|
||||
E: fmt::Display,
|
||||
F: std::future::Future<Output = Result<T, E>>,
|
||||
S: Stream<Item = I> + Unpin,
|
||||
P: FnMut(&I) -> bool,
|
||||
{
|
||||
run_generation_operation_with_timeout(
|
||||
stage,
|
||||
stage.deadline(),
|
||||
future,
|
||||
events,
|
||||
running,
|
||||
is_target_disconnect,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn run_generation_operation_with_timeout<T, E, F, S, I, P>(
|
||||
stage: BleOperationStage,
|
||||
timeout: Duration,
|
||||
future: F,
|
||||
events: &mut S,
|
||||
running: &AtomicBool,
|
||||
mut is_target_disconnect: P,
|
||||
) -> Result<T, BleGenerationExit>
|
||||
where
|
||||
E: fmt::Display,
|
||||
F: std::future::Future<Output = Result<T, E>>,
|
||||
S: Stream<Item = I> + Unpin,
|
||||
P: FnMut(&I) -> bool,
|
||||
{
|
||||
let deadline = tokio::time::Instant::now() + timeout;
|
||||
tokio::pin!(future);
|
||||
loop {
|
||||
if !running.load(Ordering::SeqCst) {
|
||||
return Err(BleGenerationExit::StopRequested { stage });
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut future => return result.map_err(|error| BleGenerationExit::StageFailed {
|
||||
stage,
|
||||
reason: error.to_string(),
|
||||
}),
|
||||
event = events.next() => match event {
|
||||
Some(event) if is_target_disconnect(&event) => {
|
||||
return Err(BleGenerationExit::TargetDisconnected { stage });
|
||||
}
|
||||
Some(_) => continue,
|
||||
None => return Err(BleGenerationExit::EventStreamEnded { stage }),
|
||||
},
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
return Err(BleGenerationExit::DeadlineElapsed { stage });
|
||||
}
|
||||
_ = tokio::time::sleep(STOP_POLL) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(super) struct PendingOutbound {
|
||||
payload: Bytes,
|
||||
station_id: bool,
|
||||
}
|
||||
|
||||
impl PendingOutbound {
|
||||
pub(super) const fn new(payload: Bytes, station_id: bool) -> Self {
|
||||
Self {
|
||||
payload,
|
||||
station_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn payload(&self) -> &Bytes {
|
||||
&self.payload
|
||||
}
|
||||
|
||||
pub(super) const fn is_station_id(&self) -> bool {
|
||||
self.station_id
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::stream;
|
||||
|
||||
#[tokio::test]
|
||||
async fn target_disconnect_preempts_platform_future_that_never_resolves() {
|
||||
for stage in [
|
||||
BleOperationStage::Connect,
|
||||
BleOperationStage::ConnectedCheck,
|
||||
BleOperationStage::Discovery,
|
||||
BleOperationStage::PairingRead,
|
||||
BleOperationStage::PairingSubscribe,
|
||||
BleOperationStage::Subscribe,
|
||||
BleOperationStage::NotificationAcquisition,
|
||||
BleOperationStage::Detect,
|
||||
BleOperationStage::Capability,
|
||||
BleOperationStage::Configure,
|
||||
BleOperationStage::ActiveWrite,
|
||||
] {
|
||||
let running = AtomicBool::new(true);
|
||||
let mut events = stream::iter(["other", "target"]);
|
||||
let outcome = run_generation_operation_with_timeout(
|
||||
stage,
|
||||
Duration::from_secs(1),
|
||||
std::future::pending::<Result<(), &'static str>>(),
|
||||
&mut events,
|
||||
&running,
|
||||
|event| *event == "target",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
outcome,
|
||||
Err(BleGenerationExit::TargetDisconnected { stage })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unrelated_disconnect_does_not_end_generation() {
|
||||
let running = AtomicBool::new(true);
|
||||
let mut events = stream::iter(["other"]).chain(stream::pending());
|
||||
let outcome = run_generation_operation_with_timeout(
|
||||
BleOperationStage::Subscribe,
|
||||
Duration::from_secs(1),
|
||||
async { Ok::<_, &'static str>(7) },
|
||||
&mut events,
|
||||
&running,
|
||||
|event| *event == "target",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(outcome, Ok(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_stage_has_an_independent_deadline() {
|
||||
for stage in [
|
||||
BleOperationStage::Connect,
|
||||
BleOperationStage::ConnectedCheck,
|
||||
BleOperationStage::Discovery,
|
||||
BleOperationStage::PairingRead,
|
||||
BleOperationStage::PairingSubscribe,
|
||||
BleOperationStage::Subscribe,
|
||||
BleOperationStage::NotificationAcquisition,
|
||||
BleOperationStage::Detect,
|
||||
BleOperationStage::Capability,
|
||||
BleOperationStage::Configure,
|
||||
BleOperationStage::ActiveWrite,
|
||||
BleOperationStage::Disconnect,
|
||||
] {
|
||||
let running = AtomicBool::new(true);
|
||||
let mut events = stream::pending::<&'static str>();
|
||||
let outcome = run_generation_operation_with_timeout(
|
||||
stage,
|
||||
Duration::from_millis(2),
|
||||
std::future::pending::<Result<(), &'static str>>(),
|
||||
&mut events,
|
||||
&running,
|
||||
|_| false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(outcome, Err(BleGenerationExit::DeadlineElapsed { stage }));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_preempts_pending_operation() {
|
||||
let running = AtomicBool::new(false);
|
||||
let mut events = stream::pending::<&'static str>();
|
||||
let outcome = run_generation_operation_with_timeout(
|
||||
BleOperationStage::ActiveWrite,
|
||||
Duration::from_secs(1),
|
||||
std::future::pending::<Result<(), &'static str>>(),
|
||||
&mut events,
|
||||
&running,
|
||||
|_| false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
outcome,
|
||||
Err(BleGenerationExit::StopRequested {
|
||||
stage: BleOperationStage::ActiveWrite,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn event_stream_closure_is_not_success() {
|
||||
let running = AtomicBool::new(true);
|
||||
let mut events = stream::empty::<&'static str>();
|
||||
let outcome = run_generation_operation_with_timeout(
|
||||
BleOperationStage::Connect,
|
||||
Duration::from_secs(1),
|
||||
std::future::pending::<Result<(), &'static str>>(),
|
||||
&mut events,
|
||||
&running,
|
||||
|_| false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
outcome,
|
||||
Err(BleGenerationExit::EventStreamEnded {
|
||||
stage: BleOperationStage::Connect,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_ids_are_monotonic_and_pending_payload_is_stable() {
|
||||
let mut id = BleGenerationId::default();
|
||||
assert!(id.next() < id.next());
|
||||
let pending = PendingOutbound::new(Bytes::from_static(b"packet"), false);
|
||||
assert_eq!(pending.payload(), &Bytes::from_static(b"packet"));
|
||||
assert!(!pending.is_station_id());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Bounded native TX admission. A packet is admitted in full or refused before
|
||||
//! any of its frames are sent. Callers serialize this queue and native writes
|
||||
//! under the same lock, including readiness callbacks and connection retirement.
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const PACKET_CAPACITY: usize = 128;
|
||||
const MAX_PACKET_FRAMES: usize = 64;
|
||||
const MAX_PACKET_BYTES: usize = 4096;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PacketQueue {
|
||||
packets: VecDeque<VecDeque<Vec<u8>>>,
|
||||
accepted: u64,
|
||||
rejected: u64,
|
||||
sent_frames: u64,
|
||||
sent_bytes: u64,
|
||||
blocked: u64,
|
||||
high_water: usize,
|
||||
reported: (u64, u64),
|
||||
}
|
||||
|
||||
impl PacketQueue {
|
||||
pub(crate) fn enqueue(&mut self, frames: Vec<Vec<u8>>) -> bool {
|
||||
if self.packets.len() >= PACKET_CAPACITY
|
||||
|| frames.is_empty()
|
||||
|| frames.len() > MAX_PACKET_FRAMES
|
||||
|| frames.iter().map(Vec::len).sum::<usize>() > MAX_PACKET_BYTES
|
||||
{
|
||||
self.rejected = self.rejected.saturating_add(1);
|
||||
return false;
|
||||
}
|
||||
self.packets.push_back(frames.into());
|
||||
self.accepted = self.accepted.saturating_add(1);
|
||||
self.high_water = self.high_water.max(self.packets.len());
|
||||
true
|
||||
}
|
||||
|
||||
/// Sends only the oldest frame. A refusal leaves it in place. Returns
|
||||
/// true only when one frame was accepted by the native stack.
|
||||
pub(crate) fn drain_one(&mut self, mut send: impl FnMut(&[u8]) -> bool) -> bool {
|
||||
let Some(packet) = self.packets.front_mut() else {
|
||||
return false;
|
||||
};
|
||||
let frame = packet.front().expect("admitted nonempty packet");
|
||||
if !send(frame) {
|
||||
self.blocked = self.blocked.saturating_add(1);
|
||||
return false;
|
||||
}
|
||||
self.sent_bytes = self.sent_bytes.saturating_add(frame.len() as u64);
|
||||
self.sent_frames = self.sent_frames.saturating_add(1);
|
||||
packet.pop_front();
|
||||
if packet.is_empty() {
|
||||
self.packets.pop_front();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.packets.len()
|
||||
}
|
||||
|
||||
pub(crate) fn report(&mut self, role: &'static str, value_limit: usize) {
|
||||
// Closed schema: no addresses, identifiers, payloads or native errors.
|
||||
// Sample admission milestones and exponentially spaced refusals.
|
||||
if (self.accepted != self.reported.0
|
||||
&& (self.accepted == 1 || self.accepted.is_multiple_of(64)))
|
||||
|| (self.rejected != self.reported.1 && self.rejected.is_power_of_two())
|
||||
{
|
||||
self.reported = (self.accepted, self.rejected);
|
||||
tracing::debug!(
|
||||
target: "rns_interface::ble_peer::transfer",
|
||||
role, value_limit, queued_packets = self.len(),
|
||||
high_water = self.high_water, accepted_packets = self.accepted,
|
||||
rejected_packets = self.rejected, sent_frames = self.sent_frames,
|
||||
sent_bytes = self.sent_bytes, backpressure = self.blocked,
|
||||
"BLE transmit queue counters"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reports_admission_milestones_and_spaced_refusals() {
|
||||
let mut q = PacketQueue::default();
|
||||
assert!(q.enqueue(vec![vec![1]]));
|
||||
q.report("test", 20);
|
||||
assert_eq!(q.reported, (1, 0));
|
||||
for _ in 1..63 {
|
||||
assert!(q.enqueue(vec![vec![1]]));
|
||||
q.report("test", 20);
|
||||
}
|
||||
assert_eq!(q.reported, (1, 0));
|
||||
assert!(q.enqueue(vec![vec![1]]));
|
||||
q.report("test", 20);
|
||||
assert_eq!(q.reported, (64, 0));
|
||||
for rejected in 1u64..=4 {
|
||||
assert!(!q.enqueue(vec![]));
|
||||
q.report("test", 20);
|
||||
assert_eq!(q.reported.1, if rejected == 3 { 2 } else { rejected });
|
||||
}
|
||||
assert_eq!(q.len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backpressure_keeps_middle_frame_ahead_of_later_packets() {
|
||||
let mut q = PacketQueue::default();
|
||||
assert!(q.enqueue(vec![vec![0], vec![1], vec![2]]));
|
||||
let mut sent = Vec::new();
|
||||
assert!(q.drain_one(|f| {
|
||||
sent.push(f[0]);
|
||||
true
|
||||
}));
|
||||
assert!(!q.drain_one(|_| false));
|
||||
assert!(q.enqueue(vec![vec![3], vec![4]]));
|
||||
while q.drain_one(|f| {
|
||||
sent.push(f[0]);
|
||||
true
|
||||
}) {}
|
||||
assert_eq!(sent, [0, 1, 2, 3, 4]);
|
||||
assert_eq!(q.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_refuses_entire_new_packet_without_evicting_old_frames() {
|
||||
let mut q = PacketQueue::default();
|
||||
for n in 0..PACKET_CAPACITY {
|
||||
assert!(q.enqueue(vec![vec![n as u8], vec![0xff]]));
|
||||
}
|
||||
assert!(!q.enqueue(vec![vec![0xee]; 3]));
|
||||
let mut sent = Vec::new();
|
||||
while q.drain_one(|f| {
|
||||
sent.push(f[0]);
|
||||
true
|
||||
}) {}
|
||||
let expected: Vec<_> = (0..PACKET_CAPACITY).flat_map(|n| [n as u8, 0xff]).collect();
|
||||
assert_eq!(sent, expected);
|
||||
assert_eq!(q.rejected, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_retirement_do_not_replay_partial_packets() {
|
||||
let mut q = PacketQueue::default();
|
||||
assert!(!q.enqueue(vec![]));
|
||||
assert!(!q.enqueue(vec![vec![0]; MAX_PACKET_FRAMES + 1]));
|
||||
assert!(!q.enqueue(vec![vec![0; MAX_PACKET_BYTES + 1]]));
|
||||
assert!(q.enqueue(vec![vec![0], vec![1]]));
|
||||
assert!(q.drain_one(|_| true));
|
||||
q = PacketQueue::default(); // New connection owns a new queue.
|
||||
assert!(!q.drain_one(|_| panic!("retired frame replayed")));
|
||||
assert!(q.enqueue(vec![vec![9]]));
|
||||
assert!(q.drain_one(|f| {
|
||||
assert_eq!(f, [9]);
|
||||
true
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,15 @@ pub async fn spawn_kiss_interface(
|
||||
crate::traits::InterfaceError::SendFailed(format!("kiss serial open: {}", e))
|
||||
})?;
|
||||
|
||||
spawn_kiss_with_port(config, id, transport_tx, port).await
|
||||
}
|
||||
|
||||
async fn spawn_kiss_with_port(
|
||||
config: KissInterfaceConfig,
|
||||
id: InterfaceId,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
port: Box<dyn serialport::SerialPort>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
tracing::info!(
|
||||
name = %config.name,
|
||||
port = %config.port,
|
||||
@@ -91,6 +100,7 @@ pub async fn spawn_kiss_interface(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let flow_control = config.flow_control;
|
||||
@@ -139,7 +149,19 @@ pub async fn spawn_kiss_interface(
|
||||
// beacon; cleared when the beacon goes out.
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let data = if let Some((interval, ref callsign)) = beacon {
|
||||
let background_packet = if rx.is_empty() && online_w.load(Ordering::SeqCst) {
|
||||
background.try_start_when(rns_transport::now_f64(), || {
|
||||
!flow_control
|
||||
|| ready_w
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_ok()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data = if let Some(packet) = &background_packet {
|
||||
packet.raw().clone()
|
||||
} else if let Some((interval, ref callsign)) = beacon {
|
||||
match tokio::time::timeout(Duration::from_secs(1), rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
@@ -153,9 +175,10 @@ pub async fn spawn_kiss_interface(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match rx.recv().await {
|
||||
Some(data) => data,
|
||||
None => break,
|
||||
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => continue,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -173,14 +196,12 @@ pub async fn spawn_kiss_interface(
|
||||
}
|
||||
|
||||
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
// Flow control: bounded wait so a stuck TNC can't hang transmit.
|
||||
if flow_control {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
tracing::warn!("KISS flow control timeout, proceeding anyway");
|
||||
break;
|
||||
}
|
||||
// READY is one packet permit. A timeout must never synthesize it.
|
||||
if flow_control && background_packet.is_none() {
|
||||
while ready_w
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
@@ -334,4 +355,59 @@ mod tests {
|
||||
let cfg = KissInterfaceConfig::new("kiss0", "/dev/ttyS0", 9600);
|
||||
assert_eq!(cfg.mode, InterfaceMode::Full);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn background_actor_kiss_pty_preserves_control_and_one_packet_ready() {
|
||||
use serialport::SerialPort;
|
||||
use std::io::{Read, Write};
|
||||
let (mut master, slave) = serialport::TTYPort::pair().unwrap();
|
||||
let name = slave.name().unwrap();
|
||||
master.set_timeout(Duration::from_millis(300)).unwrap();
|
||||
let (inbound, mut received) = mpsc::channel(4);
|
||||
let mut config = KissInterfaceConfig::new("arbitrary TNC", &name, 9600);
|
||||
config.flow_control = true;
|
||||
// macOS pseudo terminals cannot accept the hardware baud ioctl;
|
||||
// inject the already-open pair into the same production driver.
|
||||
let driver = spawn_kiss_with_port(config, 1, inbound, Box::new(slave))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut revoke = kiss::frame_with_command(kiss::CMD_READY, &[0]);
|
||||
revoke.extend(kiss::frame(b"read barrier"));
|
||||
master.write_all(&revoke).unwrap();
|
||||
received.recv().await.unwrap();
|
||||
let (actor, control, raw) = crate::background_announce::scheduled_actor(driver.tx.clone());
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let mut probe = [0; 2048];
|
||||
assert!(
|
||||
master.read(&mut probe).is_err(),
|
||||
"no timeout may synthesize READY"
|
||||
);
|
||||
driver
|
||||
.tx
|
||||
.send(Bytes::from_static(b"local control"))
|
||||
.await
|
||||
.unwrap();
|
||||
master
|
||||
.write_all(&kiss::frame_with_command(kiss::CMD_READY, &[1]))
|
||||
.unwrap();
|
||||
let expected = kiss::frame(b"local control");
|
||||
let mut actual = vec![0; expected.len()];
|
||||
master.read_exact(&mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
assert!(
|
||||
master.read(&mut probe).is_err(),
|
||||
"one READY cannot write two packets"
|
||||
);
|
||||
master
|
||||
.write_all(&kiss::frame_with_command(kiss::CMD_READY, &[1]))
|
||||
.unwrap();
|
||||
let expected = kiss::frame(&raw);
|
||||
let mut actual = vec![0; expected.len()];
|
||||
master.read_exact(&mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
driver.online.store(false, Ordering::SeqCst);
|
||||
control.send(TransportMessage::Shutdown).await.unwrap();
|
||||
actor.await.unwrap();
|
||||
driver.read_task.await.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,16 @@ pub mod ble_central_apple;
|
||||
pub mod ble_central_apple_connect;
|
||||
#[cfg(feature = "ble")]
|
||||
pub mod ble_central_lifecycle;
|
||||
#[cfg(all(feature = "ble", any(target_os = "windows", target_os = "linux", test)))]
|
||||
mod ble_connect;
|
||||
#[cfg(feature = "ble")]
|
||||
pub mod ble_peer;
|
||||
#[cfg(feature = "ble")]
|
||||
pub mod ble_peer_lifecycle;
|
||||
#[cfg(feature = "ble")]
|
||||
pub mod ble_rnode;
|
||||
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos", test)))]
|
||||
mod ble_tx_queue;
|
||||
pub mod hdlc;
|
||||
pub mod i2p;
|
||||
pub mod kiss;
|
||||
@@ -52,3 +56,5 @@ pub mod tcp;
|
||||
pub mod traits;
|
||||
pub mod udp;
|
||||
pub mod weave;
|
||||
|
||||
mod background_announce;
|
||||
@@ -21,10 +21,10 @@ pub const DEFAULT_SOCKET_PATH: &str = "/tmp/rns_reticulum.sock";
|
||||
|
||||
/// On Android `/tmp` isn't writable; falls back to caller's data directory.
|
||||
pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
|
||||
if cfg!(target_os = "android") {
|
||||
if let Some(dir) = data_dir {
|
||||
return dir.join("cache").join("rns_reticulum.sock");
|
||||
}
|
||||
if cfg!(target_os = "android")
|
||||
&& let Some(dir) = data_dir
|
||||
{
|
||||
return dir.join("cache").join("rns_reticulum.sock");
|
||||
}
|
||||
std::path::PathBuf::from(DEFAULT_SOCKET_PATH)
|
||||
}
|
||||
@@ -686,6 +686,7 @@ mod tests {
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = prefix;
|
||||
let listener =
|
||||
std::net::TcpListener::bind("127.0.0.1:0").expect("reserve local test port");
|
||||
let port = listener.local_addr().expect("read local test port").port();
|
||||
|
||||
@@ -150,6 +150,7 @@ pub const DEFAULT_TCP_PORT: u16 = 7633;
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RNodeStartupOptions {
|
||||
capability_policy: RNodeCapabilityPolicy,
|
||||
persist_bluetooth_enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
@@ -177,9 +178,21 @@ impl RNodeStartupOptions {
|
||||
pub const fn require_capability_admission() -> Self {
|
||||
Self {
|
||||
capability_policy: RNodeCapabilityPolicy::RequireValidatedAdmission,
|
||||
persist_bluetooth_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask BLE transports to persist Bluetooth as enabled on the RNode after
|
||||
/// the device has been admitted successfully.
|
||||
///
|
||||
/// This is an opt-in product policy. Generic rsReticulum callers retain
|
||||
/// the historical byte sequence unless they select it explicitly, and
|
||||
/// non-BLE RNode transports never emit the Bluetooth control command.
|
||||
pub const fn with_persisted_bluetooth_enabled(mut self) -> Self {
|
||||
self.persist_bluetooth_enabled = true;
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
@@ -192,12 +205,18 @@ impl RNodeStartupOptions {
|
||||
RNodeCapabilityPolicy::RequireValidatedAdmission
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "ble", target_os = "android", test))]
|
||||
pub(crate) const fn persists_bluetooth_enabled(self) -> bool {
|
||||
self.persist_bluetooth_enabled
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RNodeStartupOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
capability_policy: RNodeCapabilityPolicy::Legacy,
|
||||
persist_bluetooth_enabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -605,6 +624,14 @@ fn project_rnode_protocol_state(
|
||||
*snapshot != before
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn sync_rnode_interface_online(online: &AtomicBool, state: &RNodeProtocolState) {
|
||||
online.store(
|
||||
matches!(state.readiness(), RNodeReadiness::Ready),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
@@ -1253,7 +1280,7 @@ struct RNodeControlWriteRequest {
|
||||
enum RNodeWriterExit {
|
||||
Detached,
|
||||
Cancelled,
|
||||
Offline,
|
||||
CarrierOffline,
|
||||
LanesClosed,
|
||||
}
|
||||
|
||||
@@ -1266,10 +1293,19 @@ enum RNodeWriterFinish {
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
struct RNodeWriterContext {
|
||||
background: Arc<Mutex<Option<crate::background_announce::BackgroundAnnounceReceiver>>>,
|
||||
id: InterfaceId,
|
||||
flow_control: bool,
|
||||
ready: Arc<AtomicBool>,
|
||||
online: Arc<AtomicBool>,
|
||||
/// Physical stream liveness for the active connection generation.
|
||||
///
|
||||
/// This deliberately remains separate from `interface_online`: startup
|
||||
/// controls must be writable while the public interface is still waiting
|
||||
/// for complete protocol evidence.
|
||||
carrier_online: Arc<AtomicBool>,
|
||||
/// Public/protocol readiness. Packet writes are held until the exact
|
||||
/// reducer state is ready, matching upstream's `interface_ready` gate.
|
||||
interface_online: Arc<AtomicBool>,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
txb: Arc<AtomicU64>,
|
||||
beacon: Option<(Duration, Bytes)>,
|
||||
@@ -1314,19 +1350,18 @@ impl RNodeWriteInterrupt {
|
||||
|
||||
fn interrupt(&mut self) {
|
||||
#[cfg(feature = "serial")]
|
||||
if let Some(stream) = self.serial.take() {
|
||||
if let Err(error) = stream
|
||||
if let Some(stream) = self.serial.take()
|
||||
&& let Err(error) = stream
|
||||
.into_inner()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clear(serialport::ClearBuffer::Output)
|
||||
{
|
||||
tracing::debug!(error = %error, "RNode serial output purge during writer cleanup");
|
||||
}
|
||||
{
|
||||
tracing::debug!(error = %error, "RNode serial output purge during writer cleanup");
|
||||
}
|
||||
if let Some(stream) = self.tcp.take() {
|
||||
if let Err(error) = stream.shutdown(std::net::Shutdown::Both) {
|
||||
tracing::debug!(error = %error, "RNode TCP shutdown during writer cleanup");
|
||||
}
|
||||
if let Some(stream) = self.tcp.take()
|
||||
&& let Err(error) = stream.shutdown(std::net::Shutdown::Both)
|
||||
{
|
||||
tracing::debug!(error = %error, "RNode TCP shutdown during writer cleanup");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1395,6 +1430,7 @@ struct RNodeGenerationWriter {
|
||||
// First field on purpose: cancellation of an owning future interrupts the
|
||||
// physical transport before the actor task guard aborts.
|
||||
interrupt: RNodeWriteInterrupt,
|
||||
background: Arc<Mutex<Option<crate::background_announce::BackgroundAnnounceReceiver>>>,
|
||||
packet_tx: mpsc::Sender<Bytes>,
|
||||
control_tx: mpsc::Sender<RNodeControlWriteRequest>,
|
||||
ready: Arc<AtomicBool>,
|
||||
@@ -1603,16 +1639,47 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
if pending_packet.is_none() {
|
||||
if let Some((interval, ref callsign)) = context.beacon {
|
||||
if first_tx.is_some_and(|started| started.elapsed() >= interval) {
|
||||
tracing::debug!(id = context.id, "RNode station-ID beacon is due");
|
||||
pending_packet = Some(callsign.clone());
|
||||
}
|
||||
}
|
||||
if pending_packet.is_none()
|
||||
&& let Some((interval, ref callsign)) = context.beacon
|
||||
&& first_tx.is_some_and(|started| started.elapsed() >= interval)
|
||||
{
|
||||
tracing::debug!(id = context.id, "RNode station-ID beacon is due");
|
||||
pending_packet = Some(callsign.clone());
|
||||
}
|
||||
|
||||
// Background bypasses both ordinary FIFOs and is selected only at
|
||||
// the physical writer, with the same one-packet READY permit.
|
||||
let background = context.background.lock().unwrap().clone();
|
||||
if pending_packet.is_none()
|
||||
&& packet_rx.is_empty()
|
||||
&& context.carrier_online.load(Ordering::SeqCst)
|
||||
&& context.interface_online.load(Ordering::SeqCst)
|
||||
&& let Some(background) = background.filter(|lane| lane.ordinary_is_empty())
|
||||
&& let Some(packet) = background.try_start_when(rns_transport::now_f64(), || {
|
||||
!context.flow_control
|
||||
|| context
|
||||
.ready
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_ok()
|
||||
})
|
||||
{
|
||||
let (framed, accounting) =
|
||||
prepare_rnode_packet(packet.raw().clone(), &context, &mut first_tx);
|
||||
writer = write_rnode_operation(
|
||||
writer,
|
||||
framed,
|
||||
RNodeWritePhase::Packet,
|
||||
Some(accounting),
|
||||
&mut idle_probe,
|
||||
)
|
||||
.await?;
|
||||
drop(packet);
|
||||
continue;
|
||||
}
|
||||
|
||||
let packet_permitted = pending_packet.is_some()
|
||||
&& context.carrier_online.load(Ordering::SeqCst)
|
||||
&& context.interface_online.load(Ordering::SeqCst)
|
||||
&& (!context.flow_control
|
||||
|| context
|
||||
.ready
|
||||
@@ -1637,8 +1704,8 @@ where
|
||||
continue;
|
||||
}
|
||||
|
||||
if pending_packet.is_some() && !context.online.load(Ordering::SeqCst) {
|
||||
return Ok(RNodeWriterExit::Offline);
|
||||
if pending_packet.is_some() && !context.carrier_online.load(Ordering::SeqCst) {
|
||||
return Ok(RNodeWriterExit::CarrierOffline);
|
||||
}
|
||||
if !packet_lane_open && !control_lane_open && pending_packet.is_none() {
|
||||
return Ok(RNodeWriterExit::LanesClosed);
|
||||
@@ -1683,6 +1750,9 @@ where
|
||||
_ = wait_for_rnode_probe_deadline(probe_deadline) => {
|
||||
RNodeWriterEvent::ProbePoll
|
||||
}
|
||||
_ = tokio::time::sleep(RNODE_FLOW_POLL_INTERVAL) => {
|
||||
RNodeWriterEvent::FlowPoll
|
||||
}
|
||||
packet = packet_rx.recv(), if packet_lane_open => {
|
||||
RNodeWriterEvent::Packet(packet)
|
||||
}
|
||||
@@ -1749,10 +1819,12 @@ where
|
||||
{
|
||||
let (packet_tx, packet_rx) = mpsc::channel(RNODE_PACKET_WRITE_QUEUE);
|
||||
let (control_tx, control_rx) = mpsc::channel(RNODE_CONTROL_WRITE_QUEUE);
|
||||
let background = context.background.clone();
|
||||
let ready = context.ready.clone();
|
||||
let cancelled = context.cancelled.clone();
|
||||
let idle_probes_enabled = context.idle_probes_enabled.clone();
|
||||
let online = context.online.clone();
|
||||
let carrier_online = context.carrier_online.clone();
|
||||
let interface_online = context.interface_online.clone();
|
||||
let id = context.id;
|
||||
let task = tokio::spawn(async move {
|
||||
let result = run_rnode_writer(writer, packet_rx, control_rx, context).await;
|
||||
@@ -1763,12 +1835,14 @@ where
|
||||
failure = ?failure.kind,
|
||||
"RNode writer failed"
|
||||
);
|
||||
online.store(false, Ordering::SeqCst);
|
||||
carrier_online.store(false, Ordering::SeqCst);
|
||||
interface_online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
result
|
||||
});
|
||||
RNodeGenerationWriter {
|
||||
interrupt: RNodeWriteInterrupt::none(),
|
||||
background,
|
||||
packet_tx,
|
||||
control_tx,
|
||||
ready,
|
||||
@@ -1779,33 +1853,41 @@ where
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn spawn_rnode_generation_writer(
|
||||
port: &RNodeStream,
|
||||
config: &RNodeConfig,
|
||||
struct RNodeGenerationWriterOptions {
|
||||
id: InterfaceId,
|
||||
online: Arc<AtomicBool>,
|
||||
carrier_online: Arc<AtomicBool>,
|
||||
interface_online: Arc<AtomicBool>,
|
||||
txb: Arc<AtomicU64>,
|
||||
beacon: Option<(Duration, Bytes)>,
|
||||
idle_probes_enabled: bool,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
fn spawn_rnode_generation_writer(
|
||||
port: &RNodeStream,
|
||||
config: &RNodeConfig,
|
||||
options: RNodeGenerationWriterOptions,
|
||||
) -> std::io::Result<RNodeGenerationWriter> {
|
||||
let interrupt = RNodeWriteInterrupt::from_stream(port)?;
|
||||
let write_stream = port.try_clone()?;
|
||||
let mut writer = spawn_rnode_writer(
|
||||
write_stream,
|
||||
RNodeWriterContext {
|
||||
id,
|
||||
background: Arc::new(Mutex::new(None)),
|
||||
id: options.id,
|
||||
flow_control: config.flow_control,
|
||||
// Upstream flow control starts with one permissive packet token;
|
||||
// exact-width CMD_READY frames replenish or revoke that token.
|
||||
// Reducer readiness remains observational.
|
||||
// This token is independent of the exact protocol-readiness gate.
|
||||
ready: Arc::new(AtomicBool::new(true)),
|
||||
online,
|
||||
carrier_online: options.carrier_online,
|
||||
interface_online: options.interface_online,
|
||||
cancelled: Arc::new(AtomicBool::new(false)),
|
||||
txb,
|
||||
beacon,
|
||||
txb: options.txb,
|
||||
beacon: options.beacon,
|
||||
beacon_poll_interval: RNODE_BEACON_POLL_INTERVAL,
|
||||
idle_probe_interval: port.is_tcp().then_some(RNODE_TCP_IDLE_PROBE_INTERVAL),
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(idle_probes_enabled)),
|
||||
idle_probes_enabled: Arc::new(AtomicBool::new(options.idle_probes_enabled)),
|
||||
},
|
||||
);
|
||||
writer.interrupt = interrupt;
|
||||
@@ -1823,6 +1905,7 @@ async fn finish_rnode_writer(writer: RNodeGenerationWriter) -> RNodeWriterFinish
|
||||
cancelled: _,
|
||||
idle_probes_enabled: _,
|
||||
mut task,
|
||||
background: _,
|
||||
} = writer;
|
||||
drop(packet_tx);
|
||||
drop(control_tx);
|
||||
@@ -2310,25 +2393,30 @@ async fn start_rnode_generation(
|
||||
port: RNodeStream,
|
||||
config: &RNodeConfig,
|
||||
id: InterfaceId,
|
||||
online: &Arc<AtomicBool>,
|
||||
carrier_online: &Arc<AtomicBool>,
|
||||
interface_online: &Arc<AtomicBool>,
|
||||
txb: &Arc<AtomicU64>,
|
||||
beacon: &Option<(Duration, Bytes)>,
|
||||
) -> Result<(RNodeStream, RNodeGenerationWriter), crate::traits::InterfaceError> {
|
||||
let writer = spawn_rnode_generation_writer(
|
||||
&port,
|
||||
config,
|
||||
id,
|
||||
online.clone(),
|
||||
txb.clone(),
|
||||
beacon.clone(),
|
||||
true,
|
||||
RNodeGenerationWriterOptions {
|
||||
id,
|
||||
carrier_online: carrier_online.clone(),
|
||||
interface_online: interface_online.clone(),
|
||||
txb: txb.clone(),
|
||||
beacon: beacon.clone(),
|
||||
idle_probes_enabled: true,
|
||||
},
|
||||
)
|
||||
.map_err(|error| {
|
||||
crate::traits::InterfaceError::SendFailed(format!("rnode writer clone: {error}"))
|
||||
})?;
|
||||
|
||||
if let Err(failure) = initialise_rnode_writer(&writer, config).await {
|
||||
online.store(false, Ordering::SeqCst);
|
||||
carrier_online.store(false, Ordering::SeqCst);
|
||||
interface_online.store(false, Ordering::SeqCst);
|
||||
finish_rnode_writer(writer).await;
|
||||
return Err(crate::traits::InterfaceError::SendFailed(format!(
|
||||
"rnode writer startup: {failure}"
|
||||
@@ -2504,18 +2592,22 @@ async fn start_strict_rnode_generation(
|
||||
port: RNodeStream,
|
||||
config: &RNodeConfig,
|
||||
id: InterfaceId,
|
||||
online: &Arc<AtomicBool>,
|
||||
carrier_online: &Arc<AtomicBool>,
|
||||
interface_online: &Arc<AtomicBool>,
|
||||
txb: &Arc<AtomicU64>,
|
||||
beacon: &Option<(Duration, Bytes)>,
|
||||
) -> Result<(RNodeStrictAdmission, RNodeGenerationWriter), RNodeSpawnError> {
|
||||
let writer = spawn_rnode_generation_writer(
|
||||
&port,
|
||||
config,
|
||||
id,
|
||||
online.clone(),
|
||||
txb.clone(),
|
||||
beacon.clone(),
|
||||
false,
|
||||
RNodeGenerationWriterOptions {
|
||||
id,
|
||||
carrier_online: carrier_online.clone(),
|
||||
interface_online: interface_online.clone(),
|
||||
txb: txb.clone(),
|
||||
beacon: beacon.clone(),
|
||||
idle_probes_enabled: false,
|
||||
},
|
||||
)
|
||||
.map_err(|error| {
|
||||
crate::traits::InterfaceError::SendFailed(format!("rnode writer clone: {error}"))
|
||||
@@ -2524,7 +2616,8 @@ async fn start_strict_rnode_generation(
|
||||
match run_rnode_capability_preflight(port, &writer, config, None).await {
|
||||
Ok(admission) => Ok((admission, writer)),
|
||||
Err(error) => {
|
||||
online.store(false, Ordering::SeqCst);
|
||||
carrier_online.store(false, Ordering::SeqCst);
|
||||
interface_online.store(false, Ordering::SeqCst);
|
||||
let _ = finish_rnode_writer(writer).await;
|
||||
Err(match error {
|
||||
RNodeStrictPreflightError::Transport(error) => RNodeSpawnError::Interface(error),
|
||||
@@ -2821,6 +2914,17 @@ pub fn build_detect_sequence() -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Build the firmware command that enables Bluetooth and persists that choice
|
||||
/// for future RNode boots without opening pairing mode or changing bonds.
|
||||
///
|
||||
/// BLE drivers send this only after admitting the device and treat the later
|
||||
/// exact typed-Ready state from the same connection generation as the durable
|
||||
/// startup boundary. Serial, USB, and RNode-over-TCP never call this helper.
|
||||
#[cfg(any(feature = "ble", test))]
|
||||
pub(crate) fn build_persist_bluetooth_enabled_sequence() -> Vec<u8> {
|
||||
build_command_stage(CMD_BT_CTRL, &[0x01])
|
||||
}
|
||||
|
||||
/// Airtime-lock commands. Percent is encoded as `(percent * 100)` big-endian u16.
|
||||
pub fn build_airtime_sequence(config: &RNodeConfig) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(16);
|
||||
@@ -2879,6 +2983,54 @@ pub fn build_init_sequence(config: &RNodeConfig) -> Vec<u8> {
|
||||
build_radio_configuration_sequence_before_on(&settings, &airtime)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "ble", test))]
|
||||
fn build_command_stage(command: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let mut stage = Vec::with_capacity(payload.len() + 4);
|
||||
kiss::frame_with_command_into(command, payload, &mut stage);
|
||||
stage
|
||||
}
|
||||
|
||||
/// Build the independently paced radio-control stages used after a BLE
|
||||
/// connection becomes usable.
|
||||
///
|
||||
/// Unlike [`build_init_sequence`], this sequence deliberately never emits
|
||||
/// `RADIO_STATE_OFF`. A BLE client can therefore reconnect and reassert the
|
||||
/// desired RF parameters without tearing down the radio session that remained
|
||||
/// active while Bluetooth was out of range. The command order mirrors the
|
||||
/// upstream Android RNode BLE initialization path; callers are responsible for
|
||||
/// validation and pacing each returned stage.
|
||||
#[cfg(any(feature = "ble", test))]
|
||||
pub(crate) fn build_ble_radio_reassertion_stages(config: &RNodeConfig) -> Vec<Vec<u8>> {
|
||||
let mut stages = Vec::with_capacity(8);
|
||||
stages.push(build_command_stage(
|
||||
CMD_FREQUENCY,
|
||||
&u32_to_bytes(config.frequency),
|
||||
));
|
||||
stages.push(build_command_stage(
|
||||
CMD_BANDWIDTH,
|
||||
&u32_to_bytes(config.bandwidth),
|
||||
));
|
||||
stages.push(build_command_stage(CMD_TXPOWER, &[config.tx_power]));
|
||||
stages.push(build_command_stage(CMD_SF, &[config.spreading_factor]));
|
||||
stages.push(build_command_stage(CMD_CR, &[config.coding_rate]));
|
||||
|
||||
if let Some(st) = config.st_alock {
|
||||
stages.push(build_command_stage(
|
||||
CMD_ST_ALOCK,
|
||||
&((st * 100.0) as u16).to_be_bytes(),
|
||||
));
|
||||
}
|
||||
if let Some(lt) = config.lt_alock {
|
||||
stages.push(build_command_stage(
|
||||
CMD_LT_ALOCK,
|
||||
&((lt * 100.0) as u16).to_be_bytes(),
|
||||
));
|
||||
}
|
||||
|
||||
stages.push(build_command_stage(CMD_RADIO_STATE, &[RADIO_STATE_ON]));
|
||||
stages
|
||||
}
|
||||
|
||||
/// KISS sequence for returning an RNode radio to idle before disconnecting.
|
||||
pub fn build_radio_off_sequence() -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(4);
|
||||
@@ -3145,10 +3297,15 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
"RNode on-air bitrate calculated"
|
||||
);
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
// The physical stream is already open, but upstream does not expose an
|
||||
// RNode as online until detection, firmware, configuration and radio state
|
||||
// have all been validated. Keep those two states independent.
|
||||
let carrier_online = Arc::new(AtomicBool::new(true));
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
let rx = Arc::new(tokio::sync::Mutex::new(rx));
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
@@ -3173,8 +3330,16 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
// detect/init write+flush stages; strict mode inserts bounded capability
|
||||
// admission after detect and before any init bytes.
|
||||
let (port, initial_writer, initial_protocol_seed) = if options.requires_capability_admission() {
|
||||
let (admitted, writer) =
|
||||
start_strict_rnode_generation(port, &config, id, &online, &shared_txb, &beacon).await?;
|
||||
let (admitted, writer) = start_strict_rnode_generation(
|
||||
port,
|
||||
&config,
|
||||
id,
|
||||
&carrier_online,
|
||||
&online,
|
||||
&shared_txb,
|
||||
&beacon,
|
||||
)
|
||||
.await?;
|
||||
(
|
||||
admitted.port,
|
||||
writer,
|
||||
@@ -3184,8 +3349,16 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
},
|
||||
)
|
||||
} else {
|
||||
let (port, writer) =
|
||||
start_rnode_generation(port, &config, id, &online, &shared_txb, &beacon).await?;
|
||||
let (port, writer) = start_rnode_generation(
|
||||
port,
|
||||
&config,
|
||||
id,
|
||||
&carrier_online,
|
||||
&online,
|
||||
&shared_txb,
|
||||
&beacon,
|
||||
)
|
||||
.await?;
|
||||
(port, writer, RNodeGenerationProtocolSeed::Legacy)
|
||||
};
|
||||
|
||||
@@ -3196,6 +3369,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
);
|
||||
let stop_guard = register_rnode_stop(id, stop_tx);
|
||||
let online_r = online.clone();
|
||||
let carrier_online_r = carrier_online.clone();
|
||||
let rxb_r = shared_rxb.clone();
|
||||
let txb_r = shared_txb.clone();
|
||||
let task_config = config.clone();
|
||||
@@ -3230,6 +3404,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
let opened = match open_result {
|
||||
Ok(port) => port,
|
||||
Err(e) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
snapshot_publisher.connection_attempt_failed();
|
||||
tracing::warn!(
|
||||
@@ -3253,14 +3428,18 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
let reconnect_writer = match spawn_rnode_generation_writer(
|
||||
&opened,
|
||||
&task_config,
|
||||
id,
|
||||
online_r.clone(),
|
||||
txb_r.clone(),
|
||||
beacon.clone(),
|
||||
!options.requires_capability_admission(),
|
||||
RNodeGenerationWriterOptions {
|
||||
id,
|
||||
carrier_online: carrier_online_r.clone(),
|
||||
interface_online: online_r.clone(),
|
||||
txb: txb_r.clone(),
|
||||
beacon: beacon.clone(),
|
||||
idle_probes_enabled: !options.requires_capability_admission(),
|
||||
},
|
||||
) {
|
||||
Ok(writer) => writer,
|
||||
Err(e) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
snapshot_publisher.connection_attempt_failed();
|
||||
tracing::warn!(
|
||||
@@ -3324,6 +3503,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
Err(RNodeStrictPreflightError::Capability(
|
||||
RNodeCapabilityAdmissionError::ResponseTimedOut,
|
||||
)) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
reconnect_writer.cancel();
|
||||
let writer_finish = finish_rnode_writer(reconnect_writer).await;
|
||||
@@ -3350,6 +3530,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
continue;
|
||||
}
|
||||
Err(RNodeStrictPreflightError::Capability(error)) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
reconnect_writer.cancel();
|
||||
let writer_finish = finish_rnode_writer(reconnect_writer).await;
|
||||
@@ -3368,6 +3549,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
return;
|
||||
}
|
||||
Err(RNodeStrictPreflightError::Transport(error)) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
reconnect_writer.cancel();
|
||||
let writer_finish = finish_rnode_writer(reconnect_writer).await;
|
||||
@@ -3420,6 +3602,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
return;
|
||||
}
|
||||
Err(failure) => {
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
reconnect_writer.cancel();
|
||||
let writer_finish = finish_rnode_writer(reconnect_writer).await;
|
||||
@@ -3450,10 +3633,12 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
}
|
||||
};
|
||||
|
||||
online_r.store(true, Ordering::SeqCst);
|
||||
carrier_online_r.store(true, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
let mut protocol_state = match protocol_seed {
|
||||
RNodeGenerationProtocolSeed::Legacy => {
|
||||
let state = RNodeProtocolState::new(protocol_target);
|
||||
sync_rnode_interface_online(&online_r, &state);
|
||||
snapshot_publisher.connection_established();
|
||||
state
|
||||
}
|
||||
@@ -3461,6 +3646,7 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
protocol_state,
|
||||
admission,
|
||||
} => {
|
||||
sync_rnode_interface_online(&online_r, &protocol_state);
|
||||
snapshot_publisher
|
||||
.capability_connection_established(&protocol_state, admission);
|
||||
protocol_state
|
||||
@@ -3468,6 +3654,8 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
};
|
||||
let mut port_r = port_r;
|
||||
|
||||
background.retire_generation();
|
||||
*generation_writer.background.lock().unwrap() = Some(background.clone());
|
||||
let ready = generation_writer.ready.clone();
|
||||
let packet_tx = generation_writer.packet_tx.clone();
|
||||
let control_tx = generation_writer.control_tx.clone();
|
||||
@@ -3493,12 +3681,14 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
loop {
|
||||
if stop_rx.try_recv().is_ok() {
|
||||
tracing::info!(name = %task_name, "RNode stop requested");
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
snapshot_publisher.shutting_down(RNodeRuntimeReason::StopRequested);
|
||||
let _ = send_detach_request(&control_tx, id).await;
|
||||
stop_requested = true;
|
||||
break;
|
||||
}
|
||||
if generation_writer.task.is_finished() || !online_r.load(Ordering::SeqCst) {
|
||||
if generation_writer.task.is_finished() || !carrier_online_r.load(Ordering::SeqCst)
|
||||
{
|
||||
break;
|
||||
}
|
||||
let result =
|
||||
@@ -3511,6 +3701,9 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
if n > 0 {
|
||||
for (cmd, frame) in deframer.feed(&buf[..n]) {
|
||||
let effect = protocol_state.apply_frame(cmd, &frame);
|
||||
// Publish Ready only after the public handle and
|
||||
// packet gate reflect the same reducer state.
|
||||
sync_rnode_interface_online(&online_r, &protocol_state);
|
||||
snapshot_publisher.protocol_effect(&protocol_state, effect);
|
||||
match process_rnode_response(
|
||||
cmd,
|
||||
@@ -3554,8 +3747,10 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
}
|
||||
|
||||
if transport_closed {
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
snapshot_publisher.shutting_down(RNodeRuntimeReason::TransportConsumerClosed);
|
||||
}
|
||||
carrier_online_r.store(false, Ordering::SeqCst);
|
||||
online_r.store(false, Ordering::SeqCst);
|
||||
generation_writer.cancel();
|
||||
fwd_handle.abort_and_wait().await;
|
||||
@@ -3615,6 +3810,30 @@ pub async fn spawn_rnode_interface_with_driver_and_options(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn persisted_bluetooth_policy_is_explicit_and_composable() {
|
||||
let default = RNodeStartupOptions::default();
|
||||
assert!(!default.persists_bluetooth_enabled());
|
||||
assert!(!default.requires_capability_admission());
|
||||
|
||||
let persisted = default.with_persisted_bluetooth_enabled();
|
||||
assert!(persisted.persists_bluetooth_enabled());
|
||||
assert!(!persisted.requires_capability_admission());
|
||||
|
||||
let strict_persisted =
|
||||
RNodeStartupOptions::require_capability_admission().with_persisted_bluetooth_enabled();
|
||||
assert!(strict_persisted.persists_bluetooth_enabled());
|
||||
assert!(strict_persisted.requires_capability_admission());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_bluetooth_command_is_exact_and_does_not_open_pairing() {
|
||||
assert_eq!(
|
||||
build_persist_bluetooth_enabled_sequence(),
|
||||
vec![kiss::FEND, CMD_BT_CTRL, 0x01, kiss::FEND]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_failure_classes_keep_legacy_log_tokens() {
|
||||
let cases: &[(RNodeCapabilityAdmissionError, &str)] = &[
|
||||
@@ -3831,16 +4050,18 @@ mod tests {
|
||||
fn scripted_writer_context(
|
||||
flow_control: bool,
|
||||
ready: Arc<AtomicBool>,
|
||||
online: Arc<AtomicBool>,
|
||||
carrier_online: Arc<AtomicBool>,
|
||||
txb: Arc<AtomicU64>,
|
||||
beacon: Option<(Duration, Bytes)>,
|
||||
beacon_poll_interval: Duration,
|
||||
) -> RNodeWriterContext {
|
||||
RNodeWriterContext {
|
||||
background: Arc::new(Mutex::new(None)),
|
||||
id: 0x5C71,
|
||||
flow_control,
|
||||
ready,
|
||||
online,
|
||||
carrier_online,
|
||||
interface_online: Arc::new(AtomicBool::new(true)),
|
||||
cancelled: Arc::new(AtomicBool::new(false)),
|
||||
txb,
|
||||
beacon,
|
||||
@@ -4270,6 +4491,71 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ble_radio_reassertion_stages_match_upstream_order_without_radio_off() {
|
||||
let mut config = RNodeConfig::new("rnode0", "ble://RNode Test");
|
||||
config.frequency = 915_000_000;
|
||||
config.bandwidth = 250_000;
|
||||
config.spreading_factor = 9;
|
||||
config.coding_rate = 5;
|
||||
config.tx_power = 17;
|
||||
config.st_alock = Some(10.0);
|
||||
config.lt_alock = Some(1.0);
|
||||
|
||||
let stages = build_ble_radio_reassertion_stages(&config);
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames: Vec<_> = stages
|
||||
.iter()
|
||||
.flat_map(|stage| deframer.feed(stage))
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![
|
||||
(CMD_FREQUENCY, config.frequency.to_be_bytes().to_vec()),
|
||||
(CMD_BANDWIDTH, config.bandwidth.to_be_bytes().to_vec()),
|
||||
(CMD_TXPOWER, vec![config.tx_power]),
|
||||
(CMD_SF, vec![config.spreading_factor]),
|
||||
(CMD_CR, vec![config.coding_rate]),
|
||||
(CMD_ST_ALOCK, 1_000u16.to_be_bytes().to_vec()),
|
||||
(CMD_LT_ALOCK, 100u16.to_be_bytes().to_vec()),
|
||||
(CMD_RADIO_STATE, vec![RADIO_STATE_ON]),
|
||||
]
|
||||
);
|
||||
assert!(frames.iter().all(|(command, payload)| {
|
||||
*command != CMD_RADIO_STATE || payload.as_slice() != [RADIO_STATE_OFF]
|
||||
}));
|
||||
assert_eq!(
|
||||
stages.len(),
|
||||
frames.len(),
|
||||
"each BLE control command must remain an independently paced stage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ble_radio_reassertion_omits_unconfigured_airtime_stages() {
|
||||
let config = RNodeConfig::new("rnode0", "ble://RNode Test");
|
||||
let stages = build_ble_radio_reassertion_stages(&config);
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let commands: Vec<_> = stages
|
||||
.iter()
|
||||
.flat_map(|stage| deframer.feed(stage))
|
||||
.map(|(command, _)| command)
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
commands,
|
||||
vec![
|
||||
CMD_FREQUENCY,
|
||||
CMD_BANDWIDTH,
|
||||
CMD_TXPOWER,
|
||||
CMD_SF,
|
||||
CMD_CR,
|
||||
CMD_RADIO_STATE,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Byte-exact vs Python `setSTALock`/`setLTALock` (RNodeInterface.py:612-630):
|
||||
/// `at = int(pct * 100)` big-endian u16, KISS-escaped, framed per command.
|
||||
#[test]
|
||||
@@ -6594,7 +6880,7 @@ mod tests {
|
||||
|
||||
for_each_protocol_permutation(values, size - 1, callback);
|
||||
for index in 0..(size - 1) {
|
||||
let swap_index = if size % 2 == 0 { index } else { 0 };
|
||||
let swap_index = if size.is_multiple_of(2) { index } else { 0 };
|
||||
values.swap(swap_index, size - 1);
|
||||
for_each_protocol_permutation(values, size - 1, callback);
|
||||
}
|
||||
@@ -6975,6 +7261,39 @@ mod tests {
|
||||
assert_eq!(snapshot.reason, None);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[test]
|
||||
fn test_rnode_public_online_tracks_exact_ready_and_reset() {
|
||||
let mut state = RNodeProtocolState::new(TEST_PROTOCOL_TARGET);
|
||||
let online = AtomicBool::new(true);
|
||||
|
||||
sync_rnode_interface_online(&online, &state);
|
||||
assert!(
|
||||
!online.load(Ordering::SeqCst),
|
||||
"an open carrier without protocol evidence is not publicly online"
|
||||
);
|
||||
|
||||
for (position, (command, payload)) in protocol_required_frames(TEST_PROTOCOL_TARGET)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
state.apply_frame(command, &payload);
|
||||
sync_rnode_interface_online(&online, &state);
|
||||
assert_eq!(
|
||||
online.load(Ordering::SeqCst),
|
||||
position == 7,
|
||||
"public online may change only with exact reducer readiness"
|
||||
);
|
||||
}
|
||||
|
||||
state.apply_frame(CMD_RESET, &[0xF8]);
|
||||
sync_rnode_interface_online(&online, &state);
|
||||
assert!(
|
||||
!online.load(Ordering::SeqCst),
|
||||
"reset must revoke public readiness while the carrier remains open"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
async fn wait_for_rnode_snapshot(
|
||||
state: &mut RNodeDriverSubscription,
|
||||
@@ -7091,16 +7410,25 @@ mod tests {
|
||||
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[tokio::test]
|
||||
async fn test_rnode_driver_transmits_while_lifecycle_awaits_readiness() {
|
||||
async fn test_rnode_driver_holds_outbound_until_exact_protocol_readiness() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let config = RNodeConfig::new("rnode-awaiting-traffic", &format!("tcp://{addr}"));
|
||||
let target = RNodeProtocolTarget::new(
|
||||
config.frequency,
|
||||
config.bandwidth,
|
||||
config.spreading_factor,
|
||||
config.coding_rate,
|
||||
config.tx_power,
|
||||
);
|
||||
let expected_startup = tcp_startup_bytes(&config);
|
||||
let payload = Bytes::from_static(b"traffic-before-protocol-readiness");
|
||||
let expected_packet = kiss::frame(&payload);
|
||||
let server_expected_packet = expected_packet.clone();
|
||||
let expected_detach = build_detach_sequence();
|
||||
let (packet_tx, mut packet_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (blocked_tx, mut blocked_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
|
||||
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
@@ -7111,6 +7439,30 @@ mod tests {
|
||||
read_exact_tcp(&mut stream, expected_startup.len()),
|
||||
expected_startup
|
||||
);
|
||||
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_millis(150)))
|
||||
.unwrap();
|
||||
let mut premature = [0u8; 1];
|
||||
match std::io::Read::read(&mut stream, &mut premature) {
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) => {}
|
||||
result => panic!("RNode wrote application data before protocol Ready: {result:?}"),
|
||||
}
|
||||
blocked_tx.send(()).unwrap();
|
||||
|
||||
ready_rx.recv().unwrap();
|
||||
let mut readiness = Vec::new();
|
||||
for (command, payload) in protocol_required_frames(target) {
|
||||
kiss::frame_with_command_into(command, &payload, &mut readiness);
|
||||
}
|
||||
std::io::Write::write_all(&mut stream, &readiness).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(2)))
|
||||
.unwrap();
|
||||
packet_tx
|
||||
.send(read_exact_tcp(&mut stream, server_expected_packet.len()))
|
||||
.unwrap();
|
||||
@@ -7133,6 +7485,28 @@ mod tests {
|
||||
.await;
|
||||
|
||||
spawned.interface.tx.send(payload.clone()).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(2), blocked_rx.recv())
|
||||
.await
|
||||
.expect("pre-readiness packet gate check timed out")
|
||||
.expect("pre-readiness packet gate server ended");
|
||||
assert!(!spawned.interface.online.load(Ordering::SeqCst));
|
||||
assert_eq!(
|
||||
spawned
|
||||
.interface
|
||||
.txb
|
||||
.as_ref()
|
||||
.expect("RNode TX counter")
|
||||
.load(Ordering::Relaxed),
|
||||
0,
|
||||
"queued data must not be physically written or accounted before Ready"
|
||||
);
|
||||
|
||||
ready_tx.send(()).unwrap();
|
||||
wait_for_rnode_snapshot(&mut state, |snapshot| {
|
||||
snapshot.connection_generation == 1 && snapshot.phase == RNodeRuntimePhase::Ready
|
||||
})
|
||||
.await;
|
||||
assert!(spawned.interface.online.load(Ordering::SeqCst));
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(2), packet_rx.recv())
|
||||
.await
|
||||
@@ -7140,7 +7514,21 @@ mod tests {
|
||||
.expect("outbound RNode server ended"),
|
||||
expected_packet
|
||||
);
|
||||
assert_eq!(state.snapshot().phase, RNodeRuntimePhase::AwaitingReadiness);
|
||||
// A peer read can race the blocking writer's completion/accounting
|
||||
// publication; reading bytes is not the driver's completion barrier.
|
||||
yield_until_rnode_test(
|
||||
|| {
|
||||
spawned
|
||||
.interface
|
||||
.txb
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.load(Ordering::Relaxed)
|
||||
== payload.len() as u64
|
||||
},
|
||||
"RNode completed-write accounting did not converge",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
spawned
|
||||
.interface
|
||||
@@ -7158,8 +7546,8 @@ mod tests {
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(2), spawned.interface.read_task)
|
||||
.await
|
||||
.expect("awaiting-readiness read task timed out")
|
||||
.expect("awaiting-readiness read task panicked");
|
||||
.expect("readiness-gated read task timed out")
|
||||
.expect("readiness-gated read task panicked");
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
@@ -7759,6 +8147,13 @@ mod tests {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let config = RNodeConfig::new("rnode-tcp", &format!("tcp://{addr}"));
|
||||
let target = RNodeProtocolTarget::new(
|
||||
config.frequency,
|
||||
config.bandwidth,
|
||||
config.spreading_factor,
|
||||
config.coding_rate,
|
||||
config.tx_power,
|
||||
);
|
||||
let expected_init_len = build_detect_sequence().len()
|
||||
+ build_init_sequence(&config).len()
|
||||
+ build_airtime_sequence(&config).len();
|
||||
@@ -7781,6 +8176,11 @@ mod tests {
|
||||
}
|
||||
}
|
||||
if attempt == 2 {
|
||||
let mut readiness = Vec::new();
|
||||
for (command, payload) in protocol_required_frames(target) {
|
||||
kiss::frame_with_command_into(command, &payload, &mut readiness);
|
||||
}
|
||||
std::io::Write::write_all(&mut stream, &readiness).unwrap();
|
||||
accepted_tx.send(attempt).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
} else {
|
||||
@@ -7821,4 +8221,83 @@ mod tests {
|
||||
drop(handle.tx);
|
||||
server.join().unwrap();
|
||||
}
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn background_actor_final_writer_survives_1000_windows_without_filling_either_fifo() {
|
||||
let (outer, mut outer_rx) = mpsc::channel(2);
|
||||
let background = crate::background_announce::register(&outer).unwrap();
|
||||
let (actor, actor_control, raw) =
|
||||
crate::background_announce::scheduled_actor_with_backlog(outer.clone(), 1100);
|
||||
let scripted = ScriptedWriter::default();
|
||||
let ready = Arc::new(AtomicBool::new(false));
|
||||
let context = scripted_writer_context(
|
||||
true,
|
||||
ready.clone(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
Arc::new(AtomicU64::new(0)),
|
||||
None,
|
||||
Duration::from_millis(5),
|
||||
);
|
||||
*context.background.lock().unwrap() = Some(background.clone());
|
||||
let writer = spawn_rnode_writer(scripted.clone(), context);
|
||||
let inner = writer.packet_tx.clone();
|
||||
let forwarder = tokio::spawn(async move {
|
||||
while let Some(packet) = outer_rx.recv().await {
|
||||
if inner.send(packet).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
yield_to_rnode_tasks().await;
|
||||
for _ in 0..1000 {
|
||||
actor_control
|
||||
.send(TransportMessage::Tick(rns_transport::messages::TimerTick {
|
||||
timestamp: rns_transport::now_f64(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::advance(Duration::from_secs(134)).await;
|
||||
yield_to_rnode_tasks().await;
|
||||
assert!(background.has_offer());
|
||||
assert_eq!(outer.capacity(), 2);
|
||||
assert_eq!(writer.packet_tx.capacity(), RNODE_PACKET_WRITE_QUEUE);
|
||||
assert!(scripted.writes().is_empty());
|
||||
}
|
||||
outer
|
||||
.send(Bytes::from_static(b"local control"))
|
||||
.await
|
||||
.unwrap();
|
||||
yield_to_rnode_tasks().await;
|
||||
ready.store(true, Ordering::SeqCst);
|
||||
tokio::time::advance(RNODE_FLOW_POLL_INTERVAL).await;
|
||||
yield_until_rnode_test(
|
||||
|| scripted.flush_calls() == 1,
|
||||
"ordinary control should precede background",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(scripted.writes(), vec![kiss::frame(b"local control")]);
|
||||
assert!(!ready.load(Ordering::SeqCst));
|
||||
ready.store(true, Ordering::SeqCst);
|
||||
tokio::time::advance(RNODE_FLOW_POLL_INTERVAL).await;
|
||||
yield_until_rnode_test(
|
||||
|| scripted.flush_calls() == 2,
|
||||
"background should progress on next permit",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(scripted.writes()[1], kiss::frame(&raw));
|
||||
// More work may be offered after completion, but no READY means no burst.
|
||||
tokio::time::advance(Duration::from_secs(134)).await;
|
||||
yield_to_rnode_tasks().await;
|
||||
assert_eq!(scripted.writes().len(), 2);
|
||||
assert!(!ready.load(Ordering::SeqCst));
|
||||
actor_control
|
||||
.send(TransportMessage::Shutdown)
|
||||
.await
|
||||
.unwrap();
|
||||
actor.await.unwrap();
|
||||
forwarder.abort();
|
||||
writer.cancel();
|
||||
tokio::time::advance(RNODE_FLOW_POLL_INTERVAL).await;
|
||||
finish_rnode_writer(writer).await;
|
||||
}
|
||||
}
|
||||
@@ -149,21 +149,21 @@ impl SubInterfaceConfig {
|
||||
self.coding_rate, self.name
|
||||
));
|
||||
}
|
||||
if let Some(st) = self.st_alock {
|
||||
if !(0.0..=100.0).contains(&st) {
|
||||
return Err(format!(
|
||||
"Invalid short-term airtime limit {} for sub-interface {}",
|
||||
st, self.name
|
||||
));
|
||||
}
|
||||
if let Some(st) = self.st_alock
|
||||
&& !(0.0..=100.0).contains(&st)
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid short-term airtime limit {} for sub-interface {}",
|
||||
st, self.name
|
||||
));
|
||||
}
|
||||
if let Some(lt) = self.lt_alock {
|
||||
if !(0.0..=100.0).contains(<) {
|
||||
return Err(format!(
|
||||
"Invalid long-term airtime limit {} for sub-interface {}",
|
||||
lt, self.name
|
||||
));
|
||||
}
|
||||
if let Some(lt) = self.lt_alock
|
||||
&& !(0.0..=100.0).contains(<)
|
||||
{
|
||||
return Err(format!(
|
||||
"Invalid long-term airtime limit {} for sub-interface {}",
|
||||
lt, self.name
|
||||
));
|
||||
}
|
||||
if self.vport as usize >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
@@ -371,10 +371,10 @@ impl StartupEvidence {
|
||||
if payload.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if payload.len() % 2 != 0 {
|
||||
if !payload.len().is_multiple_of(2) {
|
||||
return Err("RNodeMulti returned a malformed interface list".into());
|
||||
}
|
||||
for pair in payload.chunks_exact(2) {
|
||||
for pair in payload.as_chunks::<2>().0 {
|
||||
let vport = pair[0] as usize;
|
||||
if vport >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
@@ -741,6 +741,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
// stays ordered relative to each data frame.
|
||||
let (write_tx, mut write_rx) = mpsc::channel::<WriteRequest>(256);
|
||||
|
||||
let mut background_lanes = Vec::with_capacity(num_subs);
|
||||
let mut handles = Vec::with_capacity(num_subs);
|
||||
let mut sub_txb: Vec<Arc<AtomicU64>> = Vec::with_capacity(num_subs);
|
||||
let mut sub_rxb: Vec<Arc<AtomicU64>> = Vec::with_capacity(num_subs);
|
||||
@@ -760,6 +761,14 @@ pub async fn spawn_rnode_multi_interface(
|
||||
// Adapt the per-handle `Vec<u8>` channel into the shared WriteRequest
|
||||
// channel so the handle type stays symmetric with other interfaces.
|
||||
let (sub_tx, mut sub_rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&sub_tx)?;
|
||||
background_lanes.push((
|
||||
sub_cfg.vport,
|
||||
background,
|
||||
config.flow_control || sub_cfg.flow_control,
|
||||
txb.clone(),
|
||||
sub_onlines[i].clone(),
|
||||
));
|
||||
let write_tx_clone = write_tx.clone();
|
||||
let vport = sub_cfg.vport;
|
||||
let sub_flow_control = config.flow_control || sub_cfg.flow_control;
|
||||
@@ -859,13 +868,56 @@ pub async fn spawn_rnode_multi_interface(
|
||||
ok
|
||||
})
|
||||
.map(|(interval, callsign)| (Duration::from_secs(interval), Bytes::from(callsign)));
|
||||
let beacon_vports: Vec<u8> = config.subinterfaces.iter().map(|s| s.vport).collect();
|
||||
let beacon_vports: Vec<_> = config
|
||||
.subinterfaces
|
||||
.iter()
|
||||
.map(|sub| (sub.vport, config.flow_control || sub.flow_control))
|
||||
.collect();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
let mut background_cursor = 0usize;
|
||||
let mut pending_beacons = std::collections::VecDeque::<WriteRequest>::new();
|
||||
let mut first_tx: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let req = if let Some((interval, ref callsign)) = beacon {
|
||||
let mut background_packet = None;
|
||||
let mut background_request = None;
|
||||
if write_rx.is_empty() && pending_beacons.is_empty() && online_w.load(Ordering::SeqCst)
|
||||
{
|
||||
for offset in 0..background_lanes.len() {
|
||||
let index = (background_cursor + offset) % background_lanes.len();
|
||||
let (vport, lane, flow_control, txb, online) = &background_lanes[index];
|
||||
if online.load(Ordering::SeqCst)
|
||||
&& lane.ordinary_is_empty()
|
||||
&& let Some(packet) = lane.try_start_when(rns_transport::now_f64(), || {
|
||||
!*flow_control
|
||||
|| ready_w
|
||||
.compare_exchange(
|
||||
true,
|
||||
false,
|
||||
Ordering::SeqCst,
|
||||
Ordering::SeqCst,
|
||||
)
|
||||
.is_ok()
|
||||
})
|
||||
{
|
||||
txb.fetch_add(packet.raw().len() as u64, Ordering::Relaxed);
|
||||
background_request = Some(WriteRequest {
|
||||
index: *vport,
|
||||
data: packet.raw().clone(),
|
||||
flow_control: *flow_control,
|
||||
});
|
||||
background_packet = Some(packet);
|
||||
background_cursor = (index + 1) % background_lanes.len();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let req = if let Some(request) = pending_beacons.pop_front() {
|
||||
request
|
||||
} else if let Some(request) = background_request {
|
||||
request
|
||||
} else if let Some((interval, ref callsign)) = beacon {
|
||||
match tokio::time::timeout(Duration::from_secs(1), write_rx.recv()).await {
|
||||
Ok(Some(req)) => req,
|
||||
Ok(None) => break,
|
||||
@@ -879,27 +931,23 @@ pub async fn spawn_rnode_multi_interface(
|
||||
"RNodeMulti transmitting station-ID beacon on all subinterfaces"
|
||||
);
|
||||
first_tx = None;
|
||||
let mut frames = Vec::new();
|
||||
for &vport in &beacon_vports {
|
||||
frames
|
||||
.extend_from_slice(&build_subinterface_data_frame(vport, callsign));
|
||||
}
|
||||
match crate::serial_io::blocking_write_all(port_w, frames).await {
|
||||
Ok(p) => {
|
||||
port_w = p;
|
||||
continue;
|
||||
}
|
||||
Err(_) => {
|
||||
flags_w.trip_device();
|
||||
break;
|
||||
}
|
||||
// Each beacon is a complete radio packet and consumes
|
||||
// its own READY permit in the common writer below.
|
||||
for &(vport, flow_control) in &beacon_vports {
|
||||
pending_beacons.push_back(WriteRequest {
|
||||
index: vport,
|
||||
data: callsign.clone(),
|
||||
flow_control,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match write_rx.recv().await {
|
||||
Some(req) => req,
|
||||
None => break,
|
||||
match tokio::time::timeout(Duration::from_millis(100), write_rx.recv()).await {
|
||||
Ok(Some(req)) => req,
|
||||
Ok(None) => break,
|
||||
Err(_) => continue,
|
||||
}
|
||||
};
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
@@ -913,15 +961,15 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
}
|
||||
|
||||
if req.flow_control {
|
||||
// Bound CMD_READY wait at ~5 s so a stuck TNC can't block tx.
|
||||
let mut wait_count = 0;
|
||||
while !ready_w.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
wait_count += 1;
|
||||
if !online_w.load(Ordering::SeqCst) || wait_count > 500 {
|
||||
break;
|
||||
if req.flow_control && background_packet.is_none() {
|
||||
while ready_w
|
||||
.compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1055,8 +1103,9 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
rnode::CMD_READY => {
|
||||
let is_ready = frame.first().copied().unwrap_or(0) != 0;
|
||||
ready_r.store(is_ready, Ordering::SeqCst);
|
||||
if frame.len() == 1 {
|
||||
ready_r.store(frame[0] != 0, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
rnode::CMD_DETECT => {
|
||||
@@ -1222,7 +1271,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
CMD_INTERFACES => {
|
||||
// Reply is one or more `[vport, radio_type]` pairs.
|
||||
for pair in frame.chunks_exact(2) {
|
||||
for pair in frame.as_chunks::<2>().0 {
|
||||
let vp = pair[0];
|
||||
let rt = pair[1];
|
||||
let rtype = RadioType::from_u8(rt)
|
||||
@@ -1235,7 +1284,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
"RNodeMulti radio module reported"
|
||||
);
|
||||
}
|
||||
if frame.len() % 2 != 0 {
|
||||
if !frame.len().is_multiple_of(2) {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti returned a malformed interface list"
|
||||
|
||||
@@ -565,7 +565,7 @@ mod tests {
|
||||
|
||||
for_each_permutation(values, size - 1, callback);
|
||||
for index in 0..(size - 1) {
|
||||
let swap_index = if size % 2 == 0 { index } else { 0 };
|
||||
let swap_index = if size.is_multiple_of(2) { index } else { 0 };
|
||||
values.swap(swap_index, size - 1);
|
||||
for_each_permutation(values, size - 1, callback);
|
||||
}
|
||||
|
||||
@@ -100,6 +100,7 @@ pub async fn spawn_serial_interface(
|
||||
let shared_rxb = Arc::new(AtomicU64::new(0));
|
||||
let shared_txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, mut rx) = mpsc::channel::<Bytes>(256);
|
||||
let background = crate::background_announce::register(&tx)?;
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
|
||||
@@ -111,7 +112,24 @@ pub async fn spawn_serial_interface(
|
||||
let txb_w = shared_txb.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut port_w = port_write;
|
||||
while let Some(data) = rx.recv().await {
|
||||
loop {
|
||||
if !online_w.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let background_packet = if rx.is_empty() {
|
||||
background.try_start(rns_transport::now_f64())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data = if let Some(packet) = &background_packet {
|
||||
packet.raw().clone()
|
||||
} else {
|
||||
match tokio::time::timeout(Duration::from_millis(100), rx.recv()).await {
|
||||
Ok(Some(data)) => data,
|
||||
Ok(None) => break,
|
||||
Err(_) => continue,
|
||||
}
|
||||
};
|
||||
txb_w.fetch_add(data.len() as u64, std::sync::atomic::Ordering::Relaxed);
|
||||
let framed = hdlc::frame(&data);
|
||||
match crate::serial_io::blocking_write_all(port_w, framed).await {
|
||||
|
||||
@@ -231,21 +231,21 @@ mod tests {
|
||||
let candidates = ["lo", "lo0", "Loopback Pseudo-Interface 1"];
|
||||
let mut found_v4 = false;
|
||||
for name in candidates {
|
||||
if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false) {
|
||||
if v4.is_loopback() {
|
||||
found_v4 = true;
|
||||
break;
|
||||
}
|
||||
if let Some(IpAddr::V4(v4)) = iface_addr_for(name, false)
|
||||
&& v4.is_loopback()
|
||||
{
|
||||
found_v4 = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Hermetic CI may not expose loopback by name; only assert when seen.
|
||||
if let Ok(ifaces) = if_addrs::get_if_addrs() {
|
||||
if ifaces.iter().any(|i| candidates.contains(&i.name.as_str())) {
|
||||
assert!(
|
||||
found_v4,
|
||||
"expected a loopback IPv4 on one of {candidates:?}"
|
||||
);
|
||||
}
|
||||
if let Ok(ifaces) = if_addrs::get_if_addrs()
|
||||
&& ifaces.iter().any(|i| candidates.contains(&i.name.as_str()))
|
||||
{
|
||||
assert!(
|
||||
found_v4,
|
||||
"expected a loopback IPv4 on one of {candidates:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,10 +102,8 @@ fn address_for_device(device: &str, prefer_ipv6: bool) -> Option<std::net::IpAdd
|
||||
.filter(|a| a.name == device)
|
||||
.map(|a| a.ip())
|
||||
.collect();
|
||||
if prefer_ipv6 {
|
||||
if let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
}
|
||||
if prefer_ipv6 && let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
}
|
||||
on_dev
|
||||
.iter()
|
||||
|
||||
@@ -59,19 +59,19 @@ pub async fn spawn_udp_interface(
|
||||
// config error, not a silent fallback to wildcard.
|
||||
let mut listen_ip_cfg = config.listen_ip.clone();
|
||||
let mut forward_ip_cfg = config.forward_ip.clone();
|
||||
if let Some(device) = config.device.as_deref() {
|
||||
if listen_ip_cfg.is_none() || forward_ip_cfg.is_none() {
|
||||
let bcast = crate::socket_tuning::iface_broadcast_for(device).ok_or_else(|| {
|
||||
crate::traits::InterfaceError::SendFailed(format!(
|
||||
"UDP device '{device}' not found or has no IPv4 broadcast address"
|
||||
))
|
||||
})?;
|
||||
if listen_ip_cfg.is_none() {
|
||||
listen_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
if forward_ip_cfg.is_none() {
|
||||
forward_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
if let Some(device) = config.device.as_deref()
|
||||
&& (listen_ip_cfg.is_none() || forward_ip_cfg.is_none())
|
||||
{
|
||||
let bcast = crate::socket_tuning::iface_broadcast_for(device).ok_or_else(|| {
|
||||
crate::traits::InterfaceError::SendFailed(format!(
|
||||
"UDP device '{device}' not found or has no IPv4 broadcast address"
|
||||
))
|
||||
})?;
|
||||
if listen_ip_cfg.is_none() {
|
||||
listen_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
if forward_ip_cfg.is_none() {
|
||||
forward_ip_cfg = Some(bcast.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-link"
|
||||
description = "Link layer and encrypted channel for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -137,22 +137,23 @@ impl KeepaliveState {
|
||||
|
||||
pub(crate) fn is_stale_at(&self, now: Instant) -> bool {
|
||||
let mut latest = self.last_inbound;
|
||||
if let Some(proof) = self.last_proof {
|
||||
if proof > latest {
|
||||
latest = proof;
|
||||
}
|
||||
if let Some(proof) = self.last_proof
|
||||
&& proof > latest
|
||||
{
|
||||
latest = proof;
|
||||
}
|
||||
if let Some(activated) = self.activated_at {
|
||||
if activated > latest {
|
||||
latest = activated;
|
||||
}
|
||||
if let Some(activated) = self.activated_at
|
||||
&& activated > latest
|
||||
{
|
||||
latest = activated;
|
||||
}
|
||||
now.saturating_duration_since(latest) >= self.stale_time
|
||||
}
|
||||
|
||||
/// How long to wait in STALE before tearing the link down.
|
||||
pub fn stale_grace_timeout(&self, rtt: Duration) -> Duration {
|
||||
rtt * KEEPALIVE_TIMEOUT_FACTOR as u32 + Duration::from_secs_f64(STALE_GRACE)
|
||||
rtt.saturating_mul(KEEPALIVE_TIMEOUT_FACTOR as u32)
|
||||
.saturating_add(Duration::from_secs_f64(STALE_GRACE))
|
||||
}
|
||||
|
||||
pub fn mark_keepalive_sent(&mut self) {
|
||||
@@ -319,12 +320,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_jitter_desynchronizes_keepalives() {
|
||||
let links: Vec<KeepaliveState> = (0..20)
|
||||
let links: Vec<KeepaliveState> = (0usize..20)
|
||||
.map(|i| {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
|
||||
ks.jitter_offset = Duration::from_millis(500);
|
||||
ks.jitter_negative = i % 2 == 0;
|
||||
ks.jitter_negative = i.is_multiple_of(2);
|
||||
// Push last_inbound just past the interval boundary.
|
||||
ks.last_inbound = instant_before_now(ks.keepalive_interval);
|
||||
ks
|
||||
@@ -333,12 +334,12 @@ mod tests {
|
||||
|
||||
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
|
||||
|
||||
let links_past: Vec<KeepaliveState> = (0..20)
|
||||
let links_past: Vec<KeepaliveState> = (0usize..20)
|
||||
.map(|i| {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
|
||||
ks.jitter_offset = Duration::from_millis(500);
|
||||
ks.jitter_negative = i % 2 == 0;
|
||||
ks.jitter_negative = i.is_multiple_of(2);
|
||||
ks.last_inbound = instant_before_now(Duration::from_secs(6));
|
||||
ks
|
||||
})
|
||||
|
||||
+643
-114
@@ -29,6 +29,32 @@ pub enum LinkState {
|
||||
Closed = 0x04,
|
||||
}
|
||||
|
||||
/// The local endpoint's immutable role in a Link session.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LinkRole {
|
||||
Initiator,
|
||||
Responder,
|
||||
}
|
||||
|
||||
/// Failure while generating or validating an ordinary Link packet proof.
|
||||
#[derive(Debug, thiserror::Error, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PacketProofError {
|
||||
#[error("packet proof operation is not valid for this Link role")]
|
||||
WrongRole,
|
||||
#[error("packet proof operation is not valid while Link is {0:?}")]
|
||||
InvalidState(LinkState),
|
||||
#[error("packet proof signer is unavailable")]
|
||||
SignerUnavailable,
|
||||
#[error("peer packet proof key is unavailable")]
|
||||
PeerKeyUnavailable,
|
||||
#[error("packet proof must be exactly 96 bytes")]
|
||||
MalformedProof,
|
||||
#[error("packet proof hash does not match")]
|
||||
HashMismatch,
|
||||
#[error("packet proof signature is invalid")]
|
||||
InvalidSignature,
|
||||
}
|
||||
|
||||
/// Reason for link closure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CloseReason {
|
||||
@@ -107,6 +133,20 @@ fn msgpack_value_to_bytes(value: &rmpv::Value) -> Result<Vec<u8>, LinkCryptoErro
|
||||
}
|
||||
}
|
||||
|
||||
/// Ceiling for peer-reported RTTs: Link.py's keepalive and stale time already
|
||||
/// saturate above `KEEPALIVE_MAX_RTT`, and no idle Link outlives a round trip
|
||||
/// longer than its stale window.
|
||||
const PEER_RTT_MAX_SECS: f64 = STALE_TIME_DEFAULT;
|
||||
|
||||
/// Peer RTT as Link.py's `max(measured, peer)` would use it: NaN and negative
|
||||
/// values never win, larger ones saturate so derived timers stay finite.
|
||||
fn peer_reported_rtt(secs: f64) -> Option<Duration> {
|
||||
if secs.is_nan() || secs < 0.0 {
|
||||
return None;
|
||||
}
|
||||
Duration::try_from_secs_f64(secs.min(PEER_RTT_MAX_SECS)).ok()
|
||||
}
|
||||
|
||||
/// An encrypted bidirectional tunnel between two peers.
|
||||
///
|
||||
/// The state machine is driven by `tick()` calls from the owning actor/runtime;
|
||||
@@ -123,11 +163,14 @@ pub struct Link {
|
||||
|
||||
ephemeral_keys: Option<EphemeralKeys>,
|
||||
peer_x25519_pub: Option<[u8; 32]>,
|
||||
/// Peer's Ed25519 identity key — used to verify the link proof signature.
|
||||
peer_ed25519_pub: Option<[u8; 32]>,
|
||||
/// Role-dependent peer key used to verify ordinary Link packet proofs.
|
||||
/// Initiators store the responder destination identity key; responders
|
||||
/// store the transient key advertised in LINKREQUEST.
|
||||
peer_packet_proof_key: Option<[u8; 32]>,
|
||||
|
||||
/// Identity signing key for `Link::sign()` and local-side proofs.
|
||||
sig_prv: Option<Ed25519PrivateKey>,
|
||||
/// Destination identity signing key for software responder proofs.
|
||||
/// Initiators always use the transient key in `ephemeral_keys` instead.
|
||||
responder_identity_signing_key: Option<Ed25519PrivateKey>,
|
||||
|
||||
session_keys: Option<LinkKeys>,
|
||||
|
||||
@@ -233,9 +276,8 @@ impl Link {
|
||||
mode: DEFAULT_MODE,
|
||||
ephemeral_keys: Some(ephemeral_keys),
|
||||
peer_x25519_pub: None,
|
||||
peer_ed25519_pub: None,
|
||||
// Initiator supplies its signing key later via set_signing_key().
|
||||
sig_prv: None,
|
||||
peer_packet_proof_key: None,
|
||||
responder_identity_signing_key: None,
|
||||
session_keys: None,
|
||||
request_time: now,
|
||||
rtt: None,
|
||||
@@ -296,13 +338,13 @@ impl Link {
|
||||
return Err(HandshakeError::InvalidSignature);
|
||||
}
|
||||
|
||||
// Python reads the LRPROOF mode byte before validating the exact proof
|
||||
// length; a wrong mode closes the pending link even for otherwise odd
|
||||
// proof lengths.
|
||||
// LRPROOF is unauthenticated until its signature validates. Reject a
|
||||
// mismatched mode without mutating the pending Link, otherwise any
|
||||
// party that learns the link id could cancel establishment before the
|
||||
// legitimate proof arrives.
|
||||
if proof_data.len() > 96 {
|
||||
let proof_mode = (proof_data[96] & MODE_BYTEMASK as u8) >> 5;
|
||||
if proof_mode != self.mode {
|
||||
self.state = LinkState::Closed;
|
||||
return Err(HandshakeError::InvalidSignature);
|
||||
}
|
||||
}
|
||||
@@ -310,25 +352,25 @@ impl Link {
|
||||
let proof = LinkProofData::unpack(proof_data)?;
|
||||
|
||||
if proof.signalling.mode != self.mode {
|
||||
self.state = LinkState::Closed;
|
||||
return Err(HandshakeError::InvalidSignature);
|
||||
}
|
||||
|
||||
self.establishment_cost += proof_data.len();
|
||||
|
||||
// Verify the signature before deriving session keys so we never hold keys
|
||||
// tied to an unvalidated proof, even transiently.
|
||||
// tied to an unvalidated proof, even transiently. Invalid proofs leave
|
||||
// the initiator Pending so another interface can still deliver the
|
||||
// authentic proof before the establishment timeout.
|
||||
if !proof.validate(
|
||||
identity_verify_key,
|
||||
&self.link_id,
|
||||
identity_ed25519_pub_bytes,
|
||||
) {
|
||||
self.state = LinkState::Closed;
|
||||
return Err(HandshakeError::InvalidSignature);
|
||||
}
|
||||
|
||||
self.establishment_cost += proof_data.len();
|
||||
|
||||
self.peer_x25519_pub = Some(proof.responder_x25519_pub);
|
||||
self.peer_ed25519_pub = Some(*identity_ed25519_pub_bytes);
|
||||
self.peer_packet_proof_key = Some(*identity_ed25519_pub_bytes);
|
||||
|
||||
let ephemeral = self
|
||||
.ephemeral_keys
|
||||
@@ -495,8 +537,9 @@ impl Link {
|
||||
mode: request.signalling.mode,
|
||||
ephemeral_keys: Some(responder_keys),
|
||||
peer_x25519_pub: Some(request.peer_x25519_pub),
|
||||
peer_ed25519_pub: Some(request.peer_ed25519_pub),
|
||||
sig_prv: identity_signing_key.map(|key| Ed25519PrivateKey::from_bytes(&key.to_bytes())),
|
||||
peer_packet_proof_key: Some(request.peer_ed25519_pub),
|
||||
responder_identity_signing_key: identity_signing_key
|
||||
.map(|key| Ed25519PrivateKey::from_bytes(&key.to_bytes())),
|
||||
session_keys: Some(session_keys),
|
||||
request_time: now,
|
||||
rtt: None,
|
||||
@@ -552,14 +595,13 @@ impl Link {
|
||||
.map_err(|_| HandshakeError::InvalidSignature)?;
|
||||
|
||||
// RTT is a msgpack f64 — see matching encode in validate_proof().
|
||||
if let Ok(value) = rmpv::decode::read_value(&mut &plaintext[..]) {
|
||||
if let Some(peer_rtt) = value.as_f64() {
|
||||
let local_rtt = self.request_time.elapsed().as_secs_f64();
|
||||
let rtt = local_rtt.max(peer_rtt);
|
||||
let rtt_dur = Duration::from_secs_f64(rtt);
|
||||
self.rtt = Some(rtt_dur);
|
||||
self.keepalive.update_from_rtt(rtt_dur);
|
||||
}
|
||||
if let Ok(value) = rmpv::decode::read_value(&mut &plaintext[..])
|
||||
&& let Some(peer_rtt) = value.as_f64()
|
||||
{
|
||||
let local_rtt = self.request_time.elapsed();
|
||||
let rtt = peer_reported_rtt(peer_rtt).map_or(local_rtt, |peer| peer.max(local_rtt));
|
||||
self.rtt = Some(rtt);
|
||||
self.keepalive.update_from_rtt(rtt);
|
||||
}
|
||||
|
||||
self.state = LinkState::Active;
|
||||
@@ -1009,7 +1051,8 @@ impl Link {
|
||||
/// Update RTT from an LRRTT packet (context 0xFE) received after handshake.
|
||||
///
|
||||
/// The initiator sends the first measurement as part of `validate_proof`; this
|
||||
/// path handles subsequent updates during the link's lifetime.
|
||||
/// path handles subsequent updates during the link's lifetime. A NaN or
|
||||
/// negative RTT with no prior measurement is rejected.
|
||||
pub fn update_rtt_from_packet(
|
||||
&mut self,
|
||||
encrypted_data: &[u8],
|
||||
@@ -1022,10 +1065,9 @@ impl Link {
|
||||
|
||||
// Prefer the larger of peer and local measurements so timeouts are based on
|
||||
// the slower path — a one-sided smaller value would understate round-trip.
|
||||
let rtt = if let Some(existing) = self.rtt {
|
||||
Duration::from_secs_f64(peer_rtt.max(existing.as_secs_f64()))
|
||||
} else {
|
||||
Duration::from_secs_f64(peer_rtt)
|
||||
let rtt = match (peer_reported_rtt(peer_rtt), self.rtt) {
|
||||
(Some(peer), Some(existing)) => peer.max(existing),
|
||||
(peer, existing) => peer.or(existing).ok_or(LinkCryptoError::DecryptionFailed)?,
|
||||
};
|
||||
|
||||
self.rtt = Some(rtt);
|
||||
@@ -1043,33 +1085,130 @@ impl Link {
|
||||
self.encrypt(&rtt_bytes)
|
||||
}
|
||||
|
||||
/// Sign a received packet hash and return a `packet_hash(32) || signature(64)` proof.
|
||||
/// Return this endpoint's immutable Link role.
|
||||
pub fn role(&self) -> LinkRole {
|
||||
if self.is_initiator {
|
||||
LinkRole::Initiator
|
||||
} else {
|
||||
LinkRole::Responder
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_packet_proof_state(&self) -> Result<(), PacketProofError> {
|
||||
let allowed = matches!(self.state, LinkState::Active | LinkState::Stale)
|
||||
|| (self.role() == LinkRole::Responder && self.state == LinkState::Handshake);
|
||||
if allowed {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PacketProofError::InvalidState(self.state))
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_packet_proof(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
signature: Option<[u8; 64]>,
|
||||
) -> Result<Vec<u8>, PacketProofError> {
|
||||
self.ensure_packet_proof_state()?;
|
||||
let signature = signature.ok_or(PacketProofError::SignerUnavailable)?;
|
||||
let mut proof = Vec::with_capacity(96);
|
||||
proof.extend_from_slice(packet_hash);
|
||||
proof.extend_from_slice(&signature);
|
||||
Ok(proof)
|
||||
}
|
||||
|
||||
/// Prove a received packet with the one key allowed by this endpoint's role.
|
||||
///
|
||||
/// Initiators use the transient Ed25519 key advertised in LINKREQUEST.
|
||||
/// Software responders use the destination identity key retained at Link
|
||||
/// construction. External-signing responders must instead call
|
||||
/// [`Link::prove_responder_packet_with`]. No role-incompatible fallback is
|
||||
/// attempted.
|
||||
pub fn prove_packet_with_local_signer(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
) -> Result<Vec<u8>, PacketProofError> {
|
||||
self.ensure_packet_proof_state()?;
|
||||
let signature = match self.role() {
|
||||
LinkRole::Initiator => self
|
||||
.ephemeral_keys
|
||||
.as_ref()
|
||||
.map(|keys| keys.ed25519_prv.sign(packet_hash)),
|
||||
LinkRole::Responder => self
|
||||
.responder_identity_signing_key
|
||||
.as_ref()
|
||||
.map(|key| key.sign(packet_hash)),
|
||||
};
|
||||
self.encode_packet_proof(packet_hash, signature)
|
||||
}
|
||||
|
||||
/// Prove a responder-received packet with a destination identity backend.
|
||||
///
|
||||
/// The role and state are checked before the callback is invoked so an
|
||||
/// initiator cannot accidentally prompt an external identity signer.
|
||||
pub fn prove_responder_packet_with<F>(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
sign_fn: F,
|
||||
) -> Result<Vec<u8>, PacketProofError>
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
if self.role() != LinkRole::Responder {
|
||||
return Err(PacketProofError::WrongRole);
|
||||
}
|
||||
self.ensure_packet_proof_state()?;
|
||||
self.encode_packet_proof(packet_hash, sign_fn(packet_hash))
|
||||
}
|
||||
|
||||
/// Validate an exact explicit packet proof against the role-dependent peer key.
|
||||
pub fn validate_peer_packet_proof(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
proof_data: &[u8],
|
||||
) -> Result<(), PacketProofError> {
|
||||
if proof_data.len() != 96 {
|
||||
return Err(PacketProofError::MalformedProof);
|
||||
}
|
||||
if &proof_data[..32] != packet_hash {
|
||||
return Err(PacketProofError::HashMismatch);
|
||||
}
|
||||
let mut signature = [0u8; 64];
|
||||
signature.copy_from_slice(&proof_data[32..]);
|
||||
let peer_key = self
|
||||
.peer_packet_proof_key
|
||||
.as_ref()
|
||||
.ok_or(PacketProofError::PeerKeyUnavailable)?;
|
||||
let verify_key = Ed25519PublicKey::from_bytes(peer_key)
|
||||
.map_err(|_| PacketProofError::PeerKeyUnavailable)?;
|
||||
verify_key
|
||||
.verify(packet_hash, &signature)
|
||||
.map_err(|_| PacketProofError::InvalidSignature)
|
||||
}
|
||||
|
||||
/// Legacy responder-only packet proof helper.
|
||||
#[deprecated(note = "use prove_packet_with_local_signer or prove_responder_packet_with")]
|
||||
pub fn prove_packet(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
identity_signing_key: &Ed25519PrivateKey,
|
||||
) -> Result<Vec<u8>, LinkCryptoError> {
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| Some(identity_signing_key.sign(hash)))
|
||||
self.prove_responder_packet_with(packet_hash, |hash| Some(identity_signing_key.sign(hash)))
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)
|
||||
}
|
||||
|
||||
/// Sign a received link packet with this link's ephemeral signing key.
|
||||
///
|
||||
/// Initiators advertise an ephemeral Ed25519 public key in the LINKREQUEST;
|
||||
/// responders validate later link-packet proofs against that key.
|
||||
/// Legacy role-aware local packet proof helper.
|
||||
#[deprecated(note = "use prove_packet_with_local_signer")]
|
||||
pub fn prove_packet_with_link_key(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
) -> Result<Vec<u8>, LinkCryptoError> {
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| {
|
||||
self.sign(hash).or_else(|| {
|
||||
self.ephemeral_keys
|
||||
.as_ref()
|
||||
.map(|keys| keys.ed25519_prv.sign(hash))
|
||||
})
|
||||
})
|
||||
self.prove_packet_with_local_signer(packet_hash)
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)
|
||||
}
|
||||
|
||||
/// Variant of [`Link::prove_packet`] for external signers.
|
||||
/// Legacy responder-only external signer helper.
|
||||
#[deprecated(note = "use prove_responder_packet_with")]
|
||||
pub fn prove_packet_with<F>(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
@@ -1078,10 +1217,12 @@ impl Link {
|
||||
where
|
||||
F: FnOnce(&[u8]) -> [u8; 64],
|
||||
{
|
||||
self.prove_packet_with_fallible(packet_hash, |hash| Some(sign_fn(hash)))
|
||||
self.prove_responder_packet_with(packet_hash, |hash| Some(sign_fn(hash)))
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)
|
||||
}
|
||||
|
||||
/// Variant of [`Link::prove_packet_with`] for signers that can be unavailable.
|
||||
/// Legacy responder-only fallible external signer helper.
|
||||
#[deprecated(note = "use prove_responder_packet_with")]
|
||||
pub fn prove_packet_with_fallible<F>(
|
||||
&self,
|
||||
packet_hash: &[u8; 32],
|
||||
@@ -1090,47 +1231,14 @@ impl Link {
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
// A responder can receive ordinary Link data immediately after its
|
||||
// proof, before the initiator's LRRTT activates the responder side.
|
||||
// Python proves that data in HANDSHAKE, and the session keys/signing
|
||||
// identity are already established at this point.
|
||||
let can_prove = matches!(self.state, LinkState::Active | LinkState::Stale)
|
||||
|| (!self.is_initiator && self.state == LinkState::Handshake);
|
||||
if !can_prove {
|
||||
return Err(LinkCryptoError::EncryptionFailed);
|
||||
}
|
||||
|
||||
let signature = sign_fn(packet_hash).ok_or(LinkCryptoError::EncryptionFailed)?;
|
||||
|
||||
let mut proof = Vec::with_capacity(96);
|
||||
proof.extend_from_slice(packet_hash);
|
||||
proof.extend_from_slice(&signature);
|
||||
|
||||
Ok(proof)
|
||||
self.prove_responder_packet_with(packet_hash, sign_fn)
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)
|
||||
}
|
||||
|
||||
/// Verify a `packet_hash(32) || signature(64)` proof against the peer's identity key.
|
||||
/// Verify an exact packet proof against the role-dependent peer key.
|
||||
pub fn validate_packet_proof(&self, packet_hash: &[u8; 32], proof_data: &[u8]) -> bool {
|
||||
if proof_data.len() < 96 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let received_hash = &proof_data[..32];
|
||||
if received_hash != packet_hash {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut signature = [0u8; 64];
|
||||
signature.copy_from_slice(&proof_data[32..96]);
|
||||
|
||||
if let Some(peer_ed25519_pub) = &self.peer_ed25519_pub {
|
||||
match Ed25519PublicKey::from_bytes(peer_ed25519_pub) {
|
||||
Ok(verify_key) => verify_key.verify(packet_hash, &signature).is_ok(),
|
||||
Err(_) => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
self.validate_peer_packet_proof(packet_hash, proof_data)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Flag that a channel has been attached.
|
||||
@@ -1279,6 +1387,19 @@ impl Link {
|
||||
self.rtt.map(|r| r.as_secs_f64()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Proof window for an ordinary packet on this established Link.
|
||||
///
|
||||
/// Link traffic uses measured round-trip time times
|
||||
/// [`TRAFFIC_TIMEOUT_FACTOR`], with a five-millisecond minimum. This is
|
||||
/// neither Link establishment timing nor the idle keepalive interval.
|
||||
/// A missing RTT uses a conservative half-second RTT fallback.
|
||||
pub fn packet_proof_timeout(&self) -> Duration {
|
||||
self.rtt
|
||||
.unwrap_or(Duration::from_millis(500))
|
||||
.saturating_mul(TRAFFIC_TIMEOUT_FACTOR as u32)
|
||||
.max(Duration::from_millis(5))
|
||||
}
|
||||
|
||||
/// Drive the link state machine forward; call periodically from the owning actor.
|
||||
#[tracing::instrument(
|
||||
level = "trace",
|
||||
@@ -1290,7 +1411,10 @@ impl Link {
|
||||
),
|
||||
)]
|
||||
pub fn tick(&mut self) -> LinkAction {
|
||||
let now = Instant::now();
|
||||
self.tick_at(Instant::now())
|
||||
}
|
||||
|
||||
fn tick_at(&mut self, now: Instant) -> LinkAction {
|
||||
for receipt in &mut self.pending_requests {
|
||||
receipt.check_timeout();
|
||||
}
|
||||
@@ -1324,12 +1448,12 @@ impl Link {
|
||||
// otherwise we'd have nothing to sign the teardown with.
|
||||
let rtt = self.rtt.unwrap_or(Duration::from_secs(1));
|
||||
let grace = self.keepalive.stale_grace_timeout(rtt);
|
||||
if let Some(stale_since) = self.stale_since {
|
||||
if now.saturating_duration_since(stale_since) >= grace {
|
||||
let teardown_data = self.encrypt(&self.link_id).unwrap_or_default();
|
||||
self.close(CloseReason::Timeout);
|
||||
return LinkAction::SendTeardownAndClose(teardown_data);
|
||||
}
|
||||
if let Some(stale_since) = self.stale_since
|
||||
&& now.saturating_duration_since(stale_since) >= grace
|
||||
{
|
||||
let teardown_data = self.encrypt(&self.link_id).unwrap_or_default();
|
||||
self.close(CloseReason::Timeout);
|
||||
return LinkAction::SendTeardownAndClose(teardown_data);
|
||||
}
|
||||
LinkAction::None
|
||||
}
|
||||
@@ -1400,23 +1524,31 @@ impl Link {
|
||||
self.ephemeral_keys = None;
|
||||
self.session_keys = None;
|
||||
self.peer_x25519_pub = None;
|
||||
self.peer_ed25519_pub = None;
|
||||
self.sig_prv = None;
|
||||
self.peer_packet_proof_key = None;
|
||||
self.responder_identity_signing_key = None;
|
||||
}
|
||||
|
||||
/// Attach the initiator's identity signing key after construction.
|
||||
/// Legacy attachment of a software responder destination identity key.
|
||||
#[deprecated(
|
||||
note = "construct responders with their signer; initiators use transient Link keys"
|
||||
)]
|
||||
pub fn set_signing_key(&mut self, key: &Ed25519PrivateKey) {
|
||||
self.sig_prv = Some(Ed25519PrivateKey::from_bytes(&key.to_bytes()));
|
||||
if self.role() == LinkRole::Responder {
|
||||
self.responder_identity_signing_key =
|
||||
Some(Ed25519PrivateKey::from_bytes(&key.to_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sign a message with the link's identity key, or `None` if no key is set.
|
||||
/// Sign a message with a software responder's destination identity key.
|
||||
pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> {
|
||||
self.sig_prv.as_ref().map(|key| key.sign(message))
|
||||
self.responder_identity_signing_key
|
||||
.as_ref()
|
||||
.map(|key| key.sign(message))
|
||||
}
|
||||
|
||||
/// Verify a signature using the peer's Ed25519 identity key.
|
||||
/// Verify a signature using the peer's role-dependent packet proof key.
|
||||
pub fn validate(&self, signature: &[u8], message: &[u8]) -> bool {
|
||||
if let Some(ref peer_pub_bytes) = self.peer_ed25519_pub {
|
||||
if let Some(ref peer_pub_bytes) = self.peer_packet_proof_key {
|
||||
if signature.len() != 64 {
|
||||
return false;
|
||||
}
|
||||
@@ -1632,10 +1764,10 @@ impl Link {
|
||||
|
||||
/// Default request timeout: `rtt * TRAFFIC_TIMEOUT_FACTOR + 1.125 * RESPONSE_MAX_GRACE_TIME`.
|
||||
pub fn default_request_timeout(&self) -> Duration {
|
||||
let rtt_secs = self.rtt.map(|r| r.as_secs_f64()).unwrap_or(1.0);
|
||||
let timeout =
|
||||
rtt_secs * TRAFFIC_TIMEOUT_FACTOR + crate::constants::RESPONSE_MAX_GRACE_TIME * 1.125;
|
||||
Duration::from_secs_f64(timeout)
|
||||
self.rtt
|
||||
.unwrap_or(Duration::from_secs(1))
|
||||
.saturating_mul(TRAFFIC_TIMEOUT_FACTOR as u32)
|
||||
.saturating_add(Duration::from_secs_f64(RESPONSE_MAX_GRACE_TIME * 1.125))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1659,6 +1791,21 @@ mod tests {
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
use rns_crypto::sha::full_hash;
|
||||
|
||||
#[test]
|
||||
fn packet_proof_clock_uses_rtt_not_link_keepalive() {
|
||||
let (mut link, _) = Link::new_initiator([0x61; 16], 1);
|
||||
assert_eq!(link.packet_proof_timeout(), Duration::from_secs(3));
|
||||
for (rtt, expected) in [
|
||||
(Duration::ZERO, Duration::from_millis(5)),
|
||||
(Duration::from_millis(200), Duration::from_millis(1200)),
|
||||
(Duration::from_secs(90), Duration::from_secs(540)),
|
||||
(Duration::MAX, Duration::MAX),
|
||||
] {
|
||||
link.rtt = Some(rtt);
|
||||
assert_eq!(link.packet_proof_timeout(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_initiator_creation() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
@@ -1719,7 +1866,9 @@ mod tests {
|
||||
assert_eq!(responder.state, LinkState::Handshake);
|
||||
assert_eq!(initiator.state, LinkState::Active);
|
||||
let packet_hash = [0xCD; 32];
|
||||
let packet_proof = responder.prove_packet(&packet_hash, &identity_key).unwrap();
|
||||
let packet_proof = responder
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &packet_proof));
|
||||
}
|
||||
|
||||
@@ -1759,6 +1908,7 @@ mod tests {
|
||||
fn test_wrong_proof_identity() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
let identity_key = Ed25519PrivateKey::generate();
|
||||
let identity_pub = identity_key.public_key();
|
||||
let wrong_identity = Ed25519PrivateKey::generate();
|
||||
let wrong_pub = wrong_identity.public_key();
|
||||
|
||||
@@ -1770,7 +1920,16 @@ mod tests {
|
||||
// Hand the initiator a mismatched public key on proof validation.
|
||||
let result = initiator.validate_proof(&proof_data, &wrong_pub, &wrong_pub.to_bytes());
|
||||
assert!(result.is_err());
|
||||
assert_eq!(initiator.state, LinkState::Closed);
|
||||
assert_eq!(initiator.state, LinkState::Pending);
|
||||
|
||||
// An unauthenticated proof must not win a race against the authentic
|
||||
// responder proof arriving later on another candidate interface.
|
||||
assert!(
|
||||
initiator
|
||||
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(initiator.state, LinkState::Active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1813,7 +1972,7 @@ mod tests {
|
||||
.is_err(),
|
||||
"initiator requested AES256 and must reject an AES128 proof"
|
||||
);
|
||||
assert_eq!(request_link.state, LinkState::Closed);
|
||||
assert_eq!(request_link.state, LinkState::Pending);
|
||||
|
||||
let mut unsupported_request = request_data;
|
||||
unsupported_request[64] = MODE_AES256_GCM << 5;
|
||||
@@ -1838,7 +1997,7 @@ mod tests {
|
||||
proof_data[96] = MODE_AES128_CBC << 5;
|
||||
let result = initiator.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes());
|
||||
assert!(matches!(result, Err(HandshakeError::InvalidSignature)));
|
||||
assert_eq!(initiator.state, LinkState::Closed);
|
||||
assert_eq!(initiator.state, LinkState::Pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2501,12 +2660,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_prove_packet_roundtrip() {
|
||||
let (initiator, responder, dest_identity) = make_active_link();
|
||||
let (initiator, responder, _dest_identity) = make_active_link();
|
||||
|
||||
let packet_hash = full_hash(b"test packet data");
|
||||
|
||||
let proof = responder
|
||||
.prove_packet(&packet_hash, &dest_identity)
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
assert_eq!(proof.len(), 96);
|
||||
|
||||
@@ -2515,17 +2674,155 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_prove_packet_wrong_hash_fails() {
|
||||
let (initiator, responder, dest_identity) = make_active_link();
|
||||
let (initiator, responder, _dest_identity) = make_active_link();
|
||||
|
||||
let packet_hash = full_hash(b"test packet");
|
||||
let wrong_hash = full_hash(b"wrong packet");
|
||||
|
||||
let proof = responder
|
||||
.prove_packet(&packet_hash, &dest_identity)
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
assert!(!initiator.validate_packet_proof(&wrong_hash, &proof));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_proofs_use_only_the_role_authorized_key() {
|
||||
let (initiator, responder, _destination_identity) = make_active_link();
|
||||
let packet_hash = full_hash(b"role-specific Link packet proof");
|
||||
|
||||
let initiator_proof = initiator
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
assert!(responder.validate_packet_proof(&packet_hash, &initiator_proof));
|
||||
|
||||
let unrelated_initiator_identity = Ed25519PrivateKey::generate();
|
||||
let mut wrong_initiator_proof = packet_hash.to_vec();
|
||||
wrong_initiator_proof.extend_from_slice(&unrelated_initiator_identity.sign(&packet_hash));
|
||||
assert!(!responder.validate_packet_proof(&packet_hash, &wrong_initiator_proof));
|
||||
|
||||
let responder_proof = responder
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &responder_proof));
|
||||
|
||||
let wrong_responder_identity = Ed25519PrivateKey::generate();
|
||||
let mut wrong_responder_proof = packet_hash.to_vec();
|
||||
wrong_responder_proof.extend_from_slice(&wrong_responder_identity.sign(&packet_hash));
|
||||
assert!(!initiator.validate_packet_proof(&packet_hash, &wrong_responder_proof));
|
||||
|
||||
let mut trailing = responder_proof;
|
||||
trailing.push(0);
|
||||
assert_eq!(
|
||||
initiator.validate_peer_packet_proof(&packet_hash, &trailing),
|
||||
Err(PacketProofError::MalformedProof)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_responder_packet_proofs_obey_role_and_state() {
|
||||
let dest_hash = [0xD7; 16];
|
||||
let destination_identity = Ed25519PrivateKey::generate();
|
||||
let destination_public = destination_identity.public_key();
|
||||
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let (mut responder, link_proof) = Link::new_responder_with(
|
||||
&request_data,
|
||||
&destination_public.to_bytes(),
|
||||
dest_hash,
|
||||
1,
|
||||
|data| Some(destination_identity.sign(data)),
|
||||
)
|
||||
.unwrap();
|
||||
let rtt = initiator
|
||||
.validate_proof(
|
||||
&link_proof,
|
||||
&destination_public,
|
||||
&destination_public.to_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
let packet_hash = full_hash(b"external responder proof");
|
||||
|
||||
assert_eq!(responder.state, LinkState::Handshake);
|
||||
let handshake_proof = responder
|
||||
.prove_responder_packet_with(&packet_hash, |hash| Some(destination_identity.sign(hash)))
|
||||
.unwrap();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &handshake_proof));
|
||||
|
||||
responder.receive_rtt_packet(&rtt).unwrap();
|
||||
let active_proof = responder
|
||||
.prove_responder_packet_with(&packet_hash, |hash| Some(destination_identity.sign(hash)))
|
||||
.unwrap();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &active_proof));
|
||||
|
||||
responder.state = LinkState::Stale;
|
||||
assert!(
|
||||
responder
|
||||
.prove_responder_packet_with(&packet_hash, |hash| {
|
||||
Some(destination_identity.sign(hash))
|
||||
})
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
let mut signer_called = false;
|
||||
assert_eq!(
|
||||
initiator.prove_responder_packet_with(&packet_hash, |_| {
|
||||
signer_called = true;
|
||||
Some([0u8; 64])
|
||||
}),
|
||||
Err(PacketProofError::WrongRole)
|
||||
);
|
||||
assert!(!signer_called);
|
||||
|
||||
assert_eq!(
|
||||
responder.prove_responder_packet_with(&packet_hash, |_| None),
|
||||
Err(PacketProofError::SignerUnavailable)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_proof_state_matrix_rejects_pending_handshake_initiator_and_closed() {
|
||||
let dest_hash = [0xD8; 16];
|
||||
let (mut initiator, _) = Link::new_initiator(dest_hash, 1);
|
||||
let packet_hash = full_hash(b"packet proof state matrix");
|
||||
assert_eq!(
|
||||
initiator.prove_packet_with_local_signer(&packet_hash),
|
||||
Err(PacketProofError::InvalidState(LinkState::Pending))
|
||||
);
|
||||
|
||||
initiator.state = LinkState::Handshake;
|
||||
assert_eq!(
|
||||
initiator.prove_packet_with_local_signer(&packet_hash),
|
||||
Err(PacketProofError::InvalidState(LinkState::Handshake))
|
||||
);
|
||||
|
||||
initiator.mark_closed(CloseReason::Timeout);
|
||||
assert_eq!(
|
||||
initiator.prove_packet_with_local_signer(&packet_hash),
|
||||
Err(PacketProofError::InvalidState(LinkState::Closed))
|
||||
);
|
||||
|
||||
let (mut active_initiator, mut active_responder, _) = make_active_link();
|
||||
let initiator_proof = active_initiator
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
let responder_proof = active_responder
|
||||
.prove_packet_with_local_signer(&packet_hash)
|
||||
.unwrap();
|
||||
active_initiator.mark_closed(CloseReason::Timeout);
|
||||
active_responder.mark_closed(CloseReason::Timeout);
|
||||
assert_eq!(
|
||||
active_initiator.validate_peer_packet_proof(&packet_hash, &responder_proof),
|
||||
Err(PacketProofError::PeerKeyUnavailable)
|
||||
);
|
||||
assert_eq!(
|
||||
active_responder.validate_peer_packet_proof(&packet_hash, &initiator_proof),
|
||||
Err(PacketProofError::PeerKeyUnavailable)
|
||||
);
|
||||
assert_eq!(
|
||||
active_responder.prove_packet_with_local_signer(&packet_hash),
|
||||
Err(PacketProofError::InvalidState(LinkState::Closed))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtt_packet_update() {
|
||||
let (initiator, mut responder, _) = make_active_link();
|
||||
@@ -2666,7 +2963,7 @@ mod tests {
|
||||
let message = b"hello from responder";
|
||||
let sig = responder_link
|
||||
.sign(message)
|
||||
.expect("responder should have sig_prv");
|
||||
.expect("responder should have a destination identity signer");
|
||||
let _ = initiator_link;
|
||||
assert_eq!(sig.len(), 64);
|
||||
}
|
||||
@@ -2696,4 +2993,236 @@ mod tests {
|
||||
link.close(CloseReason::Timeout);
|
||||
assert!(link.sign(b"test").is_none());
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
enum PeerRtt {
|
||||
Saturates,
|
||||
Zero,
|
||||
Ignored,
|
||||
}
|
||||
|
||||
/// Degenerate msgpack RTT numbers and how Link.py's `max()` treats them.
|
||||
fn hostile_peer_rtts() -> Vec<(rmpv::Value, PeerRtt)> {
|
||||
use rmpv::Value;
|
||||
vec![
|
||||
(Value::F64(f64::INFINITY), PeerRtt::Saturates),
|
||||
(Value::F64(f64::NEG_INFINITY), PeerRtt::Ignored),
|
||||
(Value::F64(f64::NAN), PeerRtt::Ignored),
|
||||
(Value::F64(-1.0), PeerRtt::Ignored),
|
||||
(Value::F64(-0.0), PeerRtt::Zero),
|
||||
(Value::F64(0.0), PeerRtt::Zero),
|
||||
(Value::F64(f64::from_bits(1)), PeerRtt::Zero),
|
||||
(Value::F64(1e300), PeerRtt::Saturates),
|
||||
(Value::F64(18_446_744_073_709_551_616.0), PeerRtt::Saturates),
|
||||
// Representable as a Duration, but overflowed the stale and request timers.
|
||||
(Value::F64(1e19), PeerRtt::Saturates),
|
||||
(Value::F32(f32::INFINITY), PeerRtt::Saturates),
|
||||
(Value::from(u64::MAX), PeerRtt::Saturates),
|
||||
(Value::from(i64::MIN), PeerRtt::Ignored),
|
||||
]
|
||||
}
|
||||
|
||||
fn encrypted_rtt(sender: &Link, value: &rmpv::Value) -> Vec<u8> {
|
||||
let mut encoded = Vec::new();
|
||||
rmpv::encode::write_value(&mut encoded, value).unwrap();
|
||||
sender.encrypt(&encoded).unwrap()
|
||||
}
|
||||
|
||||
/// Python's builtin `min(a, b)`: `b` only wins when strictly smaller.
|
||||
fn py_min(a: f64, b: f64) -> f64 {
|
||||
if b < a { b } else { a }
|
||||
}
|
||||
|
||||
/// Python's builtin `max(a, b)`: `b` only wins when strictly greater.
|
||||
fn py_max(a: f64, b: f64) -> f64 {
|
||||
if b > a { b } else { a }
|
||||
}
|
||||
|
||||
/// Link.py `max(measured_rtt, rtt)`.
|
||||
fn link_py_rtt(measured: f64, peer: f64) -> f64 {
|
||||
py_max(measured, peer)
|
||||
}
|
||||
|
||||
/// Link.py `__update_keepalive`.
|
||||
fn link_py_keepalive(rtt: f64) -> f64 {
|
||||
py_max(
|
||||
py_min(rtt * (KEEPALIVE_MAX / KEEPALIVE_MAX_RTT), KEEPALIVE_MAX),
|
||||
KEEPALIVE_MIN,
|
||||
)
|
||||
}
|
||||
|
||||
fn assert_link_py_keepalive(link: &Link, link_py_rtt: f64, case: &rmpv::Value) {
|
||||
let keepalive = link_py_keepalive(link_py_rtt);
|
||||
assert_eq!(
|
||||
link.keepalive.keepalive_interval,
|
||||
Duration::from_secs_f64(keepalive),
|
||||
"keepalive for {case}"
|
||||
);
|
||||
assert_eq!(
|
||||
link.keepalive.stale_time,
|
||||
Duration::from_secs_f64(keepalive * STALE_FACTOR),
|
||||
"stale time for {case}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Initiator is Active; responder awaits the LRRTT in Handshake.
|
||||
fn lrrtt_pair() -> (Link, Link) {
|
||||
let dest_hash = [0xA5; 16];
|
||||
let identity_key = Ed25519PrivateKey::generate();
|
||||
let identity_pub = identity_key.public_key();
|
||||
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
|
||||
let (responder, proof_data) =
|
||||
Link::new_responder(&request_data, &identity_key, dest_hash, 1).unwrap();
|
||||
initiator
|
||||
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
|
||||
.unwrap();
|
||||
(initiator, responder)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lrrtt_activation_bounds_hostile_peer_rtt_like_link_py() {
|
||||
let ceiling = Duration::from_secs_f64(PEER_RTT_MAX_SECS);
|
||||
for (value, expected) in hostile_peer_rtts() {
|
||||
let (initiator, mut responder) = lrrtt_pair();
|
||||
responder
|
||||
.receive_rtt_packet(&encrypted_rtt(&initiator, &value))
|
||||
.unwrap();
|
||||
let measured_bound = responder.request_time.elapsed();
|
||||
|
||||
assert_eq!(responder.state, LinkState::Active, "{value}");
|
||||
let rtt = responder.rtt.unwrap();
|
||||
match expected {
|
||||
PeerRtt::Saturates => {
|
||||
assert_eq!(rtt, ceiling, "{value}");
|
||||
assert_eq!(
|
||||
responder.keepalive.keepalive_interval,
|
||||
Duration::from_secs_f64(KEEPALIVE_MAX)
|
||||
);
|
||||
assert_eq!(
|
||||
responder.keepalive.stale_time,
|
||||
Duration::from_secs_f64(STALE_TIME_DEFAULT)
|
||||
);
|
||||
}
|
||||
PeerRtt::Zero | PeerRtt::Ignored => {
|
||||
assert!(rtt <= measured_bound, "{value} must keep the local RTT")
|
||||
}
|
||||
}
|
||||
let measured = rtt.min(measured_bound).as_secs_f64();
|
||||
let peer = value.as_f64().unwrap();
|
||||
assert_link_py_keepalive(&responder, link_py_rtt(measured, peer), &value);
|
||||
assert!(responder.establishment_rate.is_none_or(f64::is_finite));
|
||||
assert!(responder.default_request_timeout() > rtt);
|
||||
assert!(responder.keepalive.stale_grace_timeout(rtt) > rtt);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtt_update_bounds_hostile_peer_rtt_with_and_without_prior_measurement() {
|
||||
let ceiling = Duration::from_secs_f64(PEER_RTT_MAX_SECS);
|
||||
let prior = Duration::from_millis(200);
|
||||
for (value, expected) in hostile_peer_rtts() {
|
||||
let (initiator, mut responder, _) = make_active_link();
|
||||
let payload = encrypted_rtt(&initiator, &value);
|
||||
let peer = value.as_f64().unwrap();
|
||||
|
||||
responder.rtt = Some(prior);
|
||||
let updated = responder.update_rtt_from_packet(&payload).unwrap();
|
||||
let kept = if expected == PeerRtt::Saturates {
|
||||
ceiling
|
||||
} else {
|
||||
prior
|
||||
};
|
||||
assert_eq!(updated, kept, "{value} with a prior RTT");
|
||||
assert_eq!(responder.rtt, Some(kept));
|
||||
assert_link_py_keepalive(&responder, link_py_rtt(prior.as_secs_f64(), peer), &value);
|
||||
|
||||
responder.rtt = None;
|
||||
let keepalive_before = responder.keepalive.keepalive_interval;
|
||||
match (expected, responder.update_rtt_from_packet(&payload)) {
|
||||
(PeerRtt::Saturates, Ok(rtt)) => assert_eq!(rtt, ceiling),
|
||||
(PeerRtt::Zero, Ok(rtt)) => assert_eq!(rtt, Duration::ZERO),
|
||||
(PeerRtt::Ignored, Err(LinkCryptoError::DecryptionFailed)) => {
|
||||
assert_eq!(responder.rtt, None);
|
||||
assert_eq!(responder.keepalive.keepalive_interval, keepalive_before);
|
||||
}
|
||||
(expected, result) => {
|
||||
panic!("{value} without a prior RTT: expected {expected:?}, got {result:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drives a responder from a hostile LRRTT through keepalive replies,
|
||||
/// STALE and teardown. Link.py keeps the same 360 s keepalive and 720 s
|
||||
/// stale window for an infinite RTT.
|
||||
#[test]
|
||||
fn hostile_lrrtt_link_keeps_link_py_keepalive_and_stale_timing() {
|
||||
for peer_rtt in [f64::INFINITY, 1e19] {
|
||||
let (initiator, mut responder) = lrrtt_pair();
|
||||
responder
|
||||
.receive_rtt_packet(&encrypted_rtt(&initiator, &rmpv::Value::F64(peer_rtt)))
|
||||
.unwrap();
|
||||
let rtt = responder.rtt.unwrap();
|
||||
assert_eq!(rtt, Duration::from_secs_f64(PEER_RTT_MAX_SECS));
|
||||
let keepalive = responder.keepalive.keepalive_interval;
|
||||
assert_eq!(keepalive, Duration::from_secs_f64(KEEPALIVE_MAX));
|
||||
|
||||
// Link.py answers a keepalive once `keepalive` has passed since outbound.
|
||||
let replied_at = Instant::now();
|
||||
responder.keepalive.last_outbound = Some(replied_at);
|
||||
assert!(
|
||||
!responder.keepalive.should_respond_to_keepalive_at(
|
||||
replied_at + keepalive - Duration::from_secs(1)
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
responder
|
||||
.keepalive
|
||||
.should_respond_to_keepalive_at(replied_at + keepalive)
|
||||
);
|
||||
|
||||
let stale_at =
|
||||
responder.keepalive.activated_at.unwrap() + responder.keepalive.stale_time;
|
||||
assert_eq!(
|
||||
responder.tick_at(stale_at - Duration::from_secs(1)),
|
||||
LinkAction::None
|
||||
);
|
||||
assert_eq!(responder.tick_at(stale_at), LinkAction::TransitionedToStale);
|
||||
assert_eq!(responder.state, LinkState::Stale);
|
||||
|
||||
let grace = responder.keepalive.stale_grace_timeout(rtt);
|
||||
assert_eq!(grace, rtt * 4 + Duration::from_secs(5));
|
||||
assert_eq!(
|
||||
responder.tick_at(stale_at + grace - Duration::from_secs(1)),
|
||||
LinkAction::None
|
||||
);
|
||||
assert!(matches!(
|
||||
responder.tick_at(stale_at + grace),
|
||||
LinkAction::SendTeardownAndClose(_)
|
||||
));
|
||||
assert_eq!(responder.state, LinkState::Closed);
|
||||
assert_eq!(responder.teardown_reason, Some(CloseReason::Timeout));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_link_timers_saturate_instead_of_panicking() {
|
||||
let (mut link, _, _) = make_active_link();
|
||||
link.rtt = Some(Duration::MAX);
|
||||
assert_eq!(link.default_request_timeout(), Duration::MAX);
|
||||
assert_eq!(link.packet_proof_timeout(), Duration::MAX);
|
||||
assert_eq!(
|
||||
link.keepalive.stale_grace_timeout(Duration::MAX),
|
||||
Duration::MAX
|
||||
);
|
||||
link.keepalive.update_from_rtt(Duration::MAX);
|
||||
assert_eq!(
|
||||
link.keepalive.keepalive_interval,
|
||||
Duration::from_secs_f64(KEEPALIVE_MAX)
|
||||
);
|
||||
|
||||
link.state = LinkState::Stale;
|
||||
link.stale_since = Some(Instant::now());
|
||||
assert_eq!(link.tick(), LinkAction::None);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-protocol"
|
||||
description = "Resource, Channel, and Buffer protocols for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -154,10 +154,11 @@ impl StreamWriter {
|
||||
if segment_len <= 32 {
|
||||
break;
|
||||
}
|
||||
if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len]) {
|
||||
if compressed.len() < self.max_data_len && compressed.len() < segment_len {
|
||||
return (compressed, segment_len, true);
|
||||
}
|
||||
if let Ok(compressed) = compression::bz2_compress(&chunk[..segment_len])
|
||||
&& compressed.len() < self.max_data_len
|
||||
&& compressed.len() < segment_len
|
||||
{
|
||||
return (compressed, segment_len, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -362,13 +362,13 @@ impl Channel {
|
||||
|
||||
let seq = self.next_tx_sequence;
|
||||
let mut envelope = Envelope::pack(msg, seq);
|
||||
if let Some(max) = max_envelope_size {
|
||||
if envelope.raw.len() > max {
|
||||
return Err(ChannelError::MessageTooLarge {
|
||||
actual: envelope.raw.len(),
|
||||
max,
|
||||
});
|
||||
}
|
||||
if let Some(max) = max_envelope_size
|
||||
&& envelope.raw.len() > max
|
||||
{
|
||||
return Err(ChannelError::MessageTooLarge {
|
||||
actual: envelope.raw.len(),
|
||||
max,
|
||||
});
|
||||
}
|
||||
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
|
||||
envelope.state = MessageState::Sent;
|
||||
@@ -482,12 +482,12 @@ impl Channel {
|
||||
Ok(delivered)
|
||||
}
|
||||
|
||||
/// Match Python's receive guard: future sequence numbers are buffered
|
||||
/// without a window-distance cap, while old sequence numbers are only
|
||||
/// accepted when the current receive window wraps past zero.
|
||||
/// Match Python RNS 1.4.2's receive guard: future sequence numbers are
|
||||
/// accepted only through `WINDOW_MAX`, while old sequence numbers are
|
||||
/// accepted only when the current receive window wraps past zero.
|
||||
fn is_acceptable_sequence(&self, seq: u16) -> bool {
|
||||
if seq >= self.next_rx_sequence {
|
||||
return true;
|
||||
return (seq as u32) <= self.next_rx_sequence as u32 + WINDOW_MAX as u32;
|
||||
}
|
||||
|
||||
let window_overflow =
|
||||
@@ -891,6 +891,34 @@ mod tests {
|
||||
assert_eq!(d3[0].1, b"third");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_drops_far_future_sequence_until_window_reaches_it() {
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
|
||||
let raw = |sequence: u16, payload: &[u8]| {
|
||||
let mut raw = Vec::with_capacity(ENVELOPE_HEADER_SIZE + payload.len());
|
||||
raw.extend_from_slice(&0x0001u16.to_be_bytes());
|
||||
raw.extend_from_slice(&sequence.to_be_bytes());
|
||||
raw.extend_from_slice(&(payload.len() as u16).to_be_bytes());
|
||||
raw.extend_from_slice(payload);
|
||||
raw
|
||||
};
|
||||
|
||||
let far_future = (WINDOW_MAX + 1) as u16;
|
||||
assert!(rx.receive(&raw(far_future, b"future")).unwrap().is_empty());
|
||||
|
||||
let mut delivered = Vec::new();
|
||||
for sequence in 0..=WINDOW_MAX as u16 {
|
||||
delivered.extend(rx.receive(&raw(sequence, b"in-window")).unwrap());
|
||||
}
|
||||
assert_eq!(delivered.len(), WINDOW_MAX + 1);
|
||||
|
||||
let retried = rx.receive(&raw(far_future, b"future")).unwrap();
|
||||
assert_eq!(retried.len(), 1);
|
||||
assert_eq!(retried[0].1, b"future");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_flow_control() {
|
||||
let mut ch = Channel::new(0.1);
|
||||
|
||||
+576
-201
@@ -758,9 +758,7 @@ impl InboundResource {
|
||||
/// memory for a transfer that will never complete.
|
||||
pub fn handle_cancel(&mut self) {
|
||||
self.state = ResourceState::Failed;
|
||||
for part in &mut self.parts {
|
||||
*part = None;
|
||||
}
|
||||
self.parts.fill(None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,6 +1371,10 @@ pub struct OutboundTransfer {
|
||||
pub sent_parts: usize,
|
||||
sent_part_indices: HashSet<usize>,
|
||||
req_hashlist: HashSet<[u8; 32]>,
|
||||
// Only newly requested parts advance this clock. Link keepalives, duplicate
|
||||
// requests and local polling are not Resource progress.
|
||||
last_progress: Instant,
|
||||
last_request_parts: usize,
|
||||
}
|
||||
|
||||
impl OutboundTransfer {
|
||||
@@ -1422,95 +1424,79 @@ impl OutboundTransfer {
|
||||
sent_parts: 0,
|
||||
sent_part_indices: HashSet::new(),
|
||||
req_hashlist: HashSet::new(),
|
||||
last_progress: Instant::now(),
|
||||
last_request_parts: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Advance the transfer state machine one step and emit the side-effect
|
||||
/// the caller should perform. Safe to poll idle.
|
||||
/// Advertise and drive bounded phase timeouts. Parts are emitted only in
|
||||
/// response to the receiver's [`Self::handle_request`] (or
|
||||
/// [`Self::handle_request_packet`]); polling never sends unsolicited parts.
|
||||
pub fn tick(&mut self) -> TransferAction {
|
||||
if self.resource.state == ResourceState::Complete {
|
||||
return TransferAction::Complete;
|
||||
}
|
||||
if self.resource.state == ResourceState::Failed {
|
||||
if matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Failed | ResourceState::Rejected | ResourceState::Corrupt
|
||||
) {
|
||||
return TransferAction::Failed("transfer failed".to_string());
|
||||
}
|
||||
|
||||
if !self.advertised {
|
||||
self.advertised = true;
|
||||
self.started_at = Instant::now();
|
||||
self.resource.state = ResourceState::Advertised;
|
||||
return TransferAction::SendAdvertisement(self.create_advertisement());
|
||||
}
|
||||
|
||||
if self.awaiting_hmu {
|
||||
if let Some(last) = self.last_part_sent {
|
||||
let timeout = self.part_timeout();
|
||||
if last.elapsed() > timeout {
|
||||
self.retries += 1;
|
||||
if self.retries > MAX_RETRIES {
|
||||
self.resource.state = ResourceState::Failed;
|
||||
return TransferAction::Failed("max retries exceeded".to_string());
|
||||
}
|
||||
// Back off before resending the window.
|
||||
self.awaiting_hmu = false;
|
||||
self.resource.window.shrink();
|
||||
}
|
||||
}
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
if self.cursor < self.resource.num_parts() {
|
||||
let window_end =
|
||||
(self.cursor + self.resource.window.window).min(self.resource.num_parts());
|
||||
|
||||
if self.window_cursor < window_end {
|
||||
let part_idx = self.window_cursor;
|
||||
self.window_cursor += 1;
|
||||
|
||||
if !self.confirmed_parts[part_idx] {
|
||||
let part_data = self.resource.get_part(part_idx).map(|p| p.to_vec());
|
||||
if let Some(part_data) = part_data {
|
||||
self.last_part_sent = Some(Instant::now());
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
if self.sent_part_indices.insert(part_idx) {
|
||||
self.sent_parts += 1;
|
||||
}
|
||||
|
||||
if self.window_cursor >= window_end {
|
||||
// Last part in the window is now in flight; stop
|
||||
// sending and wait for the receiver's HMU.
|
||||
self.awaiting_hmu = true;
|
||||
self.window_max_sent = window_end;
|
||||
}
|
||||
|
||||
return TransferAction::SendPart(part_idx, part_data);
|
||||
}
|
||||
} else {
|
||||
return self.tick();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.all_confirmed() {
|
||||
self.resource.state = ResourceState::AwaitingProof;
|
||||
}
|
||||
|
||||
TransferAction::None
|
||||
self.check_timeout()
|
||||
}
|
||||
|
||||
/// Sender-side advertisement watchdog for request-driven runtimes.
|
||||
/// Sender-side watchdog for every request-driven phase.
|
||||
///
|
||||
/// An outbound transfer remains `Advertised` until the receiver's first
|
||||
/// `RESOURCE_REQ` arrives. If that advertisement is lost, resend it up to
|
||||
/// the Python-compatible retry limit instead of leaving the transfer
|
||||
/// dormant forever.
|
||||
/// dormant forever. After acceptance the receiver owns part/HMU retries;
|
||||
/// the sender allows that bounded retry envelope, then fails if no new
|
||||
/// parts were requested. A missing final proof likewise fails rather than
|
||||
/// retaining the transfer forever. This does not imply delivery failure at
|
||||
/// the receiver, and does not add a generic network proof cache.
|
||||
pub fn check_timeout(&mut self) -> TransferAction {
|
||||
if matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Failed | ResourceState::Rejected | ResourceState::Corrupt
|
||||
) {
|
||||
// Some owners send a request-handler's cancel action first and
|
||||
// conclude on their next poll. Do not leave that failed owner
|
||||
// dormant merely because it is no longer Advertised.
|
||||
return TransferAction::Failed("transfer failed".to_string());
|
||||
}
|
||||
if matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Transferring | ResourceState::AwaitingProof
|
||||
) {
|
||||
let timeout = self.progress_timeout();
|
||||
if self.last_progress.elapsed() > timeout {
|
||||
let reason = if self.resource.state == ResourceState::AwaitingProof {
|
||||
"resource proof timed out"
|
||||
} else {
|
||||
"resource part requests timed out"
|
||||
};
|
||||
self.resource.state = ResourceState::Failed;
|
||||
return TransferAction::Failed(reason.to_string());
|
||||
}
|
||||
return TransferAction::None;
|
||||
}
|
||||
if self.resource.state != ResourceState::Advertised {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
let timeout = Duration::from_secs_f64(
|
||||
self.rtt.as_secs_f64() * rns_link::constants::TRAFFIC_TIMEOUT_FACTOR + PROCESSING_GRACE,
|
||||
);
|
||||
let timeout = self
|
||||
.rtt
|
||||
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
|
||||
.saturating_add(Duration::from_secs_f64(PROCESSING_GRACE));
|
||||
if self.started_at.elapsed() <= timeout {
|
||||
return TransferAction::None;
|
||||
}
|
||||
@@ -1525,6 +1511,37 @@ impl OutboundTransfer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact finite wait owned by this sender, as `(started_at, timeout)`.
|
||||
///
|
||||
/// Embedders can mirror this deadline without imposing an absolute age
|
||||
/// limit on a healthy Resource. Advertisement retries are included in the
|
||||
/// returned envelope; transferring/proof waits advance only when the
|
||||
/// receiver requests new parts. A delayed observation must retain its
|
||||
/// original `started_at`, not restart the timeout on receipt. Terminal or
|
||||
/// not-yet-advertised transfers have no active wait.
|
||||
pub fn timeout_window(&self) -> Option<(Instant, Duration)> {
|
||||
match self.resource.state {
|
||||
ResourceState::Advertised => {
|
||||
let attempt = self
|
||||
.rtt
|
||||
.saturating_mul(rns_link::constants::TRAFFIC_TIMEOUT_FACTOR as u32)
|
||||
.saturating_add(Duration::from_secs_f64(PROCESSING_GRACE));
|
||||
Some((
|
||||
self.started_at,
|
||||
attempt.saturating_mul(
|
||||
MAX_ADV_RETRIES
|
||||
.saturating_sub(self.retries)
|
||||
.saturating_add(1) as u32,
|
||||
),
|
||||
))
|
||||
}
|
||||
ResourceState::Transferring | ResourceState::AwaitingProof => {
|
||||
Some((self.last_progress, self.progress_timeout()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume a hashmap-update frame from the receiver.
|
||||
///
|
||||
/// Wire layout:
|
||||
@@ -1536,7 +1553,15 @@ impl OutboundTransfer {
|
||||
/// When not exhausted, parts in the sent window whose hash is *not* in
|
||||
/// the requested set are marked confirmed.
|
||||
pub fn handle_hmu(&mut self, hmu_data: &[u8]) {
|
||||
if hmu_data.is_empty() {
|
||||
if hmu_data.is_empty()
|
||||
|| matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Complete
|
||||
| ResourceState::Failed
|
||||
| ResourceState::Rejected
|
||||
| ResourceState::Corrupt
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1548,11 +1573,14 @@ impl OutboundTransfer {
|
||||
offset += MAPHASH_LEN;
|
||||
}
|
||||
|
||||
// Skip resource_hash(32) — we already know which resource this is
|
||||
// Do not allow another Resource's control frame to change this owner.
|
||||
if hmu_data.len() < offset + 32 {
|
||||
// Malformed HMU, not enough data for resource_hash
|
||||
return;
|
||||
}
|
||||
if hmu_data[offset..offset + 32] != self.resource.resource_hash {
|
||||
return;
|
||||
}
|
||||
offset += 32;
|
||||
|
||||
// When not exhausted: the remaining data contains hashes of parts
|
||||
@@ -1561,7 +1589,7 @@ impl OutboundTransfer {
|
||||
// Parse the set of requested (needed) hashes
|
||||
let requested_data = &hmu_data[offset..];
|
||||
let mut requested_set: HashSet<[u8; MAPHASH_LEN]> = HashSet::new();
|
||||
for chunk in requested_data.chunks_exact(MAPHASH_LEN) {
|
||||
for chunk in requested_data.as_chunks::<MAPHASH_LEN>().0 {
|
||||
let mut mh = [0u8; MAPHASH_LEN];
|
||||
mh.copy_from_slice(chunk);
|
||||
requested_set.insert(mh);
|
||||
@@ -1644,22 +1672,24 @@ impl OutboundTransfer {
|
||||
}
|
||||
|
||||
pub fn handle_request(&mut self, request_data: &[u8]) -> Vec<TransferAction> {
|
||||
if request_data.is_empty() || self.resource.state == ResourceState::Failed {
|
||||
if request_data.is_empty()
|
||||
|| matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Complete
|
||||
| ResourceState::Failed
|
||||
| ResourceState::Rejected
|
||||
| ResourceState::Corrupt
|
||||
)
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Refine the RTT estimate using the elapsed time since startup.
|
||||
let elapsed = self.started_at.elapsed();
|
||||
if self.rtt == Duration::ZERO || elapsed < self.rtt {
|
||||
self.rtt = elapsed;
|
||||
if !matches!(
|
||||
request_data[0],
|
||||
HASHMAP_IS_NOT_EXHAUSTED | HASHMAP_IS_EXHAUSTED
|
||||
) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if self.resource.state != ResourceState::Transferring {
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
}
|
||||
|
||||
self.retries = 0;
|
||||
|
||||
let wants_more_hashmap = request_data[0] == HASHMAP_IS_EXHAUSTED;
|
||||
let pad = if wants_more_hashmap {
|
||||
1 + MAPHASH_LEN
|
||||
@@ -1672,11 +1702,16 @@ impl OutboundTransfer {
|
||||
if request_data.len() < hash_offset {
|
||||
return Vec::new();
|
||||
}
|
||||
if request_data[pad..hash_offset] != self.resource.resource_hash
|
||||
|| !(request_data.len() - hash_offset).is_multiple_of(MAPHASH_LEN)
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let requested_hashes_data = &request_data[hash_offset..];
|
||||
|
||||
let mut requested_map_hashes: Vec<[u8; MAPHASH_LEN]> = Vec::new();
|
||||
for chunk in requested_hashes_data.chunks_exact(MAPHASH_LEN) {
|
||||
for chunk in requested_hashes_data.as_chunks::<MAPHASH_LEN>().0 {
|
||||
let mut mh = [0u8; MAPHASH_LEN];
|
||||
mh.copy_from_slice(chunk);
|
||||
requested_map_hashes.push(mh);
|
||||
@@ -1691,23 +1726,21 @@ impl OutboundTransfer {
|
||||
|
||||
let mut actions: Vec<TransferAction> = Vec::new();
|
||||
let mut sent_count = 0;
|
||||
let previously_sent = self.sent_parts;
|
||||
|
||||
for i in search_start..search_end {
|
||||
if i < self.resource.map_hashes.len()
|
||||
&& requested_map_hashes.contains(&self.resource.map_hashes[i])
|
||||
&& let Some(part_data) = self.resource.get_part(i)
|
||||
{
|
||||
if let Some(part_data) = self.resource.get_part(i) {
|
||||
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
|
||||
if self.sent_part_indices.insert(i) {
|
||||
self.sent_parts += 1;
|
||||
}
|
||||
sent_count += 1;
|
||||
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
|
||||
if self.sent_part_indices.insert(i) {
|
||||
self.sent_parts += 1;
|
||||
}
|
||||
sent_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
self.last_part_sent = Some(Instant::now());
|
||||
|
||||
if wants_more_hashmap && request_data.len() > MAPHASH_LEN {
|
||||
let mut last_map_hash = [0u8; MAPHASH_LEN];
|
||||
last_map_hash.copy_from_slice(&request_data[1..1 + MAPHASH_LEN]);
|
||||
@@ -1736,7 +1769,7 @@ impl OutboundTransfer {
|
||||
|
||||
// Python cancels if an exhausted request cursor is not aligned to
|
||||
// a hashmap segment boundary.
|
||||
if hashmap_max_len > 0 && part_index % hashmap_max_len != 0 {
|
||||
if hashmap_max_len > 0 && !part_index.is_multiple_of(hashmap_max_len) {
|
||||
self.resource.state = ResourceState::Failed;
|
||||
actions.push(TransferAction::SendCancel(
|
||||
CancelType::Icl,
|
||||
@@ -1786,10 +1819,23 @@ impl OutboundTransfer {
|
||||
}
|
||||
|
||||
if sent_count > 0 {
|
||||
let total_sent = self.confirmed_parts.iter().filter(|&&c| c).count() + sent_count;
|
||||
if total_sent >= self.resource.num_parts() {
|
||||
self.resource.state = ResourceState::AwaitingProof;
|
||||
let now = Instant::now();
|
||||
if self.resource.state == ResourceState::Advertised && self.rtt == Duration::ZERO {
|
||||
// A later window's request is not a new handshake sample, and
|
||||
// must not collapse a known slow-Link RTT to a local tick.
|
||||
self.rtt = now.duration_since(self.started_at);
|
||||
}
|
||||
self.last_part_sent = Some(now);
|
||||
if self.sent_parts > previously_sent {
|
||||
self.last_progress = now;
|
||||
self.last_request_parts = sent_count;
|
||||
self.retries = 0;
|
||||
}
|
||||
self.resource.state = if self.sent_parts == self.resource.num_parts() {
|
||||
ResourceState::AwaitingProof
|
||||
} else {
|
||||
ResourceState::Transferring
|
||||
};
|
||||
}
|
||||
|
||||
actions
|
||||
@@ -1801,6 +1847,17 @@ impl OutboundTransfer {
|
||||
|
||||
/// Check a delivery proof; transitions to `Complete` on match.
|
||||
pub fn handle_proof(&mut self, proof_data: &[u8]) -> bool {
|
||||
if matches!(
|
||||
self.resource.state,
|
||||
ResourceState::Complete
|
||||
| ResourceState::Failed
|
||||
| ResourceState::Rejected
|
||||
| ResourceState::Corrupt
|
||||
) || proof_data.len() != 64
|
||||
|| proof_data[..32] != self.resource.resource_hash
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.resource.validate_proof(proof_data)
|
||||
}
|
||||
|
||||
@@ -1808,12 +1865,21 @@ impl OutboundTransfer {
|
||||
self.confirmed_parts.iter().all(|&c| c)
|
||||
}
|
||||
|
||||
/// Retransmit timeout, scaled by retry count and capped at 30s to keep
|
||||
/// a pathologically slow link from stalling a transfer forever.
|
||||
fn part_timeout(&self) -> Duration {
|
||||
let base = self.rtt.as_secs_f64() * PART_TIMEOUT_FACTOR_AFTER_RTT;
|
||||
let timeout = base.max(0.025) * (self.retries as f64 + 1.5);
|
||||
Duration::from_secs_f64(timeout.min(30.0))
|
||||
fn progress_timeout(&self) -> Duration {
|
||||
// Preserve the receiver's retry budget (including its increasing
|
||||
// per-retry delay), and allow a whole requested window to traverse the
|
||||
// slow link. No fixed 30-second cap: an individual LoRa packet can
|
||||
// legitimately take longer than that. Only new parts restart this
|
||||
// envelope, so repeated requests cannot keep a dead transfer alive.
|
||||
let retry_wait = PER_RETRY_DELAY * (MAX_RETRIES * (MAX_RETRIES + 1) / 2) as f64;
|
||||
let request_count = MAX_RETRIES
|
||||
.saturating_add(self.last_request_parts)
|
||||
.try_into()
|
||||
.unwrap_or(u32::MAX);
|
||||
self.rtt
|
||||
.saturating_mul(PART_TIMEOUT_FACTOR as u32)
|
||||
.saturating_mul(request_count)
|
||||
.saturating_add(Duration::from_secs_f64(SENDER_GRACE_TIME + retry_wait))
|
||||
}
|
||||
|
||||
/// Build the msgpack-encoded advertisement that precedes the transfer.
|
||||
@@ -2052,13 +2118,18 @@ impl InboundTransfer {
|
||||
),
|
||||
)]
|
||||
pub fn receive_part(&mut self, data: Vec<u8>) -> TransferAction {
|
||||
if self.resource.state != ResourceState::Transferring {
|
||||
return TransferAction::None;
|
||||
}
|
||||
let payload_len = data.len();
|
||||
if !self.resource.receive_part(data) {
|
||||
// Malformed, irrelevant and duplicate parts are not progress and
|
||||
// must not refill the receiver's retry budget.
|
||||
return TransferAction::None;
|
||||
}
|
||||
self.last_activity = Instant::now();
|
||||
self.retries_left = MAX_RETRIES;
|
||||
|
||||
// Track cumulative received bytes so update_eifr can compute a
|
||||
// measured rate over each completed request round.
|
||||
let payload_len = data.len();
|
||||
|
||||
// The first reply after a request gives us an RTT sample; once we
|
||||
// have it we can relax the initial timeout multiplier.
|
||||
if self.req_resp.is_none() {
|
||||
@@ -2070,48 +2141,46 @@ impl InboundTransfer {
|
||||
}
|
||||
}
|
||||
|
||||
if self.resource.receive_part(data) {
|
||||
self.parts_since_hmu += 1;
|
||||
self.rtt_rxd_bytes = self.rtt_rxd_bytes.saturating_add(payload_len);
|
||||
self.parts_since_hmu += 1;
|
||||
// Count accepted bytes only when measuring a completed window.
|
||||
self.rtt_rxd_bytes = self.rtt_rxd_bytes.saturating_add(payload_len);
|
||||
|
||||
if self.outstanding_parts > 0 {
|
||||
self.outstanding_parts -= 1;
|
||||
}
|
||||
|
||||
if self.resource.is_complete() {
|
||||
self.parts_since_hmu = 0;
|
||||
return TransferAction::Complete;
|
||||
}
|
||||
|
||||
if self.outstanding_parts == 0 {
|
||||
// Window drained — compute req_data_rtt_rate from the byte
|
||||
// delta since last request, refresh EIFR, then grow the
|
||||
// window. Mirrors Python Resource.py:896-903.
|
||||
if let Some(sent_at) = self.req_sent {
|
||||
let rtt = self.last_activity.duration_since(sent_at).as_secs_f64();
|
||||
if rtt > 0.0 {
|
||||
let req_transferred = self
|
||||
.rtt_rxd_bytes
|
||||
.saturating_sub(self.rtt_rxd_bytes_at_part_req);
|
||||
self.req_data_rtt_rate = req_transferred as f64 / rtt;
|
||||
self.update_eifr();
|
||||
self.rtt_rxd_bytes_at_part_req = self.rtt_rxd_bytes;
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = self.started_at.elapsed().as_secs_f64();
|
||||
let received = self.resource.received_count();
|
||||
let rate = if elapsed > 0.0 {
|
||||
(received * SDU) as f64 / elapsed
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
self.resource.window.grow(rate as usize);
|
||||
|
||||
return self.request_next();
|
||||
}
|
||||
if self.outstanding_parts > 0 {
|
||||
self.outstanding_parts -= 1;
|
||||
}
|
||||
|
||||
if self.resource.is_complete() {
|
||||
self.parts_since_hmu = 0;
|
||||
return TransferAction::Complete;
|
||||
}
|
||||
|
||||
if self.outstanding_parts == 0 {
|
||||
// Window drained — compute req_data_rtt_rate from the byte
|
||||
// delta since last request, refresh EIFR, then grow the
|
||||
// window. Mirrors Python Resource.py:896-903.
|
||||
if let Some(sent_at) = self.req_sent {
|
||||
let rtt = self.last_activity.duration_since(sent_at).as_secs_f64();
|
||||
if rtt > 0.0 {
|
||||
let req_transferred = self
|
||||
.rtt_rxd_bytes
|
||||
.saturating_sub(self.rtt_rxd_bytes_at_part_req);
|
||||
self.req_data_rtt_rate = req_transferred as f64 / rtt;
|
||||
self.update_eifr();
|
||||
self.rtt_rxd_bytes_at_part_req = self.rtt_rxd_bytes;
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = self.started_at.elapsed().as_secs_f64();
|
||||
let received = self.resource.received_count();
|
||||
let rate = if elapsed > 0.0 {
|
||||
(received * SDU) as f64 / elapsed
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
self.resource.window.grow(rate as usize);
|
||||
|
||||
return self.request_next();
|
||||
}
|
||||
TransferAction::None
|
||||
}
|
||||
|
||||
@@ -2120,7 +2189,7 @@ impl InboundTransfer {
|
||||
/// an HMU refreshes the hashmap. See `handle_request` on the sender for
|
||||
/// the wire layout.
|
||||
pub fn request_next(&mut self) -> TransferAction {
|
||||
if self.resource.state == ResourceState::Failed {
|
||||
if self.resource.state != ResourceState::Transferring || self.resource.is_complete() {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
@@ -2260,7 +2329,7 @@ impl InboundTransfer {
|
||||
/// Wire layout:
|
||||
/// resource_hash(32) || msgpack([segment_index, hashmap_bytes])
|
||||
pub fn hashmap_update(&mut self, segment: usize, hashmap_data: &[u8]) -> TransferAction {
|
||||
if self.resource.state == ResourceState::Failed {
|
||||
if self.resource.state != ResourceState::Transferring {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
@@ -2273,7 +2342,7 @@ impl InboundTransfer {
|
||||
|
||||
// An empty/degenerate HMU carries no hashes and is invalid — cancel the
|
||||
// transfer rather than spinning on an unsatisfiable request (1.3.9).
|
||||
if hashmap_data.len() < MAPHASH_LEN {
|
||||
if hashmap_data.len() < MAPHASH_LEN || !hashmap_data.len().is_multiple_of(MAPHASH_LEN) {
|
||||
return self.cancel();
|
||||
}
|
||||
|
||||
@@ -2284,6 +2353,18 @@ impl InboundTransfer {
|
||||
if segment_start >= self.resource.total_parts {
|
||||
return self.cancel();
|
||||
}
|
||||
let hashes_count = hashmap_data.len() / MAPHASH_LEN;
|
||||
if segment_start > self.hashmap_height {
|
||||
// The receiver requested the next contiguous map, not a gap that
|
||||
// would fill unknown entries with zero hashes.
|
||||
return self.cancel();
|
||||
}
|
||||
if segment_start.saturating_add(hashes_count) <= self.hashmap_height {
|
||||
// A delayed copy of the previous HMU can arrive during the next
|
||||
// HMU wait. It is not progress and must not refill retries or
|
||||
// clear the current outstanding request.
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
self.last_activity = Instant::now();
|
||||
@@ -2293,7 +2374,6 @@ impl InboundTransfer {
|
||||
// `segment` is wire-supplied: indices are bounded by total_parts
|
||||
// (Python preallocates hashmap to total_parts, so out-of-range
|
||||
// writes are impossible there) — anything beyond is hostile.
|
||||
let hashes_count = hashmap_data.len() / MAPHASH_LEN;
|
||||
for i in 0..hashes_count {
|
||||
let idx = match segment_start.checked_add(i) {
|
||||
Some(idx) if idx < self.resource.total_parts => idx,
|
||||
@@ -2338,10 +2418,8 @@ impl InboundTransfer {
|
||||
hmu.push(exhausted);
|
||||
|
||||
// If exhausted (complete), include the last map hash
|
||||
if is_complete {
|
||||
if let Some(last_mh) = self.resource.map_hashes.last() {
|
||||
hmu.extend_from_slice(last_mh);
|
||||
}
|
||||
if is_complete && let Some(last_mh) = self.resource.map_hashes.last() {
|
||||
hmu.extend_from_slice(last_mh);
|
||||
}
|
||||
|
||||
// Include the resource hash for identification
|
||||
@@ -2889,7 +2967,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_transfer_advertise_then_send() {
|
||||
fn test_outbound_transfer_waits_for_receiver_request() {
|
||||
let mut transfer = OutboundTransfer::new(
|
||||
b"hello transfer".to_vec(),
|
||||
false,
|
||||
@@ -2902,9 +2980,18 @@ mod tests {
|
||||
assert!(matches!(action, TransferAction::SendAdvertisement(_)));
|
||||
assert!(transfer.advertised);
|
||||
|
||||
// Subsequent ticks should send parts
|
||||
let action = transfer.tick();
|
||||
assert!(matches!(action, TransferAction::SendPart(0, _)));
|
||||
for _ in 0..100 {
|
||||
assert_eq!(transfer.tick(), TransferAction::None);
|
||||
}
|
||||
assert_eq!(transfer.resource.state, ResourceState::Advertised);
|
||||
assert_eq!(transfer.sent_parts, 0);
|
||||
let mut request = vec![HASHMAP_IS_NOT_EXHAUSTED];
|
||||
request.extend_from_slice(&transfer.resource.resource_hash);
|
||||
request.extend_from_slice(&transfer.resource.map_hashes[0]);
|
||||
assert!(matches!(
|
||||
transfer.handle_request(&request).as_slice(),
|
||||
[TransferAction::SendPart(0, _)]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3149,10 +3236,14 @@ mod tests {
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
|
||||
let first_progress = match sender.tick() {
|
||||
TransferAction::SendPart(_, _) => sender.progress(),
|
||||
other => panic!("expected first part, got {other:?}"),
|
||||
};
|
||||
let mut first_request = vec![HASHMAP_IS_NOT_EXHAUSTED];
|
||||
first_request.extend_from_slice(&sender.resource.resource_hash);
|
||||
first_request.extend_from_slice(&sender.resource.map_hashes[0]);
|
||||
assert!(matches!(
|
||||
sender.handle_request(&first_request).as_slice(),
|
||||
[TransferAction::SendPart(0, _)]
|
||||
));
|
||||
let first_progress = sender.progress();
|
||||
assert!(first_progress > 0.0);
|
||||
assert!(first_progress < 1.0);
|
||||
|
||||
@@ -3214,19 +3305,8 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Step 3: Sender sends parts, receiver receives them
|
||||
let num_parts = sender.resource.num_parts();
|
||||
for _ in 0..num_parts {
|
||||
let action = sender.tick();
|
||||
if let TransferAction::SendPart(_idx, part_data) = action {
|
||||
let recv_action = receiver.receive_part(part_data);
|
||||
|
||||
// If receiver sends HMU, sender processes it
|
||||
if let TransferAction::SendHmu(hmu) = recv_action {
|
||||
sender.handle_hmu(&hmu);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Step 3: Receiver requests parts; sender never pushes unrequested data.
|
||||
drive_requested_transfer(&mut sender, &mut receiver);
|
||||
|
||||
// Step 4: Receiver completes and sends proof
|
||||
assert!(receiver.resource.is_complete());
|
||||
@@ -3264,36 +3344,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Transfer loop: send parts, handle HMUs
|
||||
let mut iterations = 0;
|
||||
let max_iterations = sender.resource.num_parts() * 3 + 10;
|
||||
while !receiver.resource.is_complete() && iterations < max_iterations {
|
||||
let action = sender.tick();
|
||||
match action {
|
||||
TransferAction::SendPart(_idx, part_data) => {
|
||||
let recv_action = receiver.receive_part(part_data);
|
||||
if let TransferAction::SendHmu(hmu) = recv_action {
|
||||
sender.handle_hmu(&hmu);
|
||||
}
|
||||
}
|
||||
// Sender is waiting for HMU; generate one if receiver has progress.
|
||||
TransferAction::None if receiver.resource.consecutive_completed > 0 => {
|
||||
let hmu = receiver.create_hmu();
|
||||
sender.handle_hmu(&hmu);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
iterations += 1;
|
||||
}
|
||||
|
||||
assert!(
|
||||
receiver.resource.is_complete(),
|
||||
"transfer incomplete after {} iterations ({} of {} parts received for {} byte payload)",
|
||||
iterations,
|
||||
receiver.resource.received_count(),
|
||||
receiver.resource.total_parts,
|
||||
data_len,
|
||||
);
|
||||
drive_requested_transfer(&mut sender, &mut receiver);
|
||||
|
||||
// Assemble and verify
|
||||
let (assembled, proof) = receiver.complete(None).unwrap();
|
||||
@@ -3305,6 +3356,330 @@ mod tests {
|
||||
assert_eq!(sender.resource.state, ResourceState::Complete);
|
||||
}
|
||||
|
||||
fn drive_requested_transfer(sender: &mut OutboundTransfer, receiver: &mut InboundTransfer) {
|
||||
let mut pending = receiver.request_next();
|
||||
for _ in 0..sender.resource.num_parts() * 4 + 10 {
|
||||
let TransferAction::SendRequest(request) = pending else {
|
||||
panic!("expected receiver-owned request, got {pending:?}");
|
||||
};
|
||||
pending = TransferAction::None;
|
||||
for action in sender.handle_request(&request) {
|
||||
let reply = match action {
|
||||
TransferAction::SendPart(_, data) => receiver.receive_part(data),
|
||||
TransferAction::SendHmu(data) => {
|
||||
let (_, segment, hashes) = parse_hashmap_update(&data).unwrap();
|
||||
receiver.hashmap_update(segment, &hashes)
|
||||
}
|
||||
other => panic!("unexpected sender action: {other:?}"),
|
||||
};
|
||||
if matches!(reply, TransferAction::SendRequest(_)) {
|
||||
pending = reply;
|
||||
}
|
||||
}
|
||||
if receiver.resource.is_complete() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
panic!("receiver did not complete the requested transfer");
|
||||
}
|
||||
|
||||
fn loss_test_pair(size: usize, rtt: Duration) -> (Vec<u8>, OutboundTransfer, InboundTransfer) {
|
||||
let data = rns_crypto::random::random_bytes(size);
|
||||
let mut sender = OutboundTransfer::new(data.clone(), false, rtt).unwrap();
|
||||
let TransferAction::SendAdvertisement(bytes) = sender.tick() else {
|
||||
panic!("missing advertisement");
|
||||
};
|
||||
let adv = crate::resource_adv::ResourceAdvertisement::unpack(&bytes).unwrap();
|
||||
let map_hashes = adv.get_map_hashes();
|
||||
let receiver = InboundTransfer::from_advertisement(
|
||||
adv.num_parts,
|
||||
adv.transfer_size,
|
||||
adv.data_size,
|
||||
sender.resource.random_hash,
|
||||
adv.resource_hash,
|
||||
adv.flags,
|
||||
map_hashes,
|
||||
rtt,
|
||||
)
|
||||
.unwrap();
|
||||
(data, sender, receiver)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_advertisement_and_initial_request_recover_without_unsolicited_parts() {
|
||||
let (data, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
|
||||
// Lose the first advertisement, then the first receiver request. The
|
||||
// sender remains Advertised through arbitrary local polling.
|
||||
sender.started_at = Instant::now() - Duration::from_secs(60);
|
||||
assert!(matches!(
|
||||
sender.tick(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
receiver.request_next(),
|
||||
TransferAction::SendRequest(_)
|
||||
));
|
||||
for _ in 0..100 {
|
||||
assert_eq!(sender.tick(), TransferAction::None);
|
||||
}
|
||||
assert_eq!(sender.resource.state, ResourceState::Advertised);
|
||||
receiver.last_activity = Instant::now() - Duration::from_secs(60);
|
||||
assert!(matches!(
|
||||
receiver.check_timeout(),
|
||||
TransferAction::SendRequest(_)
|
||||
));
|
||||
drive_requested_transfer(&mut sender, &mut receiver);
|
||||
let (received, proof) = receiver.complete(None).unwrap();
|
||||
assert_eq!(received, data);
|
||||
assert!(sender.handle_proof(&proof));
|
||||
assert!(
|
||||
!sender.handle_proof(&proof),
|
||||
"proof completion is claimed once"
|
||||
);
|
||||
assert!(sender.handle_request(&[0; 33]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_window_and_hashmap_recover_via_receiver_retries() {
|
||||
let (data, mut sender, mut receiver) = loss_test_pair(100_000, Duration::from_secs(2));
|
||||
let mut pending = receiver.request_next();
|
||||
let mut lost_part = false;
|
||||
let mut lost_request = false;
|
||||
let mut lost_hmu = false;
|
||||
for _ in 0..1000 {
|
||||
if matches!(pending, TransferAction::None) {
|
||||
receiver.last_activity = Instant::now() - Duration::from_secs(600);
|
||||
pending = receiver.check_timeout();
|
||||
}
|
||||
let TransferAction::SendRequest(request) = pending else {
|
||||
panic!("receiver did not rearm a lost request/window: {pending:?}");
|
||||
};
|
||||
pending = TransferAction::None;
|
||||
if !lost_request && lost_part && receiver.resource.received_count() > 4 {
|
||||
lost_request = true;
|
||||
continue;
|
||||
}
|
||||
for action in sender.handle_request(&request) {
|
||||
let reply = match action {
|
||||
TransferAction::SendPart(_, _) if !lost_part => {
|
||||
lost_part = true;
|
||||
continue;
|
||||
}
|
||||
TransferAction::SendPart(_, part) => receiver.receive_part(part),
|
||||
TransferAction::SendHmu(_) if !lost_hmu => {
|
||||
lost_hmu = true;
|
||||
continue;
|
||||
}
|
||||
TransferAction::SendHmu(hmu) => {
|
||||
let (_, segment, map) = parse_hashmap_update(&hmu).unwrap();
|
||||
receiver.hashmap_update(segment, &map)
|
||||
}
|
||||
other => panic!("unexpected sender action: {other:?}"),
|
||||
};
|
||||
if matches!(reply, TransferAction::SendRequest(_)) {
|
||||
pending = reply;
|
||||
}
|
||||
}
|
||||
if receiver.resource.is_complete() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(lost_part && lost_request && lost_hmu);
|
||||
let (received, proof) = receiver.complete(None).unwrap();
|
||||
assert_eq!(received, data);
|
||||
assert_eq!(sender.sent_parts, sender.resource.num_parts());
|
||||
assert_eq!(sender.resource.state, ResourceState::AwaitingProof);
|
||||
assert!(sender.handle_proof(&proof));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_all_feedback_has_bounded_sender_and_receiver_owners() {
|
||||
let (_, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
|
||||
let TransferAction::SendRequest(request) = receiver.request_next() else {
|
||||
panic!()
|
||||
};
|
||||
assert!(!sender.handle_request(&request).is_empty());
|
||||
assert_eq!(sender.resource.state, ResourceState::Transferring);
|
||||
let progress_at = sender.last_progress;
|
||||
// Repeating a valid request can recover loss but is not new progress.
|
||||
for _ in 0..20 {
|
||||
sender.handle_request(&request);
|
||||
}
|
||||
assert_eq!(sender.last_progress, progress_at);
|
||||
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
|
||||
assert_eq!(
|
||||
sender.tick(),
|
||||
TransferAction::Failed("resource part requests timed out".to_string())
|
||||
);
|
||||
assert!(sender.handle_request(&request).is_empty());
|
||||
|
||||
for _ in 0..MAX_RETRIES {
|
||||
receiver.last_activity = Instant::now() - Duration::from_secs(600);
|
||||
assert!(matches!(
|
||||
receiver.check_timeout(),
|
||||
TransferAction::SendRequest(_)
|
||||
));
|
||||
}
|
||||
receiver.last_activity = Instant::now() - Duration::from_secs(600);
|
||||
assert!(matches!(
|
||||
receiver.check_timeout(),
|
||||
TransferAction::Failed(_)
|
||||
));
|
||||
assert_eq!(
|
||||
receiver.receive_part(sender.resource.parts[0].clone()),
|
||||
TransferAction::None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_final_proof_terminates_without_false_success_or_resurrection() {
|
||||
let (data, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
|
||||
drive_requested_transfer(&mut sender, &mut receiver);
|
||||
let (received, proof) = receiver.complete(None).unwrap();
|
||||
assert_eq!(received, data);
|
||||
assert_eq!(sender.resource.state, ResourceState::AwaitingProof);
|
||||
// Receiver has delivered, but its proof is lost. Sender must release
|
||||
// ownership as failed, never infer success from all parts being sent.
|
||||
sender.last_progress = Instant::now() - sender.progress_timeout() - Duration::from_secs(1);
|
||||
assert_eq!(
|
||||
sender.tick(),
|
||||
TransferAction::Failed("resource proof timed out".to_string())
|
||||
);
|
||||
assert!(!sender.handle_proof(&proof));
|
||||
assert_eq!(
|
||||
receiver.receive_part(sender.resource.parts[0].clone()),
|
||||
TransferAction::None
|
||||
);
|
||||
assert_eq!(receiver.resource.state, ResourceState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_slow_window_progress_can_exceed_three_minutes() {
|
||||
let (_, mut sender, mut receiver) = loss_test_pair(100_000, Duration::from_secs(30));
|
||||
let TransferAction::SendRequest(request) = receiver.request_next() else {
|
||||
panic!()
|
||||
};
|
||||
sender.handle_request(&request);
|
||||
assert_eq!(
|
||||
sender.rtt,
|
||||
Duration::from_secs(30),
|
||||
"do not replace the slow RTT with local scheduling time"
|
||||
);
|
||||
assert!(sender.progress_timeout() > Duration::from_secs(180));
|
||||
sender.last_progress = Instant::now() - Duration::from_secs(180);
|
||||
assert_eq!(sender.check_timeout(), TransferAction::None);
|
||||
// No absolute transfer deadline: requesting new parts restarts the
|
||||
// bounded no-progress owner even after a long healthy transfer.
|
||||
let mut next = vec![HASHMAP_IS_NOT_EXHAUSTED];
|
||||
next.extend_from_slice(&sender.resource.resource_hash);
|
||||
next.extend_from_slice(&sender.resource.map_hashes[4]);
|
||||
sender.started_at = Instant::now() - Duration::from_secs(3600);
|
||||
sender.handle_request(&next);
|
||||
assert!(sender.last_progress.elapsed() < Duration::from_secs(1));
|
||||
assert_eq!(sender.check_timeout(), TransferAction::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_invalid_or_duplicate_input_does_not_rearm_liveness() {
|
||||
let (_, mut sender, mut receiver) = loss_test_pair(8192, Duration::from_secs(2));
|
||||
let TransferAction::SendRequest(mut request) = receiver.request_next() else {
|
||||
panic!()
|
||||
};
|
||||
request[1] ^= 1;
|
||||
assert!(sender.handle_request(&request).is_empty());
|
||||
assert_eq!(sender.resource.state, ResourceState::Advertised);
|
||||
request[1] ^= 1;
|
||||
request.push(0);
|
||||
assert!(sender.handle_request(&request).is_empty());
|
||||
assert_eq!(sender.resource.state, ResourceState::Advertised);
|
||||
receiver.receive_part(sender.resource.parts[0].clone());
|
||||
let progress_at = receiver.last_activity;
|
||||
receiver.retries_left = 3;
|
||||
receiver.receive_part(sender.resource.parts[0].clone());
|
||||
receiver.receive_part(vec![0; 5]);
|
||||
assert_eq!(receiver.last_activity, progress_at);
|
||||
assert_eq!(receiver.retries_left, 3);
|
||||
sender.handle_cancel();
|
||||
let mut proof = sender.resource.resource_hash.to_vec();
|
||||
proof.extend_from_slice(&sender.resource.expected_proof);
|
||||
assert!(!sender.handle_proof(&proof));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_watchdog_saturates_extreme_public_rtt_without_panicking() {
|
||||
let (_, mut sender, mut receiver) = loss_test_pair(8192, Duration::MAX);
|
||||
assert_eq!(sender.timeout_window().unwrap().1, Duration::MAX);
|
||||
assert_eq!(sender.check_timeout(), TransferAction::None);
|
||||
let TransferAction::SendRequest(request) = receiver.request_next() else {
|
||||
panic!()
|
||||
};
|
||||
sender.handle_request(&request);
|
||||
assert_eq!(sender.progress_timeout(), Duration::MAX);
|
||||
assert_eq!(sender.timeout_window().unwrap().1, Duration::MAX);
|
||||
assert_eq!(sender.check_timeout(), TransferAction::None);
|
||||
assert_eq!(sender.tick(), TransferAction::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_timeout_observation_tracks_only_owned_bounded_phases() {
|
||||
let mut sender =
|
||||
OutboundTransfer::new(vec![0x81; 8192], false, Duration::from_secs(2)).unwrap();
|
||||
assert!(sender.timeout_window().is_none());
|
||||
assert!(matches!(
|
||||
sender.tick(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
let first = sender.timeout_window().unwrap();
|
||||
assert_eq!(first.1, Duration::from_secs(65));
|
||||
sender.started_at = Instant::now() - Duration::from_secs(14);
|
||||
assert!(matches!(
|
||||
sender.check_timeout(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
let retry = sender.timeout_window().unwrap();
|
||||
assert_eq!(retry.1, Duration::from_secs(52));
|
||||
assert!(retry.0 >= first.0);
|
||||
sender.handle_cancel();
|
||||
assert!(sender.timeout_window().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_request_cancel_is_visible_to_poll_only_owners() {
|
||||
let (_, mut sender, _) = loss_test_pair(20_000, Duration::from_secs(1));
|
||||
let mut request = vec![HASHMAP_IS_EXHAUSTED];
|
||||
request.extend_from_slice(&sender.resource.map_hashes[0]);
|
||||
request.extend_from_slice(&sender.resource.resource_hash);
|
||||
assert!(matches!(
|
||||
sender.handle_request(&request).as_slice(),
|
||||
[TransferAction::SendCancel(CancelType::Icl, _)]
|
||||
));
|
||||
assert!(matches!(sender.check_timeout(), TransferAction::Failed(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_loss_delayed_hashmap_does_not_refill_retry_budget() {
|
||||
let (_, sender, mut receiver) = loss_test_pair(100_000, Duration::from_secs(2));
|
||||
let mut old_map = Vec::new();
|
||||
for hash in sender
|
||||
.resource
|
||||
.map_hashes
|
||||
.iter()
|
||||
.take(receiver.hashmap_height)
|
||||
{
|
||||
old_map.extend_from_slice(hash);
|
||||
}
|
||||
receiver.waiting_for_hmu = true;
|
||||
receiver.retries_left = 2;
|
||||
let activity = receiver.last_activity;
|
||||
assert_eq!(receiver.hashmap_update(0, &old_map), TransferAction::None);
|
||||
assert!(receiver.waiting_for_hmu);
|
||||
assert_eq!(receiver.retries_left, 2);
|
||||
assert_eq!(receiver.last_activity, activity);
|
||||
receiver.handle_cancel();
|
||||
assert_eq!(receiver.request_next(), TransferAction::None);
|
||||
assert_eq!(receiver.hashmap_update(1, &old_map), TransferAction::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transfer_size_class_01_tiny() {
|
||||
// 1 byte — single part, minimal resource
|
||||
|
||||
@@ -265,7 +265,9 @@ impl ResourceAdvertisement {
|
||||
/// Split the packed `hashmap` field into fixed-length map-hash entries.
|
||||
pub fn get_map_hashes(&self) -> Vec<[u8; MAPHASH_LEN]> {
|
||||
self.hashmap
|
||||
.chunks_exact(MAPHASH_LEN)
|
||||
.as_chunks::<MAPHASH_LEN>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|chunk| {
|
||||
let mut hash = [0u8; MAPHASH_LEN];
|
||||
hash.copy_from_slice(chunk);
|
||||
|
||||
@@ -552,10 +552,10 @@ fn value_to_u64(value: &Value, field: &'static str) -> Result<u64, RnshCodecErro
|
||||
if let Some(number) = value.as_u64() {
|
||||
return Ok(number);
|
||||
}
|
||||
if let Some(number) = value.as_i64() {
|
||||
if number >= 0 {
|
||||
return Ok(number as u64);
|
||||
}
|
||||
if let Some(number) = value.as_i64()
|
||||
&& number >= 0
|
||||
{
|
||||
return Ok(number as u64);
|
||||
}
|
||||
Err(RnshCodecError::InvalidShape(field))
|
||||
}
|
||||
@@ -564,10 +564,10 @@ fn value_to_i64(value: &Value, field: &'static str) -> Result<i64, RnshCodecErro
|
||||
if let Some(number) = value.as_i64() {
|
||||
return Ok(number);
|
||||
}
|
||||
if let Some(number) = value.as_u64() {
|
||||
if number <= i64::MAX as u64 {
|
||||
return Ok(number as i64);
|
||||
}
|
||||
if let Some(number) = value.as_u64()
|
||||
&& number <= i64::MAX as u64
|
||||
{
|
||||
return Ok(number as i64);
|
||||
}
|
||||
Err(RnshCodecError::InvalidShape(field))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-ratkey"
|
||||
description = "Hardware-backed identity (YubiKey/Nitrokey PIV) for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -565,14 +565,13 @@ fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> {
|
||||
return Some(value);
|
||||
}
|
||||
|
||||
if tag_first == TAG_DYNAMIC_AUTH
|
||||
if (tag_first == TAG_DYNAMIC_AUTH
|
||||
|| tag_first == 0xAC
|
||||
|| tag_first == 0x53
|
||||
|| (tag_total_len == 2)
|
||||
|| (tag_total_len == 2))
|
||||
&& let Some(found) = find_tlv_value(value, target_tag)
|
||||
{
|
||||
if let Some(found) = find_tlv_value(value, target_tag) {
|
||||
return Some(found);
|
||||
}
|
||||
return Some(found);
|
||||
}
|
||||
|
||||
pos += value_len;
|
||||
|
||||
@@ -255,12 +255,11 @@ fn bundled_trust_anchors() -> Vec<TrustAnchor> {
|
||||
(YUBICO_PIV_ROOT_CA_LEGACY_PEM, YUBICO_LEGACY_ROOT_SHA256),
|
||||
(YUBICO_ATTESTATION_ROOT_1_PEM, YUBICO_NEW_ROOT_SHA256),
|
||||
] {
|
||||
if let Some(der) = pem_to_der(pem) {
|
||||
if hex::encode(Sha256::digest(&der)) == fp {
|
||||
if let Ok(cert) = Certificate::from_der(&der) {
|
||||
anchors.push(TrustAnchor { cert });
|
||||
}
|
||||
}
|
||||
if let Some(der) = pem_to_der(pem)
|
||||
&& hex::encode(Sha256::digest(&der)) == fp
|
||||
&& let Ok(cert) = Certificate::from_der(&der)
|
||||
{
|
||||
anchors.push(TrustAnchor { cert });
|
||||
}
|
||||
}
|
||||
anchors
|
||||
@@ -505,12 +504,12 @@ fn find_oid_value(der: &[u8], oid_bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
// Unwrap one level if OCTET STRING wraps another OCTET STRING or INTEGER.
|
||||
if tag == 0x04 && value.len() >= 2 {
|
||||
let inner_tag = value[0];
|
||||
if inner_tag == 0x04 || inner_tag == 0x02 {
|
||||
if let Some((inner_len, inner_len_bytes)) = decode_der_length(&value[1..]) {
|
||||
let inner_start = 1 + inner_len_bytes;
|
||||
if inner_start + inner_len <= value.len() {
|
||||
return Some(value[inner_start..inner_start + inner_len].to_vec());
|
||||
}
|
||||
if (inner_tag == 0x04 || inner_tag == 0x02)
|
||||
&& let Some((inner_len, inner_len_bytes)) = decode_der_length(&value[1..])
|
||||
{
|
||||
let inner_start = 1 + inner_len_bytes;
|
||||
if inner_start + inner_len <= value.len() {
|
||||
return Some(value[inner_start..inner_start + inner_len].to_vec());
|
||||
}
|
||||
}
|
||||
return Some(value.to_vec());
|
||||
|
||||
@@ -64,10 +64,10 @@ impl LocalKeyBackend for HardwareBackend {
|
||||
|
||||
fn lock(&self) {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
if let Ok(tx) = self.cmd_tx.lock() {
|
||||
if tx.send(Cmd::Lock { reply }).is_ok() {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
if let Ok(tx) = self.cmd_tx.lock()
|
||||
&& tx.send(Cmd::Lock { reply }).is_ok()
|
||||
{
|
||||
let _ = rx.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ fn check(alg: u8, key: &[u8], data: &[u8]) -> Result<(), RatkeyError> {
|
||||
)));
|
||||
}
|
||||
let block = block_len(alg).expect("supported alg has a block size");
|
||||
if data.is_empty() || data.len() % block != 0 {
|
||||
if data.is_empty() || !data.len().is_multiple_of(block) {
|
||||
return Err(RatkeyError::InvalidHwid(format!(
|
||||
"management-key ECB input not block-aligned: {} bytes (block {block})",
|
||||
data.len()
|
||||
|
||||
@@ -186,10 +186,11 @@ impl MockPivSession {
|
||||
}
|
||||
|
||||
fn check_touch(&self, slot: u8) -> Result<(), RatkeyError> {
|
||||
if let Some(slot_state) = self.slots.get(&slot) {
|
||||
if slot_state.touch_policy == TouchPolicy::Always && self.touch_required {
|
||||
return Err(RatkeyError::TouchRequired);
|
||||
}
|
||||
if let Some(slot_state) = self.slots.get(&slot)
|
||||
&& slot_state.touch_policy == TouchPolicy::Always
|
||||
&& self.touch_required
|
||||
{
|
||||
return Err(RatkeyError::TouchRequired);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-runtime"
|
||||
description = "Core runtime, config parsing, and lifecycle for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -33,6 +34,7 @@ serde = { workspace = true }
|
||||
subtle = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
nix = { workspace = true }
|
||||
zeroize = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -571,7 +571,7 @@ fn validate_identity_hash_list(section: &ConfigSection, key: &str) -> Result<(),
|
||||
}
|
||||
|
||||
fn hex_decode(s: &str) -> Option<Vec<u8>> {
|
||||
if s.len() % 2 != 0 {
|
||||
if !s.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
(0..s.len())
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Deadline-aware, handler-free destination identity resolution.
|
||||
//!
|
||||
//! Python applications resolve finite destinations through validated identity
|
||||
//! recall and path requests. They do not install temporary announce handlers.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_transport::messages::{
|
||||
RecalledDestinationRpcEntry, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::{Instant, sleep_until, timeout_at};
|
||||
|
||||
const RECALL_POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DestinationResolveOptions {
|
||||
/// Complete command admission, path request and recall before this budget.
|
||||
pub timeout: Duration,
|
||||
/// Remove an existing route before requesting a fresh path response when
|
||||
/// the validated identity is not already cached.
|
||||
pub drop_existing_path: bool,
|
||||
/// Request a path refresh even when validated identity data is cached.
|
||||
/// The cached identity remains immediately usable, matching upstream
|
||||
/// applications that refresh routing separately from identity recall.
|
||||
pub refresh_cached_path: bool,
|
||||
}
|
||||
|
||||
impl DestinationResolveOptions {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
timeout,
|
||||
drop_existing_path: false,
|
||||
refresh_cached_path: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum DestinationResolveError {
|
||||
#[error("destination resolution timed out")]
|
||||
Timeout,
|
||||
#[error("Reticulum transport is unavailable")]
|
||||
TransportUnavailable,
|
||||
#[error("Reticulum transport returned an unexpected response during {0}")]
|
||||
UnexpectedResponse(&'static str),
|
||||
}
|
||||
|
||||
/// Resolve one validated destination without installing an announce handler.
|
||||
///
|
||||
/// A missing identity always emits an explicit path request. This deliberately
|
||||
/// covers the state where a route exists but its validated announce metadata
|
||||
/// is absent: `AwaitPath` alone would return immediately and never repair the
|
||||
/// identity cache.
|
||||
pub async fn resolve_destination_on_transport(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
destination_hash: [u8; 16],
|
||||
options: DestinationResolveOptions,
|
||||
) -> Result<RecalledDestinationRpcEntry, DestinationResolveError> {
|
||||
let deadline = Instant::now()
|
||||
.checked_add(options.timeout)
|
||||
.ok_or(DestinationResolveError::Timeout)?;
|
||||
|
||||
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await? {
|
||||
if options.refresh_cached_path {
|
||||
send_before_deadline(
|
||||
transport_tx,
|
||||
TransportMessage::RequestPath { destination_hash },
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
return Ok(recalled);
|
||||
}
|
||||
|
||||
if options.drop_existing_path {
|
||||
match query_before_deadline(
|
||||
transport_tx,
|
||||
TransportQuery::DropPath {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
TransportQueryResponse::Ok => {}
|
||||
_ => return Err(DestinationResolveError::UnexpectedResponse("path drop")),
|
||||
}
|
||||
}
|
||||
|
||||
send_before_deadline(
|
||||
transport_tx,
|
||||
TransportMessage::RequestPath { destination_hash },
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
if let Some(recalled) = recall_destination(transport_tx, destination_hash, deadline).await?
|
||||
{
|
||||
return Ok(recalled);
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Err(DestinationResolveError::Timeout);
|
||||
}
|
||||
sleep_until(std::cmp::min(deadline, now + RECALL_POLL_INTERVAL)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn recall_destination(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
destination_hash: [u8; 16],
|
||||
deadline: Instant,
|
||||
) -> Result<Option<RecalledDestinationRpcEntry>, DestinationResolveError> {
|
||||
match query_before_deadline(
|
||||
transport_tx,
|
||||
TransportQuery::RecallDestination {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
TransportQueryResponse::RecalledDestination(Some(recalled))
|
||||
if recalled.dest_hash != destination_hash =>
|
||||
{
|
||||
Err(DestinationResolveError::UnexpectedResponse(
|
||||
"destination recall",
|
||||
))
|
||||
}
|
||||
TransportQueryResponse::RecalledDestination(recalled) => Ok(recalled),
|
||||
_ => Err(DestinationResolveError::UnexpectedResponse(
|
||||
"destination recall",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_before_deadline(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
query: TransportQuery,
|
||||
deadline: Instant,
|
||||
) -> Result<TransportQueryResponse, DestinationResolveError> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
send_before_deadline(
|
||||
transport_tx,
|
||||
TransportMessage::Rpc { query, response_tx },
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
timeout_at(deadline, response_rx)
|
||||
.await
|
||||
.map_err(|_| DestinationResolveError::Timeout)?
|
||||
.map_err(|_| DestinationResolveError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn send_before_deadline(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
message: TransportMessage,
|
||||
deadline: Instant,
|
||||
) -> Result<(), DestinationResolveError> {
|
||||
timeout_at(deadline, transport_tx.send(message))
|
||||
.await
|
||||
.map_err(|_| DestinationResolveError::Timeout)?
|
||||
.map_err(|_| DestinationResolveError::TransportUnavailable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn recalled(destination_hash: [u8; 16], public_key: [u8; 64]) -> RecalledDestinationRpcEntry {
|
||||
RecalledDestinationRpcEntry {
|
||||
dest_hash: destination_hash,
|
||||
public_key,
|
||||
app_data: None,
|
||||
ratchet: None,
|
||||
hops: 2,
|
||||
timestamp: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cache_hit_returns_without_network_discovery() {
|
||||
let destination_hash = [0x11; 16];
|
||||
let public_key = [0x22; 64];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
let responder = tokio::spawn(async move {
|
||||
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
|
||||
else {
|
||||
panic!("expected destination recall");
|
||||
};
|
||||
assert!(
|
||||
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
|
||||
);
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
|
||||
destination_hash,
|
||||
public_key,
|
||||
))))
|
||||
.unwrap();
|
||||
assert!(transport_rx.try_recv().is_err());
|
||||
});
|
||||
|
||||
let resolved = resolve_destination_on_transport(
|
||||
&transport_tx,
|
||||
destination_hash,
|
||||
DestinationResolveOptions::new(Duration::from_secs(1)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resolved.public_key, public_key);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_identity_requests_path_without_announce_registration() {
|
||||
let destination_hash = [0x33; 16];
|
||||
let public_key = [0x44; 64];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(8);
|
||||
let responder = tokio::spawn(async move {
|
||||
let mut recalls = 0;
|
||||
while let Some(message) = transport_rx.recv().await {
|
||||
match message {
|
||||
TransportMessage::Rpc { query, response_tx } => {
|
||||
assert!(
|
||||
matches!(query, TransportQuery::RecallDestination { dest } if dest == destination_hash)
|
||||
);
|
||||
recalls += 1;
|
||||
let result = if recalls >= 2 {
|
||||
Some(recalled(destination_hash, public_key))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(result))
|
||||
.unwrap();
|
||||
if recalls >= 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
TransportMessage::RequestPath {
|
||||
destination_hash: dest,
|
||||
} => {
|
||||
assert_eq!(dest, destination_hash);
|
||||
}
|
||||
other => panic!("unexpected finite discovery message: {other:?}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let resolved = resolve_destination_on_transport(
|
||||
&transport_tx,
|
||||
destination_hash,
|
||||
DestinationResolveOptions::new(Duration::from_secs(1)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resolved.public_key, public_key);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cached_identity_can_refresh_path_without_waiting_for_announce() {
|
||||
let destination_hash = [0x45; 16];
|
||||
let public_key = [0x46; 64];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
let responder = tokio::spawn(async move {
|
||||
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
|
||||
else {
|
||||
panic!("expected destination recall");
|
||||
};
|
||||
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
|
||||
destination_hash,
|
||||
public_key,
|
||||
))))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await.unwrap(),
|
||||
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
|
||||
));
|
||||
});
|
||||
|
||||
let resolved = resolve_destination_on_transport(
|
||||
&transport_tx,
|
||||
destination_hash,
|
||||
DestinationResolveOptions {
|
||||
timeout: Duration::from_secs(1),
|
||||
drop_existing_path: false,
|
||||
refresh_cached_path: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resolved.public_key, public_key);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn telephony_policy_drops_stale_path_before_request() {
|
||||
let destination_hash = [0x55; 16];
|
||||
let public_key = [0x66; 64];
|
||||
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.unwrap()
|
||||
else {
|
||||
panic!("expected initial recall");
|
||||
};
|
||||
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(None))
|
||||
.unwrap();
|
||||
|
||||
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
|
||||
else {
|
||||
panic!("expected path drop");
|
||||
};
|
||||
assert!(matches!(query, TransportQuery::DropPath { dest } if dest == destination_hash));
|
||||
response_tx.send(TransportQueryResponse::Ok).unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await.unwrap(),
|
||||
TransportMessage::RequestPath { destination_hash: dest } if dest == destination_hash
|
||||
));
|
||||
let TransportMessage::Rpc { query, response_tx } = transport_rx.recv().await.unwrap()
|
||||
else {
|
||||
panic!("expected recall after path request");
|
||||
};
|
||||
assert!(matches!(query, TransportQuery::RecallDestination { .. }));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(Some(recalled(
|
||||
destination_hash,
|
||||
public_key,
|
||||
))))
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let resolved = resolve_destination_on_transport(
|
||||
&transport_tx,
|
||||
destination_hash,
|
||||
DestinationResolveOptions {
|
||||
timeout: Duration::from_secs(1),
|
||||
drop_existing_path: true,
|
||||
refresh_cached_path: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resolved.public_key, public_key);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn one_deadline_bounds_blocked_command_admission() {
|
||||
let destination_hash = [0x77; 16];
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(1);
|
||||
transport_tx
|
||||
.send(TransportMessage::RequestPath { destination_hash })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = resolve_destination_on_transport(
|
||||
&transport_tx,
|
||||
destination_hash,
|
||||
DestinationResolveOptions::new(Duration::from_millis(5)),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error, DestinationResolveError::Timeout);
|
||||
}
|
||||
}
|
||||
@@ -430,13 +430,13 @@ pub fn synthesize_interface(
|
||||
|
||||
// IFAC sizes outside 1..=64 would panic deep in the transport actor on
|
||||
// first egress (`ifac_sign` asserts); reject at config parse instead.
|
||||
if let Some(size) = section.get_uint("ifac_size") {
|
||||
if !(1..=64).contains(&size) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.ifac_size"),
|
||||
message: format!("{size} is out of range (1-64 bytes)"),
|
||||
});
|
||||
}
|
||||
if let Some(size) = section.get_uint("ifac_size")
|
||||
&& !(1..=64).contains(&size)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.ifac_size"),
|
||||
message: format!("{size} is out of range (1-64 bytes)"),
|
||||
});
|
||||
}
|
||||
|
||||
let iface_type = section.get("type").ok_or_else(|| {
|
||||
@@ -1102,21 +1102,21 @@ fn parse_rnode_airtime(
|
||||
.get_float("airtime_limit_long")
|
||||
.or_else(|| section.get_float("lt_alock"))
|
||||
.map(|v| v as f32);
|
||||
if let Some(v) = st_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_short"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = st_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_short"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = lt_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_long"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = lt_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{name}.airtime_limit_long"),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
Ok((flow_control, st_alock, lt_alock))
|
||||
}
|
||||
@@ -1382,21 +1382,21 @@ fn validate_rnode_multi_subinterface(
|
||||
message: format!("{} is outside 5..=8", sub.coding_rate),
|
||||
});
|
||||
}
|
||||
if let Some(v) = sub.st_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.airtime_limit_short", sub.name),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = sub.st_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.airtime_limit_short", sub.name),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = sub.lt_alock {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.airtime_limit_long", sub.name),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if let Some(v) = sub.lt_alock
|
||||
&& !(0.0..=100.0).contains(&v)
|
||||
{
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
field: format!("{}.airtime_limit_long", sub.name),
|
||||
message: format!("{v} is outside 0..=100 percent"),
|
||||
});
|
||||
}
|
||||
if sub.frequency == 0 {
|
||||
return Err(InterfaceFactoryError::InvalidValue {
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
pub mod buffer_stream;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod destination_resolver;
|
||||
pub mod destination_runtime;
|
||||
pub mod interface_factory;
|
||||
mod interface_registry;
|
||||
pub mod jobs;
|
||||
pub mod lifecycle;
|
||||
pub mod link_client;
|
||||
mod link_endpoint;
|
||||
pub mod link_manager;
|
||||
pub mod link_session;
|
||||
pub mod platform;
|
||||
@@ -22,11 +24,15 @@ pub mod rncp;
|
||||
pub mod rnsh;
|
||||
pub mod rpc;
|
||||
pub mod rpc_server;
|
||||
pub mod shared_instance;
|
||||
|
||||
/// Common application-facing types for Reticulum programs.
|
||||
///
|
||||
/// This is additive convenience; module-qualified paths remain supported.
|
||||
pub mod prelude {
|
||||
pub use crate::destination_resolver::{
|
||||
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
|
||||
};
|
||||
pub use crate::destination_runtime::{
|
||||
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
|
||||
DestinationRuntimeError, DestinationRuntimeOptions, IdentityGatePolicy,
|
||||
@@ -61,4 +67,7 @@ pub mod prelude {
|
||||
RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
|
||||
};
|
||||
pub use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
pub use rns_transport::path_recovery::{
|
||||
PathRecoveryError, PathRecoveryHandle, PathRecoveryOutcome,
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PublicKey;
|
||||
@@ -18,7 +18,11 @@ use rns_protocol::resource::{InboundTransfer, TransferAction};
|
||||
use rns_protocol::resource_adv::ResourceAdvertisement;
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{
|
||||
AnnounceHandlerEvent, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole, OutboundRequest, TransportMessage,
|
||||
};
|
||||
|
||||
use crate::destination_resolver::{
|
||||
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -47,6 +51,12 @@ pub struct LinkClient {
|
||||
identity: Arc<Identity>,
|
||||
}
|
||||
|
||||
struct LinkClientEndpoint<'a> {
|
||||
delivery_rx: &'a mut mpsc::Receiver<DestinationEvent>,
|
||||
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
|
||||
attached_interface: InterfaceId,
|
||||
}
|
||||
|
||||
impl LinkClient {
|
||||
pub fn new(transport_tx: mpsc::Sender<TransportMessage>, identity: Identity) -> Self {
|
||||
Self {
|
||||
@@ -72,36 +82,14 @@ impl LinkClient {
|
||||
let dest_hash =
|
||||
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
|
||||
|
||||
let pubkey =
|
||||
if let Some(public_key) = self.recall_routable_pubkey(dest_hash, deadline).await? {
|
||||
public_key
|
||||
} else {
|
||||
// Register the handler before the path request so the answering
|
||||
// announce (carrying the pubkey) is observed.
|
||||
let (ann_tx, mut ann_rx) = mpsc::channel::<AnnounceHandlerEvent>(64);
|
||||
self.send_msg(TransportMessage::RegisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
receive_path_responses: true,
|
||||
callback_tx: ann_tx,
|
||||
})
|
||||
.await?;
|
||||
|
||||
self.send_msg(TransportMessage::RequestPath {
|
||||
destination_hash: dest_hash,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let public_key = match time_remaining(deadline) {
|
||||
Ok(remaining) => wait_for_pubkey(&mut ann_rx, dest_hash, remaining).await,
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let _ = self
|
||||
.transport_tx
|
||||
.try_send(TransportMessage::DeregisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
});
|
||||
public_key?
|
||||
};
|
||||
let pubkey = resolve_destination_on_transport(
|
||||
&self.transport_tx,
|
||||
dest_hash,
|
||||
DestinationResolveOptions::new(time_remaining(deadline)?),
|
||||
)
|
||||
.await
|
||||
.map_err(map_destination_resolve_error)?
|
||||
.public_key;
|
||||
|
||||
let (mut link, request_data) = Link::new_initiator(dest_hash, hops);
|
||||
let link_id = link.link_id;
|
||||
@@ -115,6 +103,11 @@ impl LinkClient {
|
||||
delivery_tx: Some(dest_tx),
|
||||
})
|
||||
.await?;
|
||||
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
|
||||
self.transport_tx.clone(),
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
);
|
||||
|
||||
let req_pkt = build_link_request_packet(dest_hash, &request_data);
|
||||
self.send_msg(TransportMessage::Outbound(OutboundRequest {
|
||||
@@ -123,25 +116,51 @@ impl LinkClient {
|
||||
}))
|
||||
.await?;
|
||||
|
||||
let proof_data = wait_for_proof(&mut dest_rx, link_id, time_remaining(deadline)?).await?;
|
||||
|
||||
let identity_ed25519_pub: [u8; 32] = pubkey[32..64].try_into().map_err(|_| {
|
||||
LinkClientError::ProofInvalid("remote public key is not 64 bytes".into())
|
||||
})?;
|
||||
let identity_verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
|
||||
.map_err(|e| LinkClientError::ProofInvalid(format!("verify key: {e}")))?;
|
||||
let proof = timeout(
|
||||
time_remaining(deadline)?,
|
||||
crate::link_endpoint::wait_for_valid_proof(
|
||||
&mut dest_rx,
|
||||
&mut link,
|
||||
&identity_verify_key,
|
||||
&identity_ed25519_pub,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("link proof"))?
|
||||
.map_err(|error| match error {
|
||||
crate::link_endpoint::LinkProofWaitError::LinkClosed => {
|
||||
LinkClientError::HandshakeFailed("link closed".into())
|
||||
}
|
||||
crate::link_endpoint::LinkProofWaitError::DeliveryClosed => {
|
||||
LinkClientError::HandshakeFailed("destination channel closed".into())
|
||||
}
|
||||
})?;
|
||||
let attached_interface = proof.interface_id;
|
||||
let rtt_data = proof.rtt_data;
|
||||
|
||||
let rtt_data = link
|
||||
.validate_proof(&proof_data, &identity_verify_key, &identity_ed25519_pub)
|
||||
.map_err(|e| LinkClientError::ProofInvalid(format!("{e:?}")))?;
|
||||
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
|
||||
&self.transport_tx,
|
||||
link_id,
|
||||
attached_interface,
|
||||
LinkEndpointRole::Initiator,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)?;
|
||||
registration.endpoint_bound();
|
||||
let mut endpoint = LinkClientEndpoint {
|
||||
delivery_rx: &mut dest_rx,
|
||||
lifecycle_rx: &mut endpoint_lifecycle_rx,
|
||||
attached_interface,
|
||||
};
|
||||
|
||||
let rtt_pkt =
|
||||
build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
|
||||
self.send_msg(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: rtt_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await?;
|
||||
self.send_link_packet(link_id, rtt_pkt).await?;
|
||||
|
||||
let our_pub = self.identity.get_public_key();
|
||||
let our_priv = self
|
||||
@@ -156,11 +175,7 @@ impl LinkClient {
|
||||
rns_wire::context::PacketContext::LinkIdentify,
|
||||
&identify_data,
|
||||
);
|
||||
self.send_msg(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: identify_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await?;
|
||||
self.send_link_packet(link_id, identify_pkt).await?;
|
||||
|
||||
let req_timeout = Duration::from_secs(5);
|
||||
let (encrypted_req, request_id) = link
|
||||
@@ -176,15 +191,11 @@ impl LinkClient {
|
||||
rns_wire::flags::HeaderType::Header1,
|
||||
);
|
||||
link.update_pending_request_id(&request_id, packet_request_id);
|
||||
self.send_msg(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: request_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await?;
|
||||
self.send_link_packet(link_id, request_pkt).await?;
|
||||
|
||||
let response = wait_for_response(
|
||||
&self.transport_tx,
|
||||
&mut dest_rx,
|
||||
&mut endpoint,
|
||||
&mut link,
|
||||
link_id,
|
||||
packet_request_id,
|
||||
@@ -193,10 +204,12 @@ impl LinkClient {
|
||||
.await;
|
||||
|
||||
// Tear down even on failure so the remote doesn't keep link state.
|
||||
let _ = self.send_close(&mut link).await;
|
||||
let _ = self
|
||||
.transport_tx
|
||||
.try_send(TransportMessage::DeregisterDestination { hash: link_id });
|
||||
let endpoint_closing = self.send_close(&mut link).await.unwrap_or(false);
|
||||
if !endpoint_closing {
|
||||
let _ = registration.cleanup().await;
|
||||
} else {
|
||||
registration.disarm();
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
@@ -208,73 +221,36 @@ impl LinkClient {
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn recall_routable_pubkey(
|
||||
&self,
|
||||
destination_hash: [u8; 16],
|
||||
deadline: Instant,
|
||||
) -> Result<Option<[u8; 64]>, LinkClientError> {
|
||||
let has_path = self
|
||||
.transport_query(
|
||||
TransportQuery::HasPath {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
if !matches!(has_path, TransportQueryResponse::BoolResult(true)) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
match self
|
||||
.transport_query(
|
||||
TransportQuery::RecallDestination {
|
||||
dest: destination_hash,
|
||||
},
|
||||
deadline,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
TransportQueryResponse::RecalledDestination(Some(destination))
|
||||
if destination.dest_hash == destination_hash =>
|
||||
{
|
||||
Ok(Some(destination.public_key))
|
||||
}
|
||||
TransportQueryResponse::RecalledDestination(None) => Ok(None),
|
||||
response => Err(LinkClientError::UnexpectedResponse(format!(
|
||||
"destination recall returned {response:?}"
|
||||
))),
|
||||
}
|
||||
async fn send_link_packet(&self, link_id: [u8; 16], raw: Bytes) -> Result<(), LinkClientError> {
|
||||
crate::link_endpoint::send(
|
||||
&self.transport_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
raw,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn transport_query(
|
||||
&self,
|
||||
query: TransportQuery,
|
||||
deadline: Instant,
|
||||
) -> Result<TransportQueryResponse, LinkClientError> {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.send_msg(TransportMessage::Rpc { query, response_tx })
|
||||
.await?;
|
||||
timeout(time_remaining(deadline)?, response_rx)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("transport query"))?
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn send_close(&self, link: &mut Link) -> Result<(), LinkClientError> {
|
||||
async fn send_close(&self, link: &mut Link) -> Result<bool, LinkClientError> {
|
||||
let link_id = link.link_id;
|
||||
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
};
|
||||
let close_pkt = build_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::LinkClose,
|
||||
&teardown_data,
|
||||
);
|
||||
self.send_msg(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: close_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
crate::link_endpoint::send_and_unbind(
|
||||
&self.transport_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
close_pkt,
|
||||
)
|
||||
.await
|
||||
.map(|()| true)
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,63 +263,19 @@ fn time_remaining(deadline: Instant) -> Result<Duration, LinkClientError> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_pubkey(
|
||||
rx: &mut mpsc::Receiver<AnnounceHandlerEvent>,
|
||||
target_dest_hash: [u8; 16],
|
||||
deadline: Duration,
|
||||
) -> Result<[u8; 64], LinkClientError> {
|
||||
let fut = async {
|
||||
while let Some(ev) = rx.recv().await {
|
||||
if ev.destination_hash == target_dest_hash {
|
||||
if let Some(pk) = ev.public_key {
|
||||
return Ok(pk);
|
||||
}
|
||||
}
|
||||
fn map_destination_resolve_error(error: DestinationResolveError) -> LinkClientError {
|
||||
match error {
|
||||
DestinationResolveError::Timeout => LinkClientError::Timeout("destination resolution"),
|
||||
DestinationResolveError::TransportUnavailable => LinkClientError::TransportUnavailable,
|
||||
DestinationResolveError::UnexpectedResponse(operation) => {
|
||||
LinkClientError::UnexpectedResponse(operation.to_string())
|
||||
}
|
||||
Err(LinkClientError::PubkeyNotDiscovered)
|
||||
};
|
||||
timeout(deadline, fut)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("path/announce discovery"))?
|
||||
}
|
||||
|
||||
async fn wait_for_proof(
|
||||
rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
link_id: [u8; 16],
|
||||
deadline: Duration,
|
||||
) -> Result<Vec<u8>, LinkClientError> {
|
||||
let fut = async {
|
||||
while let Some(ev) = rx.recv().await {
|
||||
match ev {
|
||||
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
|
||||
return Err(LinkClientError::HandshakeFailed("link closed".into()));
|
||||
}
|
||||
DestinationEvent::InboundPacket { raw, .. } => {
|
||||
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok(h) => h,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let is_proof = header.flags.packet_type == rns_wire::flags::PacketType::Proof
|
||||
&& header.destination_hash == link_id;
|
||||
if is_proof && raw.len() > data_offset {
|
||||
return Ok(raw[data_offset..].to_vec());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(LinkClientError::HandshakeFailed(
|
||||
"destination channel closed".into(),
|
||||
))
|
||||
};
|
||||
timeout(deadline, fut)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("link proof"))?
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_response(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut LinkClientEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
link_id: [u8; 16],
|
||||
request_id: [u8; 16],
|
||||
@@ -352,12 +284,27 @@ async fn wait_for_response(
|
||||
let fut = async {
|
||||
let mut inbound_resources: HashMap<[u8; 32], InboundTransfer> = HashMap::new();
|
||||
|
||||
while let Some(ev) = rx.recv().await {
|
||||
loop {
|
||||
let ev = tokio::select! {
|
||||
event = endpoint.delivery_rx.recv() => event.ok_or_else(|| LinkClientError::HandshakeFailed(
|
||||
"destination channel closed".into(),
|
||||
))?,
|
||||
terminal = endpoint.lifecycle_rx.recv() => {
|
||||
return Err(LinkClientError::HandshakeFailed(format!(
|
||||
"link endpoint terminated: {terminal:?}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
match ev {
|
||||
DestinationEvent::LinkClosed { link_id: closed_id } if closed_id == link_id => {
|
||||
return Err(LinkClientError::HandshakeFailed("link closed".into()));
|
||||
}
|
||||
DestinationEvent::InboundPacket { raw, .. } => {
|
||||
DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} => {
|
||||
if interface_id != endpoint.attached_interface {
|
||||
continue;
|
||||
}
|
||||
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok(h) => h,
|
||||
Err(_) => continue,
|
||||
@@ -428,7 +375,8 @@ async fn wait_for_response(
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&req,
|
||||
true,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
inbound_resources.insert(adv.resource_hash, transfer);
|
||||
@@ -479,7 +427,8 @@ async fn wait_for_response(
|
||||
context,
|
||||
&payload,
|
||||
true,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
if let Some(rh) = completed_rh {
|
||||
@@ -509,7 +458,7 @@ async fn wait_for_response(
|
||||
})?
|
||||
};
|
||||
|
||||
send_link_proof(transport_tx, link_id, &proof)?;
|
||||
send_link_proof(transport_tx, link_id, &proof).await?;
|
||||
inbound_resources.remove(&rh);
|
||||
match link.handle_response_plaintext(&assembled) {
|
||||
Ok((id, response_data)) => {
|
||||
@@ -551,7 +500,8 @@ async fn wait_for_response(
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&req,
|
||||
true,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
// Empty/invalid HMU cancels the transfer (RESOURCE_RCL, 1.3.9).
|
||||
TransferAction::SendCancel(cancel_type, resource_hash) => {
|
||||
@@ -570,7 +520,8 @@ async fn wait_for_response(
|
||||
context,
|
||||
&resource_hash,
|
||||
true,
|
||||
)?;
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -588,18 +539,15 @@ async fn wait_for_response(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(LinkClientError::HandshakeFailed(
|
||||
"destination channel closed".into(),
|
||||
))
|
||||
};
|
||||
timeout(deadline, fut)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::Timeout("response"))?
|
||||
}
|
||||
|
||||
fn send_link_data(
|
||||
async fn send_link_data(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link: &Link,
|
||||
link: &mut Link,
|
||||
link_id: [u8; 16],
|
||||
context: rns_wire::context::PacketContext,
|
||||
body: &[u8],
|
||||
@@ -612,15 +560,12 @@ fn send_link_data(
|
||||
body.to_vec()
|
||||
};
|
||||
let packet = build_data_packet(link_id, context, &payload);
|
||||
transport_tx
|
||||
.try_send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: packet,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, packet)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
fn send_link_proof(
|
||||
async fn send_link_proof(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
proof: &[u8],
|
||||
@@ -630,11 +575,8 @@ fn send_link_proof(
|
||||
rns_wire::context::PacketContext::ResourcePrf,
|
||||
proof,
|
||||
);
|
||||
transport_tx
|
||||
.try_send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: packet,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, packet)
|
||||
.await
|
||||
.map_err(|_| LinkClientError::TransportUnavailable)
|
||||
}
|
||||
|
||||
@@ -736,62 +678,6 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validated_cached_identity_and_live_path_skip_network_discovery() {
|
||||
let destination_hash = [0xD4; 16];
|
||||
let remote_identity = Identity::new();
|
||||
let public_key = remote_identity.get_public_key();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected path query");
|
||||
};
|
||||
assert!(matches!(
|
||||
query,
|
||||
TransportQuery::HasPath { dest } if dest == destination_hash
|
||||
));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::BoolResult(true))
|
||||
.unwrap();
|
||||
|
||||
let Some(TransportMessage::Rpc { query, response_tx }) = transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected destination recall");
|
||||
};
|
||||
assert!(matches!(
|
||||
query,
|
||||
TransportQuery::RecallDestination { dest } if dest == destination_hash
|
||||
));
|
||||
response_tx
|
||||
.send(TransportQueryResponse::RecalledDestination(Some(
|
||||
rns_transport::messages::RecalledDestinationRpcEntry {
|
||||
dest_hash: destination_hash,
|
||||
public_key,
|
||||
app_data: None,
|
||||
ratchet: None,
|
||||
hops: 1,
|
||||
timestamp: 1.0,
|
||||
},
|
||||
)))
|
||||
.unwrap();
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"cache hit must not emit a path request"
|
||||
);
|
||||
});
|
||||
|
||||
let client = LinkClient::new(transport_tx, Identity::new());
|
||||
assert_eq!(
|
||||
client
|
||||
.recall_routable_pubkey(destination_hash, Instant::now() + Duration::from_secs(1),)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(public_key)
|
||||
);
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_close_uses_authenticated_teardown_payload() {
|
||||
let dest_hash = [0xCC; 16];
|
||||
@@ -807,13 +693,22 @@ mod tests {
|
||||
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
let client = LinkClient::new(transport_tx, Identity::new());
|
||||
client.send_close(&mut initiator).await.unwrap();
|
||||
let close = tokio::spawn(async move { client.send_close(&mut initiator).await });
|
||||
|
||||
let TransportMessage::Outbound(request) = transport_rx.try_recv().unwrap() else {
|
||||
let TransportMessage::SendLinkEndpointAndUnbind {
|
||||
role,
|
||||
request,
|
||||
result_tx,
|
||||
..
|
||||
} = transport_rx.recv().await.unwrap()
|
||||
else {
|
||||
panic!("expected outbound close packet");
|
||||
};
|
||||
assert_eq!(role, LinkEndpointRole::Initiator);
|
||||
let (header, offset) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose);
|
||||
assert!(responder.receive_teardown(&request.raw[offset..]));
|
||||
let _ = result_tx.send(rns_transport::messages::LinkEndpointSendResult::Sent);
|
||||
assert!(close.await.unwrap().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PublicKey;
|
||||
use rns_link::link::Link;
|
||||
use rns_transport::link_messages::{DestinationEvent, PacketMetrics};
|
||||
use rns_transport::messages::{
|
||||
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
|
||||
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
|
||||
TransportMessage,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum LinkEndpointError {
|
||||
#[error("transport channel is unavailable")]
|
||||
TransportUnavailable,
|
||||
#[error("Link endpoint could not be bound: {0:?}")]
|
||||
Bind(LinkEndpointBindResult),
|
||||
#[error("Link endpoint rejected outbound packet: {0:?}")]
|
||||
Send(LinkEndpointSendResult),
|
||||
#[error("Link endpoint cleanup was rejected: {0:?}")]
|
||||
Unbind(LinkEndpointUnbindResult),
|
||||
}
|
||||
|
||||
/// Owns cleanup for a temporary initiator Link destination until ownership is
|
||||
/// transferred to a long-lived actor or an atomic final send succeeds.
|
||||
///
|
||||
/// Cancellation cannot use `try_send`: a full transport ingress queue is a
|
||||
/// normal transient condition. Drop therefore transfers cleanup to a retained
|
||||
/// task which waits for admission, verifies typed endpoint ownership, and only
|
||||
/// then deregisters the temporary destination.
|
||||
pub(crate) struct LinkEndpointCleanupGuard {
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
endpoint_bound: bool,
|
||||
armed: bool,
|
||||
}
|
||||
|
||||
impl LinkEndpointCleanupGuard {
|
||||
pub(crate) fn new(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
) -> Self {
|
||||
Self {
|
||||
transport_tx,
|
||||
link_id,
|
||||
role,
|
||||
endpoint_bound: false,
|
||||
armed: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn endpoint_bound(&mut self) {
|
||||
self.endpoint_bound = true;
|
||||
}
|
||||
|
||||
pub(crate) fn disarm(&mut self) {
|
||||
self.armed = false;
|
||||
}
|
||||
|
||||
pub(crate) async fn cleanup(&mut self) -> Result<(), LinkEndpointError> {
|
||||
cleanup_registered_link(
|
||||
&self.transport_tx,
|
||||
self.link_id,
|
||||
self.role,
|
||||
self.endpoint_bound,
|
||||
)
|
||||
.await?;
|
||||
self.endpoint_bound = false;
|
||||
self.armed = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LinkEndpointCleanupGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.armed {
|
||||
return;
|
||||
}
|
||||
let transport_tx = self.transport_tx.clone();
|
||||
let link_id = self.link_id;
|
||||
let role = self.role;
|
||||
let endpoint_bound = self.endpoint_bound;
|
||||
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
|
||||
tracing::error!(
|
||||
link_id = %hex::encode(link_id),
|
||||
role = ?role,
|
||||
"cannot retain Link endpoint cleanup without a Tokio runtime"
|
||||
);
|
||||
return;
|
||||
};
|
||||
runtime.spawn(async move {
|
||||
if let Err(error) =
|
||||
cleanup_registered_link(&transport_tx, link_id, role, endpoint_bound).await
|
||||
{
|
||||
tracing::error!(
|
||||
link_id = %hex::encode(link_id),
|
||||
role = ?role,
|
||||
error = %error,
|
||||
"retained Link endpoint cleanup failed"
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PendingLinkEndpointSend {
|
||||
pub(crate) link_id: [u8; 16],
|
||||
pub(crate) role: LinkEndpointRole,
|
||||
pub(crate) final_unbind: bool,
|
||||
/// Ordinary packet proof clock to arm only after endpoint acceptance.
|
||||
pub(crate) packet_proof_hash: Option<[u8; 32]>,
|
||||
pub(crate) result_rx: oneshot::Receiver<LinkEndpointSendResult>,
|
||||
}
|
||||
|
||||
struct AtomicFinalSendGuard {
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
result_rx: Option<oneshot::Receiver<LinkEndpointSendResult>>,
|
||||
}
|
||||
|
||||
impl AtomicFinalSendGuard {
|
||||
async fn result(&mut self) -> Result<LinkEndpointSendResult, LinkEndpointError> {
|
||||
let result = self
|
||||
.result_rx
|
||||
.as_mut()
|
||||
.expect("atomic final-send result receiver")
|
||||
.await;
|
||||
self.result_rx = None;
|
||||
result.map_err(|_| LinkEndpointError::TransportUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AtomicFinalSendGuard {
|
||||
fn drop(&mut self) {
|
||||
let Some(result_rx) = self.result_rx.take() else {
|
||||
return;
|
||||
};
|
||||
let transport_tx = self.transport_tx.clone();
|
||||
let link_id = self.link_id;
|
||||
let role = self.role;
|
||||
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
|
||||
tracing::error!(
|
||||
link_id = %hex::encode(link_id),
|
||||
role = ?role,
|
||||
"cannot retain atomic Link close result without a Tokio runtime"
|
||||
);
|
||||
return;
|
||||
};
|
||||
runtime.spawn(async move {
|
||||
match result_rx.await {
|
||||
Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => {}
|
||||
Ok(_) | Err(_) => {
|
||||
let _ = cleanup_registered_link(&transport_tx, link_id, role, true).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum LinkProofWaitError {
|
||||
LinkClosed,
|
||||
DeliveryClosed,
|
||||
}
|
||||
|
||||
pub(crate) struct ValidatedLinkProof {
|
||||
pub(crate) rtt_data: Vec<u8>,
|
||||
pub(crate) interface_id: InterfaceId,
|
||||
pub(crate) metrics: PacketMetrics,
|
||||
}
|
||||
|
||||
/// Wait for the first cryptographically valid LRPROOF while the Link remains
|
||||
/// pending. Invalid candidates are unauthenticated input and cannot terminate
|
||||
/// establishment or select the endpoint interface.
|
||||
pub(crate) async fn wait_for_valid_proof(
|
||||
delivery_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
link: &mut Link,
|
||||
identity_verify_key: &Ed25519PublicKey,
|
||||
identity_ed25519_pub_bytes: &[u8; 32],
|
||||
) -> Result<ValidatedLinkProof, LinkProofWaitError> {
|
||||
let link_id = link.link_id;
|
||||
while let Some(event) = delivery_rx.recv().await {
|
||||
match event {
|
||||
DestinationEvent::LinkClosed { link_id: closed } if closed == link_id => {
|
||||
return Err(LinkProofWaitError::LinkClosed);
|
||||
}
|
||||
DestinationEvent::InboundPacket {
|
||||
raw,
|
||||
interface_id,
|
||||
metrics,
|
||||
} => {
|
||||
let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else {
|
||||
continue;
|
||||
};
|
||||
if header.destination_hash != link_id
|
||||
|| header.flags.packet_type != rns_wire::flags::PacketType::Proof
|
||||
|| raw.len() <= data_offset
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match link.validate_proof(
|
||||
&raw[data_offset..],
|
||||
identity_verify_key,
|
||||
identity_ed25519_pub_bytes,
|
||||
) {
|
||||
Ok(rtt_data) => {
|
||||
return Ok(ValidatedLinkProof {
|
||||
rtt_data,
|
||||
interface_id,
|
||||
metrics,
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
link_id = %hex::encode(link_id),
|
||||
interface_id,
|
||||
error = ?error,
|
||||
"ignoring unauthenticated LRPROOF candidate"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(LinkProofWaitError::DeliveryClosed)
|
||||
}
|
||||
|
||||
pub(crate) async fn bind(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
interface_id: InterfaceId,
|
||||
role: LinkEndpointRole,
|
||||
) -> Result<mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>, LinkEndpointError> {
|
||||
let (lifecycle_tx, lifecycle_rx) = mpsc::unbounded_channel();
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::BindLinkEndpoint {
|
||||
binding: LinkEndpointBinding {
|
||||
link_id,
|
||||
interface_id,
|
||||
role,
|
||||
},
|
||||
lifecycle_tx,
|
||||
result_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
|
||||
match result_rx
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?
|
||||
{
|
||||
// A successful fresh bind transfers this lifecycle sender into the
|
||||
// transport actor. `AlreadyBound` retains the original sender, so the
|
||||
// newly-created receiver would never observe terminal events and must
|
||||
// fail closed instead of pretending to own the endpoint.
|
||||
LinkEndpointBindResult::Bound => Ok(lifecycle_rx),
|
||||
result => Err(LinkEndpointError::Bind(result)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn send_best_effort(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
raw: Bytes,
|
||||
) -> Result<LinkEndpointSendResult, LinkEndpointError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::SendLinkEndpointBestEffort {
|
||||
link_id,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)
|
||||
}
|
||||
|
||||
pub(crate) async fn send_and_unbind(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
raw: Bytes,
|
||||
) -> Result<(), LinkEndpointError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::SendLinkEndpointAndUnbind {
|
||||
link_id,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
|
||||
// Once admitted, retain ownership of the typed result across caller
|
||||
// cancellation. A successful atomic operation owns the final FIFO drain;
|
||||
// a rejected one falls back to ordered explicit cleanup.
|
||||
let mut final_send = AtomicFinalSendGuard {
|
||||
transport_tx: transport_tx.clone(),
|
||||
link_id,
|
||||
role,
|
||||
result_rx: Some(result_rx),
|
||||
};
|
||||
match final_send.result().await? {
|
||||
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. } => Ok(()),
|
||||
result => Err(LinkEndpointError::Send(result)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn send(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
raw: Bytes,
|
||||
) -> Result<(), LinkEndpointError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::SendLinkEndpoint {
|
||||
link_id,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
|
||||
match result_rx
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?
|
||||
{
|
||||
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. } => Ok(()),
|
||||
result => Err(LinkEndpointError::Send(result)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn unbind(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
) -> Result<LinkEndpointUnbindResult, LinkEndpointError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::UnbindLinkEndpoint {
|
||||
link_id,
|
||||
role,
|
||||
result_tx,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)
|
||||
}
|
||||
|
||||
async fn cleanup_registered_link(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
endpoint_bound: bool,
|
||||
) -> Result<(), LinkEndpointError> {
|
||||
if endpoint_bound {
|
||||
match unbind(transport_tx, link_id, role).await? {
|
||||
LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound => {}
|
||||
result @ LinkEndpointUnbindResult::RoleMismatch => {
|
||||
return Err(LinkEndpointError::Unbind(result));
|
||||
}
|
||||
}
|
||||
}
|
||||
transport_tx
|
||||
.send(TransportMessage::DeregisterDestination { hash: link_id })
|
||||
.await
|
||||
.map_err(|_| LinkEndpointError::TransportUnavailable)
|
||||
}
|
||||
|
||||
pub(crate) fn send_message(
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
raw: Bytes,
|
||||
) -> (TransportMessage, PendingLinkEndpointSend) {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
(
|
||||
TransportMessage::SendLinkEndpoint {
|
||||
link_id,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx,
|
||||
},
|
||||
PendingLinkEndpointSend {
|
||||
link_id,
|
||||
role,
|
||||
final_unbind: false,
|
||||
packet_proof_hash: None,
|
||||
result_rx,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn send_and_unbind_message(
|
||||
link_id: [u8; 16],
|
||||
role: LinkEndpointRole,
|
||||
raw: Bytes,
|
||||
) -> (TransportMessage, PendingLinkEndpointSend) {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
(
|
||||
TransportMessage::SendLinkEndpointAndUnbind {
|
||||
link_id,
|
||||
role,
|
||||
request: OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
},
|
||||
result_tx,
|
||||
},
|
||||
PendingLinkEndpointSend {
|
||||
link_id,
|
||||
role,
|
||||
final_unbind: true,
|
||||
packet_proof_hash: None,
|
||||
result_rx,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PrivateKey;
|
||||
use rns_link::link::{Link, LinkState};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn proof_packet(link_id: [u8; 16], proof: &[u8]) -> Bytes {
|
||||
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::Proof,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash: link_id,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(proof);
|
||||
raw.into()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_proof_does_not_win_interface_race_before_valid_proof() {
|
||||
let destination_hash = [0xA4; 16];
|
||||
let signing_key = Ed25519PrivateKey::generate();
|
||||
let verify_key = signing_key.public_key();
|
||||
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
|
||||
let (_responder, proof) =
|
||||
Link::new_responder(&request_data, &signing_key, destination_hash, 1).unwrap();
|
||||
let mut invalid = proof.clone();
|
||||
invalid[0] ^= 0x80;
|
||||
let link_id = initiator.link_id;
|
||||
let (event_tx, mut event_rx) = mpsc::channel(2);
|
||||
event_tx
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: proof_packet(link_id, &invalid),
|
||||
interface_id: 41,
|
||||
metrics: PacketMetrics {
|
||||
rssi: Some(-10.0),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
event_tx
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: proof_packet(link_id, &proof),
|
||||
interface_id: 42,
|
||||
metrics: PacketMetrics {
|
||||
rssi: Some(-80.0),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let validated = wait_for_valid_proof(
|
||||
&mut event_rx,
|
||||
&mut initiator,
|
||||
&verify_key,
|
||||
&verify_key.to_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(validated.interface_id, 42);
|
||||
assert_eq!(validated.metrics.rssi, Some(-80.0));
|
||||
assert!(matches!(
|
||||
initiator.state,
|
||||
LinkState::Handshake | LinkState::Active
|
||||
));
|
||||
assert!(initiator.session_keys().is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_proof_only_waits_for_original_timeout() {
|
||||
let destination_hash = [0xA5; 16];
|
||||
let signing_key = Ed25519PrivateKey::generate();
|
||||
let verify_key = signing_key.public_key();
|
||||
let (mut initiator, request_data) = Link::new_initiator(destination_hash, 1);
|
||||
let (_responder, mut proof) =
|
||||
Link::new_responder(&request_data, &signing_key, destination_hash, 1).unwrap();
|
||||
proof[0] ^= 0x80;
|
||||
let link_id = initiator.link_id;
|
||||
let (event_tx, mut event_rx) = mpsc::channel(1);
|
||||
event_tx
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: proof_packet(link_id, &proof),
|
||||
interface_id: 99,
|
||||
metrics: PacketMetrics::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(20),
|
||||
wait_for_valid_proof(
|
||||
&mut event_rx,
|
||||
&mut initiator,
|
||||
&verify_key,
|
||||
&verify_key.to_bytes(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(initiator.state, LinkState::Pending);
|
||||
drop(event_tx);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropped_cleanup_guard_survives_transport_ingress_backpressure() {
|
||||
let link_id = [0xC1; 16];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(1);
|
||||
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
|
||||
let mut guard =
|
||||
LinkEndpointCleanupGuard::new(transport_tx, link_id, LinkEndpointRole::Initiator);
|
||||
guard.endpoint_bound();
|
||||
drop(guard);
|
||||
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::Shutdown)
|
||||
));
|
||||
let Some(TransportMessage::UnbindLinkEndpoint {
|
||||
link_id: unbound,
|
||||
role,
|
||||
result_tx,
|
||||
}) = transport_rx.recv().await
|
||||
else {
|
||||
panic!("retained cleanup must enqueue typed unbind after capacity returns");
|
||||
};
|
||||
assert_eq!(unbound, link_id);
|
||||
assert_eq!(role, LinkEndpointRole::Initiator);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), transport_rx.recv())
|
||||
.await
|
||||
.is_err(),
|
||||
"destination deregistration must wait for the typed unbind result"
|
||||
);
|
||||
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::DeregisterDestination { hash }) if hash == link_id
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn role_mismatch_never_deregisters_another_endpoint_owner() {
|
||||
let link_id = [0xC2; 16];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(2);
|
||||
let cleanup = tokio::spawn(async move {
|
||||
cleanup_registered_link(&transport_tx, link_id, LinkEndpointRole::Initiator, true).await
|
||||
});
|
||||
let Some(TransportMessage::UnbindLinkEndpoint { result_tx, .. }) =
|
||||
transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected typed unbind");
|
||||
};
|
||||
let _ = result_tx.send(LinkEndpointUnbindResult::RoleMismatch);
|
||||
assert!(matches!(
|
||||
cleanup.await.unwrap(),
|
||||
Err(LinkEndpointError::Unbind(
|
||||
LinkEndpointUnbindResult::RoleMismatch
|
||||
))
|
||||
));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"role mismatch must not deregister the foreign Link destination"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_atomic_close_retains_queued_fifo_ownership() {
|
||||
let link_id = [0xC3; 16];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(2);
|
||||
let call_tx = transport_tx.clone();
|
||||
let close = tokio::spawn(async move {
|
||||
send_and_unbind(
|
||||
&call_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
proof_packet(link_id, b"final"),
|
||||
)
|
||||
.await
|
||||
});
|
||||
let Some(TransportMessage::SendLinkEndpointAndUnbind { result_tx, .. }) =
|
||||
transport_rx.recv().await
|
||||
else {
|
||||
panic!("expected atomic final send");
|
||||
};
|
||||
close.abort();
|
||||
let _ = close.await;
|
||||
let _ = result_tx.send(LinkEndpointSendResult::Queued { depth: 1 });
|
||||
tokio::task::yield_now().await;
|
||||
tokio::task::yield_now().await;
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"accepted atomic close owns FIFO drain; cancellation must not preempt it"
|
||||
);
|
||||
drop(transport_tx);
|
||||
}
|
||||
}
|
||||
+3322
-491
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -228,10 +228,10 @@ impl DeliveryProofWaiter {
|
||||
Ok(None) => return None,
|
||||
Err(_) => return None,
|
||||
};
|
||||
if let DestinationEvent::DeliveryProof { msg_id, rtt } = ev {
|
||||
if msg_id == self.msg_id {
|
||||
return Some(rtt);
|
||||
}
|
||||
if let DestinationEvent::DeliveryProof { msg_id, rtt } = ev
|
||||
&& msg_id == self.msg_id
|
||||
{
|
||||
return Some(rtt);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -458,12 +458,11 @@ async fn collect_path_meta(tx: &mpsc::Sender<TransportMessage>, dest: [u8; 16])
|
||||
let mut meta = PathMeta::default();
|
||||
if let Ok(TransportQueryResponse::PathTable(entries)) =
|
||||
query(tx, TransportQuery::GetPathTable).await
|
||||
&& let Some(entry) = entries.into_iter().find(|e| e.hash == dest)
|
||||
{
|
||||
if let Some(entry) = entries.into_iter().find(|e| e.hash == dest) {
|
||||
meta.hops = entry.hops;
|
||||
meta.via = entry.via;
|
||||
meta.interface = Some(entry.interface);
|
||||
}
|
||||
meta.hops = entry.hops;
|
||||
meta.via = entry.via;
|
||||
meta.interface = Some(entry.interface);
|
||||
}
|
||||
meta
|
||||
}
|
||||
|
||||
+1301
-172
File diff suppressed because it is too large.
Load diff
+218
-188
@@ -20,7 +20,8 @@ use rns_protocol::resource::{
|
||||
};
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{
|
||||
AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
AnnounceRpcEntry, InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole, OutboundRequest,
|
||||
TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
@@ -40,6 +41,16 @@ pub const DEFAULT_RNCP_APP_NAME: &str = "rncp.receive";
|
||||
/// `FAILED` on a loaded peer.
|
||||
const RNCP_POST_PROOF_SETTLE: Duration = Duration::from_millis(250);
|
||||
|
||||
async fn send_endpoint_packet(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
raw: Bytes,
|
||||
) -> Result<(), RncpError> {
|
||||
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, raw)
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)
|
||||
}
|
||||
|
||||
pub fn default_rncp_app_name() -> &'static str {
|
||||
DEFAULT_RNCP_APP_NAME
|
||||
}
|
||||
@@ -236,7 +247,6 @@ pub async fn spawn_rncp_listener(
|
||||
})
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
|
||||
let mut link_mgr = LinkManager::with_destination(
|
||||
transport_tx.clone(),
|
||||
dest_rx,
|
||||
@@ -521,6 +531,11 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
|
||||
transport_tx.clone(),
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
);
|
||||
|
||||
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
|
||||
transport_tx
|
||||
@@ -531,37 +546,21 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
|
||||
let proof_body = match timeout(remaining(deadline), wait_for_proof(&mut lpkt_rx, link_id)).await
|
||||
{
|
||||
Ok(Ok(body)) => body,
|
||||
Ok(Err(e)) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(RncpError::Timeout("link proof"));
|
||||
}
|
||||
};
|
||||
let (rtt_data, attached_interface) =
|
||||
wait_for_valid_rncp_proof(&mut lpkt_rx, &mut link, &pubkey, deadline).await?;
|
||||
|
||||
let identity_ed25519_pub: [u8; 32] = pubkey[32..64]
|
||||
.try_into()
|
||||
.map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?;
|
||||
let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
|
||||
.map_err(|e| RncpError::ProofInvalid(format!("verify key: {e}")))?;
|
||||
|
||||
let rtt_data = link
|
||||
.validate_proof(&proof_body, &verify_key, &identity_ed25519_pub)
|
||||
.map_err(|e| RncpError::ProofInvalid(format!("{e:?}")))?;
|
||||
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
attached_interface,
|
||||
LinkEndpointRole::Initiator,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
registration.endpoint_bound();
|
||||
|
||||
let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: rtt_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, rtt_pkt).await?;
|
||||
|
||||
let our_pub = identity.get_public_key();
|
||||
let our_priv = identity.get_signing_key().ok_or(RncpError::NoSigningKey)?;
|
||||
@@ -573,13 +572,7 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
rns_wire::context::PacketContext::LinkIdentify,
|
||||
&ident_data,
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: ident_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, ident_pkt).await?;
|
||||
|
||||
// Encrypt full payload BEFORE chunking (Resource.py:424).
|
||||
let session_keys = link
|
||||
@@ -634,6 +627,8 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
link_id,
|
||||
resource,
|
||||
lpkt_rx: &mut lpkt_rx,
|
||||
endpoint_lifecycle_rx: &mut endpoint_lifecycle_rx,
|
||||
attached_interface,
|
||||
progress_tx: progress_tx.clone(),
|
||||
progress_base: completed_parts as f32 / total_parts_nonzero as f32,
|
||||
progress_span: segment_parts as f32 / total_parts_nonzero as f32,
|
||||
@@ -650,15 +645,23 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
tokio::time::sleep(RNCP_POST_PROOF_SETTLE).await;
|
||||
}
|
||||
|
||||
if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: close_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await;
|
||||
let endpoint_closing = if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
crate::link_endpoint::send_and_unbind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
close_pkt,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !endpoint_closing {
|
||||
let _ = registration.cleanup().await;
|
||||
} else {
|
||||
registration.disarm();
|
||||
}
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
|
||||
transfer_result?;
|
||||
|
||||
@@ -695,6 +698,8 @@ struct OutboundDrive<'a> {
|
||||
link_id: [u8; 16],
|
||||
resource: OutboundResource,
|
||||
lpkt_rx: &'a mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint_lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
|
||||
attached_interface: InterfaceId,
|
||||
progress_tx: Option<mpsc::Sender<f32>>,
|
||||
progress_base: f32,
|
||||
progress_span: f32,
|
||||
@@ -708,6 +713,8 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
|
||||
link_id,
|
||||
resource,
|
||||
lpkt_rx,
|
||||
endpoint_lifecycle_rx,
|
||||
attached_interface,
|
||||
progress_tx,
|
||||
progress_base,
|
||||
progress_span,
|
||||
@@ -740,15 +747,32 @@ async fn drive_outbound(request: OutboundDrive<'_>) -> Result<(), RncpError> {
|
||||
}
|
||||
|
||||
let recv_timeout = remaining(deadline).min(Duration::from_secs(5));
|
||||
let ev = match tokio::time::timeout(recv_timeout, lpkt_rx.recv()).await {
|
||||
Ok(Some(ev)) => ev,
|
||||
Ok(None) => return Err(RncpError::ResourceFailed("link channel closed".into())),
|
||||
let ev = match tokio::time::timeout(recv_timeout, async {
|
||||
tokio::select! {
|
||||
event = lpkt_rx.recv() => event.ok_or_else(|| {
|
||||
RncpError::ResourceFailed("link channel closed".into())
|
||||
}),
|
||||
terminal = endpoint_lifecycle_rx.recv() => Err(RncpError::ResourceFailed(
|
||||
format!("link endpoint terminated: {terminal:?}")
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(ev)) => ev,
|
||||
Ok(Err(error)) => return Err(error),
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let DestinationEvent::InboundPacket { raw, .. } = ev else {
|
||||
let DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} = ev
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if interface_id != attached_interface {
|
||||
continue;
|
||||
}
|
||||
let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok(h) => h,
|
||||
Err(_) => continue,
|
||||
@@ -819,13 +843,7 @@ async fn send_keepalive_response(
|
||||
rns_wire::context::PacketContext::Keepalive,
|
||||
&[rns_link::constants::KEEPALIVE_RESPONSE],
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)
|
||||
send_endpoint_packet(transport_tx, link_id, raw).await
|
||||
}
|
||||
|
||||
async fn send_transfer_action(
|
||||
@@ -836,13 +854,7 @@ async fn send_transfer_action(
|
||||
) -> Result<(), RncpError> {
|
||||
if let TransferAction::SendProof(proof) = action {
|
||||
let raw = build_resource_proof_packet(link_id, &proof);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(transport_tx, link_id, raw).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -897,13 +909,7 @@ async fn send_transfer_action(
|
||||
TransferAction::Failed(reason) => return Err(RncpError::ResourceFailed(reason)),
|
||||
};
|
||||
let raw = build_data_packet(link_id, context, &body);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)
|
||||
send_endpoint_packet(transport_tx, link_id, raw).await
|
||||
}
|
||||
|
||||
fn remaining(deadline: Instant) -> Duration {
|
||||
@@ -970,29 +976,32 @@ async fn lookup_pubkey(
|
||||
.and_then(|a| a.public_key))
|
||||
}
|
||||
|
||||
async fn wait_for_proof(
|
||||
async fn wait_for_valid_rncp_proof(
|
||||
rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
link_id: [u8; 16],
|
||||
) -> Result<Vec<u8>, RncpError> {
|
||||
while let Some(ev) = rx.recv().await {
|
||||
let DestinationEvent::InboundPacket { raw, .. } = ev else {
|
||||
continue;
|
||||
};
|
||||
let Ok((header, off)) = rns_wire::header::PacketHeader::unpack(&raw) else {
|
||||
continue;
|
||||
};
|
||||
if header.flags.packet_type == rns_wire::flags::PacketType::Proof
|
||||
&& header.destination_hash == link_id
|
||||
&& raw.len() > off
|
||||
{
|
||||
return Ok(raw[off..].to_vec());
|
||||
link: &mut Link,
|
||||
public_key: &[u8; 64],
|
||||
deadline: Instant,
|
||||
) -> Result<(Vec<u8>, InterfaceId), RncpError> {
|
||||
let identity_ed25519_pub: [u8; 32] = public_key[32..64]
|
||||
.try_into()
|
||||
.map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?;
|
||||
let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
|
||||
.map_err(|e| RncpError::ProofInvalid(format!("verify key: {e}")))?;
|
||||
let proof = timeout(
|
||||
remaining(deadline),
|
||||
crate::link_endpoint::wait_for_valid_proof(rx, link, &verify_key, &identity_ed25519_pub),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RncpError::Timeout("link proof"))?
|
||||
.map_err(|error| match error {
|
||||
crate::link_endpoint::LinkProofWaitError::LinkClosed => {
|
||||
RncpError::HandshakeFailed("link closed".into())
|
||||
}
|
||||
}
|
||||
Err(RncpError::HandshakeFailed("channel closed".into()))
|
||||
}
|
||||
|
||||
async fn cleanup_destination(transport_tx: &mpsc::Sender<TransportMessage>, link_id: [u8; 16]) {
|
||||
let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id });
|
||||
crate::link_endpoint::LinkProofWaitError::DeliveryClosed => {
|
||||
RncpError::HandshakeFailed("channel closed".into())
|
||||
}
|
||||
})?;
|
||||
Ok((proof.rtt_data, proof.interface_id))
|
||||
}
|
||||
|
||||
fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes {
|
||||
@@ -1115,6 +1124,11 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
})
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
|
||||
transport_tx.clone(),
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
);
|
||||
|
||||
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
|
||||
transport_tx
|
||||
@@ -1125,37 +1139,21 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
|
||||
let proof_body = match timeout(remaining(deadline), wait_for_proof(&mut lpkt_rx, link_id)).await
|
||||
{
|
||||
Ok(Ok(body)) => body,
|
||||
Ok(Err(e)) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(RncpError::Timeout("link proof"));
|
||||
}
|
||||
};
|
||||
let (rtt_data, attached_interface) =
|
||||
wait_for_valid_rncp_proof(&mut lpkt_rx, &mut link, &pubkey, deadline).await?;
|
||||
|
||||
let identity_ed25519_pub: [u8; 32] = pubkey[32..64]
|
||||
.try_into()
|
||||
.map_err(|_| RncpError::ProofInvalid("remote pub key length".into()))?;
|
||||
let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
|
||||
.map_err(|e| RncpError::ProofInvalid(format!("verify key: {e}")))?;
|
||||
|
||||
let rtt_data = link
|
||||
.validate_proof(&proof_body, &verify_key, &identity_ed25519_pub)
|
||||
.map_err(|e| RncpError::ProofInvalid(format!("{e:?}")))?;
|
||||
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
attached_interface,
|
||||
LinkEndpointRole::Initiator,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
registration.endpoint_bound();
|
||||
|
||||
let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: rtt_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, rtt_pkt).await?;
|
||||
|
||||
let our_pub = identity.get_public_key();
|
||||
let our_priv = identity.get_signing_key().ok_or(RncpError::NoSigningKey)?;
|
||||
@@ -1167,13 +1165,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
rns_wire::context::PacketContext::LinkIdentify,
|
||||
&ident_data,
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: ident_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, ident_pkt).await?;
|
||||
|
||||
let (req_encrypted, _req_id) = link
|
||||
.request_str(FETCH_PATH_NAME, remote_path, remaining(deadline))
|
||||
@@ -1186,13 +1178,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
let packet_request_id =
|
||||
rns_wire::hash::truncated_packet_hash(&req_pkt, rns_wire::flags::HeaderType::Header1);
|
||||
link.update_pending_request_id(&_req_id, packet_request_id);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: req_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, req_pkt).await?;
|
||||
|
||||
let session_keys = link
|
||||
.session_keys()
|
||||
@@ -1218,15 +1204,32 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
break Err(RncpError::Timeout("fetch"));
|
||||
}
|
||||
let recv_timeout = remaining(deadline).min(Duration::from_secs(5));
|
||||
let ev = match tokio::time::timeout(recv_timeout, lpkt_rx.recv()).await {
|
||||
Ok(Some(ev)) => ev,
|
||||
Ok(None) => break Err(RncpError::ResourceFailed("link channel closed".into())),
|
||||
let ev = match tokio::time::timeout(recv_timeout, async {
|
||||
tokio::select! {
|
||||
event = lpkt_rx.recv() => event.ok_or_else(|| {
|
||||
RncpError::ResourceFailed("link channel closed".into())
|
||||
}),
|
||||
terminal = endpoint_lifecycle_rx.recv() => Err(RncpError::ResourceFailed(
|
||||
format!("link endpoint terminated: {terminal:?}")
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(ev)) => ev,
|
||||
Ok(Err(error)) => break Err(error),
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let DestinationEvent::InboundPacket { raw, .. } = ev else {
|
||||
let DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} = ev
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if interface_id != attached_interface {
|
||||
continue;
|
||||
}
|
||||
let (header, off) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok(h) => h,
|
||||
Err(_) => continue,
|
||||
@@ -1304,21 +1307,15 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if let TransferAction::SendRequest(req_data) = t.request_next() {
|
||||
if let Ok(encrypted) = link.encrypt(&req_data) {
|
||||
let req_raw = build_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&encrypted,
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: req_raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
}
|
||||
if let TransferAction::SendRequest(req_data) = t.request_next()
|
||||
&& let Ok(encrypted) = link.encrypt(&req_data)
|
||||
{
|
||||
let req_raw = build_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&encrypted,
|
||||
);
|
||||
send_endpoint_packet(&transport_tx, link_id, req_raw).await?;
|
||||
}
|
||||
transfers.insert(adv.resource_hash, t);
|
||||
}
|
||||
@@ -1359,13 +1356,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
};
|
||||
if let Ok(encrypted) = link.encrypt(&payload) {
|
||||
let raw = build_data_packet(link_id, context, &encrypted);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
send_endpoint_packet(&transport_tx, link_id, raw).await?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1397,12 +1388,12 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
}
|
||||
};
|
||||
let prf_raw = build_resource_proof_packet(link_id, &proof);
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: prf_raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await;
|
||||
// The received file is not locally concluded until its
|
||||
// Resource proof has been admitted on the exact Link
|
||||
// endpoint. Otherwise a stale or lost binding could make
|
||||
// the receiver publish success that the sender can never
|
||||
// observe.
|
||||
send_endpoint_packet(&transport_tx, link_id, prf_raw).await?;
|
||||
|
||||
transfers.remove(&rh);
|
||||
|
||||
@@ -1465,21 +1456,15 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
let Some(t) = transfers.get_mut(&rh) else {
|
||||
continue;
|
||||
};
|
||||
if let TransferAction::SendRequest(req) = t.hashmap_update(segment, &hashmap) {
|
||||
if let Ok(encrypted) = link.encrypt(&req) {
|
||||
let req_raw = build_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&encrypted,
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: req_raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RncpError::TransportUnavailable)?;
|
||||
}
|
||||
if let TransferAction::SendRequest(req) = t.hashmap_update(segment, &hashmap)
|
||||
&& let Ok(encrypted) = link.encrypt(&req)
|
||||
{
|
||||
let req_raw = build_data_packet(
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&encrypted,
|
||||
);
|
||||
send_endpoint_packet(&transport_tx, link_id, req_raw).await?;
|
||||
}
|
||||
}
|
||||
rns_wire::context::PacketContext::LinkClose if link.receive_teardown(body) => {
|
||||
@@ -1489,15 +1474,23 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: close_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await;
|
||||
let endpoint_closing = if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
crate::link_endpoint::send_and_unbind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
close_pkt,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !endpoint_closing {
|
||||
let _ = registration.cleanup().await;
|
||||
} else {
|
||||
registration.disarm();
|
||||
}
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
|
||||
let (file_name, payload) = result?;
|
||||
let bytes = payload.len();
|
||||
@@ -1558,6 +1551,43 @@ mod tests {
|
||||
assert_eq!(&raw[off..], &[0x22; 64]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resource_proof_rejection_is_not_a_successful_send() {
|
||||
let link_id = [0x12; 16];
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(1);
|
||||
let send = tokio::spawn(async move {
|
||||
send_endpoint_packet(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
build_resource_proof_packet(link_id, &[0x34; 64]),
|
||||
)
|
||||
.await
|
||||
});
|
||||
let TransportMessage::SendLinkEndpoint {
|
||||
role,
|
||||
request,
|
||||
result_tx,
|
||||
..
|
||||
} = transport_rx
|
||||
.recv()
|
||||
.await
|
||||
.expect("typed Resource proof send")
|
||||
else {
|
||||
panic!("Resource proof must use the established-Link endpoint");
|
||||
};
|
||||
assert_eq!(role, LinkEndpointRole::Initiator);
|
||||
let (header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
|
||||
assert_eq!(
|
||||
header.context,
|
||||
rns_wire::context::PacketContext::ResourcePrf
|
||||
);
|
||||
let _ = result_tx.send(rns_transport::messages::LinkEndpointSendResult::NotBound);
|
||||
assert!(matches!(
|
||||
send.await.unwrap(),
|
||||
Err(RncpError::TransportUnavailable)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_close_packet_uses_authenticated_teardown_payload() {
|
||||
let dest_hash = [0x33; 16];
|
||||
|
||||
+174
-144
@@ -29,7 +29,8 @@ use rns_protocol::rnsh::{
|
||||
};
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{
|
||||
AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
AnnounceRpcEntry, InterfaceId, LinkEndpointLifecycleEvent, LinkEndpointRole, OutboundRequest,
|
||||
TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
|
||||
use crate::lifecycle::ShutdownSignal;
|
||||
@@ -38,7 +39,7 @@ use crate::link_manager::{
|
||||
};
|
||||
|
||||
pub const RNSH_APP_NAME: &str = "rnsh";
|
||||
pub const RNSH_SOFTWARE_VERSION: &str = "0.2.0";
|
||||
pub const RNSH_SOFTWARE_VERSION: &str = "0.3.0";
|
||||
const CLIENT_CHUNK_LEN: usize = 240;
|
||||
const CHANNEL_SEND_RETRY: Duration = Duration::from_millis(20);
|
||||
const CLIENT_PRE_EOF_DRAIN_MIN: Duration = Duration::from_secs(3);
|
||||
@@ -323,6 +324,11 @@ pub async fn rnsh_client_execute(
|
||||
})
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)?;
|
||||
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
|
||||
transport_tx.clone(),
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
);
|
||||
|
||||
let link_req_pkt = build_link_request_packet(destination_hash, &request_data);
|
||||
transport_tx
|
||||
@@ -333,40 +339,37 @@ pub async fn rnsh_client_execute(
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)?;
|
||||
|
||||
let proof_body = match tokio::time::timeout(
|
||||
remaining(deadline),
|
||||
wait_for_link_proof(&mut lpkt_rx, link_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(body)) => body,
|
||||
Ok(Err(e)) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(e);
|
||||
}
|
||||
Err(_) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(RnshError::Timeout("link proof"));
|
||||
}
|
||||
};
|
||||
|
||||
let identity_ed25519_pub: [u8; 32] = pubkey[32..64]
|
||||
.try_into()
|
||||
.map_err(|_| RnshError::ProofInvalid("remote public key length".into()))?;
|
||||
let verify_key = Ed25519PublicKey::from_bytes(&identity_ed25519_pub)
|
||||
.map_err(|e| RnshError::ProofInvalid(format!("verify key: {e}")))?;
|
||||
|
||||
let rtt_data = link
|
||||
.validate_proof(&proof_body, &verify_key, &identity_ed25519_pub)
|
||||
.map_err(|e| RnshError::ProofInvalid(format!("{e:?}")))?;
|
||||
let proof = wait_for_valid_link_proof(
|
||||
&mut lpkt_rx,
|
||||
&mut link,
|
||||
&verify_key,
|
||||
&identity_ed25519_pub,
|
||||
deadline,
|
||||
)
|
||||
.await?;
|
||||
let attached_interface = proof.interface_id;
|
||||
let rtt_data = proof.rtt_data;
|
||||
let mut endpoint_lifecycle_rx = crate::link_endpoint::bind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
attached_interface,
|
||||
LinkEndpointRole::Initiator,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)?;
|
||||
registration.endpoint_bound();
|
||||
let mut endpoint = ClientLinkEndpoint {
|
||||
attached_interface,
|
||||
lifecycle_rx: &mut endpoint_lifecycle_rx,
|
||||
packet_rx: &mut lpkt_rx,
|
||||
};
|
||||
let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: rtt_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)?;
|
||||
send_client_endpoint_packet(&transport_tx, link_id, rtt_pkt).await?;
|
||||
|
||||
let signing_key = cfg
|
||||
.identity
|
||||
@@ -384,13 +387,7 @@ pub async fn rnsh_client_execute(
|
||||
rns_wire::context::PacketContext::LinkIdentify,
|
||||
&identify_data,
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: identify_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)?;
|
||||
send_client_endpoint_packet(&transport_tx, link_id, identify_pkt).await?;
|
||||
tokio::time::sleep(Duration::from_secs_f64(post_identify_delay)).await;
|
||||
}
|
||||
|
||||
@@ -407,7 +404,7 @@ pub async fn rnsh_client_execute(
|
||||
|
||||
send_client_message_when_ready(
|
||||
&transport_tx,
|
||||
&mut lpkt_rx,
|
||||
&mut endpoint,
|
||||
&mut link,
|
||||
&mut channel,
|
||||
&mut pending_messages,
|
||||
@@ -419,7 +416,7 @@ pub async fn rnsh_client_execute(
|
||||
loop {
|
||||
if let Some(message) = pop_or_receive_client_message(
|
||||
&transport_tx,
|
||||
&mut lpkt_rx,
|
||||
&mut endpoint,
|
||||
&mut link,
|
||||
&mut channel,
|
||||
&mut pending_messages,
|
||||
@@ -430,14 +427,12 @@ pub async fn rnsh_client_execute(
|
||||
match message {
|
||||
RnshMessage::VersionInfo(version) => {
|
||||
if version.protocol_version != PROTOCOL_VERSION {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(RnshError::Remote("incompatible rnsh protocol".into()));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(75)).await;
|
||||
break;
|
||||
}
|
||||
RnshMessage::Error(err) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(RnshError::Remote(
|
||||
err.msg.unwrap_or_else(|| "remote error".into()),
|
||||
));
|
||||
@@ -461,7 +456,7 @@ pub async fn rnsh_client_execute(
|
||||
);
|
||||
send_client_message_when_ready(
|
||||
&transport_tx,
|
||||
&mut lpkt_rx,
|
||||
&mut endpoint,
|
||||
&mut link,
|
||||
&mut channel,
|
||||
&mut pending_messages,
|
||||
@@ -472,7 +467,7 @@ pub async fn rnsh_client_execute(
|
||||
|
||||
let return_code = match run_client_io_loop(
|
||||
&transport_tx,
|
||||
&mut lpkt_rx,
|
||||
&mut endpoint,
|
||||
&mut link,
|
||||
&mut channel,
|
||||
&mut pending_messages,
|
||||
@@ -487,20 +482,27 @@ pub async fn rnsh_client_execute(
|
||||
{
|
||||
Ok(return_code) => return_code,
|
||||
Err(error) => {
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
let _ = transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: close_pkt,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await;
|
||||
let endpoint_closing = if let Some(close_pkt) = build_link_close(&mut link) {
|
||||
crate::link_endpoint::send_and_unbind(
|
||||
&transport_tx,
|
||||
link_id,
|
||||
LinkEndpointRole::Initiator,
|
||||
close_pkt,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !endpoint_closing {
|
||||
let _ = registration.cleanup().await;
|
||||
} else {
|
||||
registration.disarm();
|
||||
}
|
||||
cleanup_destination(&transport_tx, link_id).await;
|
||||
|
||||
Ok(RnshClientOutcome {
|
||||
stdout,
|
||||
@@ -509,6 +511,22 @@ pub async fn rnsh_client_execute(
|
||||
})
|
||||
}
|
||||
|
||||
struct ClientLinkEndpoint<'a> {
|
||||
attached_interface: InterfaceId,
|
||||
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
|
||||
packet_rx: &'a mut mpsc::Receiver<DestinationEvent>,
|
||||
}
|
||||
|
||||
async fn send_client_endpoint_packet(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
link_id: [u8; 16],
|
||||
raw: Bytes,
|
||||
) -> Result<(), RnshError> {
|
||||
crate::link_endpoint::send(transport_tx, link_id, LinkEndpointRole::Initiator, raw)
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)
|
||||
}
|
||||
|
||||
fn register_rnsh_message_types(channel: &mut LinkChannel) -> Result<(), ChannelError> {
|
||||
for msg_type in MESSAGE_TYPES {
|
||||
channel.register_message_type(msg_type)?;
|
||||
@@ -533,7 +551,7 @@ struct ClientIoState<'a> {
|
||||
|
||||
async fn run_client_io_loop(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
lpkt_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut ClientLinkEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
@@ -598,7 +616,7 @@ async fn run_client_io_loop(
|
||||
let deadline_wait = remaining(deadline);
|
||||
|
||||
tokio::select! {
|
||||
maybe_event = lpkt_rx.recv() => {
|
||||
maybe_event = endpoint.packet_rx.recv() => {
|
||||
let Some(event) = maybe_event else {
|
||||
return Err(RnshError::HandshakeFailed("link channel closed".into()));
|
||||
};
|
||||
@@ -608,8 +626,14 @@ async fn run_client_io_loop(
|
||||
channel,
|
||||
pending_messages,
|
||||
event,
|
||||
endpoint.attached_interface,
|
||||
).await?;
|
||||
}
|
||||
terminal = endpoint.lifecycle_rx.recv() => {
|
||||
return Err(RnshError::HandshakeFailed(format!(
|
||||
"link endpoint terminated: {terminal:?}"
|
||||
)));
|
||||
}
|
||||
maybe_chunk = recv_optional_stdin_chunk(&mut stdin_rx), if !stdin_eof_sent => {
|
||||
match maybe_chunk {
|
||||
Some(data) if !data.is_empty() => {
|
||||
@@ -619,7 +643,7 @@ async fn run_client_io_loop(
|
||||
}
|
||||
send_client_message_when_ready(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -632,7 +656,7 @@ async fn run_client_io_loop(
|
||||
if !pending_has_remote_terminal(pending_messages) {
|
||||
drain_client_messages_before_stdin_eof(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -643,7 +667,7 @@ async fn run_client_io_loop(
|
||||
if !pending_has_remote_terminal(pending_messages) {
|
||||
send_client_message_when_ready(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -660,7 +684,7 @@ async fn run_client_io_loop(
|
||||
Some(window) => {
|
||||
send_client_message_when_ready(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -722,23 +746,23 @@ async fn handle_client_message(
|
||||
RnshMessage::StreamData(stream) => match stream.stream_id {
|
||||
STREAM_ID_STDOUT => {
|
||||
stdout.extend_from_slice(&stream.data);
|
||||
if let Some(tx) = stdout_tx {
|
||||
if !stream.data.is_empty() {
|
||||
tx.send(stream.data).await.map_err(|_| {
|
||||
RnshError::Process("stdout stream receiver closed".into())
|
||||
})?;
|
||||
}
|
||||
if let Some(tx) = stdout_tx
|
||||
&& !stream.data.is_empty()
|
||||
{
|
||||
tx.send(stream.data)
|
||||
.await
|
||||
.map_err(|_| RnshError::Process("stdout stream receiver closed".into()))?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
STREAM_ID_STDERR => {
|
||||
stderr.extend_from_slice(&stream.data);
|
||||
if let Some(tx) = stderr_tx {
|
||||
if !stream.data.is_empty() {
|
||||
tx.send(stream.data).await.map_err(|_| {
|
||||
RnshError::Process("stderr stream receiver closed".into())
|
||||
})?;
|
||||
}
|
||||
if let Some(tx) = stderr_tx
|
||||
&& !stream.data.is_empty()
|
||||
{
|
||||
tx.send(stream.data)
|
||||
.await
|
||||
.map_err(|_| RnshError::Process("stderr stream receiver closed".into()))?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
@@ -1158,10 +1182,10 @@ async fn handle_listener_channel_message(
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(stdin) = session.stdin.as_mut() {
|
||||
if !stream.data.is_empty() {
|
||||
stdin.write_all(&stream.data).await?;
|
||||
}
|
||||
if let Some(stdin) = session.stdin.as_mut()
|
||||
&& !stream.data.is_empty()
|
||||
{
|
||||
stdin.write_all(&stream.data).await?;
|
||||
}
|
||||
if stream.eof {
|
||||
if let Some(stdin) = session.stdin.as_mut() {
|
||||
@@ -1314,20 +1338,20 @@ async fn start_listener_process(
|
||||
stderr,
|
||||
)));
|
||||
}
|
||||
if let Some(ref pty) = pty {
|
||||
if !pipe_stdout || !pipe_stderr {
|
||||
let stream_id = if !pipe_stdout {
|
||||
STREAM_ID_STDOUT
|
||||
} else {
|
||||
STREAM_ID_STDERR
|
||||
};
|
||||
reader_tasks.push(tokio::spawn(stream_reader_task(
|
||||
command_tx.clone(),
|
||||
link_id,
|
||||
stream_id,
|
||||
pty_reader_file(pty)?,
|
||||
)));
|
||||
}
|
||||
if let Some(ref pty) = pty
|
||||
&& (!pipe_stdout || !pipe_stderr)
|
||||
{
|
||||
let stream_id = if !pipe_stdout {
|
||||
STREAM_ID_STDOUT
|
||||
} else {
|
||||
STREAM_ID_STDERR
|
||||
};
|
||||
reader_tasks.push(tokio::spawn(stream_reader_task(
|
||||
command_tx.clone(),
|
||||
link_id,
|
||||
stream_id,
|
||||
pty_reader_file(pty)?,
|
||||
)));
|
||||
}
|
||||
|
||||
let window = pty.take().map(pty_window_target);
|
||||
@@ -1469,7 +1493,7 @@ where
|
||||
|
||||
async fn send_client_message_when_ready<M>(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
lpkt_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut ClientLinkEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
@@ -1485,7 +1509,7 @@ where
|
||||
Err(RnshError::Channel(err)) if err.contains("not ready") => {
|
||||
let _ = receive_client_messages(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -1542,13 +1566,7 @@ async fn send_client_channel_data(
|
||||
let packet_hash = rns_wire::hash::packet_hash(&raw, channel_header.flags.header_type);
|
||||
channel.track_outbound_packet_hash(packet_hash, sequence);
|
||||
link.record_tx(data.len());
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: Bytes::from(raw),
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)
|
||||
send_client_endpoint_packet(transport_tx, link_id, Bytes::from(raw)).await
|
||||
}
|
||||
|
||||
async fn resend_timed_out_client_channel_messages(
|
||||
@@ -1568,7 +1586,7 @@ async fn resend_timed_out_client_channel_messages(
|
||||
|
||||
async fn pop_or_receive_client_message(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
lpkt_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut ClientLinkEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
@@ -1579,7 +1597,7 @@ async fn pop_or_receive_client_message(
|
||||
}
|
||||
receive_client_messages(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -1592,7 +1610,7 @@ async fn pop_or_receive_client_message(
|
||||
|
||||
async fn drain_client_messages_before_stdin_eof(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
lpkt_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut ClientLinkEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
@@ -1613,7 +1631,7 @@ async fn drain_client_messages_before_stdin_eof(
|
||||
}
|
||||
receive_client_messages(
|
||||
transport_tx,
|
||||
lpkt_rx,
|
||||
endpoint,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
@@ -1628,7 +1646,7 @@ async fn drain_client_messages_before_stdin_eof(
|
||||
|
||||
async fn receive_client_messages(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
lpkt_rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
endpoint: &mut ClientLinkEndpoint<'_>,
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
@@ -1642,16 +1660,35 @@ async fn receive_client_messages(
|
||||
let wait = wait
|
||||
.min(channel.next_timeout_duration().unwrap_or(wait))
|
||||
.min(remaining(deadline));
|
||||
let event = match tokio::time::timeout(wait, lpkt_rx.recv()).await {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => return Err(RnshError::HandshakeFailed("link channel closed".into())),
|
||||
let event = match tokio::time::timeout(wait, async {
|
||||
tokio::select! {
|
||||
event = endpoint.packet_rx.recv() => event.ok_or_else(|| {
|
||||
RnshError::HandshakeFailed("link channel closed".into())
|
||||
}),
|
||||
terminal = endpoint.lifecycle_rx.recv() => Err(RnshError::HandshakeFailed(
|
||||
format!("link endpoint terminated: {terminal:?}")
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(Ok(event)) => event,
|
||||
Ok(Err(error)) => return Err(error),
|
||||
Err(_) => {
|
||||
resend_timed_out_client_channel_messages(transport_tx, link, channel).await?;
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
|
||||
process_client_destination_event(transport_tx, link, channel, pending_messages, event).await
|
||||
process_client_destination_event(
|
||||
transport_tx,
|
||||
link,
|
||||
channel,
|
||||
pending_messages,
|
||||
event,
|
||||
endpoint.attached_interface,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn process_client_destination_event(
|
||||
@@ -1660,10 +1697,17 @@ async fn process_client_destination_event(
|
||||
channel: &mut LinkChannel,
|
||||
pending_messages: &mut VecDeque<RnshMessage>,
|
||||
event: DestinationEvent,
|
||||
attached_interface: InterfaceId,
|
||||
) -> Result<bool, RnshError> {
|
||||
let DestinationEvent::InboundPacket { raw, .. } = event else {
|
||||
let DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} = event
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
if interface_id != attached_interface {
|
||||
return Ok(false);
|
||||
}
|
||||
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(_) => return Ok(false),
|
||||
@@ -1676,7 +1720,7 @@ async fn process_client_destination_event(
|
||||
rns_wire::flags::PacketType::Proof if body.len() >= 96 => {
|
||||
let mut packet_hash = [0u8; 32];
|
||||
packet_hash.copy_from_slice(&body[..32]);
|
||||
if link.validate_packet_proof(&packet_hash, body) {
|
||||
if link.validate_peer_packet_proof(&packet_hash, body).is_ok() {
|
||||
channel.delivered_by_packet_hash(&packet_hash, link.rtt_secs());
|
||||
}
|
||||
}
|
||||
@@ -1692,7 +1736,7 @@ async fn process_client_destination_event(
|
||||
rns_wire::context::PacketContext::Channel => {
|
||||
link.record_inbound();
|
||||
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
|
||||
if let Ok(proof_data) = link.prove_packet_with_link_key(&packet_hash) {
|
||||
if let Ok(proof_data) = link.prove_packet_with_local_signer(&packet_hash) {
|
||||
send_link_packet_proof(
|
||||
transport_tx,
|
||||
*channel.link_id(),
|
||||
@@ -1773,29 +1817,27 @@ async fn lookup_pubkey(
|
||||
.and_then(|a| a.public_key))
|
||||
}
|
||||
|
||||
async fn wait_for_link_proof(
|
||||
async fn wait_for_valid_link_proof(
|
||||
rx: &mut mpsc::Receiver<DestinationEvent>,
|
||||
link_id: [u8; 16],
|
||||
) -> Result<Vec<u8>, RnshError> {
|
||||
while let Some(event) = rx.recv().await {
|
||||
let DestinationEvent::InboundPacket { raw, .. } = event else {
|
||||
continue;
|
||||
};
|
||||
let Ok((header, data_offset)) = rns_wire::header::PacketHeader::unpack(&raw) else {
|
||||
continue;
|
||||
};
|
||||
if header.flags.packet_type == rns_wire::flags::PacketType::Proof
|
||||
&& header.destination_hash == link_id
|
||||
&& raw.len() > data_offset
|
||||
{
|
||||
return Ok(raw[data_offset..].to_vec());
|
||||
link: &mut Link,
|
||||
verify_key: &Ed25519PublicKey,
|
||||
identity_ed25519_pub: &[u8; 32],
|
||||
deadline: Instant,
|
||||
) -> Result<crate::link_endpoint::ValidatedLinkProof, RnshError> {
|
||||
tokio::time::timeout(
|
||||
remaining(deadline),
|
||||
crate::link_endpoint::wait_for_valid_proof(rx, link, verify_key, identity_ed25519_pub),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RnshError::Timeout("link proof"))?
|
||||
.map_err(|error| match error {
|
||||
crate::link_endpoint::LinkProofWaitError::LinkClosed => {
|
||||
RnshError::HandshakeFailed("link closed".into())
|
||||
}
|
||||
}
|
||||
Err(RnshError::HandshakeFailed("channel closed".into()))
|
||||
}
|
||||
|
||||
async fn cleanup_destination(transport_tx: &mpsc::Sender<TransportMessage>, link_id: [u8; 16]) {
|
||||
let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id });
|
||||
crate::link_endpoint::LinkProofWaitError::DeliveryClosed => {
|
||||
RnshError::HandshakeFailed("channel closed".into())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_keepalive_response(
|
||||
@@ -1807,13 +1849,7 @@ async fn send_keepalive_response(
|
||||
rns_wire::context::PacketContext::Keepalive,
|
||||
&[rns_link::constants::KEEPALIVE_RESPONSE],
|
||||
);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw,
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)
|
||||
send_client_endpoint_packet(transport_tx, link_id, raw).await
|
||||
}
|
||||
|
||||
async fn send_link_packet_proof(
|
||||
@@ -1837,13 +1873,7 @@ async fn send_link_packet_proof(
|
||||
};
|
||||
let mut raw = header.pack();
|
||||
raw.extend_from_slice(proof_data);
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: Bytes::from(raw),
|
||||
destination_hash: link_id,
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| RnshError::TransportUnavailable)
|
||||
send_client_endpoint_packet(transport_tx, link_id, Bytes::from(raw)).await
|
||||
}
|
||||
|
||||
fn build_link_close(link: &mut Link) -> Option<Bytes> {
|
||||
|
||||
@@ -1530,7 +1530,9 @@ pub async fn connect_unix_and_request(
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn connect_unix_stream(socket_path: &str) -> std::io::Result<tokio::net::UnixStream> {
|
||||
pub(crate) async fn connect_unix_stream(
|
||||
socket_path: &str,
|
||||
) -> std::io::Result<tokio::net::UnixStream> {
|
||||
if let Some(abstract_name) = socket_path.strip_prefix('\0') {
|
||||
return connect_abstract_unix_stream(abstract_name);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::lifecycle::ShutdownSignal;
|
||||
use crate::rpc::{self, RpcError, RpcRequest, RpcResponse};
|
||||
|
||||
const MAX_REQUEST_SIZE: usize = 1_048_576;
|
||||
const MAX_CONTROL_CLIENTS: usize = 64;
|
||||
const CONTROL_SESSION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
pub async fn run_rpc_server(
|
||||
port: u16,
|
||||
@@ -55,7 +57,7 @@ pub async fn run_unix_rpc_server(
|
||||
)))
|
||||
}
|
||||
|
||||
async fn run_rpc_server_with_listener(
|
||||
pub(crate) async fn run_rpc_server_with_listener(
|
||||
listener: TcpListener,
|
||||
rpc_key: Vec<u8>,
|
||||
_transport_tx: mpsc::Sender<TransportMessage>,
|
||||
@@ -63,19 +65,24 @@ async fn run_rpc_server_with_listener(
|
||||
) -> Result<(), RpcError> {
|
||||
let port = listener.local_addr().map_err(RpcError::Io)?.port();
|
||||
tracing::info!("RPC server listening on 127.0.0.1:{}", port);
|
||||
let rpc_key = zeroize::Zeroizing::new(rpc_key);
|
||||
let mut clients = tokio::task::JoinSet::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => break,
|
||||
_ = clients.join_next(), if !clients.is_empty() => {},
|
||||
accept_result = listener.accept() => {
|
||||
match accept_result {
|
||||
Ok((stream, addr)) => {
|
||||
if clients.len() >= MAX_CONTROL_CLIENTS { continue; }
|
||||
tracing::debug!("RPC connection from {}", addr);
|
||||
let key = rpc_key.clone();
|
||||
let tx = _transport_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_rpc_client(stream, &key, tx).await {
|
||||
tracing::debug!("RPC client error: {}", e);
|
||||
}
|
||||
clients.spawn(async move {
|
||||
let _ = tokio::time::timeout(CONTROL_SESSION_TIMEOUT,
|
||||
handle_rpc_client(stream, &key, tx)).await;
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -83,18 +90,14 @@ async fn run_rpc_server_with_listener(
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = shutdown.wait() => {
|
||||
tracing::info!("RPC server shutting down");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn run_unix_rpc_server_with_listener(
|
||||
pub(crate) async fn run_unix_rpc_server_with_listener(
|
||||
listener: tokio::net::UnixListener,
|
||||
display_path: String,
|
||||
rpc_key: Vec<u8>,
|
||||
@@ -102,19 +105,24 @@ async fn run_unix_rpc_server_with_listener(
|
||||
shutdown: ShutdownSignal,
|
||||
) -> Result<(), RpcError> {
|
||||
tracing::info!("RPC server listening on {}", display_path);
|
||||
let rpc_key = zeroize::Zeroizing::new(rpc_key);
|
||||
let mut clients = tokio::task::JoinSet::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => break,
|
||||
_ = clients.join_next(), if !clients.is_empty() => {},
|
||||
accept_result = listener.accept() => {
|
||||
match accept_result {
|
||||
Ok((stream, _addr)) => {
|
||||
if clients.len() >= MAX_CONTROL_CLIENTS { continue; }
|
||||
tracing::debug!("Unix RPC connection accepted");
|
||||
let key = rpc_key.clone();
|
||||
let tx = transport_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_rpc_client(stream, &key, tx).await {
|
||||
tracing::debug!("Unix RPC client error: {}", e);
|
||||
}
|
||||
clients.spawn(async move {
|
||||
let _ = tokio::time::timeout(CONTROL_SESSION_TIMEOUT,
|
||||
handle_rpc_client(stream, &key, tx)).await;
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -122,18 +130,16 @@ async fn run_unix_rpc_server_with_listener(
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = shutdown.wait() => {
|
||||
tracing::info!("Unix RPC server shutting down");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clients.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn bind_unix_rpc_listener(socket_path: &str) -> std::io::Result<tokio::net::UnixListener> {
|
||||
pub(crate) fn bind_unix_rpc_listener(
|
||||
socket_path: &str,
|
||||
) -> std::io::Result<tokio::net::UnixListener> {
|
||||
if let Some(abstract_name) = socket_path.strip_prefix('\0') {
|
||||
return bind_abstract_unix_listener(abstract_name);
|
||||
}
|
||||
@@ -715,6 +721,55 @@ fn packet_hash_to_array(hash: &[u8]) -> Option<[u8; 32]> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// These are cross-process compatibility checks, not latency benchmarks.
|
||||
// Keep one finite wall-clock budget even on oversubscribed Windows runners;
|
||||
// no production RPC or admission timeout is changed by this fixture budget.
|
||||
const PYTHON_FIXTURE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
async fn python_multiprocessing_available() -> bool {
|
||||
let result = tokio::time::timeout(
|
||||
PYTHON_FIXTURE_TIMEOUT,
|
||||
tokio::process::Command::new("python3")
|
||||
.kill_on_drop(true)
|
||||
.args(["-c", "import multiprocessing.connection"])
|
||||
.status(),
|
||||
)
|
||||
.await
|
||||
.expect("Python availability check timed out");
|
||||
match result {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
|
||||
result => {
|
||||
assert!(result.expect("start Python availability check").success());
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn python_listener_port(line: &str) -> Option<u16> {
|
||||
line.trim_end()
|
||||
.strip_prefix("READY ")?
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|port| *port != 0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_listener_readiness_requires_an_actual_bound_port() {
|
||||
assert_eq!(python_listener_port("READY 12345\n"), Some(12345));
|
||||
assert_eq!(python_listener_port("READY 65535\r\n"), Some(65535));
|
||||
for invalid in [
|
||||
"",
|
||||
"READY",
|
||||
"READY 0",
|
||||
"READY 65536",
|
||||
"READY -1",
|
||||
"READY 1\nREADY 2",
|
||||
"ERROR 12",
|
||||
] {
|
||||
assert_eq!(python_listener_port(invalid), None, "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn all_rpc_requests() -> Vec<RpcRequest> {
|
||||
vec![
|
||||
RpcRequest::GetPathTable { max_hops: Some(5) },
|
||||
@@ -955,12 +1010,7 @@ mod tests {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_rpc_server_accepts_python_multiprocessing_client() {
|
||||
if std::process::Command::new("python3")
|
||||
.arg("-c")
|
||||
.arg("import multiprocessing.connection")
|
||||
.status()
|
||||
.is_err()
|
||||
{
|
||||
if !python_multiprocessing_available().await {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -994,13 +1044,19 @@ conn.close()
|
||||
if b"\xaainterfaces" not in resp:
|
||||
raise SystemExit(f"unexpected interface_stats response: {resp.hex()}")
|
||||
"#;
|
||||
let output = std::process::Command::new("python3")
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.arg(port.to_string())
|
||||
.arg(hex::encode(&rpc_key))
|
||||
.output()
|
||||
.expect("python3 should run");
|
||||
let output = tokio::time::timeout(
|
||||
PYTHON_FIXTURE_TIMEOUT,
|
||||
tokio::process::Command::new("python3")
|
||||
.kill_on_drop(true)
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.arg(port.to_string())
|
||||
.arg(hex::encode(&rpc_key))
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.expect("Python client fixture timed out")
|
||||
.expect("python3 should run");
|
||||
|
||||
shutdown.trigger();
|
||||
|
||||
@@ -1014,16 +1070,10 @@ if b"\xaainterfaces" not in resp:
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_rust_client_accepts_python_multiprocessing_listener() {
|
||||
if std::process::Command::new("python3")
|
||||
.arg("-c")
|
||||
.arg("import multiprocessing.connection")
|
||||
.status()
|
||||
.is_err()
|
||||
{
|
||||
if !python_multiprocessing_available().await {
|
||||
return;
|
||||
}
|
||||
|
||||
let port = portpicker_ephemeral();
|
||||
let rpc_key = b"python_listener_key".to_vec();
|
||||
// umsgpack frames over send_bytes/recv_bytes, matching a >=1.3.4
|
||||
// Python rpc_loop (commit a2ef9782); hardcoded so no msgpack module
|
||||
@@ -1032,10 +1082,9 @@ if b"\xaainterfaces" not in resp:
|
||||
import multiprocessing.connection
|
||||
import sys
|
||||
|
||||
port = int(sys.argv[1])
|
||||
authkey = bytes.fromhex(sys.argv[2])
|
||||
listener = multiprocessing.connection.Listener(("127.0.0.1", port), authkey=authkey)
|
||||
print("READY", flush=True)
|
||||
authkey = bytes.fromhex(sys.argv[1])
|
||||
listener = multiprocessing.connection.Listener(("127.0.0.1", 0), authkey=authkey)
|
||||
print(f"READY {listener.address[1]}", flush=True)
|
||||
conn = listener.accept()
|
||||
call = conn.recv_bytes()
|
||||
if call != bytes.fromhex("81a3676574aa6c696e6b5f636f756e74"): # {"get": "link_count"}
|
||||
@@ -1044,62 +1093,57 @@ conn.send_bytes(b"\x07") # 7
|
||||
conn.close()
|
||||
listener.close()
|
||||
"#;
|
||||
let mut child = std::process::Command::new("python3")
|
||||
let mut child = tokio::process::Command::new("python3")
|
||||
.kill_on_drop(true)
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.arg(port.to_string())
|
||||
.arg(hex::encode(&rpc_key))
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.expect("python3 should start");
|
||||
|
||||
let stdout = child.stdout.take().expect("python listener stdout");
|
||||
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
use std::io::BufRead as _;
|
||||
// Python owns port zero's listener continuously: never select and
|
||||
// release a "free" port before another process gets a chance to bind.
|
||||
let result = tokio::time::timeout(PYTHON_FIXTURE_TIMEOUT, async {
|
||||
use tokio::io::AsyncBufReadExt as _;
|
||||
let stdout = child.stdout.take().expect("python listener stdout");
|
||||
let mut line = String::new();
|
||||
let result = std::io::BufReader::new(stdout)
|
||||
tokio::io::BufReader::new(stdout)
|
||||
.read_line(&mut line)
|
||||
.map(|_| line);
|
||||
let _ = ready_tx.send(result);
|
||||
});
|
||||
match ready_rx.recv_timeout(std::time::Duration::from_secs(5)) {
|
||||
Ok(Ok(line)) if line.trim() == "READY" => {}
|
||||
Ok(Ok(line)) => {
|
||||
let _ = child.kill();
|
||||
panic!("unexpected Python listener readiness line: {line:?}");
|
||||
.await
|
||||
.map_err(|error| format!("Python readiness read: {error}"))?;
|
||||
let port = python_listener_port(&line)
|
||||
.ok_or_else(|| format!("invalid Python readiness: {line:?}"))?;
|
||||
let response = rpc::connect_and_request(
|
||||
port,
|
||||
&rpc_key,
|
||||
&RpcRequest::GetLinkCount,
|
||||
PYTHON_FIXTURE_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| format!("Python listener RPC: {error}"))?;
|
||||
if !matches!(response, RpcResponse::IntResult(7)) {
|
||||
return Err(format!("unexpected Python listener response: {response:?}"));
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
let _ = child.kill();
|
||||
panic!("failed to read Python listener readiness: {e}");
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = child.kill();
|
||||
panic!("timed out waiting for Python listener readiness: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
match rpc::connect_and_request(
|
||||
port,
|
||||
&rpc_key,
|
||||
&RpcRequest::GetLinkCount,
|
||||
std::time::Duration::from_secs(5),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(RpcResponse::IntResult(7)) => {
|
||||
let status = child.wait().expect("python listener should exit");
|
||||
assert!(status.success(), "python listener exited with {status}");
|
||||
}
|
||||
Ok(other) => {
|
||||
let _ = child.kill();
|
||||
panic!("unexpected Python listener response: {other:?}");
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = child.kill();
|
||||
panic!("Rust client could not connect to Python multiprocessing listener: {e}");
|
||||
let status = child
|
||||
.wait()
|
||||
.await
|
||||
.map_err(|error| format!("Python exit: {error}"))?;
|
||||
if !status.success() {
|
||||
return Err(format!("Python listener exited with {status}"));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
// Also reap on failure; a killed-but-unwaited Python fixture must not
|
||||
// leave process/socket cleanup behind for another concurrent test.
|
||||
if !matches!(result, Ok(Ok(()))) {
|
||||
let _ = child.start_kill();
|
||||
let _ = tokio::time::timeout(std::time::Duration::from_secs(5), child.wait()).await;
|
||||
}
|
||||
result
|
||||
.expect("Python listener fixture timed out")
|
||||
.expect("Python listener compatibility");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1156,11 +1200,6 @@ listener.close()
|
||||
));
|
||||
}
|
||||
|
||||
fn portpicker_ephemeral() -> u16 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
async fn rpc_client_request(port: u16, rpc_key: &[u8], request: RpcRequest) -> RpcResponse {
|
||||
let mut last_err = None;
|
||||
for _ in 0..20 {
|
||||
|
||||
@@ -0,0 +1,902 @@
|
||||
//! Explicit local shared-instance admission for applications that require RPC.
|
||||
//!
|
||||
//! This is an opt-in application policy, not a change to Python-compatible
|
||||
//! automatic sharing. Packet IPC is not authenticated by upstream's protocol;
|
||||
//! RPC authenticates the control endpoint, not the identity of a packet socket.
|
||||
//! Both endpoints must be selected by the caller. Every reconnect revalidates
|
||||
//! RPC before resuming packet traffic. No local interface fallback is performed.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use rns_interface::hdlc::{self, HdlcDeframer};
|
||||
use rns_interface::traits::{InterfaceDirection, InterfaceHandle, InterfaceMode};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::lifecycle::ShutdownSignal;
|
||||
use crate::reticulum::{
|
||||
ReticulumConfig, ReticulumError, SharedInstanceRpcEndpoint, SharedInstanceType,
|
||||
};
|
||||
use crate::rpc::{RpcError, RpcRequest, RpcResponse};
|
||||
|
||||
const ADMISSION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const CONTROL_CHECK_INTERVAL: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A local shared-service selector. TCP never accepts a remote host address.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SharedInstanceEndpoint {
|
||||
Tcp {
|
||||
packet_port: u16,
|
||||
control_port: u16,
|
||||
},
|
||||
/// Upstream abstract Unix socket name; supported on Linux and Android.
|
||||
Unix {
|
||||
instance_name: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl SharedInstanceEndpoint {
|
||||
pub fn validate(&self) -> Result<(), SharedInstanceError> {
|
||||
match self {
|
||||
Self::Tcp {
|
||||
packet_port,
|
||||
control_port,
|
||||
} if *packet_port == 0 || *control_port == 0 || packet_port == control_port => {
|
||||
Err(SharedInstanceError::InvalidEndpoint)
|
||||
}
|
||||
Self::Unix { instance_name } => {
|
||||
if instance_name.is_empty()
|
||||
|| instance_name.len() > 64
|
||||
|| !instance_name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
|
||||
{
|
||||
return Err(SharedInstanceError::InvalidEndpoint);
|
||||
}
|
||||
if !cfg!(any(target_os = "linux", target_os = "android")) {
|
||||
return Err(SharedInstanceError::UnsupportedCarrier);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&self, config: &mut ReticulumConfig) {
|
||||
config.share_instance = true;
|
||||
match self {
|
||||
Self::Tcp {
|
||||
packet_port,
|
||||
control_port,
|
||||
} => {
|
||||
config.shared_instance_type = SharedInstanceType::Tcp;
|
||||
config.shared_instance_port = *packet_port;
|
||||
config.control_port = *control_port;
|
||||
}
|
||||
Self::Unix { instance_name } => {
|
||||
config.shared_instance_type = SharedInstanceType::Unix;
|
||||
config.instance_name = instance_name.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_config(config: &ReticulumConfig) -> Self {
|
||||
match config.shared_instance_type {
|
||||
SharedInstanceType::Tcp => Self::Tcp {
|
||||
packet_port: config.shared_instance_port,
|
||||
control_port: config.control_port,
|
||||
},
|
||||
SharedInstanceType::Unix => Self::Unix {
|
||||
instance_name: config.instance_name.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory authorization material. Debug output deliberately excludes keys.
|
||||
#[derive(Clone)]
|
||||
pub struct SharedInstanceCredentials {
|
||||
endpoint: SharedInstanceEndpoint,
|
||||
rpc_key: Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SharedInstanceCredentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("SharedInstanceCredentials")
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("rpc_key", &"[redacted]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SharedInstanceCredentials {
|
||||
/// Keys are opaque HMAC bytes, not necessarily the default 32-byte hash.
|
||||
pub fn new(
|
||||
endpoint: SharedInstanceEndpoint,
|
||||
rpc_key: Vec<u8>,
|
||||
) -> Result<Self, SharedInstanceError> {
|
||||
let rpc_key = Zeroizing::new(rpc_key);
|
||||
endpoint.validate()?;
|
||||
if rpc_key.is_empty() || rpc_key.len() > 1024 {
|
||||
return Err(SharedInstanceError::InvalidKey);
|
||||
}
|
||||
Ok(Self { endpoint, rpc_key })
|
||||
}
|
||||
|
||||
pub fn endpoint(&self) -> &SharedInstanceEndpoint {
|
||||
&self.endpoint
|
||||
}
|
||||
|
||||
pub(crate) fn apply(&self, config: &mut ReticulumConfig) {
|
||||
self.endpoint.apply(config);
|
||||
config.rpc_key = Some(self.rpc_key.to_vec());
|
||||
}
|
||||
|
||||
/// Test packet availability and authenticated interface-status RPC without
|
||||
/// starting a Reticulum runtime or persisting the credential.
|
||||
pub async fn test(&self) -> Result<(), SharedInstanceError> {
|
||||
self.connect().await.map(|_| ())
|
||||
}
|
||||
|
||||
async fn check_control(&self) -> Result<(), SharedInstanceError> {
|
||||
let request = RpcRequest::GetInterfaceStats;
|
||||
let result = match &self.endpoint {
|
||||
SharedInstanceEndpoint::Tcp { control_port, .. } => {
|
||||
crate::rpc::connect_and_request(
|
||||
*control_port,
|
||||
&self.rpc_key,
|
||||
&request,
|
||||
ADMISSION_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
}
|
||||
SharedInstanceEndpoint::Unix { instance_name } => {
|
||||
crate::rpc::connect_unix_and_request(
|
||||
&format!("\0rns/{instance_name}/rpc"),
|
||||
&self.rpc_key,
|
||||
&request,
|
||||
ADMISSION_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(RpcResponse::InterfaceStats(_)) => Ok(()),
|
||||
Ok(_) => Err(SharedInstanceError::UnsupportedControl),
|
||||
Err(RpcError::AuthFailed) => Err(SharedInstanceError::AuthenticationRejected),
|
||||
Err(_) => Err(SharedInstanceError::ControlUnavailable),
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(&self) -> Result<PacketStream, SharedInstanceError> {
|
||||
self.endpoint.validate()?;
|
||||
tokio::time::timeout(ADMISSION_TIMEOUT, async {
|
||||
let stream: PacketStream = match &self.endpoint {
|
||||
SharedInstanceEndpoint::Tcp { packet_port, .. } => {
|
||||
let stream = tokio::net::TcpStream::connect((
|
||||
std::net::Ipv4Addr::LOCALHOST,
|
||||
*packet_port,
|
||||
))
|
||||
.await
|
||||
.map_err(|_| SharedInstanceError::PacketUnavailable)?;
|
||||
stream
|
||||
.set_nodelay(true)
|
||||
.map_err(|_| SharedInstanceError::PacketUnavailable)?;
|
||||
Box::new(stream)
|
||||
}
|
||||
SharedInstanceEndpoint::Unix { instance_name } => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
Box::new(
|
||||
crate::rpc::connect_unix_stream(&format!("\0rns/{instance_name}"))
|
||||
.await
|
||||
.map_err(|_| SharedInstanceError::PacketUnavailable)?,
|
||||
)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = instance_name;
|
||||
return Err(SharedInstanceError::UnsupportedCarrier);
|
||||
}
|
||||
}
|
||||
};
|
||||
self.check_control().await?;
|
||||
Ok(stream)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SharedInstanceError::TimedOut)?
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt-in ownership policy. `Configured` preserves existing library behavior.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub enum InstancePolicy {
|
||||
#[default]
|
||||
Configured,
|
||||
Standalone,
|
||||
/// Bind both configured local listeners or fail; never become a client.
|
||||
SharedOwner,
|
||||
/// Bind an explicitly selected local endpoint pair, without rewriting config.
|
||||
SharedOwnerAt(SharedInstanceEndpoint),
|
||||
/// Require both selected endpoints; never start local interfaces.
|
||||
SharedClient(SharedInstanceCredentials),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SharedInstanceState {
|
||||
Ready,
|
||||
Reconnecting,
|
||||
AuthenticationRejected,
|
||||
ControlUnavailable,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// Bounded, credential-free shared admission failures.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum SharedInstanceError {
|
||||
#[error("invalid local shared-instance endpoint")]
|
||||
InvalidEndpoint,
|
||||
#[error("RPC key must contain 1 to 1024 bytes")]
|
||||
InvalidKey,
|
||||
#[error("this shared-instance carrier is not supported on this platform")]
|
||||
UnsupportedCarrier,
|
||||
#[error("the shared packet service is unavailable")]
|
||||
PacketUnavailable,
|
||||
#[error("the shared control service is unavailable")]
|
||||
ControlUnavailable,
|
||||
#[error("the shared instance rejected the RPC key")]
|
||||
AuthenticationRejected,
|
||||
#[error("the shared instance cannot supply interface status")]
|
||||
UnsupportedControl,
|
||||
#[error("shared-instance connection timed out")]
|
||||
TimedOut,
|
||||
#[error("shared-instance startup was cancelled")]
|
||||
Cancelled,
|
||||
#[error("the shared packet endpoint is already occupied or cannot be bound")]
|
||||
PacketBindFailed,
|
||||
#[error("the shared control endpoint is already occupied or cannot be bound")]
|
||||
ControlBindFailed,
|
||||
}
|
||||
|
||||
/// Policy startup errors are additive; the existing `ReticulumError` stays intact.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum InstanceStartupError {
|
||||
#[error(transparent)]
|
||||
Runtime(#[from] ReticulumError),
|
||||
#[error(transparent)]
|
||||
Shared(#[from] SharedInstanceError),
|
||||
}
|
||||
|
||||
trait AsyncPacketStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncPacketStream for T {}
|
||||
type PacketStream = Box<dyn AsyncPacketStream>;
|
||||
|
||||
pub(crate) async fn spawn_authenticated_client(
|
||||
credentials: SharedInstanceCredentials,
|
||||
id: u64,
|
||||
transport: mpsc::Sender<TransportMessage>,
|
||||
shutdown: ShutdownSignal,
|
||||
) -> Result<(InterfaceHandle, watch::Receiver<SharedInstanceState>), SharedInstanceError> {
|
||||
let initial = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => return Err(SharedInstanceError::Cancelled),
|
||||
result = credentials.connect() => result?,
|
||||
};
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let rxb = Arc::new(AtomicU64::new(0));
|
||||
let txb = Arc::new(AtomicU64::new(0));
|
||||
let (tx, mut rx) = mpsc::channel::<Bytes>(64);
|
||||
let (status_tx, status) = watch::channel(SharedInstanceState::Ready);
|
||||
let task_online = online.clone();
|
||||
let task_rxb = rxb.clone();
|
||||
let task_txb = txb.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let mut stream = initial;
|
||||
loop {
|
||||
let failure = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => break,
|
||||
_ = packet_loop(&mut stream, &mut rx, id, &transport, &task_rxb, &task_txb) => SharedInstanceError::PacketUnavailable,
|
||||
error = control_watchdog(&credentials) => error,
|
||||
};
|
||||
drop(stream);
|
||||
task_online.store(false, Ordering::SeqCst);
|
||||
let mut last_failure = failure;
|
||||
let mut delay = 1;
|
||||
loop {
|
||||
let state = match last_failure {
|
||||
SharedInstanceError::AuthenticationRejected => {
|
||||
SharedInstanceState::AuthenticationRejected
|
||||
}
|
||||
SharedInstanceError::ControlUnavailable
|
||||
| SharedInstanceError::UnsupportedControl => {
|
||||
SharedInstanceState::ControlUnavailable
|
||||
}
|
||||
_ => SharedInstanceState::Reconnecting,
|
||||
};
|
||||
status_tx.send_replace(state);
|
||||
// No stale outbound packets may cross an owner restart. Higher
|
||||
// protocol layers own retry; keep bounded backpressure while offline.
|
||||
let wait = tokio::time::sleep(Duration::from_secs(delay));
|
||||
tokio::pin!(wait);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => return finish_client(&task_online, &status_tx),
|
||||
_ = &mut wait => break,
|
||||
data = rx.recv() => if data.is_none() { return finish_client(&task_online, &status_tx); },
|
||||
}
|
||||
}
|
||||
while rx.try_recv().is_ok() {}
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => return finish_client(&task_online, &status_tx),
|
||||
result = credentials.connect() => result,
|
||||
};
|
||||
match result {
|
||||
Ok(connected) => {
|
||||
while rx.try_recv().is_ok() {}
|
||||
stream = connected;
|
||||
task_online.store(true, Ordering::SeqCst);
|
||||
status_tx.send_replace(SharedInstanceState::Ready);
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
last_failure = error;
|
||||
delay = (delay * 2).min(30);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_client(&task_online, &status_tx);
|
||||
});
|
||||
Ok((
|
||||
InterfaceHandle {
|
||||
id,
|
||||
parent_id: None,
|
||||
name: "Authenticated shared instance".to_string(),
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: rns_interface::traits::optimise_mtu(1_000_000_000).unwrap_or(262_144),
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
},
|
||||
status,
|
||||
))
|
||||
}
|
||||
|
||||
fn finish_client(online: &AtomicBool, status: &watch::Sender<SharedInstanceState>) {
|
||||
online.store(false, Ordering::SeqCst);
|
||||
status.send_replace(SharedInstanceState::Stopped);
|
||||
}
|
||||
|
||||
async fn control_watchdog(credentials: &SharedInstanceCredentials) -> SharedInstanceError {
|
||||
loop {
|
||||
tokio::time::sleep(CONTROL_CHECK_INTERVAL).await;
|
||||
match tokio::time::timeout(ADMISSION_TIMEOUT, credentials.check_control()).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => return error,
|
||||
Err(_) => return SharedInstanceError::ControlUnavailable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn packet_loop(
|
||||
stream: &mut PacketStream,
|
||||
outbound: &mut mpsc::Receiver<Bytes>,
|
||||
id: u64,
|
||||
transport: &mpsc::Sender<TransportMessage>,
|
||||
rxb: &AtomicU64,
|
||||
txb: &AtomicU64,
|
||||
) -> std::io::Result<()> {
|
||||
let (mut reader, mut writer) = tokio::io::split(stream);
|
||||
let mut buf = [0; 8192];
|
||||
let mut deframer = HdlcDeframer::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
read = reader.read(&mut buf) => {
|
||||
let size = read?;
|
||||
if size == 0 { return Ok(()); }
|
||||
rxb.fetch_add(size as u64, Ordering::Relaxed);
|
||||
for frame in deframer.feed(&buf[..size]) {
|
||||
if transport.send(TransportMessage::Inbound(InboundPacket {
|
||||
raw: Bytes::from(frame), interface_id: id, rssi: None, snr: None, q: None,
|
||||
})).await.is_err() { return Ok(()); }
|
||||
}
|
||||
}
|
||||
data = outbound.recv() => {
|
||||
let Some(data) = data else { return Ok(()); };
|
||||
let framed = hdlc::frame(&data);
|
||||
writer.write_all(&framed).await?;
|
||||
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum BoundControlListener {
|
||||
Tcp(tokio::net::TcpListener),
|
||||
#[cfg(unix)]
|
||||
Unix(tokio::net::UnixListener, String),
|
||||
}
|
||||
|
||||
impl BoundControlListener {
|
||||
pub(crate) async fn bind(
|
||||
config: &ReticulumConfig,
|
||||
socket_base: &Path,
|
||||
) -> Result<Self, SharedInstanceError> {
|
||||
SharedInstanceEndpoint::from_config(config).validate()?;
|
||||
match config.shared_rpc_endpoint(socket_base) {
|
||||
SharedInstanceRpcEndpoint::Tcp(port) => {
|
||||
tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port))
|
||||
.await
|
||||
.map(Self::Tcp)
|
||||
.map_err(|_| SharedInstanceError::ControlBindFailed)
|
||||
}
|
||||
SharedInstanceRpcEndpoint::Unix(path) => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
crate::rpc_server::bind_unix_rpc_listener(&path)
|
||||
.map(|listener| Self::Unix(listener, path))
|
||||
.map_err(|_| SharedInstanceError::ControlBindFailed)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
Err(SharedInstanceError::UnsupportedCarrier)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
self,
|
||||
key: Vec<u8>,
|
||||
transport: mpsc::Sender<TransportMessage>,
|
||||
shutdown: ShutdownSignal,
|
||||
) {
|
||||
let result = match self {
|
||||
Self::Tcp(listener) => {
|
||||
crate::rpc_server::run_rpc_server_with_listener(listener, key, transport, shutdown)
|
||||
.await
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Self::Unix(listener, path) => {
|
||||
crate::rpc_server::run_unix_rpc_server_with_listener(
|
||||
listener, path, key, transport, shutdown,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
tracing::warn!("owned shared control listener stopped");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::reticulum::{self, InitOptions, InstanceMode, ReticulumHandle};
|
||||
use rns_transport::messages::{TransportQuery, TransportQueryResponse};
|
||||
|
||||
struct TestConfig(std::path::PathBuf);
|
||||
impl TestConfig {
|
||||
fn new(packet: u16, control: u16, key: u8) -> Self {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"rns-strict-sharing-{}-{}",
|
||||
std::process::id(),
|
||||
hex::encode(rns_crypto::random::random_bytes(12))
|
||||
));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
std::fs::write(dir.join("config"), format!(
|
||||
"[reticulum]\nshare_instance = Yes\nshared_instance_type = tcp\nshared_instance_port = {packet}\ninstance_control_port = {control}\nrpc_key = {}\n[interfaces]\n",
|
||||
hex::encode([key; 32]))).unwrap();
|
||||
Self(dir)
|
||||
}
|
||||
async fn start(
|
||||
&self,
|
||||
policy: InstancePolicy,
|
||||
) -> Result<ReticulumHandle, InstanceStartupError> {
|
||||
reticulum::init_with_policy(
|
||||
self.0.to_str(),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
InitOptions::default(),
|
||||
Default::default(),
|
||||
policy,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
impl Drop for TestConfig {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
fn ports() -> (u16, u16) {
|
||||
let a = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let b = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
(
|
||||
a.local_addr().unwrap().port(),
|
||||
b.local_addr().unwrap().port(),
|
||||
)
|
||||
}
|
||||
fn credentials(packet_port: u16, control_port: u16, key: u8) -> SharedInstanceCredentials {
|
||||
SharedInstanceCredentials::new(
|
||||
SharedInstanceEndpoint::Tcp {
|
||||
packet_port,
|
||||
control_port,
|
||||
},
|
||||
vec![key; 32],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
async fn await_state(handle: &ReticulumHandle, expected: SharedInstanceState) {
|
||||
tokio::time::timeout(Duration::from_secs(12), async {
|
||||
while handle.shared_instance_state() != Some(expected) {
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_endpoint_and_secret_validation() {
|
||||
assert_eq!(
|
||||
SharedInstanceEndpoint::Tcp {
|
||||
packet_port: 0,
|
||||
control_port: 1
|
||||
}
|
||||
.validate(),
|
||||
Err(SharedInstanceError::InvalidEndpoint)
|
||||
);
|
||||
assert_eq!(
|
||||
SharedInstanceEndpoint::Tcp {
|
||||
packet_port: 1,
|
||||
control_port: 1
|
||||
}
|
||||
.validate(),
|
||||
Err(SharedInstanceError::InvalidEndpoint)
|
||||
);
|
||||
assert_eq!(
|
||||
SharedInstanceEndpoint::Unix {
|
||||
instance_name: "../other".into()
|
||||
}
|
||||
.validate(),
|
||||
Err(SharedInstanceError::InvalidEndpoint)
|
||||
);
|
||||
let key = SharedInstanceCredentials::new(
|
||||
SharedInstanceEndpoint::Tcp {
|
||||
packet_port: 1,
|
||||
control_port: 2,
|
||||
},
|
||||
vec![0x8a; 17],
|
||||
)
|
||||
.unwrap();
|
||||
assert!(format!("{key:?}").contains("[redacted]"));
|
||||
assert!(!format!("{key:?}").contains("138"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_owner_packet_conflict_releases_control_and_never_joins() {
|
||||
let packet = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (_, control) = ports();
|
||||
let config = TestConfig::new(packet.local_addr().unwrap().port(), control, 1);
|
||||
assert!(matches!(
|
||||
config.start(InstancePolicy::SharedOwner).await,
|
||||
Err(InstanceStartupError::Shared(
|
||||
SharedInstanceError::PacketBindFailed
|
||||
))
|
||||
));
|
||||
let _control = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, control))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), packet.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_owner_control_conflict_does_not_open_packet_listener() {
|
||||
let control = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (packet, _) = ports();
|
||||
let config = TestConfig::new(packet, control.local_addr().unwrap().port(), 1);
|
||||
assert!(matches!(
|
||||
config.start(InstancePolicy::SharedOwner).await,
|
||||
Err(InstanceStartupError::Shared(
|
||||
SharedInstanceError::ControlBindFailed
|
||||
))
|
||||
));
|
||||
let _packet = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, packet))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_auth_failure_never_returns_client_or_starts_interfaces() {
|
||||
let (packet, control) = ports();
|
||||
let owner_config = TestConfig::new(packet, control, 1);
|
||||
let owner = owner_config
|
||||
.start(InstancePolicy::SharedOwner)
|
||||
.await
|
||||
.unwrap();
|
||||
let client_config = TestConfig::new(packet, control, 2);
|
||||
let error = client_config
|
||||
.start(InstancePolicy::SharedClient(credentials(
|
||||
packet, control, 2,
|
||||
)))
|
||||
.await;
|
||||
assert!(matches!(
|
||||
error,
|
||||
Err(InstanceStartupError::Shared(
|
||||
SharedInstanceError::AuthenticationRejected
|
||||
))
|
||||
));
|
||||
// An ordinary managed node remains usable after rejecting the shared key.
|
||||
let standalone = client_config
|
||||
.start(InstancePolicy::Standalone)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(standalone.instance_mode, InstanceMode::Standalone);
|
||||
standalone.shutdown_and_wait().await;
|
||||
owner.shutdown_and_wait().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_client_reauthenticates_restart_and_rejects_runtime_spawns() {
|
||||
let (packet, control) = ports();
|
||||
let owner_config = TestConfig::new(packet, control, 1);
|
||||
let owner = owner_config
|
||||
.start(InstancePolicy::SharedOwner)
|
||||
.await
|
||||
.unwrap();
|
||||
let client_config = TestConfig::new(packet, control, 2);
|
||||
let client = client_config
|
||||
.start(InstancePolicy::SharedClient(credentials(
|
||||
packet, control, 1,
|
||||
)))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(client.instance_mode, InstanceMode::Client);
|
||||
assert_eq!(
|
||||
client.shared_instance_state(),
|
||||
Some(SharedInstanceState::Ready)
|
||||
);
|
||||
assert!(matches!(
|
||||
client
|
||||
.query_control_result(TransportQuery::GetInterfaceStats)
|
||||
.await,
|
||||
Ok(TransportQueryResponse::InterfaceStats(_))
|
||||
));
|
||||
let tcp_error = reticulum::spawn_tcp_client_runtime(&client, "forbidden", "127.0.0.1", 9)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(tcp_error.contains("owned by the existing shared instance"));
|
||||
let auto_error = reticulum::spawn_auto_interface_runtime(
|
||||
&client,
|
||||
"forbidden",
|
||||
"reticulum",
|
||||
29716,
|
||||
42671,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(auto_error.contains("owned by the existing shared instance"));
|
||||
owner.shutdown_and_wait().await;
|
||||
let wrong_config = TestConfig::new(packet, control, 3);
|
||||
let wrong_owner = wrong_config
|
||||
.start(InstancePolicy::SharedOwner)
|
||||
.await
|
||||
.unwrap();
|
||||
await_state(&client, SharedInstanceState::AuthenticationRejected).await;
|
||||
wrong_owner.shutdown_and_wait().await;
|
||||
let restored_owner = owner_config
|
||||
.start(InstancePolicy::SharedOwner)
|
||||
.await
|
||||
.unwrap();
|
||||
await_state(&client, SharedInstanceState::Ready).await;
|
||||
client.shutdown_and_wait().await;
|
||||
restored_owner.shutdown_and_wait().await;
|
||||
// Both owner listeners are gone when shutdown returns.
|
||||
let _packet = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, packet))
|
||||
.await
|
||||
.unwrap();
|
||||
let _control = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, control))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn read_reports_closed_connection(result: std::io::Result<usize>) -> bool {
|
||||
match result {
|
||||
Ok(0) => true,
|
||||
// Windows can report abortive peer closure as WSAECONNRESET rather
|
||||
// than EOF. Both prove closure; data, timeouts and other errors do not.
|
||||
Err(error) => error.kind() == std::io::ErrorKind::ConnectionReset,
|
||||
Ok(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_connection_closed(stream: &mut tokio::net::TcpStream) {
|
||||
let result = tokio::time::timeout(Duration::from_secs(2), stream.read(&mut [0]))
|
||||
.await
|
||||
.expect("unauthenticated connection must close promptly");
|
||||
assert!(read_reports_closed_connection(result));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_closure_assertion_rejects_data_and_unrelated_errors() {
|
||||
assert!(read_reports_closed_connection(Ok(0)));
|
||||
assert!(read_reports_closed_connection(Err(
|
||||
std::io::ErrorKind::ConnectionReset.into()
|
||||
)));
|
||||
assert!(!read_reports_closed_connection(Ok(1)));
|
||||
for kind in [
|
||||
std::io::ErrorKind::TimedOut,
|
||||
std::io::ErrorKind::WouldBlock,
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
] {
|
||||
assert!(!read_reports_closed_connection(Err(kind.into())));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_or_silent_rpc_drops_unauthenticated_packet_connection() {
|
||||
let packet = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let (_, control_port) = ports();
|
||||
let credentials = credentials(packet.local_addr().unwrap().port(), control_port, 1);
|
||||
assert_eq!(
|
||||
credentials.test().await,
|
||||
Err(SharedInstanceError::ControlUnavailable)
|
||||
);
|
||||
let (mut stream, _) = packet.accept().await.unwrap();
|
||||
assert_connection_closed(&mut stream).await;
|
||||
|
||||
let control = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, control_port))
|
||||
.await
|
||||
.unwrap();
|
||||
let test = tokio::spawn(async move { credentials.test().await });
|
||||
let (mut stream, _) = packet.accept().await.unwrap();
|
||||
let (mut silent_control, _) = control.accept().await.unwrap();
|
||||
assert!(matches!(
|
||||
test.await.unwrap(),
|
||||
Err(SharedInstanceError::TimedOut | SharedInstanceError::ControlUnavailable)
|
||||
));
|
||||
assert_connection_closed(&mut stream).await;
|
||||
assert_connection_closed(&mut silent_control).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_admission_closes_both_connections() {
|
||||
let packet = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let control = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let credentials = credentials(
|
||||
packet.local_addr().unwrap().port(),
|
||||
control.local_addr().unwrap().port(),
|
||||
1,
|
||||
);
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let task_shutdown = shutdown.clone();
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let task = tokio::spawn(async move {
|
||||
spawn_authenticated_client(credentials, 1, tx, task_shutdown).await
|
||||
});
|
||||
let (mut packet, _) = packet.accept().await.unwrap();
|
||||
let (mut control, _) = control.accept().await.unwrap();
|
||||
shutdown.trigger();
|
||||
assert!(matches!(
|
||||
task.await.unwrap(),
|
||||
Err(SharedInstanceError::Cancelled)
|
||||
));
|
||||
assert_connection_closed(&mut packet).await;
|
||||
assert_connection_closed(&mut control).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_owner_selectors_are_in_memory_and_reusable_after_shutdown() {
|
||||
let (packet_port, control_port) = ports();
|
||||
let config = TestConfig::new(1, 2, 1);
|
||||
let original = std::fs::read(config.0.join("config")).unwrap();
|
||||
let endpoint = SharedInstanceEndpoint::Tcp {
|
||||
packet_port,
|
||||
control_port,
|
||||
};
|
||||
let owner = config
|
||||
.start(InstancePolicy::SharedOwnerAt(endpoint.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
SharedInstanceCredentials::new(endpoint, vec![1; 32])
|
||||
.unwrap()
|
||||
.test()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(config.0.join("config")).unwrap(), original);
|
||||
owner.shutdown_and_wait().await;
|
||||
let _packet = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, packet_port))
|
||||
.await
|
||||
.unwrap();
|
||||
let _control = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, control_port))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
#[tokio::test]
|
||||
async fn abstract_unix_owner_and_authenticated_client_roundtrip() {
|
||||
let config = TestConfig::new(1, 2, 1);
|
||||
let endpoint = SharedInstanceEndpoint::Unix {
|
||||
instance_name: format!(
|
||||
"strict-test-{}",
|
||||
hex::encode(rns_crypto::random::random_bytes(12))
|
||||
),
|
||||
};
|
||||
let owner = config
|
||||
.start(InstancePolicy::SharedOwnerAt(endpoint.clone()))
|
||||
.await
|
||||
.unwrap();
|
||||
let client_config = TestConfig::new(3, 4, 9);
|
||||
let credentials = SharedInstanceCredentials::new(endpoint, vec![1; 32]).unwrap();
|
||||
credentials.test().await.unwrap();
|
||||
let client = client_config
|
||||
.start(InstancePolicy::SharedClient(credentials))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
client.shared_instance_state(),
|
||||
Some(SharedInstanceState::Ready)
|
||||
);
|
||||
assert!(matches!(
|
||||
client
|
||||
.query_control_result(TransportQuery::GetInterfaceStats)
|
||||
.await,
|
||||
Ok(TransportQueryResponse::InterfaceStats(_))
|
||||
));
|
||||
client.shutdown_and_wait().await;
|
||||
owner.shutdown_and_wait().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn occupied_auto_port_is_reported_without_breaking_tcp() {
|
||||
let auto = std::net::UdpSocket::bind("[::]:0").unwrap();
|
||||
let data_port = auto.local_addr().unwrap().port();
|
||||
let (tcp_port, _) = ports();
|
||||
let config = TestConfig::new(1, 2, 1);
|
||||
std::fs::write(config.0.join("config"), format!(
|
||||
"[reticulum]\nshare_instance = No\n[interfaces]\n[[LAN]]\ntype = AutoInterface\nenabled = Yes\ndata_port = {data_port}\n[[TCP]]\ntype = TCPServerInterface\nenabled = Yes\nlisten_ip = 127.0.0.1\nlisten_port = {tcp_port}\n"
|
||||
)).unwrap();
|
||||
let runtime = config.start(InstancePolicy::Standalone).await.unwrap();
|
||||
assert_eq!(runtime.startup_interface_failures().len(), 1);
|
||||
assert_eq!(runtime.startup_interface_failures()[0].0, "LAN");
|
||||
assert!(
|
||||
runtime.startup_interface_failures()[0]
|
||||
.1
|
||||
.contains("socket bind")
|
||||
);
|
||||
let _tcp = tokio::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, tcp_port))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(auto.local_addr().unwrap().port(), data_port);
|
||||
runtime.shutdown_and_wait().await;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
[package]
|
||||
name = "rns-tools"
|
||||
description = "Rust CLI utilities for Reticulum (rnsd-rs, rnstatus-rs, etc.)"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -24,10 +24,10 @@ use rns_transport::messages::{OutboundRequest, TransportMessage};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
fn expand_tilde(p: &str) -> PathBuf {
|
||||
if let Some(rest) = p.strip_prefix("~/") {
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
return PathBuf::from(home).join(rest);
|
||||
}
|
||||
if let Some(rest) = p.strip_prefix("~/")
|
||||
&& let Some(home) = std::env::var_os("HOME")
|
||||
{
|
||||
return PathBuf::from(home).join(rest);
|
||||
}
|
||||
PathBuf::from(p)
|
||||
}
|
||||
@@ -171,16 +171,16 @@ fn load_or_create_identity(
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
if let Some(parent) = path.parent() {
|
||||
if let Err(e) = std::fs::create_dir_all(parent) {
|
||||
return Err((
|
||||
2,
|
||||
format!(
|
||||
"Could not create identity directory \"{}\": {e}",
|
||||
parent.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some(parent) = path.parent()
|
||||
&& let Err(e) = std::fs::create_dir_all(parent)
|
||||
{
|
||||
return Err((
|
||||
2,
|
||||
format!(
|
||||
"Could not create identity directory \"{}\": {e}",
|
||||
parent.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
let id = Identity::new();
|
||||
if let Err(e) = id.to_file(&path) {
|
||||
@@ -616,11 +616,11 @@ async fn run_listen(args: Args) -> ! {
|
||||
}
|
||||
|
||||
let fetch_jail = args.jail.as_deref().map(expand_tilde);
|
||||
if let Some(ref jail) = fetch_jail {
|
||||
if !jail.is_dir() {
|
||||
eprintln!("Fetch jail directory not found: {}", jail.display());
|
||||
process::exit(3);
|
||||
}
|
||||
if let Some(ref jail) = fetch_jail
|
||||
&& !jail.is_dir()
|
||||
{
|
||||
eprintln!("Fetch jail directory not found: {}", jail.display());
|
||||
process::exit(3);
|
||||
}
|
||||
|
||||
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::<RncpEvent>(64);
|
||||
|
||||
@@ -561,29 +561,27 @@ fn import_private_identity(input: &str) -> Result<Identity, (u8, String)> {
|
||||
|
||||
fn decode_import_identity_data(input: &str, expected_len: usize) -> Option<Vec<u8>> {
|
||||
let path = Path::new(input);
|
||||
if path.is_file() {
|
||||
if let Ok(data) = std::fs::read(path) {
|
||||
if data.len() == expected_len {
|
||||
return Some(data);
|
||||
}
|
||||
}
|
||||
if path.is_file()
|
||||
&& let Ok(data) = std::fs::read(path)
|
||||
&& data.len() == expected_len
|
||||
{
|
||||
return Some(data);
|
||||
}
|
||||
if input.len() == expected_len * 2 {
|
||||
if let Ok(data) = hex::decode(input) {
|
||||
if data.len() == expected_len {
|
||||
return Some(data);
|
||||
}
|
||||
}
|
||||
if input.len() == expected_len * 2
|
||||
&& let Ok(data) = hex::decode(input)
|
||||
&& data.len() == expected_len
|
||||
{
|
||||
return Some(data);
|
||||
}
|
||||
if let Ok(data) = decode_base32(input) {
|
||||
if data.len() == expected_len {
|
||||
return Some(data);
|
||||
}
|
||||
if let Ok(data) = decode_base32(input)
|
||||
&& data.len() == expected_len
|
||||
{
|
||||
return Some(data);
|
||||
}
|
||||
if let Ok(data) = URL_SAFE.decode(input) {
|
||||
if data.len() == expected_len {
|
||||
return Some(data);
|
||||
}
|
||||
if let Ok(data) = URL_SAFE.decode(input)
|
||||
&& data.len() == expected_len
|
||||
{
|
||||
return Some(data);
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -1882,7 +1880,7 @@ fn encode_base32(bytes: &[u8]) -> String {
|
||||
let index = ((buffer << (5 - bits)) & 0x1f) as usize;
|
||||
out.push(ALPHABET[index] as char);
|
||||
}
|
||||
while out.len() % 8 != 0 {
|
||||
while !out.len().is_multiple_of(8) {
|
||||
out.push('=');
|
||||
}
|
||||
out
|
||||
|
||||
@@ -991,10 +991,10 @@ mod tests {
|
||||
|
||||
impl FrameSession for ScriptedSession {
|
||||
fn send(&mut self, frame: &rnode_admin::AdminFrame) -> Result<(), String> {
|
||||
if let Some((index, message)) = self.fail_send_at {
|
||||
if self.sent.len() == index {
|
||||
return Err(message.to_string());
|
||||
}
|
||||
if let Some((index, message)) = self.fail_send_at
|
||||
&& self.sent.len() == index
|
||||
{
|
||||
return Err(message.to_string());
|
||||
}
|
||||
self.sent.push(frame.clone());
|
||||
Ok(())
|
||||
|
||||
@@ -208,10 +208,10 @@ fn md5_digest(input: &[u8]) -> [u8; 16] {
|
||||
let mut c0 = 0x98badcfeu32;
|
||||
let mut d0 = 0x10325476u32;
|
||||
|
||||
for chunk in msg.chunks_exact(64) {
|
||||
for chunk in msg.as_chunks::<64>().0 {
|
||||
let mut m = [0u32; 16];
|
||||
for (i, word) in chunk.chunks_exact(4).enumerate() {
|
||||
m[i] = u32::from_le_bytes(word.try_into().unwrap());
|
||||
for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() {
|
||||
m[i] = u32::from_le_bytes(*word);
|
||||
}
|
||||
|
||||
let mut a = a0;
|
||||
|
||||
@@ -133,31 +133,33 @@ fn validate_wifi_inputs(args: &Args) -> Result<(), String> {
|
||||
_ => return Err("WiFi mode must be OFF, AP or STATION".to_string()),
|
||||
}
|
||||
}
|
||||
if let Some(channel) = args.channel {
|
||||
if !(1..=14).contains(&channel) {
|
||||
return Err("WiFi channel must be in 1..=14".to_string());
|
||||
}
|
||||
if let Some(channel) = args.channel
|
||||
&& !(1..=14).contains(&channel)
|
||||
{
|
||||
return Err("WiFi channel must be in 1..=14".to_string());
|
||||
}
|
||||
if let Some(ssid) = args.ssid.as_deref() {
|
||||
if !ssid.eq_ignore_ascii_case("none") && ssid.len() > 32 {
|
||||
return Err("WiFi SSID must be at most 32 bytes".to_string());
|
||||
}
|
||||
if let Some(ssid) = args.ssid.as_deref()
|
||||
&& !ssid.eq_ignore_ascii_case("none")
|
||||
&& ssid.len() > 32
|
||||
{
|
||||
return Err("WiFi SSID must be at most 32 bytes".to_string());
|
||||
}
|
||||
if let Some(psk) = args.psk.as_deref() {
|
||||
if !psk.eq_ignore_ascii_case("none") && !(8..=32).contains(&psk.len()) {
|
||||
return Err("WiFi PSK must be 8 to 32 bytes, or NONE".to_string());
|
||||
}
|
||||
if let Some(psk) = args.psk.as_deref()
|
||||
&& !psk.eq_ignore_ascii_case("none")
|
||||
&& !(8..=32).contains(&psk.len())
|
||||
{
|
||||
return Err("WiFi PSK must be 8 to 32 bytes, or NONE".to_string());
|
||||
}
|
||||
for (name, value) in [
|
||||
("IP address", args.ip.as_deref()),
|
||||
("netmask", args.nm.as_deref()),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
if !value.eq_ignore_ascii_case("none") {
|
||||
value
|
||||
.parse::<Ipv4Addr>()
|
||||
.map_err(|error| format!("invalid WiFi {name} {value}: {error}"))?;
|
||||
}
|
||||
if let Some(value) = value
|
||||
&& !value.eq_ignore_ascii_case("none")
|
||||
{
|
||||
value
|
||||
.parse::<Ipv4Addr>()
|
||||
.map_err(|error| format!("invalid WiFi {name} {value}: {error}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -1155,13 +1155,13 @@ async fn run_remote(args: Args) -> ExitCode {
|
||||
};
|
||||
req_args.push(rmpv::Value::Binary(dest.to_vec()));
|
||||
}
|
||||
if args.table {
|
||||
if let Some(m) = args.max {
|
||||
if args.destination.is_none() {
|
||||
req_args.push(rmpv::Value::Nil);
|
||||
}
|
||||
req_args.push(rmpv::Value::from(m));
|
||||
if args.table
|
||||
&& let Some(m) = args.max
|
||||
{
|
||||
if args.destination.is_none() {
|
||||
req_args.push(rmpv::Value::Nil);
|
||||
}
|
||||
req_args.push(rmpv::Value::from(m));
|
||||
}
|
||||
let req_value = rmpv::Value::Array(req_args);
|
||||
let mut payload = Vec::new();
|
||||
|
||||
@@ -25,7 +25,7 @@ use tokio::sync::mpsc;
|
||||
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
|
||||
const RNSH_PROTOCOL_VERSION: &str = "0.3.0";
|
||||
const APP_NAME: &str = "rnsh";
|
||||
const DEFAULT_SERVICE_NAME: &str = "default";
|
||||
const IDENTITY_HASH_HEX_LEN: usize = 32;
|
||||
@@ -883,7 +883,7 @@ mod tests {
|
||||
fn version_string_uses_rust_command_name() {
|
||||
assert_eq!(
|
||||
format!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
|
||||
format!("rnsh-rs {} (protocol 0.2.0)", env!("CARGO_PKG_VERSION"))
|
||||
format!("rnsh-rs {} (protocol 0.3.0)", env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -535,13 +535,13 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
println!(" IFAC : {} bits", entry.ifac_size * 8);
|
||||
}
|
||||
if args.announce_stats {
|
||||
if let Some(queued) = entry.announce_queue {
|
||||
if queued > 0 {
|
||||
println!(
|
||||
" Queued : {queued} announce{}",
|
||||
if queued == 1 { "" } else { "s" }
|
||||
);
|
||||
}
|
||||
if let Some(queued) = entry.announce_queue
|
||||
&& queued > 0
|
||||
{
|
||||
println!(
|
||||
" Queued : {queued} announce{}",
|
||||
if queued == 1 { "" } else { "s" }
|
||||
);
|
||||
}
|
||||
if entry.held_announces > 0 {
|
||||
println!(
|
||||
@@ -729,8 +729,8 @@ fn discovered_json(record: &DiscoveredInterface) -> serde_json::Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn finite_location(value: f64) -> Option<f64> {
|
||||
value.is_finite().then_some(value)
|
||||
fn finite_location(value: Option<f64>) -> Option<f64> {
|
||||
value.filter(|number| number.is_finite())
|
||||
}
|
||||
|
||||
fn print_discovered_summary(records: &[DiscoveredInterface]) {
|
||||
@@ -877,14 +877,18 @@ fn discovered_config_entry(record: &DiscoveredInterface) -> String {
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn location_summary(latitude: f64, longitude: f64, height: f64) -> String {
|
||||
if latitude == 0.0 && longitude == 0.0 {
|
||||
fn location_summary(latitude: Option<f64>, longitude: Option<f64>, height: Option<f64>) -> String {
|
||||
let latitude = finite_location(latitude);
|
||||
let longitude = finite_location(longitude);
|
||||
let height = finite_location(height);
|
||||
if latitude.is_none() && longitude.is_none() && height.is_none() {
|
||||
return "N/A".to_string();
|
||||
}
|
||||
if height != 0.0 {
|
||||
format!("{latitude:.4}, {longitude:.4}, {height:.0}m h")
|
||||
} else {
|
||||
format!("{latitude:.4}, {longitude:.4}")
|
||||
let latitude = latitude.map_or_else(|| "N/A".into(), |v| format!("{v:.4}"));
|
||||
let longitude = longitude.map_or_else(|| "N/A".into(), |v| format!("{v:.4}"));
|
||||
match height {
|
||||
Some(height) => format!("{latitude}, {longitude}, {height:.0}m h"),
|
||||
None => format!("{latitude}, {longitude}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1199,13 +1203,13 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
println!(" Blocked : {blocked}");
|
||||
}
|
||||
if args.announce_stats {
|
||||
if let Some(queued) = iface.announce_queue {
|
||||
if queued > 0 {
|
||||
println!(
|
||||
" Queued : {queued} announce{}",
|
||||
if queued == 1 { "" } else { "s" }
|
||||
);
|
||||
}
|
||||
if let Some(queued) = iface.announce_queue
|
||||
&& queued > 0
|
||||
{
|
||||
println!(
|
||||
" Queued : {queued} announce{}",
|
||||
if queued == 1 { "" } else { "s" }
|
||||
);
|
||||
}
|
||||
if iface.held_announces > 0 {
|
||||
println!(
|
||||
@@ -1459,6 +1463,41 @@ fn json_str(s: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_location_display_preserves_absence_and_real_zero() {
|
||||
assert_eq!(location_summary(None, None, None), "N/A");
|
||||
assert_eq!(
|
||||
location_summary(Some(0.0), Some(0.0), Some(0.0)),
|
||||
"0.0000, 0.0000, 0m h"
|
||||
);
|
||||
assert_eq!(
|
||||
location_summary(Some(0.0), None, Some(0.0)),
|
||||
"0.0000, N/A, 0m h"
|
||||
);
|
||||
assert_eq!(location_summary(None, None, Some(0.0)), "N/A, N/A, 0m h");
|
||||
assert_eq!(finite_location(None), None);
|
||||
assert_eq!(finite_location(Some(0.0)), Some(0.0));
|
||||
assert_eq!(finite_location(Some(f64::NAN)), None);
|
||||
let record = DiscoveredInterface {
|
||||
info: rns_transport::discovery::app_data::DiscoveryInfo {
|
||||
height: Some(0.0),
|
||||
..Default::default()
|
||||
},
|
||||
network_id: [0; 16],
|
||||
hops: 0,
|
||||
stamp_value: 14,
|
||||
stamp: vec![0; 32],
|
||||
discovered: 1,
|
||||
last_heard: 2,
|
||||
heard_count: 1,
|
||||
status: None,
|
||||
};
|
||||
let rendered = discovered_json(&record);
|
||||
assert!(rendered["latitude"].is_null());
|
||||
assert!(rendered["longitude"].is_null());
|
||||
assert_eq!(rendered["height"], 0.0);
|
||||
}
|
||||
|
||||
fn test_args() -> Args {
|
||||
Args {
|
||||
all: true,
|
||||
|
||||
@@ -6,8 +6,9 @@ pub mod hash;
|
||||
/// rsReticulum package version printed by CLI `--version` output.
|
||||
pub const RS_RETICULUM_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Python Reticulum version these tools track for CLI/protocol parity.
|
||||
pub const RETICULUM_COMPAT_VERSION: &str = "1.3.8";
|
||||
/// Python Reticulum release baseline exposed by compatibility-oriented CLI
|
||||
/// surfaces such as the `rnsd-rs` interactive console.
|
||||
pub const RETICULUM_COMPAT_VERSION: &str = "1.4.2";
|
||||
|
||||
/// Python 1.3.2 `[logging] logtimestamps` (Reticulum.py:459-461,
|
||||
/// RNS/__init__.py:85 default True): whether log lines carry a timestamp
|
||||
|
||||
@@ -65,7 +65,29 @@ fn wait_until_running(child: &mut Child, settle: Duration) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Sends a process signal after a settle period and asserts a clean exit. Retries once
|
||||
/// Being alive does not mean runtime initialization has finished. In particular,
|
||||
/// rnsd can already handle SIGTERM while it is still admitting interfaces.
|
||||
#[cfg(unix)]
|
||||
fn wait_for_ready_log(child: &mut Child, log: &Path, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if child.try_wait().expect("poll child readiness").is_some() {
|
||||
return false;
|
||||
}
|
||||
if fs::read_to_string(log)
|
||||
.is_ok_and(|text| text.contains("reticulum started in Standalone mode"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a process signal after observed readiness (or a settle period for the
|
||||
/// interactive listeners) and asserts a clean exit. The settle-only path retries once
|
||||
/// with a longer settle if the child died from the raw signal (exit by signal
|
||||
/// number): under full-workspace load the child can still be booting when the
|
||||
/// first signal lands, before its handler is registered. A real handler
|
||||
@@ -76,6 +98,7 @@ fn assert_signal_exits(
|
||||
name: &str,
|
||||
signal_name: &str,
|
||||
signal_number: i32,
|
||||
ready_log: Option<&Path>,
|
||||
) {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
@@ -83,13 +106,21 @@ fn assert_signal_exits(
|
||||
let last_attempt = settles.len() - 1;
|
||||
for (attempt, settle) in settles.into_iter().enumerate() {
|
||||
let mut child = spawn();
|
||||
if !wait_until_running(&mut child, settle) {
|
||||
let ready = match ready_log {
|
||||
Some(log) => wait_for_ready_log(&mut child, log, Duration::from_secs(20)),
|
||||
None => wait_until_running(&mut child, settle),
|
||||
};
|
||||
if !ready {
|
||||
let _ = child.kill();
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited before {signal_name}\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} did not become ready before {signal_name}\nstatus: {}\nstdout:\n{}\nstderr:\n{}\nreadiness log:\n{}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
ready_log
|
||||
.and_then(|log| fs::read_to_string(log).ok())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -113,16 +144,23 @@ fn assert_signal_exits(
|
||||
|
||||
match exit_status {
|
||||
Some(status) if status.success() => return,
|
||||
Some(status) if attempt < last_attempt && status.signal() == Some(signal_number) => {
|
||||
Some(status)
|
||||
if ready_log.is_none()
|
||||
&& attempt < last_attempt
|
||||
&& status.signal() == Some(signal_number) =>
|
||||
{
|
||||
let _ = child.wait_with_output();
|
||||
continue;
|
||||
}
|
||||
Some(status) => {
|
||||
let output = child.wait_with_output().expect("collect child output");
|
||||
panic!(
|
||||
"{name} exited unsuccessfully after {signal_name}: {status}\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} exited unsuccessfully after {signal_name}: {status}\nstdout:\n{}\nstderr:\n{}\nreadiness log:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
ready_log
|
||||
.and_then(|log| fs::read_to_string(log).ok())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
@@ -131,9 +169,12 @@ fn assert_signal_exits(
|
||||
.wait_with_output()
|
||||
.expect("collect killed child output");
|
||||
panic!(
|
||||
"{name} did not exit after {signal_name}\nstdout:\n{}\nstderr:\n{}",
|
||||
"{name} did not exit after {signal_name}\nstdout:\n{}\nstderr:\n{}\nreadiness log:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
ready_log
|
||||
.and_then(|log| fs::read_to_string(log).ok())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +203,7 @@ fn rncp_listener_exits_on_sigint() {
|
||||
"rncp-rs",
|
||||
"INT",
|
||||
2,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -185,6 +227,7 @@ fn rnsh_listener_exits_on_sigint() {
|
||||
"rnsh-rs",
|
||||
"INT",
|
||||
2,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -193,11 +236,13 @@ fn rnsh_listener_exits_on_sigint() {
|
||||
fn rnsd_flushes_state_and_exits_on_sigterm() {
|
||||
let tmp = TempDir::new("rnsd-sigterm");
|
||||
write_config(&tmp, true);
|
||||
let ready_log = tmp.path().join("logfile");
|
||||
assert_signal_exits(
|
||||
|| {
|
||||
Command::new(env!("CARGO_BIN_EXE_rnsd-rs"))
|
||||
.arg("--config")
|
||||
.arg(tmp.path())
|
||||
.arg("--service")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
@@ -206,9 +251,32 @@ fn rnsd_flushes_state_and_exits_on_sigterm() {
|
||||
"rnsd-rs",
|
||||
"TERM",
|
||||
15,
|
||||
Some(&ready_log),
|
||||
);
|
||||
assert!(
|
||||
tmp.path().join("storage/packet_hashlist.raw").is_file(),
|
||||
"orderly SIGTERM shutdown must flush transport state"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn daemon_readiness_requires_completed_initialization_and_a_live_child() {
|
||||
let tmp = TempDir::new("rnsd-readiness");
|
||||
let log = tmp.path().join("logfile");
|
||||
let mut child = Command::new("sleep")
|
||||
.arg("10")
|
||||
.spawn()
|
||||
.expect("spawn control");
|
||||
|
||||
assert!(!wait_for_ready_log(&mut child, &log, Duration::ZERO));
|
||||
// The starting message is not a promise of completed runtime initialization.
|
||||
fs::write(&log, "rnsd-rs 1.3.0 starting\n").expect("write starting log");
|
||||
assert!(!wait_for_ready_log(&mut child, &log, Duration::ZERO));
|
||||
fs::write(&log, "reticulum started in Standalone mode\n").expect("write ready log");
|
||||
assert!(wait_for_ready_log(&mut child, &log, Duration::ZERO));
|
||||
|
||||
child.kill().expect("stop control");
|
||||
child.wait().expect("reap control");
|
||||
assert!(!wait_for_ready_log(&mut child, &log, Duration::ZERO));
|
||||
}
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user