mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-27 13:52:16 +00:00
Compare commits
190
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e0d0a6888 | ||
|
|
6c77c9e69d | ||
|
|
27352fd0d4 | ||
|
|
fd973420f2 | ||
|
|
b12f331082 | ||
|
|
04300ecdf4 | ||
|
|
a1b78564e0 | ||
|
|
70b739988b | ||
|
|
140d0aeed4 | ||
|
|
ec61a566d3 | ||
|
|
1285e06cf6 | ||
|
|
bc419b109d | ||
|
|
eee619ef3b | ||
|
|
e47a1d4932 | ||
|
|
07ca72179e | ||
|
|
d24e4e3ce3 | ||
|
|
869322fa80 | ||
|
|
2bce74c74c | ||
|
|
8e58e1b708 | ||
|
|
7a187a7aa0 | ||
|
|
d424c96fa3 | ||
|
|
6547f8370d | ||
|
|
740051c41e | ||
|
|
04db8c9f46 | ||
|
|
9928abed26 | ||
|
|
9e7dd7d9b6 | ||
|
|
690c0faf05 | ||
|
|
5db4ca3eb5 | ||
|
|
5d010fb6fb | ||
|
|
7119f8019d | ||
|
|
df7c8decc1 | ||
|
|
8c8ec46da8 | ||
|
|
b2068105ae | ||
|
|
fb250c7a83 | ||
|
|
52e501fcfc | ||
|
|
dabe75fbb5 | ||
|
|
b9130e6002 | ||
|
|
126d974909 | ||
|
|
f9b457d329 | ||
|
|
93c4e3c4b1 | ||
|
|
5003e0ec8d | ||
|
|
ed58938c99 | ||
|
|
ac3239d221 | ||
|
|
fc97b9931a | ||
|
|
e7b76f8272 | ||
|
|
ba2845e166 | ||
|
|
f9bb83e089 | ||
|
|
808430d26d | ||
|
|
01fa84bf1f | ||
|
|
52998569fb | ||
|
|
5e310b7069 | ||
|
|
580ff63224 | ||
|
|
6f24711a38 | ||
|
|
12b43cebac | ||
|
|
97193439db | ||
|
|
fb976c4bc3 | ||
|
|
6b79393f58 | ||
|
|
b9287b7ecf | ||
|
|
76410efa50 | ||
|
|
b671acd51b | ||
|
|
2aada8b4db | ||
|
|
390146247d | ||
|
|
31632d7a90 | ||
|
|
4146eeb743 | ||
|
|
60a3b72146 | ||
|
|
4e1abca4ea | ||
|
|
b1854b62aa | ||
|
|
b59e8849a7 | ||
|
|
88d3d38277 | ||
|
|
b2aee9dc2c | ||
|
|
ba4ee2881f | ||
|
|
d6c3a010c0 | ||
|
|
3cccd8c7b0 | ||
|
|
74eb9949cb | ||
|
|
731fddcf73 | ||
|
|
6f43913a6c | ||
|
|
987cc947c7 | ||
|
|
1c7a0ea035 | ||
|
|
aeeb3c1ab9 | ||
|
|
7100021b75 | ||
|
|
59d59d335a | ||
|
|
e3bb3d171f | ||
|
|
0362446b74 | ||
|
|
2ec94069a4 | ||
|
|
bb7395b284 | ||
|
|
4ae8638b3e | ||
|
|
69d9e8a5b5 | ||
|
|
06a9bdd63f | ||
|
|
ca9bcae376 | ||
|
|
2be764308e | ||
|
|
a72c1215c1 | ||
|
|
a788ab984a | ||
|
|
2a67960f1d | ||
|
|
8370a1be66 | ||
|
|
30b40d8333 | ||
|
|
a319855c62 | ||
|
|
ee2b882a50 | ||
|
|
24b3dc3cbc | ||
|
|
acc0a3f93b | ||
|
|
e663260b11 | ||
|
|
69fa830d52 | ||
|
|
d406d76b35 | ||
|
|
9eed85392e | ||
|
|
82195eb2de | ||
|
|
1562d72ce1 | ||
|
|
8ae733e68a | ||
|
|
9b64aea819 | ||
|
|
d9f510a5ad | ||
|
|
cd816bee68 | ||
|
|
10ec9e9b3e | ||
|
|
4830142458 | ||
|
|
dfe42f2194 | ||
|
|
2bf531180e | ||
|
|
f284317d8d | ||
|
|
e15466bfb8 | ||
|
|
226f4fa800 | ||
|
|
a1ca1daa39 | ||
|
|
062170c541 | ||
|
|
8777f62a38 | ||
|
|
8645fdfacd | ||
|
|
b9819d3d66 | ||
|
|
4220b8d3d7 | ||
|
|
e5cbded53f | ||
|
|
8a8256cf1c | ||
|
|
1605709a48 | ||
|
|
a945ba0744 | ||
|
|
0c71ce1e09 | ||
|
|
d986749660 | ||
|
|
065741d22b | ||
|
|
6e12be1489 | ||
|
|
ea9163338f | ||
|
|
a9d3d7998f | ||
|
|
25c5e448cf | ||
|
|
9b909c2093 | ||
|
|
d90f9390ca | ||
|
|
739e30d3da | ||
|
|
44d8a13c62 | ||
|
|
e8819edc3c | ||
|
|
3f8feb169c | ||
|
|
a79b9b3210 | ||
|
|
8ac58e5f5e | ||
|
|
670875008d | ||
|
|
f853086237 | ||
|
|
36fcfeb953 | ||
|
|
7267bd4f69 | ||
|
|
4095022ea6 | ||
|
|
c4c9f14448 | ||
|
|
141a6e8889 | ||
|
|
4509145b70 | ||
|
|
17e6107aa8 | ||
|
|
c4b1301e6f | ||
|
|
c65ce4c430 | ||
|
|
27e6d03235 | ||
|
|
6c8dba7dd4 | ||
|
|
87ac41d93c | ||
|
|
ef1ff3f90c | ||
|
|
0baf1b4ad6 | ||
|
|
3c1b43d8f6 | ||
|
|
46b699af1f | ||
|
|
7d38b3f8d9 | ||
|
|
05f38400b9 | ||
|
|
4aa505a7b6 | ||
|
|
4afefd6bba | ||
|
|
7e178ce8c4 | ||
|
|
ceafedd4ee | ||
|
|
cbb0fc83bc | ||
|
|
2336f166d7 | ||
|
|
011da1459c | ||
|
|
fade1f2e47 | ||
|
|
5e213f75cf | ||
|
|
a5ab014510 | ||
|
|
198564c65d | ||
|
|
24fc3e2912 | ||
|
|
20ad6061d8 | ||
|
|
7fb33dc83d | ||
|
|
f2751f4b57 | ||
|
|
7d5ee2121d | ||
|
|
1f6865c996 | ||
|
|
753b49b83c | ||
|
|
e9169eecbd | ||
|
|
6d2b284753 | ||
|
|
468d330322 | ||
|
|
be3ac91d8a | ||
|
|
936f19a200 | ||
|
|
b9522bfab1 | ||
|
|
e6dd6b3ab3 | ||
|
|
3b91b36f3e | ||
|
|
3d7b989262 | ||
|
|
fdfbf09515 | ||
|
|
5bfbcef47f |
No files matched your search
@@ -26,12 +26,14 @@ jobs:
|
||||
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
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Test (default features)
|
||||
run: cargo test --workspace
|
||||
- name: Test BLE interface features (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo test -p rns-interface --features ble,ble_peer
|
||||
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'
|
||||
run: cargo test -p rns-interface --features ble --locked
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
@@ -43,7 +45,28 @@ jobs:
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
- name: Check public API documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
run: cargo doc --workspace --no-deps --locked
|
||||
- run: cargo check --workspace --no-default-features --locked
|
||||
|
||||
msrv:
|
||||
name: Rust 1.85 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@1.85.0
|
||||
with:
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Clippy (all targets and features)
|
||||
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
@@ -0,0 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- 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
|
||||
the bounded transport ingress is temporarily saturated.
|
||||
- Let one-shot Link clients reuse a validated cached identity when its route is
|
||||
still live, matching Python recall behavior and avoiding redundant path
|
||||
discovery.
|
||||
- Keep completed `rncp` Links alive for Python's receiver-side Resource
|
||||
conclusion callback before sending the authenticated teardown.
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
- Added application-facing Destination, announce, receipt, Link, request,
|
||||
Channel, Buffer, and Resource APIs.
|
||||
- Added resilient long-running Link sessions with recovery, liveness,
|
||||
cancellation, progress, metrics, and responder lifecycle support.
|
||||
- Hardened delivery proofs, shared-instance authority and reconnection, IFAC
|
||||
ingress, persistence, routing snapshots, and orderly shutdown.
|
||||
- Expanded RNode lifecycle, capability, BLE, USB, TCP, serial, and safe
|
||||
`rnodeconf-rs` support.
|
||||
- Added compiled examples and stricter MSRV, Clippy, interoperability, and
|
||||
public-documentation gates.
|
||||
Generated
+14
-10
@@ -1582,7 +1582,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-crypto"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"cbc",
|
||||
@@ -1603,7 +1603,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-identity"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1613,14 +1613,16 @@ dependencies = [
|
||||
"rns-crypto",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rns-interface"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bluer",
|
||||
"btleplug",
|
||||
@@ -1630,11 +1632,13 @@ dependencies = [
|
||||
"if-addrs",
|
||||
"jni",
|
||||
"libc",
|
||||
"md-5",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
"rns-transport",
|
||||
"rns-wire",
|
||||
"serde",
|
||||
@@ -1650,7 +1654,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-link"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"proptest",
|
||||
@@ -1666,7 +1670,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-protocol"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bzip2",
|
||||
"hex",
|
||||
@@ -1683,7 +1687,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-ratkey"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bip39",
|
||||
@@ -1709,7 +1713,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-runtime"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1735,7 +1739,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-tools"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
@@ -1762,7 +1766,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-transport"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"hex",
|
||||
@@ -1782,7 +1786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rns-wire"
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"rns-crypto",
|
||||
|
||||
+11
-10
@@ -14,7 +14,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.0.0"
|
||||
version = "1.1.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
@@ -42,6 +42,7 @@ base64 = "0.22"
|
||||
rmp-serde = "1"
|
||||
rmpv = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_bytes = "0.11"
|
||||
serde_json = "1"
|
||||
|
||||
# Async
|
||||
@@ -79,12 +80,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.0.0", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.0.0", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.0.0" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.0.0" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.0.0" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.0.0" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.0.0" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.0.0" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.0.0" }
|
||||
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" }
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](https://reticulum.network/)
|
||||
[](#feature-status)
|
||||
|
||||
[Reticulum Manual](https://reticulum.network/manual/) |
|
||||
@@ -116,14 +116,14 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
|
||||
#### Commands:
|
||||
|
||||
```text
|
||||
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version]
|
||||
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held]
|
||||
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [-i] [--service] [--exampleconfig] [--version]
|
||||
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|prx|ptx|held]
|
||||
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
|
||||
[--discovered|-D] [-m [-I SECONDS]] [FILTER]
|
||||
[-d|--discovered] [-D] [-m [-I SECONDS]] [FILTER]
|
||||
[-R <transport_hash> -i <identity_file>]
|
||||
rnpath-rs [--table|--rates] [destination_hash] [--max HOPS]
|
||||
rnpath-rs <destination_hash>
|
||||
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <destination_hash>
|
||||
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <full_name> <destination_hash>
|
||||
rnid-rs [-i IDENTITY|-g FILE|-m PUB|-M PRV] [-p|-P] [-x|-X] [-H ASPECT]
|
||||
[-a [ASPECT]] [-e FILE|-d FILE|-s FILE|-V FILE] [-w FILE] [-f]
|
||||
[-R|-N] [-t SECONDS] [-b|-B] [--raw] [--version]
|
||||
@@ -131,6 +131,11 @@ rncp-rs <file> <destination_hash>
|
||||
rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a <allowed_hash>]...
|
||||
rncp-rs -l -F [-j <jail_dir>] [-a <allowed_hash>|-n]...
|
||||
rncp-rs -f <destination_hash> <remote_path> [-s DEST_DIR]
|
||||
rnodeconf-rs [-i] [-N|-T] [-b|-B|-p] [-w MODE] [-D N] [-t N] [-R N] [--freq HZ]
|
||||
[--bw HZ] [--txp DBM] [--sf SF] [--cr CR] [-x|-X]
|
||||
[--eeprom-backup|--eeprom-dump] [--trust-key HASH] [--version] [PORT]
|
||||
rnsh-rs -l [-i FILE] [-s NAME] [-b PERIOD] [-a HASH]... [-n] [-A|-C] [-- CMD...]
|
||||
rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CMD...]
|
||||
```
|
||||
|
||||
Add the release `bin/` directory or `target/release` to `PATH` if
|
||||
@@ -145,7 +150,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.2.4 identity utility surface for normal
|
||||
`rnid-rs` tracks the Reticulum 1.3.8 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`
|
||||
@@ -169,7 +174,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.2.4 .rsg envelopes.
|
||||
# Sign and validate. New signatures are Reticulum 1.3.8 .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
|
||||
@@ -181,7 +186,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.2.4 validation.
|
||||
embeds the signer metadata needed for 1.3.8 validation.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -247,7 +252,7 @@ instance_control_port = 37433
|
||||
| BLE RNode | Config-backed with the `ble` feature. |
|
||||
| Bluetooth Peer | Runtime API used by Ratspeak. |
|
||||
| Android USB-OTG | Runtime API for Android app embeddings. |
|
||||
| Weave | Not implemented. |
|
||||
| Weave | Partial: interface driver implemented, not yet config-wired in the runtime. |
|
||||
| Bluetooth Classic RFCOMM | Not implemented. |
|
||||
|
||||
## Compatibility Notes
|
||||
@@ -256,8 +261,8 @@ 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.2.4 where the matching Rust
|
||||
surface is implemented and tested. `rnid-rs` has explicit 1.2.4 coverage for
|
||||
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.
|
||||
|
||||
Known gaps and intentional limits:
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-crypto"
|
||||
description = "Cryptographic primitives for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
|
||||
@@ -2,14 +2,25 @@
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::aes_cbc;
|
||||
use crate::hmac::{hmac_sha256, hmac_verify};
|
||||
use crate::pkcs7;
|
||||
use crate::random::random_16;
|
||||
use crate::random::{random_16, random_bytes};
|
||||
|
||||
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
|
||||
pub const TOKEN_OVERHEAD: usize = 48;
|
||||
/// AES block size used by legacy AES-128 tokens.
|
||||
pub const AES128_BLOCKSIZE: usize = 16;
|
||||
/// AES block size used by current AES-256 tokens.
|
||||
pub const AES256_BLOCKSIZE: usize = 16;
|
||||
/// AES-256 token key size: 32-byte signing key + 32-byte encryption key.
|
||||
pub const KEY_LENGTH: usize = 64;
|
||||
/// Legacy AES-128 token key size: 16-byte signing key + 16-byte encryption key.
|
||||
pub const LEGACY_KEY_LENGTH: usize = 32;
|
||||
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
|
||||
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
|
||||
|
||||
/// Errors surfaced by [`encrypt`] and [`decrypt`].
|
||||
#[derive(Debug, Error)]
|
||||
@@ -35,12 +46,17 @@ pub enum TokenError {
|
||||
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
|
||||
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
|
||||
match key.len() {
|
||||
64 => Ok((&key[..32], &key[32..])),
|
||||
32 => Ok((&key[..16], &key[16..])),
|
||||
KEY_LENGTH => Ok((&key[..32], &key[32..])),
|
||||
LEGACY_KEY_LENGTH => Ok((&key[..16], &key[16..])),
|
||||
n => Err(TokenError::InvalidKeyLength(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a fresh AES-256 token key with the operating-system CSPRNG.
|
||||
pub fn generate_key() -> Zeroizing<Vec<u8>> {
|
||||
Zeroizing::new(random_bytes(KEY_LENGTH))
|
||||
}
|
||||
|
||||
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
|
||||
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
|
||||
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
@@ -112,6 +128,20 @@ mod tests {
|
||||
assert_eq!(&decrypted, plaintext);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_key_is_valid_and_unique() {
|
||||
let first = generate_key();
|
||||
let second = generate_key();
|
||||
|
||||
assert_eq!(first.len(), KEY_LENGTH);
|
||||
assert_eq!(second.len(), KEY_LENGTH);
|
||||
assert_ne!(&*first, &*second);
|
||||
assert_eq!(
|
||||
decrypt(&encrypt(b"generated", &first).unwrap(), &first).unwrap(),
|
||||
b"generated"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypt_produces_correct_structure() {
|
||||
let key = [0x42u8; 64];
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-identity"
|
||||
description = "Identity, Destination, and Announce system for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
@@ -13,9 +14,13 @@ thiserror = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_bytes = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
@@ -12,6 +12,9 @@ const RANDOM_HASH_SIZE: usize = 10;
|
||||
const SIGNATURE_SIZE: usize = 64;
|
||||
const RATCHET_SIZE: usize = 32;
|
||||
|
||||
/// Maximum value carried in the low five bytes of an announce random hash.
|
||||
pub const ANNOUNCE_TIME_MAX: u64 = (1u64 << 40) - 1;
|
||||
|
||||
const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -28,6 +31,8 @@ pub enum AnnounceError {
|
||||
InvalidPublicKey,
|
||||
#[error("hash collision detected for destination")]
|
||||
HashCollision,
|
||||
#[error("announce wire time exceeds 40-bit field: {0}")]
|
||||
InvalidWireTime(u64),
|
||||
}
|
||||
|
||||
/// Parsed announce data.
|
||||
@@ -52,18 +57,33 @@ impl AnnounceData {
|
||||
app_data: Option<&[u8]>,
|
||||
ratchet_pub: Option<&[u8; 32]>,
|
||||
) -> Result<Self, AnnounceError> {
|
||||
let public_key = identity.get_public_key();
|
||||
let nh = name_hash(app_name);
|
||||
|
||||
let random_bytes = rns_crypto::random::random_bytes(5);
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let ts_bytes = ts.to_be_bytes();
|
||||
Self::create_at(identity, app_name, app_data, ratchet_pub, ts)
|
||||
}
|
||||
|
||||
/// Create and sign an announce with an explicit persisted 40-bit ordering
|
||||
/// value. Rotation and expiry clocks must be managed separately.
|
||||
pub fn create_at(
|
||||
identity: &Identity,
|
||||
app_name: &str,
|
||||
app_data: Option<&[u8]>,
|
||||
ratchet_pub: Option<&[u8; 32]>,
|
||||
wire_time: u64,
|
||||
) -> Result<Self, AnnounceError> {
|
||||
if wire_time > ANNOUNCE_TIME_MAX {
|
||||
return Err(AnnounceError::InvalidWireTime(wire_time));
|
||||
}
|
||||
|
||||
let public_key = identity.get_public_key();
|
||||
let nh = name_hash(app_name);
|
||||
let random_bytes = rns_crypto::random::random_bytes(5);
|
||||
let ts_bytes = wire_time.to_be_bytes();
|
||||
let mut random_hash = [0u8; 10];
|
||||
random_hash[..5].copy_from_slice(&random_bytes);
|
||||
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
|
||||
// The value was range checked, so these are the complete 40 bits.
|
||||
random_hash[5..].copy_from_slice(&ts_bytes[3..8]);
|
||||
|
||||
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
|
||||
@@ -241,7 +261,7 @@ impl AnnounceData {
|
||||
}
|
||||
|
||||
/// Validate destination-hash binding and first-seen public-key continuity
|
||||
/// after [`verify_signature`] has succeeded.
|
||||
/// after [`Self::verify_signature`] has succeeded.
|
||||
pub fn validate_destination_binding(
|
||||
&self,
|
||||
packet_dest_hash: &[u8; 16],
|
||||
@@ -302,6 +322,21 @@ mod tests {
|
||||
assert_eq!(validated_id.hash, id.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_wire_time_uses_exact_40_bit_value() {
|
||||
let id = Identity::new();
|
||||
let wire_time = 0x12_3456_789Au64;
|
||||
let announce = AnnounceData::create_at(&id, "test.time", None, None, wire_time).unwrap();
|
||||
assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]);
|
||||
|
||||
let maximum = AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX);
|
||||
assert!(maximum.is_ok());
|
||||
assert!(matches!(
|
||||
AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX + 1,),
|
||||
Err(AnnounceError::InvalidWireTime(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_and_validate_with_ratchet() {
|
||||
let id = Identity::new();
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Durable control-plane state for ratcheted announces.
|
||||
//!
|
||||
//! The signed Python-compatible ratchet ring contains only private keys. This
|
||||
//! sidecar deliberately keeps local policy metadata separate: the last wall
|
||||
//! time used for rotation and the last 40-bit value emitted on the wire.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::announce::ANNOUNCE_TIME_MAX;
|
||||
use crate::identity::Identity;
|
||||
use crate::persistence;
|
||||
|
||||
const CONTROL_STATE_VERSION: u8 = 1;
|
||||
const CONTROL_STATE_MAX_BYTES: usize = 4096;
|
||||
|
||||
fn invalid_data(message: impl Into<String>) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
|
||||
}
|
||||
|
||||
/// Signed, identity- and destination-bound state used to plan a ratcheted
|
||||
/// announce without mutating live state before persistence succeeds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RatchetControlState {
|
||||
identity_hash: [u8; 16],
|
||||
destination_hash: [u8; 16],
|
||||
last_rotation_wall: Option<u64>,
|
||||
last_announce_wire: Option<u64>,
|
||||
}
|
||||
|
||||
impl RatchetControlState {
|
||||
pub fn new(identity_hash: [u8; 16], destination_hash: [u8; 16]) -> Self {
|
||||
Self {
|
||||
identity_hash,
|
||||
destination_hash,
|
||||
last_rotation_wall: None,
|
||||
last_announce_wire: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn identity_hash(&self) -> [u8; 16] {
|
||||
self.identity_hash
|
||||
}
|
||||
|
||||
pub fn destination_hash(&self) -> [u8; 16] {
|
||||
self.destination_hash
|
||||
}
|
||||
|
||||
pub fn last_rotation_wall(&self) -> Option<u64> {
|
||||
self.last_rotation_wall
|
||||
}
|
||||
|
||||
pub fn last_announce_wire(&self) -> Option<u64> {
|
||||
self.last_announce_wire
|
||||
}
|
||||
|
||||
/// Anchor unknown rotation age at the current wall time. Existing age is
|
||||
/// never overwritten by this operation.
|
||||
pub fn anchor_rotation_if_unknown(&mut self, wall_now: u64) {
|
||||
if self.last_rotation_wall.is_none() {
|
||||
self.last_rotation_wall = Some(wall_now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotation is due only when a persisted age exists and the wall clock has
|
||||
/// advanced by the full interval. Clock rollback never looks elapsed.
|
||||
pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool {
|
||||
self.last_rotation_wall
|
||||
.is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs)
|
||||
}
|
||||
|
||||
/// Return a cloned candidate recording a successful rotation.
|
||||
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
|
||||
let mut candidate = self.clone();
|
||||
candidate.last_rotation_wall = Some(wall_now);
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Prepare the next wire-ordering value without mutating this live state.
|
||||
///
|
||||
/// `None` means wall time has not advanced beyond the last durable value;
|
||||
/// callers must coalesce/defer instead of inventing `last + 1`, which could
|
||||
/// make an announce appear to come from the future.
|
||||
pub fn prepare_announce(&self, wall_now: u64) -> std::io::Result<Option<Self>> {
|
||||
if wall_now > ANNOUNCE_TIME_MAX {
|
||||
return Err(invalid_data(format!(
|
||||
"wall time {wall_now} exceeds 40-bit announce field"
|
||||
)));
|
||||
}
|
||||
if self.last_announce_wire.is_some_and(|last| wall_now <= last) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut candidate = self.clone();
|
||||
candidate.last_announce_wire = Some(wall_now);
|
||||
Ok(Some(candidate))
|
||||
}
|
||||
|
||||
/// Persist this state as a signed, bounded MessagePack envelope.
|
||||
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
|
||||
if identity.hash != self.identity_hash {
|
||||
return Err(invalid_data("control state identity binding mismatch"));
|
||||
}
|
||||
self.validate()?;
|
||||
|
||||
let body = ControlStateBody {
|
||||
version: CONTROL_STATE_VERSION,
|
||||
identity_hash: self.identity_hash.to_vec(),
|
||||
destination_hash: self.destination_hash.to_vec(),
|
||||
last_rotation_wall: self.last_rotation_wall,
|
||||
last_announce_wire: self.last_announce_wire,
|
||||
};
|
||||
let packed = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&body).map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
let signature = identity.sign(&packed).ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"identity cannot sign ratchet control state",
|
||||
)
|
||||
})?;
|
||||
let envelope = ControlStateEnvelope {
|
||||
signature: signature.to_vec(),
|
||||
state: packed.to_vec(),
|
||||
};
|
||||
let encoded = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&envelope).map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
if encoded.len() > CONTROL_STATE_MAX_BYTES {
|
||||
return Err(invalid_data("ratchet control state exceeds size limit"));
|
||||
}
|
||||
persistence::atomic_write(path, &encoded)
|
||||
}
|
||||
|
||||
/// Load and verify state for exactly `identity` and `destination_hash`.
|
||||
pub fn load_verified(
|
||||
path: &Path,
|
||||
identity: &Identity,
|
||||
destination_hash: [u8; 16],
|
||||
) -> std::io::Result<Self> {
|
||||
let encoded = Zeroizing::new(
|
||||
persistence::read_file_bounded(path, CONTROL_STATE_MAX_BYTES)?
|
||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
|
||||
);
|
||||
let envelope: ControlStateEnvelope =
|
||||
rmp_serde::from_slice(&encoded).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
if envelope.signature.len() != 64 {
|
||||
return Err(invalid_data("invalid control-state signature length"));
|
||||
}
|
||||
let signature: [u8; 64] = envelope
|
||||
.signature
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state signature length"))?;
|
||||
let packed = Zeroizing::new(envelope.state);
|
||||
if !identity.verify(&packed, &signature) {
|
||||
return Err(invalid_data("invalid ratchet control-state signature"));
|
||||
}
|
||||
|
||||
let body: ControlStateBody =
|
||||
rmp_serde::from_slice(&packed).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
if body.version != CONTROL_STATE_VERSION {
|
||||
return Err(invalid_data(format!(
|
||||
"unsupported ratchet control-state version {}",
|
||||
body.version
|
||||
)));
|
||||
}
|
||||
let identity_hash: [u8; 16] = body
|
||||
.identity_hash
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state identity hash"))?;
|
||||
let stored_destination: [u8; 16] = body
|
||||
.destination_hash
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state destination hash"))?;
|
||||
if identity_hash != identity.hash {
|
||||
return Err(invalid_data("control state belongs to another identity"));
|
||||
}
|
||||
if stored_destination != destination_hash {
|
||||
return Err(invalid_data("control state belongs to another destination"));
|
||||
}
|
||||
|
||||
let state = Self {
|
||||
identity_hash,
|
||||
destination_hash: stored_destination,
|
||||
last_rotation_wall: body.last_rotation_wall,
|
||||
last_announce_wire: body.last_announce_wire,
|
||||
};
|
||||
state.validate()?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn validate(&self) -> std::io::Result<()> {
|
||||
if self
|
||||
.last_announce_wire
|
||||
.is_some_and(|value| value > ANNOUNCE_TIME_MAX)
|
||||
{
|
||||
return Err(invalid_data("stored announce time exceeds 40-bit field"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ControlStateBody {
|
||||
version: u8,
|
||||
#[serde(with = "serde_bytes")]
|
||||
identity_hash: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
destination_hash: Vec<u8>,
|
||||
last_rotation_wall: Option<u64>,
|
||||
last_announce_wire: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ControlStateEnvelope {
|
||||
#[serde(with = "serde_bytes")]
|
||||
signature: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
state: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn announce_time_never_moves_into_the_future() {
|
||||
let identity = Identity::new();
|
||||
let destination = [0x22; 16];
|
||||
let state = RatchetControlState::new(identity.hash, destination);
|
||||
let state = state.prepare_announce(100).unwrap().unwrap();
|
||||
assert_eq!(state.last_announce_wire(), Some(100));
|
||||
assert!(state.prepare_announce(100).unwrap().is_none());
|
||||
assert!(state.prepare_announce(99).unwrap().is_none());
|
||||
let next = state.prepare_announce(101).unwrap().unwrap();
|
||||
assert_eq!(next.last_announce_wire(), Some(101));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_rotation_age_is_anchored_without_immediate_rotation() {
|
||||
let identity = Identity::new();
|
||||
let mut state = RatchetControlState::new(identity.hash, [0x33; 16]);
|
||||
assert!(!state.rotation_due(100, 30));
|
||||
state.anchor_rotation_if_unknown(100);
|
||||
assert!(!state.rotation_due(100, 30));
|
||||
assert!(!state.rotation_due(99, 30));
|
||||
assert!(!state.rotation_due(129, 30));
|
||||
assert!(state.rotation_due(130, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_state_roundtrip_enforces_identity_and_destination_binding() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_control_state");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("control");
|
||||
let identity = Identity::new();
|
||||
let wrong_identity = Identity::new();
|
||||
let destination = [0x44; 16];
|
||||
let mut state = RatchetControlState::new(identity.hash, destination);
|
||||
state.anchor_rotation_if_unknown(100);
|
||||
let state = state.prepare_announce(101).unwrap().unwrap();
|
||||
state.save_verified(&path, &identity).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
RatchetControlState::load_verified(&path, &identity, destination).unwrap(),
|
||||
state
|
||||
);
|
||||
assert!(RatchetControlState::load_verified(&path, &wrong_identity, destination).is_err());
|
||||
assert!(RatchetControlState::load_verified(&path, &identity, [0x55; 16]).is_err());
|
||||
assert!(
|
||||
path.exists(),
|
||||
"rejected state remains available for recovery"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_candidate_persistence_cannot_mutate_live_state() {
|
||||
let identity = Identity::new();
|
||||
let destination = [0x66; 16];
|
||||
let live = RatchetControlState::new(identity.hash, destination);
|
||||
let candidate = live.prepare_announce(100).unwrap().unwrap();
|
||||
let missing_parent = std::env::temp_dir()
|
||||
.join("reticulum_missing_control_parent")
|
||||
.join("nested")
|
||||
.join("state");
|
||||
let _ = std::fs::remove_dir_all(
|
||||
missing_parent
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.unwrap_or_else(|| Path::new("/tmp")),
|
||||
);
|
||||
|
||||
assert!(candidate.save_verified(&missing_parent, &identity).is_err());
|
||||
assert_eq!(live.last_announce_wire(), None);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -8,9 +8,22 @@ use thiserror::Error;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::persistence;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Elliptic curve used for identity encryption and ratchets.
|
||||
pub const CURVE: &str = "Curve25519";
|
||||
/// Combined X25519 and Ed25519 public/private key size, in bits.
|
||||
pub const KEY_SIZE_BITS: usize = 512;
|
||||
/// X25519 ratchet key size, in bits.
|
||||
pub const RATCHET_SIZE_BITS: usize = 256;
|
||||
/// X25519 ratchet key size, in bytes (Python `Identity.RATCHETSIZE`).
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
/// Addressable identity hash size, in bits.
|
||||
pub const HASH_LENGTH_BITS: usize = 128;
|
||||
/// Ratchet identifier size, in bytes.
|
||||
pub const RATCHET_ID_LENGTH: usize = 10;
|
||||
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
|
||||
pub const DERIVED_KEY_LENGTH: usize = 64;
|
||||
|
||||
@@ -64,6 +77,15 @@ pub struct Identity {
|
||||
backend: Option<Arc<dyn LocalKeyBackend>>,
|
||||
}
|
||||
|
||||
/// Successful identity decryption plus the ratchet that authenticated it.
|
||||
///
|
||||
/// `ratchet_id` is absent when the identity's base key performed decryption.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DecryptionResult {
|
||||
pub plaintext: Vec<u8>,
|
||||
pub ratchet_id: Option<[u8; RATCHET_ID_LENGTH]>,
|
||||
}
|
||||
|
||||
impl Clone for Identity {
|
||||
/// Software identities clone their key material; hardware-backed identities
|
||||
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
|
||||
@@ -92,6 +114,12 @@ impl Default for Identity {
|
||||
}
|
||||
|
||||
impl Identity {
|
||||
pub const CURVE: &'static str = CURVE;
|
||||
pub const KEY_SIZE_BITS: usize = KEY_SIZE_BITS;
|
||||
pub const RATCHET_SIZE_BITS: usize = RATCHET_SIZE_BITS;
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
|
||||
|
||||
pub fn new() -> Self {
|
||||
let prv = X25519PrivateKey::generate();
|
||||
let sig_prv = Ed25519PrivateKey::generate();
|
||||
@@ -216,6 +244,11 @@ impl Identity {
|
||||
key
|
||||
}
|
||||
|
||||
/// Lowercase, delimiter-free hexadecimal identity hash.
|
||||
pub fn hexhash(&self) -> String {
|
||||
hex::encode(self.hash)
|
||||
}
|
||||
|
||||
pub fn has_private_key(&self) -> bool {
|
||||
self.prv.is_some() && self.sig_prv.is_some()
|
||||
}
|
||||
@@ -294,6 +327,21 @@ impl Identity {
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<Vec<u8>, IdentityError> {
|
||||
self.decrypt_with_ratchet_id(ciphertext, ratchets, enforce_ratchets)
|
||||
.map(|result| result.plaintext)
|
||||
}
|
||||
|
||||
/// Decrypt ciphertext and report the ratchet key that authenticated it.
|
||||
///
|
||||
/// The identifier is `SHA-256(ratchet_public_key)[:10]`, matching the
|
||||
/// reference implementation. Base-identity decryption returns no ratchet
|
||||
/// identifier.
|
||||
pub fn decrypt_with_ratchet_id(
|
||||
&self,
|
||||
ciphertext: &[u8],
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<DecryptionResult, IdentityError> {
|
||||
if ciphertext.len() < 32 {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
}
|
||||
@@ -311,7 +359,12 @@ impl Identity {
|
||||
shared.zeroize();
|
||||
if let Ok(derived) = derived_result {
|
||||
if let Ok(plaintext) = token::decrypt(ct, &derived) {
|
||||
return Ok(plaintext);
|
||||
return Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: Some(Self::ratchet_id(
|
||||
&ratchet_prv.public_key().to_bytes(),
|
||||
)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,7 +390,18 @@ impl Identity {
|
||||
let derived = derived_result?;
|
||||
let plaintext =
|
||||
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
Ok(plaintext)
|
||||
Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Derive the stable 80-bit identifier for a ratchet public key.
|
||||
pub fn ratchet_id(ratchet_public_key: &[u8; 32]) -> [u8; RATCHET_ID_LENGTH] {
|
||||
let full = rns_crypto::sha::sha256(ratchet_public_key);
|
||||
let mut id = [0u8; RATCHET_ID_LENGTH];
|
||||
id.copy_from_slice(&full[..RATCHET_ID_LENGTH]);
|
||||
id
|
||||
}
|
||||
|
||||
/// Sign `packet_hash` and return proof bytes.
|
||||
@@ -371,6 +435,12 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Identity {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "<{}>", self.hexhash())
|
||||
}
|
||||
}
|
||||
|
||||
// Msgpack envelope wrapping the raw 64-byte private key on disk.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct IdentityPersisted {
|
||||
@@ -384,6 +454,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_generate_identity() {
|
||||
let id = Identity::new();
|
||||
assert_eq!(Identity::CURVE, "Curve25519");
|
||||
assert_eq!(Identity::RATCHETSIZE, 32);
|
||||
assert!(id.has_private_key());
|
||||
assert_ne!(id.hash, [0u8; 16]);
|
||||
}
|
||||
@@ -443,8 +515,38 @@ mod tests {
|
||||
assert!(id.decrypt(&ct, None, false).is_err());
|
||||
|
||||
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
|
||||
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
|
||||
assert_eq!(&pt, plaintext);
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ct, Some(&ratchets), false)
|
||||
.unwrap();
|
||||
assert_eq!(&decrypted.plaintext, plaintext);
|
||||
assert_eq!(
|
||||
decrypted.ratchet_id,
|
||||
Some(Identity::ratchet_id(&ratchet_pub))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_identity_decryption_reports_no_ratchet() {
|
||||
let id = Identity::new();
|
||||
let ciphertext = id.encrypt(b"base identity", None).unwrap();
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ciphertext, None, false)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(decrypted.plaintext, b"base identity");
|
||||
assert_eq!(decrypted.ratchet_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_metadata_and_display_match_wire_identity() {
|
||||
let id = Identity::new();
|
||||
|
||||
assert_eq!(CURVE, "Curve25519");
|
||||
assert_eq!(KEY_SIZE_BITS, id.get_public_key().len() * 8);
|
||||
assert_eq!(RATCHET_SIZE_BITS, 32 * 8);
|
||||
assert_eq!(HASH_LENGTH_BITS, id.hash.len() * 8);
|
||||
assert_eq!(id.hexhash(), hex::encode(id.hash));
|
||||
assert_eq!(id.to_string(), format!("<{}>", hex::encode(id.hash)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,8 +2,12 @@ use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::sha256;
|
||||
use thiserror::Error;
|
||||
|
||||
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
|
||||
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
/// Fixed IFAC HKDF salt shared with the Python reference.
|
||||
///
|
||||
/// This is public for applications that need to derive or inspect
|
||||
/// Python-compatible IFAC material outside the runtime helper. Changing it
|
||||
/// would break interoperability.
|
||||
pub const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum IfacError {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`.
|
||||
|
||||
pub mod announce;
|
||||
pub mod announce_state;
|
||||
pub mod destination;
|
||||
pub mod identity;
|
||||
pub mod ifac;
|
||||
|
||||
@@ -1,43 +1,169 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
|
||||
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn invalid_data(message: &'static str) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
fn unique_temp_path(path: &Path) -> std::io::Result<PathBuf> {
|
||||
let parent = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let file_name = path.file_name().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"atomic-write target has no file name",
|
||||
)
|
||||
})?;
|
||||
let sequence = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let mut temp_name = file_name.to_os_string();
|
||||
temp_name.push(format!(".tmp-{}-{sequence}", std::process::id()));
|
||||
Ok(parent.join(temp_name))
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
fs::rename(source, destination)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
|
||||
};
|
||||
|
||||
let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let destination: Vec<u16> = destination
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
// Same-directory temporary files keep this on one volume. MoveFileExW is
|
||||
// the Windows replacement primitive; std::fs::rename rejects an existing
|
||||
// destination on Windows instead of replacing it.
|
||||
let replaced = unsafe {
|
||||
MoveFileExW(
|
||||
source.as_ptr(),
|
||||
destination.as_ptr(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
|
||||
)
|
||||
};
|
||||
if replaced == 0 {
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
enum InjectedFailure {
|
||||
Create,
|
||||
Write,
|
||||
Flush,
|
||||
Sync,
|
||||
VerifyTemp,
|
||||
Rename,
|
||||
VerifyFinal,
|
||||
}
|
||||
|
||||
fn fail_if(stage: InjectedFailure, injected: Option<InjectedFailure>) -> std::io::Result<()> {
|
||||
if injected == Some(stage) {
|
||||
Err(std::io::Error::other(format!(
|
||||
"injected atomic-write failure at {stage:?}"
|
||||
)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `data` to `path` via a unique same-directory temporary file and
|
||||
/// atomic rename.
|
||||
///
|
||||
/// On Unix the temp file is created with mode `0600` so that key material is
|
||||
/// not world-readable even during the write. After the rename the parent
|
||||
/// directory is fsynced best-effort so the rename itself survives power loss.
|
||||
/// not world-readable even during the write. The bytes are flushed, fsynced,
|
||||
/// and verified before the rename, then verified again at the final path. After
|
||||
/// the rename the parent directory is fsynced best-effort so the directory
|
||||
/// entry itself survives power loss.
|
||||
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let tmp_path = path.with_extension("tmp");
|
||||
atomic_write_inner(path, data, None)
|
||||
}
|
||||
|
||||
fn atomic_write_inner(
|
||||
path: &Path,
|
||||
data: &[u8],
|
||||
injected: Option<InjectedFailure>,
|
||||
) -> std::io::Result<()> {
|
||||
let _write_guard = ATOMIC_WRITE_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let tmp_path = unique_temp_path(path)?;
|
||||
|
||||
let result = (|| {
|
||||
fail_if(InjectedFailure::Create, injected)?;
|
||||
|
||||
{
|
||||
#[cfg(unix)]
|
||||
let mut f = {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp_path)?
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let mut f = fs::File::create(&tmp_path)?;
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp_path)?;
|
||||
|
||||
fail_if(InjectedFailure::Write, injected)?;
|
||||
f.write_all(data)?;
|
||||
|
||||
fail_if(InjectedFailure::Flush, injected)?;
|
||||
f.flush()?;
|
||||
|
||||
fail_if(InjectedFailure::Sync, injected)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
drop(f);
|
||||
|
||||
fs::rename(&tmp_path, path)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
if let Ok(d) = fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
fail_if(InjectedFailure::VerifyTemp, injected)?;
|
||||
let temp_data = read_file_bounded(&tmp_path, data.len())?
|
||||
.ok_or_else(|| invalid_data("atomic-write temp file disappeared"))?;
|
||||
if temp_data != data {
|
||||
return Err(invalid_data("atomic-write temp verification failed"));
|
||||
}
|
||||
|
||||
fail_if(InjectedFailure::Rename, injected)?;
|
||||
atomic_replace(&tmp_path, path)?;
|
||||
|
||||
fail_if(InjectedFailure::VerifyFinal, injected)?;
|
||||
let final_data = read_file_bounded(path, data.len())?
|
||||
.ok_or_else(|| invalid_data("atomic-write target disappeared"))?;
|
||||
if final_data != data {
|
||||
return Err(invalid_data("atomic-write final verification failed"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
if let Ok(d) = fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp_path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
/// Read `path` in full, returning `None` if the file does not exist.
|
||||
@@ -49,29 +175,150 @@ pub fn read_file(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read at most `max_len` bytes from `path`.
|
||||
///
|
||||
/// A file larger than the supplied bound is rejected before it can be handed
|
||||
/// to a deserializer. `None` means the path did not exist.
|
||||
pub fn read_file_bounded(path: &Path, max_len: usize) -> std::io::Result<Option<Vec<u8>>> {
|
||||
let file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let mut data = Vec::with_capacity(max_len.min(4096));
|
||||
file.take(max_len.saturating_add(1) as u64)
|
||||
.read_to_end(&mut data)?;
|
||||
if data.len() > max_len {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("file exceeds {max_len}-byte limit"),
|
||||
));
|
||||
}
|
||||
Ok(Some(data))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn unique_test_dir(label: &str) -> PathBuf {
|
||||
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!(
|
||||
"reticulum-{label}-{}-{}-{id}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos()
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_and_read() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_persistence");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let dir = unique_test_dir("persistence");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("test_atomic");
|
||||
|
||||
atomic_write(&path, b"hello world").unwrap();
|
||||
let data = read_file(&path).unwrap().unwrap();
|
||||
assert_eq!(data, b"hello world");
|
||||
|
||||
let _ = fs::remove_file(&path);
|
||||
let _ = fs::remove_dir(&dir);
|
||||
atomic_write(&path, b"replacement").unwrap();
|
||||
let data = read_file(&path).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
data, b"replacement",
|
||||
"Windows must replace an existing state file instead of failing after the first write"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_read_nonexistent() {
|
||||
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
|
||||
let path = unique_test_dir("nonexistent").join("missing");
|
||||
let result = read_file(&path).unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bounded_read_rejects_oversize_file() {
|
||||
let dir = unique_test_dir("bounded-read");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("bounded");
|
||||
fs::write(&path, [0xA5; 17]).unwrap();
|
||||
|
||||
let err = read_file_bounded(&path, 16).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert_eq!(read_file_bounded(&path, 17).unwrap().unwrap().len(), 17);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_faults_before_rename_preserve_previous_file() {
|
||||
let dir = unique_test_dir("atomic-faults");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
|
||||
for stage in [
|
||||
InjectedFailure::Create,
|
||||
InjectedFailure::Write,
|
||||
InjectedFailure::Flush,
|
||||
InjectedFailure::Sync,
|
||||
InjectedFailure::VerifyTemp,
|
||||
InjectedFailure::Rename,
|
||||
] {
|
||||
let err = atomic_write_inner(&path, b"candidate", Some(stage)).unwrap_err();
|
||||
assert!(err.to_string().contains("injected"));
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous", "stage {stage:?}");
|
||||
}
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_final_readback_failure_is_reported() {
|
||||
let dir = unique_test_dir("atomic-readback-fault");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
|
||||
let err = atomic_write_inner(&path, b"candidate", Some(InjectedFailure::VerifyFinal))
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("injected"));
|
||||
assert_eq!(
|
||||
fs::read(&path).unwrap(),
|
||||
b"candidate",
|
||||
"the caller must not commit live state even if replacement reached disk"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writers_do_not_share_temp_paths() {
|
||||
let dir = unique_test_dir("atomic-concurrent");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
|
||||
let mut writers = Vec::new();
|
||||
for byte in 0u8..16 {
|
||||
let path = path.clone();
|
||||
writers.push(std::thread::spawn(move || atomic_write(&path, &[byte; 64])));
|
||||
}
|
||||
for writer in writers {
|
||||
writer.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
let final_data = fs::read(&path).unwrap();
|
||||
assert_eq!(final_data.len(), 64);
|
||||
assert!(final_data.iter().all(|byte| *byte == final_data[0]));
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,104 @@ use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use zeroize::Zeroize;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::identity::Identity;
|
||||
use crate::persistence;
|
||||
|
||||
const RATCHET_FILE_MAX_BYTES: usize = 64 * 1024;
|
||||
const RATCHET_PACKED_MAX_BYTES: usize = 32 * 1024;
|
||||
const RECEIVED_RATCHET_FILE_MAX_BYTES: usize = 1024;
|
||||
|
||||
fn wall_time_secs() -> f64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64()
|
||||
}
|
||||
|
||||
fn invalid_data(message: impl Into<String>) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
|
||||
}
|
||||
|
||||
fn pack_ratchet_keys(keys: &[[u8; 32]]) -> std::io::Result<Zeroizing<Vec<u8>>> {
|
||||
let byte_keys: Vec<&serde_bytes::Bytes> = keys
|
||||
.iter()
|
||||
.map(|key| serde_bytes::Bytes::new(key))
|
||||
.collect();
|
||||
let packed = Zeroizing::new(
|
||||
rmp_serde::to_vec(&byte_keys).map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
if packed.len() > RATCHET_PACKED_MAX_BYTES {
|
||||
return Err(invalid_data("packed ratchet ring exceeds size limit"));
|
||||
}
|
||||
Ok(packed)
|
||||
}
|
||||
|
||||
fn unpack_ratchet_keys(packed: &[u8]) -> std::io::Result<Vec<[u8; 32]>> {
|
||||
if packed.len() > RATCHET_PACKED_MAX_BYTES {
|
||||
return Err(invalid_data("packed ratchet ring exceeds size limit"));
|
||||
}
|
||||
let mut encoded_keys: Vec<serde_bytes::ByteBuf> =
|
||||
rmp_serde::from_slice(packed).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
if encoded_keys.len() > RATCHET_COUNT {
|
||||
for key in &mut encoded_keys {
|
||||
key.as_mut().zeroize();
|
||||
}
|
||||
return Err(invalid_data(format!(
|
||||
"ratchet ring contains {} keys; maximum is {RATCHET_COUNT}",
|
||||
encoded_keys.len()
|
||||
)));
|
||||
}
|
||||
|
||||
if encoded_keys.iter().any(|key| key.len() != 32) {
|
||||
for key in &mut encoded_keys {
|
||||
key.as_mut().zeroize();
|
||||
}
|
||||
return Err(invalid_data("ratchet private key must be exactly 32 bytes"));
|
||||
}
|
||||
|
||||
let mut keys = Vec::with_capacity(RATCHET_COUNT);
|
||||
for encoded in &mut encoded_keys {
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(encoded);
|
||||
keys.push(key);
|
||||
encoded.as_mut().zeroize();
|
||||
}
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// On-disk format accepted by [`RatchetRing::load_verified`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RatchetRingFormat {
|
||||
/// Python-compatible `{signature, ratchets}` with a signature over the
|
||||
/// packed private-key list.
|
||||
Canonical,
|
||||
/// Historical Rust envelope whose signature covered only the current
|
||||
/// public ratchet and whose unsigned `last_rotation` field is ignored.
|
||||
LegacyRust,
|
||||
}
|
||||
|
||||
/// A verified ratchet ring plus the format that was read from disk.
|
||||
pub struct LoadedRatchetRing {
|
||||
ring: RatchetRing,
|
||||
format: RatchetRingFormat,
|
||||
}
|
||||
|
||||
impl LoadedRatchetRing {
|
||||
pub fn ring(&self) -> &RatchetRing {
|
||||
&self.ring
|
||||
}
|
||||
|
||||
pub fn format(&self) -> RatchetRingFormat {
|
||||
self.format
|
||||
}
|
||||
|
||||
pub fn into_ring(self) -> RatchetRing {
|
||||
self.ring
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded history of X25519 private ratchet keys for forward secrecy.
|
||||
///
|
||||
/// Index 0 is the most recent key; older keys are retained so decryption can
|
||||
@@ -24,7 +118,7 @@ pub struct RatchetRing {
|
||||
impl RatchetRing {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
keys: Vec::new(),
|
||||
keys: Vec::with_capacity(RATCHET_COUNT),
|
||||
last_rotation: 0.0,
|
||||
retained_count: RATCHET_COUNT,
|
||||
rotation_interval: RATCHET_INTERVAL,
|
||||
@@ -35,33 +129,97 @@ impl RatchetRing {
|
||||
///
|
||||
/// Any keys evicted past `retained_count` are zeroised before drop.
|
||||
pub fn rotate(&mut self) -> [u8; 32] {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
self.rotate_at(wall_time_secs())
|
||||
}
|
||||
|
||||
/// Generate a fresh ratchet while recording an explicit wall-clock time.
|
||||
///
|
||||
/// Callers that need crash safety should use [`Self::prepare_rotation_at`],
|
||||
/// persist its candidate ring, and only then call
|
||||
/// [`Self::commit_prepared_rotation`].
|
||||
pub fn rotate_at(&mut self, now: f64) -> [u8; 32] {
|
||||
let prv = X25519PrivateKey::generate();
|
||||
let pub_key = prv.public_key().to_bytes();
|
||||
|
||||
self.keys.insert(0, prv.to_bytes());
|
||||
if self.keys.len() > self.retained_count {
|
||||
for key in &mut self.keys[self.retained_count..] {
|
||||
key.zeroize();
|
||||
}
|
||||
self.keys.truncate(self.retained_count);
|
||||
// Make room before insertion so a full ring never reallocates an
|
||||
// uncleared backing buffer containing every retained private key.
|
||||
while self.keys.len() >= self.retained_count {
|
||||
let last = self.keys.len() - 1;
|
||||
self.keys[last].zeroize();
|
||||
self.keys.truncate(last);
|
||||
}
|
||||
self.last_rotation = now;
|
||||
self.keys.insert(0, prv.to_bytes());
|
||||
self.last_rotation = if now.is_finite() && now >= 0.0 {
|
||||
now
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
pub_key
|
||||
}
|
||||
|
||||
/// True when at least `rotation_interval` seconds have elapsed since the last rotate.
|
||||
pub fn needs_rotation(&self) -> bool {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
now - self.last_rotation >= self.rotation_interval as f64
|
||||
self.needs_rotation_at(wall_time_secs())
|
||||
}
|
||||
|
||||
/// Test rotation age against an explicit wall-clock value.
|
||||
///
|
||||
/// A missing age (`last_rotation == 0`) is due. A clock rollback is not:
|
||||
/// callers can anchor an unknown age with [`Self::anchor_rotation_at`] and
|
||||
/// wait one normal interval instead of rotating immediately.
|
||||
pub fn needs_rotation_at(&self, now: f64) -> bool {
|
||||
if !now.is_finite() || now < 0.0 {
|
||||
return false;
|
||||
}
|
||||
if self.last_rotation <= 0.0 {
|
||||
return true;
|
||||
}
|
||||
now >= self.last_rotation && now - self.last_rotation >= self.rotation_interval as f64
|
||||
}
|
||||
|
||||
/// Set the age anchor without generating or discarding any key material.
|
||||
pub fn anchor_rotation_at(&mut self, now: f64) -> bool {
|
||||
if !now.is_finite() || now < 0.0 {
|
||||
return false;
|
||||
}
|
||||
self.last_rotation = now;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn last_rotation(&self) -> f64 {
|
||||
self.last_rotation
|
||||
}
|
||||
|
||||
/// Prepare a candidate rotation without changing the live ring.
|
||||
pub fn prepare_rotation_at(&self, now: f64) -> PreparedRatchetRotation {
|
||||
let mut candidate = self.duplicate();
|
||||
let public_key = candidate.rotate_at(now);
|
||||
PreparedRatchetRotation {
|
||||
candidate,
|
||||
public_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the live ring with a previously persisted candidate.
|
||||
pub fn commit_prepared_rotation(&mut self, prepared: PreparedRatchetRotation) -> [u8; 32] {
|
||||
let PreparedRatchetRotation {
|
||||
mut candidate,
|
||||
public_key,
|
||||
} = prepared;
|
||||
std::mem::swap(self, &mut candidate);
|
||||
public_key
|
||||
}
|
||||
|
||||
fn duplicate(&self) -> Self {
|
||||
let mut keys = Vec::with_capacity(RATCHET_COUNT);
|
||||
keys.extend_from_slice(&self.keys);
|
||||
Self {
|
||||
keys,
|
||||
last_rotation: self.last_rotation,
|
||||
retained_count: self.retained_count,
|
||||
rotation_interval: self.rotation_interval,
|
||||
}
|
||||
}
|
||||
|
||||
/// Public key of the most recent ratchet, if the ring has been rotated at least once.
|
||||
@@ -85,9 +243,9 @@ impl RatchetRing {
|
||||
self.keys.is_empty()
|
||||
}
|
||||
|
||||
/// Set `retained_count`; returns `false` if `count == 0`.
|
||||
/// Set `retained_count`; returns `false` outside `1..=RATCHET_COUNT`.
|
||||
pub fn set_retained_ratchets(&mut self, count: usize) -> bool {
|
||||
if count > 0 {
|
||||
if (1..=RATCHET_COUNT).contains(&count) {
|
||||
self.retained_count = count;
|
||||
self.clean();
|
||||
true
|
||||
@@ -116,27 +274,56 @@ impl RatchetRing {
|
||||
|
||||
fn clean(&mut self) {
|
||||
if self.keys.len() > self.retained_count {
|
||||
for key in &mut self.keys[self.retained_count..] {
|
||||
key.zeroize();
|
||||
}
|
||||
self.keys.truncate(self.retained_count);
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist to `path` as a Python-compatible msgpack envelope.
|
||||
/// Persist to `path` as the exact Python-compatible msgpack envelope.
|
||||
///
|
||||
/// Python writes `{signature, ratchets}`. Rust also includes
|
||||
/// `last_rotation`, which Python ignores and Rust defaults when loading a
|
||||
/// Python-written file. `ratchets` is itself the msgpack-encoded key list
|
||||
/// signed by the owning identity.
|
||||
/// `signature` must cover the packed `ratchets` list. Production callers
|
||||
/// should prefer [`Self::save_verified`], which cannot sign the wrong data.
|
||||
pub fn save(&self, path: &Path, signature: &[u8; 64]) -> std::io::Result<()> {
|
||||
let ratchets_packed =
|
||||
rmp_serde::to_vec(&self.keys).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
|
||||
|
||||
let persisted = RatchetRingPersisted {
|
||||
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
|
||||
signature: signature.to_vec(),
|
||||
ratchets: ratchets_packed,
|
||||
last_rotation: self.last_rotation,
|
||||
};
|
||||
let buf =
|
||||
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
ratchets: ratchets_packed.to_vec(),
|
||||
});
|
||||
let buf = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&*persisted)
|
||||
.map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
if buf.len() > RATCHET_FILE_MAX_BYTES {
|
||||
return Err(invalid_data("ratchet ring file exceeds size limit"));
|
||||
}
|
||||
persistence::atomic_write(path, &buf)
|
||||
}
|
||||
|
||||
/// Sign the packed key list with `identity`, persist it, and verify the
|
||||
/// final bytes before returning.
|
||||
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
|
||||
let ratchets_packed = pack_ratchet_keys(&self.keys)?;
|
||||
let signature = identity.sign(&ratchets_packed).ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"identity cannot sign ratchet ring",
|
||||
)
|
||||
})?;
|
||||
|
||||
let persisted = Zeroizing::new(RatchetRingPersistedWrite {
|
||||
signature: signature.to_vec(),
|
||||
ratchets: ratchets_packed.to_vec(),
|
||||
});
|
||||
let buf = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&*persisted)
|
||||
.map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
if buf.len() > RATCHET_FILE_MAX_BYTES {
|
||||
return Err(invalid_data("ratchet ring file exceeds size limit"));
|
||||
}
|
||||
persistence::atomic_write(path, &buf)
|
||||
}
|
||||
|
||||
@@ -152,7 +339,7 @@ impl RatchetRing {
|
||||
}
|
||||
|
||||
match Self::try_load(path) {
|
||||
Ok(result) => return Ok(result),
|
||||
Ok(decoded) => return Ok((decoded.ring, decoded.signature)),
|
||||
Err(e) => {
|
||||
if attempt < delays_ms.len() - 1 {
|
||||
tracing::warn!(
|
||||
@@ -170,10 +357,40 @@ impl RatchetRing {
|
||||
Err(last_err.unwrap())
|
||||
}
|
||||
|
||||
fn try_load(path: &Path) -> std::io::Result<(Self, [u8; 64])> {
|
||||
let data = std::fs::read(path)?;
|
||||
/// Load a bounded ring and verify that its signature belongs to `identity`.
|
||||
///
|
||||
/// Canonical files are verified over the packed key list. Historical Rust
|
||||
/// files are accepted only when their old current-public-key signature is
|
||||
/// valid; their unsigned rotation timestamp is deliberately ignored.
|
||||
pub fn load_verified(path: &Path, identity: &Identity) -> std::io::Result<LoadedRatchetRing> {
|
||||
let decoded = Self::try_load(path)?;
|
||||
|
||||
let persisted: RatchetRingPersisted =
|
||||
let format = if identity.verify(&decoded.packed, &decoded.signature) {
|
||||
RatchetRingFormat::Canonical
|
||||
} else if decoded.had_legacy_rotation
|
||||
&& decoded
|
||||
.ring
|
||||
.current_public_key()
|
||||
.is_some_and(|public| identity.verify(&public, &decoded.signature))
|
||||
{
|
||||
RatchetRingFormat::LegacyRust
|
||||
} else {
|
||||
return Err(invalid_data("invalid ratchet ring signature"));
|
||||
};
|
||||
|
||||
Ok(LoadedRatchetRing {
|
||||
ring: decoded.ring,
|
||||
format,
|
||||
})
|
||||
}
|
||||
|
||||
fn try_load(path: &Path) -> std::io::Result<DecodedRatchetRing> {
|
||||
let data = Zeroizing::new(
|
||||
persistence::read_file_bounded(path, RATCHET_FILE_MAX_BYTES)?
|
||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
|
||||
);
|
||||
|
||||
let persisted: RatchetRingPersistedRead =
|
||||
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
|
||||
if persisted.signature.len() != 64 {
|
||||
@@ -186,27 +403,171 @@ impl RatchetRing {
|
||||
let mut signature = [0u8; 64];
|
||||
signature.copy_from_slice(&persisted.signature);
|
||||
|
||||
let keys: Vec<[u8; 32]> = rmp_serde::from_slice(&persisted.ratchets)
|
||||
.map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let packed = Zeroizing::new(persisted.ratchets);
|
||||
let keys = unpack_ratchet_keys(&packed)?;
|
||||
let had_legacy_rotation = persisted.last_rotation.is_some();
|
||||
|
||||
Ok((
|
||||
Self {
|
||||
Ok(DecodedRatchetRing {
|
||||
ring: Self {
|
||||
keys,
|
||||
last_rotation: persisted.last_rotation,
|
||||
// Rotation age is control-plane metadata, not part of the
|
||||
// Python ring signature. Never trust the historical unsigned
|
||||
// value from disk.
|
||||
last_rotation: 0.0,
|
||||
retained_count: RATCHET_COUNT,
|
||||
rotation_interval: RATCHET_INTERVAL,
|
||||
},
|
||||
signature,
|
||||
))
|
||||
had_legacy_rotation,
|
||||
packed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct RatchetRingPersisted {
|
||||
/// A verified ratchet ring bound to one crash-safe persistence path.
|
||||
///
|
||||
/// This is the high-level counterpart to Python's
|
||||
/// `Destination.enable_ratchets(path)`: opening loads and verifies an existing
|
||||
/// Python-compatible ring or creates a signed empty one. Rotations persist a
|
||||
/// candidate before replacing the live secret state.
|
||||
pub struct PersistentRatchetRing {
|
||||
path: PathBuf,
|
||||
ring: RatchetRing,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PersistentRatchetRing {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("PersistentRatchetRing")
|
||||
.field("path", &self.path)
|
||||
.field("retained_keys", &self.ring.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PersistentRatchetRing {
|
||||
/// Load and verify `path`, or initialize it with a signed empty ring.
|
||||
pub fn open(path: impl AsRef<Path>, identity: &Identity) -> std::io::Result<Self> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let ring = if path.is_file() {
|
||||
RatchetRing::load_verified(&path, identity)?.into_ring()
|
||||
} else {
|
||||
let ring = RatchetRing::new();
|
||||
ring.save_verified(&path, identity)?;
|
||||
ring
|
||||
};
|
||||
Ok(Self { path, ring })
|
||||
}
|
||||
|
||||
/// Persistence path for this ring.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Borrow the underlying secret ring for policy inspection.
|
||||
pub fn ring(&self) -> &RatchetRing {
|
||||
&self.ring
|
||||
}
|
||||
|
||||
/// Most recently persisted ratchet public key.
|
||||
pub fn current_public_key(&self) -> Option<[u8; 32]> {
|
||||
self.ring.current_public_key()
|
||||
}
|
||||
|
||||
/// Retained private keys, newest first, for destination decryption.
|
||||
pub fn private_keys(&self) -> &[[u8; 32]] {
|
||||
self.ring.private_keys()
|
||||
}
|
||||
|
||||
/// Number of retained private ratchets.
|
||||
pub fn len(&self) -> usize {
|
||||
self.ring.len()
|
||||
}
|
||||
|
||||
/// Whether no ratchet has been generated yet.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.ring.is_empty()
|
||||
}
|
||||
|
||||
/// Return a usable current public key, rotating first when due.
|
||||
pub fn ensure_current(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
|
||||
self.ensure_current_at(identity, wall_time_secs())
|
||||
}
|
||||
|
||||
/// Deterministic form of [`Self::ensure_current`] for runtime/tests.
|
||||
pub fn ensure_current_at(
|
||||
&mut self,
|
||||
identity: &Identity,
|
||||
now: f64,
|
||||
) -> std::io::Result<[u8; 32]> {
|
||||
if self.ring.is_empty() || self.ring.needs_rotation_at(now) {
|
||||
self.rotate_at(identity, now)
|
||||
} else {
|
||||
self.ring
|
||||
.current_public_key()
|
||||
.ok_or_else(|| invalid_data("ratchet ring has no current key"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Force a crash-safe rotation now.
|
||||
pub fn rotate(&mut self, identity: &Identity) -> std::io::Result<[u8; 32]> {
|
||||
self.rotate_at(identity, wall_time_secs())
|
||||
}
|
||||
|
||||
/// Force a crash-safe rotation at an explicit wall-clock time.
|
||||
pub fn rotate_at(&mut self, identity: &Identity, now: f64) -> std::io::Result<[u8; 32]> {
|
||||
if !now.is_finite() || now < 0.0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"ratchet rotation time must be finite and non-negative",
|
||||
));
|
||||
}
|
||||
let prepared = self.ring.prepare_rotation_at(now);
|
||||
prepared.ring().save_verified(&self.path, identity)?;
|
||||
Ok(self.ring.commit_prepared_rotation(prepared))
|
||||
}
|
||||
}
|
||||
|
||||
struct DecodedRatchetRing {
|
||||
ring: RatchetRing,
|
||||
signature: [u8; 64],
|
||||
had_legacy_rotation: bool,
|
||||
packed: Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// A rotation candidate owns a duplicate secret ring and zeroises it on drop
|
||||
/// unless it is committed into the live ring.
|
||||
pub struct PreparedRatchetRotation {
|
||||
candidate: RatchetRing,
|
||||
public_key: [u8; 32],
|
||||
}
|
||||
|
||||
impl PreparedRatchetRotation {
|
||||
pub fn ring(&self) -> &RatchetRing {
|
||||
&self.candidate
|
||||
}
|
||||
|
||||
pub fn public_key(&self) -> [u8; 32] {
|
||||
self.public_key
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Zeroize)]
|
||||
struct RatchetRingPersistedWrite {
|
||||
#[serde(with = "serde_bytes")]
|
||||
signature: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
ratchets: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RatchetRingPersistedRead {
|
||||
#[serde(with = "serde_bytes")]
|
||||
signature: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
ratchets: Vec<u8>,
|
||||
#[serde(default)]
|
||||
last_rotation: f64,
|
||||
last_rotation: Option<f64>,
|
||||
}
|
||||
|
||||
impl Zeroize for RatchetRing {
|
||||
@@ -242,28 +603,33 @@ pub struct ReceivedRatchet {
|
||||
// On-disk shape shared with the Python reference: `{"ratchet": bytes, "received": float}`.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ReceivedRatchetPersisted {
|
||||
#[serde(with = "serde_bytes")]
|
||||
ratchet: Vec<u8>,
|
||||
received: f64,
|
||||
}
|
||||
|
||||
impl ReceivedRatchet {
|
||||
pub fn new(ratchet_pub: [u8; 32]) -> Self {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
Self::new_at(ratchet_pub, wall_time_secs())
|
||||
}
|
||||
|
||||
pub fn new_at(ratchet_pub: [u8; 32], received_at: f64) -> Self {
|
||||
Self {
|
||||
ratchet_pub,
|
||||
received_at: now,
|
||||
received_at: if received_at.is_finite() && received_at >= 0.0 {
|
||||
received_at
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_expired(&self) -> bool {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
now - self.received_at > RATCHET_EXPIRY as f64
|
||||
self.is_expired_at(wall_time_secs())
|
||||
}
|
||||
|
||||
pub fn is_expired_at(&self, now: f64) -> bool {
|
||||
now.is_finite() && now >= self.received_at && now - self.received_at > RATCHET_EXPIRY as f64
|
||||
}
|
||||
|
||||
pub fn ratchet_id(&self) -> Vec<u8> {
|
||||
@@ -276,8 +642,8 @@ impl ReceivedRatchet {
|
||||
ratchet: self.ratchet_pub.to_vec(),
|
||||
received: self.received_at,
|
||||
};
|
||||
let buf =
|
||||
rmp_serde::to_vec(&persisted).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let buf = rmp_serde::to_vec_named(&persisted)
|
||||
.map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
@@ -287,7 +653,8 @@ impl ReceivedRatchet {
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> std::io::Result<Self> {
|
||||
let data = std::fs::read(path)?;
|
||||
let data = persistence::read_file_bounded(path, RECEIVED_RATCHET_FILE_MAX_BYTES)?
|
||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?;
|
||||
let persisted: ReceivedRatchetPersisted =
|
||||
rmp_serde::from_slice(&data).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
|
||||
@@ -297,6 +664,9 @@ impl ReceivedRatchet {
|
||||
"invalid ratchet public key length",
|
||||
));
|
||||
}
|
||||
if !persisted.received.is_finite() || persisted.received < 0.0 {
|
||||
return Err(invalid_data("invalid received-ratchet timestamp"));
|
||||
}
|
||||
let mut ratchet_pub = [0u8; 32];
|
||||
ratchet_pub.copy_from_slice(&persisted.ratchet);
|
||||
|
||||
@@ -387,13 +757,19 @@ impl ReceivedRatchetStore {
|
||||
/// Record `ratchet_pub` for `dest_hash`. Re-inserting the identical key is a no-op;
|
||||
/// any other value replaces the entry and is written to disk when backed.
|
||||
pub fn remember(&mut self, dest_hash: [u8; 16], ratchet_pub: [u8; 32]) {
|
||||
self.remember_at(dest_hash, ratchet_pub, wall_time_secs());
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
|
||||
let received = ReceivedRatchet::new(ratchet_pub);
|
||||
let received = ReceivedRatchet::new_at(ratchet_pub, received_at);
|
||||
|
||||
if let Some(ref dir) = self.storage_dir {
|
||||
let hexhash = hex::encode(dest_hash);
|
||||
@@ -413,6 +789,10 @@ impl ReceivedRatchetStore {
|
||||
/// Return the current ratchet public key for `dest_hash`, loading from
|
||||
/// disk on miss. Yields `None` if the entry is expired or absent.
|
||||
pub fn get(&mut self, dest_hash: &[u8; 16]) -> Option<[u8; 32]> {
|
||||
self.get_at(dest_hash, wall_time_secs())
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -420,7 +800,7 @@ impl ReceivedRatchetStore {
|
||||
if path.exists() {
|
||||
match ReceivedRatchet::load(&path) {
|
||||
Ok(ratchet) => {
|
||||
if !ratchet.is_expired() && ratchet.ratchet_pub.len() == 32 {
|
||||
if !ratchet.is_expired_at(now) {
|
||||
self.entries.insert(*dest_hash, ratchet);
|
||||
} else {
|
||||
return None;
|
||||
@@ -441,7 +821,7 @@ impl ReceivedRatchetStore {
|
||||
|
||||
self.entries
|
||||
.get(dest_hash)
|
||||
.filter(|r| !r.is_expired())
|
||||
.filter(|r| !r.is_expired_at(now))
|
||||
.map(|r| r.ratchet_pub)
|
||||
}
|
||||
|
||||
@@ -476,6 +856,7 @@ impl Default for ReceivedRatchetStore {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn test_ratchet_ring_rotate() {
|
||||
@@ -491,13 +872,56 @@ mod tests {
|
||||
assert_ne!(pub1, pub2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_rotation_does_not_mutate_live_ring_until_commit() {
|
||||
let mut ring = RatchetRing::new();
|
||||
ring.rotate_at(100.0);
|
||||
let before = ring.private_keys().to_vec();
|
||||
|
||||
let abandoned = ring.prepare_rotation_at(200.0);
|
||||
assert_eq!(ring.private_keys(), before);
|
||||
assert_eq!(abandoned.ring().len(), 2);
|
||||
drop(abandoned);
|
||||
assert_eq!(ring.private_keys(), before);
|
||||
|
||||
let prepared = ring.prepare_rotation_at(200.0);
|
||||
let expected_public = prepared.public_key();
|
||||
let committed_public = ring.commit_prepared_rotation(prepared);
|
||||
assert_eq!(committed_public, expected_public);
|
||||
assert_eq!(ring.len(), 2);
|
||||
assert_eq!(ring.current_public_key(), Some(expected_public));
|
||||
assert_eq!(ring.last_rotation(), 200.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_clock_rollback_never_looks_elapsed() {
|
||||
let mut ring = RatchetRing::new();
|
||||
ring.set_ratchet_interval(30);
|
||||
assert!(ring.needs_rotation_at(100.0));
|
||||
ring.rotate_at(100.0);
|
||||
assert!(!ring.needs_rotation_at(99.0));
|
||||
assert!(!ring.needs_rotation_at(129.999));
|
||||
assert!(ring.needs_rotation_at(130.0));
|
||||
|
||||
let mut unknown_age = RatchetRing::new();
|
||||
assert!(unknown_age.needs_rotation_at(100.0));
|
||||
assert!(unknown_age.anchor_rotation_at(100.0));
|
||||
assert!(!unknown_age.needs_rotation_at(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ratchet_ring_max_keys() {
|
||||
let mut ring = RatchetRing::new();
|
||||
let initial_capacity = ring.keys.capacity();
|
||||
for _ in 0..RATCHET_COUNT + 10 {
|
||||
ring.rotate();
|
||||
}
|
||||
assert_eq!(ring.len(), RATCHET_COUNT);
|
||||
assert_eq!(
|
||||
ring.keys.capacity(),
|
||||
initial_capacity,
|
||||
"rotating a full secret ring must not reallocate uncleared storage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -522,6 +946,197 @@ mod tests {
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_ring_initializes_rotates_and_verifies_before_use() {
|
||||
let identity = Identity::new();
|
||||
let wrong_identity = Identity::new();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum_persistent_ratchets_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
|
||||
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
assert!(path.is_file());
|
||||
assert!(persistent.is_empty());
|
||||
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
|
||||
assert_eq!(persistent.current_public_key(), Some(first));
|
||||
assert_eq!(persistent.len(), 1);
|
||||
|
||||
assert!(PersistentRatchetRing::open(&path, &wrong_identity).is_err());
|
||||
let mut reloaded = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
assert_eq!(reloaded.current_public_key(), Some(first));
|
||||
let second = reloaded.ensure_current_at(&identity, 200.0).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(reloaded.len(), 2);
|
||||
assert_eq!(
|
||||
RatchetRing::load_verified(&path, &identity)
|
||||
.unwrap()
|
||||
.ring()
|
||||
.current_public_key(),
|
||||
Some(second)
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_ring_does_not_commit_when_rotation_cannot_be_saved() {
|
||||
let identity = Identity::new();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum_persistent_ratchet_failure_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let mut persistent = PersistentRatchetRing::open(&path, &identity).unwrap();
|
||||
let first = persistent.ensure_current_at(&identity, 100.0).unwrap();
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(persistent.rotate_at(&identity, 200.0).is_err());
|
||||
assert_eq!(persistent.current_public_key(), Some(first));
|
||||
assert_eq!(persistent.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_ring_file_is_python_map_of_signed_binary_keys() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_python_wire");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let identity = Identity::new();
|
||||
let mut ring = RatchetRing::new();
|
||||
ring.rotate_at(100.0);
|
||||
ring.rotate_at(200.0);
|
||||
|
||||
ring.save_verified(&path, &identity).unwrap();
|
||||
let data = std::fs::read(&path).unwrap();
|
||||
let envelope = rmpv::decode::read_value(&mut Cursor::new(&data)).unwrap();
|
||||
let map = envelope.as_map().expect("Python envelope must be a map");
|
||||
assert_eq!(map.len(), 2);
|
||||
let signature = map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("signature"))
|
||||
.and_then(|(_, value)| value.as_slice())
|
||||
.expect("signature must be MessagePack binary");
|
||||
let packed = map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("ratchets"))
|
||||
.and_then(|(_, value)| value.as_slice())
|
||||
.expect("ratchets must be MessagePack binary");
|
||||
let signature: [u8; 64] = signature.try_into().unwrap();
|
||||
assert!(identity.verify(packed, &signature));
|
||||
|
||||
let packed_value = rmpv::decode::read_value(&mut Cursor::new(packed)).unwrap();
|
||||
let keys = packed_value.as_array().expect("ratchets must be a list");
|
||||
assert_eq!(keys.len(), 2);
|
||||
assert!(
|
||||
keys.iter()
|
||||
.all(|key| key.as_slice().is_some_and(|b| b.len() == 32))
|
||||
);
|
||||
|
||||
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
|
||||
assert_eq!(loaded.format(), RatchetRingFormat::Canonical);
|
||||
assert_eq!(loaded.ring().private_keys(), ring.private_keys());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_ring_rejects_wrong_identity_signature() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_wrong_signature");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let owner = Identity::new();
|
||||
let wrong = Identity::new();
|
||||
let mut ring = RatchetRing::new();
|
||||
ring.rotate_at(100.0);
|
||||
ring.save_verified(&path, &owner).unwrap();
|
||||
|
||||
let err = RatchetRing::load_verified(&path, &wrong)
|
||||
.err()
|
||||
.expect("wrong owner must be rejected");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert!(
|
||||
path.exists(),
|
||||
"a rejected key file must be preserved for recovery"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verified_ring_accepts_exact_legacy_rust_shape_but_ignores_age() {
|
||||
#[derive(Serialize)]
|
||||
struct LegacyRustRatchets {
|
||||
signature: Vec<u8>,
|
||||
ratchets: Vec<u8>,
|
||||
last_rotation: f64,
|
||||
}
|
||||
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_legacy_rust");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let identity = Identity::new();
|
||||
let keys = vec![[0x11; 32], [0x22; 32]];
|
||||
// This intentionally recreates the pre-fix Rust encoding: compact
|
||||
// struct, byte vectors as integer arrays, and signature over only the
|
||||
// current public ratchet.
|
||||
let ratchets = rmp_serde::to_vec(&keys).unwrap();
|
||||
let current_public = ratchet_public_bytes(&keys[0]);
|
||||
let signature = identity.sign(¤t_public).unwrap();
|
||||
let legacy = LegacyRustRatchets {
|
||||
signature: signature.to_vec(),
|
||||
ratchets,
|
||||
last_rotation: f64::MAX,
|
||||
};
|
||||
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
|
||||
|
||||
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
|
||||
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
|
||||
assert_eq!(loaded.ring().private_keys(), keys);
|
||||
assert_eq!(loaded.ring().last_rotation(), 0.0);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_load_rejects_oversize_and_overcount_without_retrying() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_bounds");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("ratchets");
|
||||
let identity = Identity::new();
|
||||
|
||||
std::fs::write(&path, vec![0u8; RATCHET_FILE_MAX_BYTES + 1]).unwrap();
|
||||
assert_eq!(
|
||||
RatchetRing::load_verified(&path, &identity)
|
||||
.err()
|
||||
.expect("oversize ring must fail")
|
||||
.kind(),
|
||||
std::io::ErrorKind::InvalidData
|
||||
);
|
||||
|
||||
let keys = vec![[0x44; 32]; RATCHET_COUNT + 1];
|
||||
let packed = rmp_serde::to_vec(&keys).unwrap();
|
||||
let envelope = RatchetRingPersistedWrite {
|
||||
signature: vec![0u8; 64],
|
||||
ratchets: packed,
|
||||
};
|
||||
std::fs::write(&path, rmp_serde::to_vec_named(&envelope).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
RatchetRing::load_verified(&path, &identity)
|
||||
.err()
|
||||
.expect("overcount ring must fail")
|
||||
.kind(),
|
||||
std::io::ErrorKind::InvalidData
|
||||
);
|
||||
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ratchet_ring_loads_python_shape_without_last_rotation() {
|
||||
#[derive(Serialize)]
|
||||
@@ -597,6 +1212,17 @@ mod tests {
|
||||
assert!((loaded.received_at - received.received_at).abs() < 0.001);
|
||||
assert!(!loaded.is_expired());
|
||||
|
||||
let encoded = std::fs::read(&path).unwrap();
|
||||
let envelope = rmpv::decode::read_value(&mut Cursor::new(encoded)).unwrap();
|
||||
let map = envelope.as_map().expect("Python envelope must be a map");
|
||||
assert_eq!(map.len(), 2);
|
||||
assert!(
|
||||
map.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("ratchet"))
|
||||
.and_then(|(_, value)| value.as_slice())
|
||||
.is_some_and(|ratchet| ratchet.len() == 32)
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
@@ -642,6 +1268,25 @@ mod tests {
|
||||
assert_eq!(store.get(&dest_hash), Some(ratchet_pub2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_received_ratchet_does_not_refresh_expiry() {
|
||||
let mut store = ReceivedRatchetStore::new();
|
||||
let dest_hash = [0xBC; 16];
|
||||
let ratchet = [0xCD; 32];
|
||||
store.remember_at(dest_hash, ratchet, 10.0);
|
||||
store.remember_at(dest_hash, ratchet, 20.0);
|
||||
|
||||
assert_eq!(
|
||||
store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64),
|
||||
Some(ratchet)
|
||||
);
|
||||
assert_eq!(
|
||||
store.get_at(&dest_hash, 10.0 + RATCHET_EXPIRY as f64 + 0.001),
|
||||
None,
|
||||
"same-key reannounce must not extend the original receive age"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_ratchet_id() {
|
||||
let pub_bytes = rns_crypto::random::random_32();
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-interface"
|
||||
description = "Network interface trait and implementations for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
@@ -10,7 +11,6 @@ default = []
|
||||
serial = ["dep:serialport"]
|
||||
rnode-tcp = []
|
||||
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
|
||||
ble_peer = ["ble"]
|
||||
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
|
||||
# and reverse-peering probes slow down in the background; BLE peer scan
|
||||
# cadence adjusts to `is_foreground`. Disabled on desktop builds.
|
||||
@@ -19,6 +19,7 @@ mobile-throttle = ["rns-transport/mobile-throttle"]
|
||||
[dependencies]
|
||||
rns-crypto = { workspace = true, features = ["std"] }
|
||||
rns-wire = { workspace = true, features = ["std"] }
|
||||
rns-identity = { workspace = true }
|
||||
rns-transport = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -34,6 +35,7 @@ rand = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
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
|
||||
@@ -49,6 +51,9 @@ objc2-core-bluetooth = "0.2"
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
# Keepalive-tuning tests read socket options back via getsockopt.
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
+1770
-333
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1737,6 +1737,7 @@ pub async fn spawn_auto_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -2003,7 +2004,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_constants() {
|
||||
assert_eq!(HW_MTU, 1196);
|
||||
const { assert!(FIXED_MTU) };
|
||||
assert_eq!(DISCOVERY_PORT, 29716);
|
||||
assert_eq!(DATA_PORT, 42671);
|
||||
assert_eq!(UNICAST_DISCOVERY_PORT, 29717);
|
||||
|
||||
@@ -407,6 +407,7 @@ pub async fn spawn_ax25kiss_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
//! buffers. Inbound deframer is capped (vs Python's unbounded) to avoid
|
||||
//! malformed-peer memory blow-up.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -16,8 +17,12 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::socket_tuning::{iface_addr_for, set_keepalive_tuned, set_socket_buffers};
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{
|
||||
InboundPacket, InterfaceInspectionSnapshot, InterfaceInspectionSource, TransportMessage,
|
||||
};
|
||||
|
||||
/// 1 MiB MTU — also the SO_RCVBUF/SNDBUF target (kernel clamps).
|
||||
pub const HW_MTU: u32 = 1_048_576;
|
||||
@@ -37,8 +42,21 @@ pub const TCP_PROBES: u32 = 12;
|
||||
/// Linux TCP_USER_TIMEOUT — drops stuck conns when peer goes silent without RST.
|
||||
pub const TCP_USER_TIMEOUT: u32 = 24;
|
||||
|
||||
pub const BLOCK_FAST_FLAPPING: bool = true;
|
||||
pub const FAST_FLAPPING_THRESHOLD: Duration = Duration::from_secs(20);
|
||||
pub const FAST_FLAPPING_GRACE: u64 = 5;
|
||||
pub const FAST_FLAPPING_BLOCK_TIME: Duration = Duration::from_secs(12 * 60 * 60);
|
||||
|
||||
const TX_CHANNEL_DEPTH: usize = 1024;
|
||||
|
||||
/// Bounds process-global fast-flap state to a conservative few hundred KiB.
|
||||
///
|
||||
/// Once full, unexpired tracked (including blocked) IPs retain their state and
|
||||
/// new IPs remain admissible but are not tracked. Strictly expired entries can
|
||||
/// be reclaimed. This prevents an address spray from turning the abuse
|
||||
/// safeguard itself into an unbounded allocation.
|
||||
const MAX_TRACKED_FAST_FLAP_IPS: usize = 4096;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackboneServerConfig {
|
||||
pub name: String,
|
||||
@@ -48,6 +66,14 @@ pub struct BackboneServerConfig {
|
||||
pub mode: InterfaceMode,
|
||||
/// Optional kernel ifname; binds to its current IP (falls back to `listen_ip`).
|
||||
pub device: Option<String>,
|
||||
/// Reject an IP after more than `fast_flapping_grace` short connections.
|
||||
pub block_fast_flapping: bool,
|
||||
/// Connections shorter than this duration count as fast flaps.
|
||||
pub fast_flapping_threshold: Duration,
|
||||
/// Number of short connections tolerated before blocking starts.
|
||||
pub fast_flapping_grace: u64,
|
||||
/// Time since the latest short connection before its state expires.
|
||||
pub fast_flapping_block_time: Duration,
|
||||
}
|
||||
|
||||
impl BackboneServerConfig {
|
||||
@@ -59,6 +85,10 @@ impl BackboneServerConfig {
|
||||
prefer_ipv6: false,
|
||||
mode: InterfaceMode::Full,
|
||||
device: None,
|
||||
block_fast_flapping: BLOCK_FAST_FLAPPING,
|
||||
fast_flapping_threshold: FAST_FLAPPING_THRESHOLD,
|
||||
fast_flapping_grace: FAST_FLAPPING_GRACE,
|
||||
fast_flapping_block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +118,222 @@ impl BackboneClientConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapPolicy {
|
||||
enabled: bool,
|
||||
threshold: Duration,
|
||||
grace: u64,
|
||||
block_time: Duration,
|
||||
}
|
||||
|
||||
impl From<&BackboneServerConfig> for FastFlapPolicy {
|
||||
fn from(config: &BackboneServerConfig) -> Self {
|
||||
Self {
|
||||
enabled: config.block_fast_flapping,
|
||||
threshold: config.fast_flapping_threshold,
|
||||
grace: config.fast_flapping_grace,
|
||||
block_time: config.fast_flapping_block_time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait MonotonicClock: Send + Sync {
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
struct SystemMonotonicClock;
|
||||
|
||||
impl MonotonicClock for SystemMonotonicClock {
|
||||
fn now(&self) -> Duration {
|
||||
static EPOCH: OnceLock<Instant> = OnceLock::new();
|
||||
EPOCH.get_or_init(Instant::now).elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct FastFlapEntry {
|
||||
last_flap: Duration,
|
||||
flaps: u64,
|
||||
}
|
||||
|
||||
struct FastFlapTable {
|
||||
entries: HashMap<IpAddr, FastFlapEntry>,
|
||||
capacity: usize,
|
||||
}
|
||||
|
||||
impl FastFlapTable {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
entries: HashMap::new(),
|
||||
capacity,
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_expired(&mut self, now: Duration, block_time: Duration) {
|
||||
self.entries
|
||||
.retain(|_, entry| now.saturating_sub(entry.last_flap) <= block_time);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FastFlapRuntime {
|
||||
clock: Arc<dyn MonotonicClock>,
|
||||
table: Arc<Mutex<FastFlapTable>>,
|
||||
}
|
||||
|
||||
impl FastFlapRuntime {
|
||||
fn production() -> Self {
|
||||
static TABLE: OnceLock<Arc<Mutex<FastFlapTable>>> = OnceLock::new();
|
||||
Self {
|
||||
clock: Arc::new(SystemMonotonicClock),
|
||||
table: Arc::clone(TABLE.get_or_init(|| {
|
||||
Arc::new(Mutex::new(FastFlapTable::new(MAX_TRACKED_FAST_FLAP_IPS)))
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn admit(&self, remote_ip: IpAddr, policy: FastFlapPolicy) -> FastFlapAdmission {
|
||||
let started_at = self.clock.now();
|
||||
if !policy.enabled {
|
||||
return FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get(&remote_ip).copied() {
|
||||
if started_at.saturating_sub(entry.last_flap) > policy.block_time {
|
||||
table.entries.remove(&remote_ip);
|
||||
} else if entry.flaps > policy.grace {
|
||||
return FastFlapAdmission::Rejected { flaps: entry.flaps };
|
||||
}
|
||||
} else if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(started_at, policy.block_time);
|
||||
}
|
||||
drop(table);
|
||||
|
||||
FastFlapAdmission::Allowed(FastFlapConnection {
|
||||
remote_ip,
|
||||
started_at: Some(started_at),
|
||||
policy,
|
||||
runtime: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn record_disconnect(&self, remote_ip: IpAddr, started_at: Duration, policy: FastFlapPolicy) {
|
||||
if !policy.enabled {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = self.clock.now();
|
||||
if now.saturating_sub(started_at) >= policy.threshold {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = table.entries.get_mut(&remote_ip) {
|
||||
entry.last_flap = now;
|
||||
entry.flaps = entry.flaps.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
table.prune_expired(now, policy.block_time);
|
||||
}
|
||||
if table.entries.len() >= table.capacity {
|
||||
tracing::debug!(
|
||||
remote_ip = %remote_ip,
|
||||
capacity = table.capacity,
|
||||
"backbone fast-flap table is full; declining to track new IP",
|
||||
);
|
||||
return;
|
||||
}
|
||||
table.entries.insert(
|
||||
remote_ip,
|
||||
FastFlapEntry {
|
||||
last_flap: now,
|
||||
flaps: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn inspection_snapshot(
|
||||
&self,
|
||||
policy: FastFlapPolicy,
|
||||
active_clients: &AtomicU64,
|
||||
) -> InterfaceInspectionSnapshot {
|
||||
let blocked_ips = if policy.enabled {
|
||||
let now = self.clock.now();
|
||||
let mut table = self.table.lock().unwrap_or_else(|e| e.into_inner());
|
||||
table.prune_expired(now, policy.block_time);
|
||||
table
|
||||
.entries
|
||||
.values()
|
||||
.filter(|entry| entry.flaps > policy.grace)
|
||||
.count() as u64
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(active_clients.load(Ordering::Relaxed)),
|
||||
blocked_ips: Some(blocked_ips),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum FastFlapAdmission {
|
||||
Allowed(FastFlapConnection),
|
||||
Rejected { flaps: u64 },
|
||||
}
|
||||
|
||||
struct FastFlapConnection {
|
||||
remote_ip: IpAddr,
|
||||
started_at: Option<Duration>,
|
||||
policy: FastFlapPolicy,
|
||||
runtime: FastFlapRuntime,
|
||||
}
|
||||
|
||||
impl FastFlapConnection {
|
||||
fn record_disconnect(&mut self) {
|
||||
if let Some(started_at) = self.started_at.take() {
|
||||
self.runtime
|
||||
.record_disconnect(self.remote_ip, started_at, self.policy);
|
||||
}
|
||||
}
|
||||
|
||||
fn disconnected(mut self) {
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FastFlapConnection {
|
||||
fn drop(&mut self) {
|
||||
// The guard lives in the child read-task future, so cancellation and
|
||||
// panic exits account for the connection just like normal EOF/errors.
|
||||
self.record_disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveClientGuard {
|
||||
active_clients: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl ActiveClientGuard {
|
||||
fn new(active_clients: Arc<AtomicU64>) -> Self {
|
||||
active_clients.fetch_add(1, Ordering::Relaxed);
|
||||
Self { active_clients }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ActiveClientGuard {
|
||||
fn drop(&mut self) {
|
||||
self.active_clients.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn keepalive_durations() -> (Duration, Duration, u32, Duration) {
|
||||
(
|
||||
Duration::from_secs(TCP_PROBE_AFTER as u64),
|
||||
@@ -220,6 +466,25 @@ pub async fn spawn_backbone_server(
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
spawn_backbone_server_with_runtime(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
FastFlapRuntime::production(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn spawn_backbone_server_with_runtime(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let listen_ip = resolve_listen_addr(&config);
|
||||
let bind_addr = if listen_ip.starts_with('[') {
|
||||
@@ -230,6 +495,26 @@ pub async fn spawn_backbone_server(
|
||||
format!("{}:{}", listen_ip, config.listen_port)
|
||||
};
|
||||
let listener = TcpListener::bind(&bind_addr).await?;
|
||||
spawn_backbone_server_on_listener(
|
||||
config,
|
||||
id,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
fast_flap_runtime,
|
||||
listener,
|
||||
)
|
||||
}
|
||||
|
||||
fn spawn_backbone_server_on_listener(
|
||||
config: BackboneServerConfig,
|
||||
id: InterfaceId,
|
||||
id_gen: Arc<AtomicU64>,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
handle_tx: mpsc::Sender<InterfaceHandle>,
|
||||
fast_flap_runtime: FastFlapRuntime,
|
||||
listener: TcpListener,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let local_addr = listener.local_addr()?;
|
||||
tracing::info!(name = %config.name, addr = %local_addr, "backbone server listening");
|
||||
|
||||
@@ -237,6 +522,14 @@ pub async fn spawn_backbone_server(
|
||||
let online2 = online.clone();
|
||||
let name = config.name.clone();
|
||||
let mode = config.mode;
|
||||
let fast_flap_policy = FastFlapPolicy::from(&config);
|
||||
let active_clients = Arc::new(AtomicU64::new(0));
|
||||
let inspection_runtime = fast_flap_runtime.clone();
|
||||
let inspection_active_clients = Arc::clone(&active_clients);
|
||||
let inspection = InterfaceInspectionSource::new(move || {
|
||||
inspection_runtime.inspection_snapshot(fast_flap_policy, inspection_active_clients.as_ref())
|
||||
});
|
||||
let task_active_clients = Arc::clone(&active_clients);
|
||||
|
||||
// Parent listener is inbound-only; drain task warns on stray writes.
|
||||
let (tx, mut listener_rx) = mpsc::channel::<Bytes>(1);
|
||||
@@ -254,6 +547,19 @@ pub async fn spawn_backbone_server(
|
||||
loop {
|
||||
match listener.accept().await {
|
||||
Ok((stream, peer)) => {
|
||||
let fast_flap_connection =
|
||||
match fast_flap_runtime.admit(peer.ip(), fast_flap_policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
tracing::warn!(
|
||||
remote_ip = %peer.ip(),
|
||||
flaps,
|
||||
"backbone: rejecting fast-flapping connection",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let client_id = id_gen.fetch_add(1, Ordering::SeqCst);
|
||||
let client_name = format!("{}/client_{}", config.name, client_id);
|
||||
tracing::info!(
|
||||
@@ -279,9 +585,13 @@ pub async fn spawn_backbone_server(
|
||||
let transport_tx2 = transport_tx.clone();
|
||||
let dereg_tx = transport_tx.clone();
|
||||
let cname = client_name.clone();
|
||||
let active_client_guard =
|
||||
ActiveClientGuard::new(Arc::clone(&task_active_clients));
|
||||
let read_handle = tokio::spawn(async move {
|
||||
let _active_client_guard = active_client_guard;
|
||||
backbone_read_loop(reader, client_id, transport_tx2, c_online_r, c_rxb_r)
|
||||
.await;
|
||||
fast_flap_connection.disconnected();
|
||||
tracing::info!(name = %cname, "backbone client disconnected");
|
||||
// Proactive notify so broadcasts don't target dead tx.
|
||||
let _ = dereg_tx
|
||||
@@ -305,10 +615,14 @@ pub async fn spawn_backbone_server(
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
inspection: None,
|
||||
tx: c_tx,
|
||||
read_task: read_handle,
|
||||
};
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("backbone handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -338,6 +652,7 @@ pub async fn spawn_backbone_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: Some(inspection),
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -506,6 +821,7 @@ pub async fn spawn_backbone_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -514,6 +830,102 @@ pub async fn spawn_backbone_client(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestClock {
|
||||
now: Arc<Mutex<Duration>>,
|
||||
}
|
||||
|
||||
impl TestClock {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
now: Arc::new(Mutex::new(Duration::ZERO)),
|
||||
}
|
||||
}
|
||||
|
||||
fn advance(&self, duration: Duration) {
|
||||
let mut now = self.now.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*now = now
|
||||
.checked_add(duration)
|
||||
.expect("test monotonic clock overflow");
|
||||
}
|
||||
}
|
||||
|
||||
impl MonotonicClock for TestClock {
|
||||
fn now(&self) -> Duration {
|
||||
*self.now.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_runtime(capacity: usize) -> (FastFlapRuntime, TestClock) {
|
||||
let clock = TestClock::new();
|
||||
(
|
||||
FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::new(Mutex::new(FastFlapTable::new(capacity))),
|
||||
},
|
||||
clock,
|
||||
)
|
||||
}
|
||||
|
||||
fn default_policy() -> FastFlapPolicy {
|
||||
FastFlapPolicy {
|
||||
enabled: BLOCK_FAST_FLAPPING,
|
||||
threshold: FAST_FLAPPING_THRESHOLD,
|
||||
grace: FAST_FLAPPING_GRACE,
|
||||
block_time: FAST_FLAPPING_BLOCK_TIME,
|
||||
}
|
||||
}
|
||||
|
||||
fn allow_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) -> FastFlapConnection {
|
||||
match runtime.admit(ip, policy) {
|
||||
FastFlapAdmission::Allowed(connection) => connection,
|
||||
FastFlapAdmission::Rejected { flaps } => {
|
||||
panic!("expected connection from {ip} to be allowed, recorded flaps: {flaps}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_rejected(runtime: &FastFlapRuntime, ip: IpAddr, policy: FastFlapPolicy) {
|
||||
assert!(matches!(
|
||||
runtime.admit(ip, policy),
|
||||
FastFlapAdmission::Rejected { .. }
|
||||
));
|
||||
}
|
||||
|
||||
fn record_short_connection(
|
||||
runtime: &FastFlapRuntime,
|
||||
clock: &TestClock,
|
||||
ip: IpAddr,
|
||||
policy: FastFlapPolicy,
|
||||
) {
|
||||
let connection = allow_connection(runtime, ip, policy);
|
||||
clock.advance(Duration::from_millis(1));
|
||||
connection.disconnected();
|
||||
}
|
||||
|
||||
fn tracked_flaps(runtime: &FastFlapRuntime, ip: IpAddr) -> Option<u64> {
|
||||
runtime
|
||||
.table
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.entries
|
||||
.get(&ip)
|
||||
.map(|entry| entry.flaps)
|
||||
}
|
||||
|
||||
fn inspection_snapshot(handle: &InterfaceHandle) -> InterfaceInspectionSnapshot {
|
||||
handle
|
||||
.inspection
|
||||
.as_ref()
|
||||
.expect("backbone listener exposes aggregate inspection")
|
||||
.snapshot()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backbone_server_config() {
|
||||
@@ -521,6 +933,13 @@ mod tests {
|
||||
assert_eq!(cfg.listen_port, 4243);
|
||||
assert!(!cfg.prefer_ipv6);
|
||||
assert!(cfg.device.is_none());
|
||||
assert!(cfg.block_fast_flapping);
|
||||
assert_eq!(cfg.fast_flapping_threshold, Duration::from_secs(20));
|
||||
assert_eq!(cfg.fast_flapping_grace, 5);
|
||||
assert_eq!(
|
||||
cfg.fast_flapping_block_time,
|
||||
Duration::from_secs(12 * 60 * 60)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -573,6 +992,316 @@ mod tests {
|
||||
assert!(mtu >= rns_wire::constants::MTU as u32 / 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_flap_grace_is_strictly_greater_than_five() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
|
||||
|
||||
// Upstream's strict `flaps > grace` admits and records six short
|
||||
// connections for grace=5. The following (seventh) admission blocks.
|
||||
for _ in 0..=policy.grace {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(6));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threshold_and_expiry_boundaries_are_strict() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let stable_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2));
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 3));
|
||||
|
||||
let stable = allow_connection(&runtime, stable_ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, stable_ip), None);
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
clock.advance(policy.block_time);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
clock.advance(Duration::from_nanos(1));
|
||||
let readmitted = allow_connection(&runtime, blocked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, blocked_ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_connection_does_not_reset_existing_flaps() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 1;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 4));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
let stable = allow_connection(&runtime, ip, policy);
|
||||
clock.advance(policy.threshold);
|
||||
stable.disconnected();
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(1));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), Some(2));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_connection_does_not_refresh_expiry() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 5));
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
clock.advance(policy.block_time - Duration::from_nanos(1));
|
||||
assert_rejected(&runtime, ip, policy);
|
||||
clock.advance(Duration::from_nanos(2));
|
||||
let readmitted = allow_connection(&runtime, ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
readmitted.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_policy_neither_tracks_nor_blocks() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.enabled = false;
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 6));
|
||||
|
||||
for _ in 0..10 {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(tracked_flaps(&runtime, ip), None);
|
||||
let admitted = allow_connection(&runtime, ip, policy);
|
||||
admitted.disconnected();
|
||||
let active_clients = AtomicU64::new(0);
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(policy, &active_clients),
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(0),
|
||||
blocked_ips: Some(0),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_uses_strict_grace_and_expiry_boundaries() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 12));
|
||||
let active_clients = AtomicU64::new(3);
|
||||
|
||||
for _ in 0..policy.grace {
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
}
|
||||
assert_eq!(
|
||||
runtime.inspection_snapshot(policy, &active_clients),
|
||||
InterfaceInspectionSnapshot {
|
||||
active_clients: Some(3),
|
||||
blocked_ips: Some(0),
|
||||
}
|
||||
);
|
||||
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
clock.advance(policy.block_time);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(1)
|
||||
);
|
||||
clock.advance(Duration::from_nanos(1));
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.blocked_ips,
|
||||
Some(0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_inspection_snapshots_are_live_and_non_destructive() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13));
|
||||
let active_clients = AtomicU64::new(1);
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
|
||||
let first = runtime.inspection_snapshot(policy, &active_clients);
|
||||
let second = runtime.inspection_snapshot(policy, &active_clients);
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(first.active_clients, Some(1));
|
||||
assert_eq!(first.blocked_ips, Some(1));
|
||||
|
||||
active_clients.store(2, Ordering::Relaxed);
|
||||
assert_eq!(
|
||||
runtime
|
||||
.inspection_snapshot(policy, &active_clients)
|
||||
.active_clients,
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_is_ip_scoped() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let blocked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
|
||||
let other_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 8));
|
||||
|
||||
record_short_connection(&runtime, &clock, blocked_ip, policy);
|
||||
assert_rejected(&runtime, blocked_ip, policy);
|
||||
let other = allow_connection(&runtime, other_ip, policy);
|
||||
other.disconnected();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_share_one_process_global_ip_keyspace() {
|
||||
let clock = TestClock::new();
|
||||
let table = Arc::new(Mutex::new(FastFlapTable::new(16)));
|
||||
let first_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table: Arc::clone(&table),
|
||||
};
|
||||
let second_listener = FastFlapRuntime {
|
||||
clock: Arc::new(clock.clone()),
|
||||
table,
|
||||
};
|
||||
let policy = default_policy();
|
||||
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9));
|
||||
|
||||
for index in 0..=policy.grace {
|
||||
let listener = if index % 2 == 0 {
|
||||
&first_listener
|
||||
} else {
|
||||
&second_listener
|
||||
};
|
||||
record_short_connection(listener, &clock, ip, policy);
|
||||
}
|
||||
assert_rejected(&first_listener, ip, policy);
|
||||
assert_rejected(&second_listener, ip, policy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_table_preserves_unexpired_entries_and_reuses_expired_slots() {
|
||||
let (runtime, clock) = test_runtime(1);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let tracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
|
||||
let untracked_ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 11));
|
||||
|
||||
record_short_connection(&runtime, &clock, tracked_ip, policy);
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), Some(1));
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), None);
|
||||
assert_rejected(&runtime, tracked_ip, policy);
|
||||
let untracked = allow_connection(&runtime, untracked_ip, policy);
|
||||
untracked.disconnected();
|
||||
|
||||
clock.advance(policy.block_time + Duration::from_nanos(1));
|
||||
record_short_connection(&runtime, &clock, untracked_ip, policy);
|
||||
assert_eq!(tracked_flaps(&runtime, tracked_ip), None);
|
||||
assert_eq!(tracked_flaps(&runtime, untracked_ip), Some(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aborted_child_read_task_records_short_connection() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let config =
|
||||
BackboneServerConfig::new("abort-accounting-test", "127.0.0.1", listen_addr.port());
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
id_gen,
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime.clone(),
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
|
||||
let _stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let child = tokio::time::timeout(Duration::from_secs(1), handle_rx.recv())
|
||||
.await
|
||||
.expect("accepted child handle timed out")
|
||||
.expect("child handle channel closed");
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(1));
|
||||
clock.advance(Duration::from_millis(1));
|
||||
child.read_task.abort();
|
||||
let _ = child.read_task.await;
|
||||
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
assert_eq!(
|
||||
tracked_flaps(&runtime, IpAddr::V4(Ipv4Addr::LOCALHOST)),
|
||||
Some(1)
|
||||
);
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_admission_does_not_consume_child_id_or_handle() {
|
||||
let (runtime, clock) = test_runtime(16);
|
||||
let mut policy = default_policy();
|
||||
policy.grace = 0;
|
||||
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
|
||||
record_short_connection(&runtime, &clock, ip, policy);
|
||||
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.await
|
||||
.unwrap();
|
||||
let listen_addr = listener.local_addr().unwrap();
|
||||
let mut config =
|
||||
BackboneServerConfig::new("blocked-id-test", "127.0.0.1", listen_addr.port());
|
||||
config.fast_flapping_grace = 0;
|
||||
let id_gen = Arc::new(AtomicU64::new(100));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(8);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(8);
|
||||
let parent = spawn_backbone_server_on_listener(
|
||||
config,
|
||||
1,
|
||||
Arc::clone(&id_gen),
|
||||
transport_tx,
|
||||
handle_tx,
|
||||
runtime,
|
||||
listener,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
|
||||
let mut stream = TcpStream::connect(listen_addr).await.unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
let closed = tokio::time::timeout(Duration::from_secs(1), stream.read(&mut byte))
|
||||
.await
|
||||
.expect("blocked connection was not closed");
|
||||
assert!(matches!(closed, Ok(0) | Err(_)));
|
||||
assert_eq!(id_gen.load(Ordering::SeqCst), 100);
|
||||
assert!(handle_rx.try_recv().is_err());
|
||||
assert_eq!(inspection_snapshot(&parent).active_clients, Some(0));
|
||||
assert_eq!(inspection_snapshot(&parent).blocked_ips, Some(1));
|
||||
|
||||
parent.read_task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backbone_max_reconnect_dereg() {
|
||||
// Connect attempts to a port nobody is listening on; with
|
||||
|
||||
@@ -374,12 +374,27 @@ pub async fn connect_peer(
|
||||
let mut g = online_flags().lock().expect("online_flags lock");
|
||||
g.insert(address.clone(), online.clone());
|
||||
}
|
||||
// CB auto-negotiates the ATT MTU during connection setup and exposes the
|
||||
// usable per-write payload via maximumWriteValueLengthForType:. Reading it
|
||||
// (rather than assuming 244) both prevents silent truncation on a link that
|
||||
// negotiated a smaller MTU and unlocks larger writes (iOS commonly 512).
|
||||
// Clamp: floor at the ATT-23 minimum, ceil at our fragment TARGET_MTU.
|
||||
const WRITE_WITHOUT_RESPONSE: usize = 1; // CBCharacteristicWriteWithoutResponse
|
||||
let negotiated: usize =
|
||||
unsafe { msg_send![peripheral.0, maximumWriteValueLengthForType: WRITE_WITHOUT_RESPONSE] };
|
||||
let write_mtu = negotiated.clamp(20, crate::ble_peer::TARGET_MTU as usize);
|
||||
tracing::info!(
|
||||
target: "ble_trace",
|
||||
step = "apple_connect.mtu",
|
||||
address = %address,
|
||||
negotiated,
|
||||
write_mtu,
|
||||
"Apple BLE central: negotiated write MTU"
|
||||
);
|
||||
let peer = Arc::new(ConnectedPeer {
|
||||
address: address.clone(),
|
||||
protocol,
|
||||
// CB auto-negotiates ATT MTU with no public read-back API.
|
||||
// 244 = ATT MTU 247 - 3-byte header (BLE 4.2+ baseline).
|
||||
write_mtu: 244,
|
||||
write_mtu,
|
||||
online: online.clone(),
|
||||
peripheral,
|
||||
delegate,
|
||||
@@ -406,39 +421,33 @@ pub fn write_peer(address: &str, data: &[u8]) -> Result<(), String> {
|
||||
return Err(format!("peer {address} marked offline"));
|
||||
}
|
||||
|
||||
// The flag can flip back to false at any time after returning true
|
||||
// (per Apple's docs); the ready-to-send delegate drains the queue.
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if ready {
|
||||
unsafe { issue_write(&peer, data) };
|
||||
return Ok(());
|
||||
// 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());
|
||||
}
|
||||
|
||||
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());
|
||||
tracing::debug!(
|
||||
target: "ble_trace",
|
||||
step = "central.write_queued",
|
||||
peer = %address,
|
||||
bytes = data.len(),
|
||||
depth = q.len(),
|
||||
"Apple BLE central: write queued (radio queue full)"
|
||||
);
|
||||
unsafe { drain_pending_writes(address) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Requeues at front if canSend flips false mid-drain.
|
||||
/// 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");
|
||||
@@ -451,23 +460,27 @@ unsafe fn drain_pending_writes(address: &str) {
|
||||
return;
|
||||
}
|
||||
let mut drained = 0usize;
|
||||
let mut g = pending_write().lock().expect("pending_write lock");
|
||||
let Some(q) = g.get_mut(address) else {
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
let entry = {
|
||||
let mut g = pending_write().lock().expect("pending_write lock");
|
||||
g.get_mut(address).and_then(|q| q.pop_front())
|
||||
};
|
||||
let Some(data) = entry else {
|
||||
break;
|
||||
};
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
let mut g = pending_write().lock().expect("pending_write lock");
|
||||
g.entry(address.to_owned()).or_default().push_front(data);
|
||||
// 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;
|
||||
}
|
||||
let ready: bool = unsafe { msg_send![peer.peripheral.0, canSendWriteWithoutResponse] };
|
||||
if !ready {
|
||||
break;
|
||||
}
|
||||
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",
|
||||
@@ -804,9 +817,14 @@ fn resolve_pending(address: &str, kind: CallbackKind, result: Result<(), String>
|
||||
}
|
||||
}
|
||||
|
||||
/// English-locale, case-insensitive substring match against rotation
|
||||
/// English-locale, case-insensitive substring match against RPA-rotation
|
||||
/// signatures: `CBErrorPeripheralConnectionTimeout` (constant or localized
|
||||
/// "timed out unexpectedly") and "specified device has disconnected".
|
||||
/// "timed out unexpectedly"), which is how a rotated-address peer presents.
|
||||
///
|
||||
/// "The specified device has disconnected" (CBErrorPeripheralDisconnected) is
|
||||
/// deliberately NOT treated as rotation: it is the generic remote-initiated
|
||||
/// disconnect, and mapping it to Rotation cleared the reconnect backoff on
|
||||
/// every ordinary drop, letting a flapping peer churn without ever backing off.
|
||||
fn classify_disconnect_reason(err: Option<&str>) -> DisconnectReason {
|
||||
let Some(s) = err else {
|
||||
return DisconnectReason::OtherError;
|
||||
@@ -814,7 +832,6 @@ fn classify_disconnect_reason(err: Option<&str>) -> DisconnectReason {
|
||||
let lower = s.to_ascii_lowercase();
|
||||
if lower.contains("timed out unexpectedly")
|
||||
|| lower.contains("cberrorperipheralconnectiontimeout")
|
||||
|| lower.contains("specified device has disconnected")
|
||||
{
|
||||
DisconnectReason::Rotation
|
||||
} else {
|
||||
@@ -1265,9 +1282,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_rotation_via_specified_device_disconnected() {
|
||||
fn classify_specified_device_disconnected_is_not_rotation() {
|
||||
// Generic remote-initiated disconnect must NOT clear reconnect backoff.
|
||||
let r = classify_disconnect_reason(Some("The specified device has disconnected from us."));
|
||||
assert_eq!(r, DisconnectReason::Rotation);
|
||||
assert_eq!(r, DisconnectReason::OtherError);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+3415
-172
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,9 @@ use tokio::net::TcpStream;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const DEFAULT_SAM_ADDRESS: &str = "127.0.0.1";
|
||||
@@ -581,6 +583,7 @@ pub async fn spawn_i2p_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -775,11 +778,15 @@ pub async fn spawn_i2p_server(
|
||||
online: c_online,
|
||||
rxb: Some(c_rxb),
|
||||
txb: Some(c_txb),
|
||||
inspection: None,
|
||||
tx: c_tx,
|
||||
read_task: c_read_task,
|
||||
};
|
||||
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("I2P server: handle registry channel closed");
|
||||
online_task.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
@@ -812,6 +819,7 @@ pub async fn spawn_i2p_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -276,6 +276,7 @@ pub async fn spawn_kiss_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub mod android_usb;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod android_usb_lifecycle;
|
||||
pub mod auto;
|
||||
pub mod ax25kiss;
|
||||
pub mod backbone;
|
||||
@@ -29,11 +31,21 @@ pub mod local;
|
||||
pub mod pipe;
|
||||
pub mod rnode;
|
||||
pub mod rnode_admin;
|
||||
pub mod rnode_capabilities;
|
||||
#[cfg(any(
|
||||
feature = "serial",
|
||||
feature = "rnode-tcp",
|
||||
feature = "ble",
|
||||
target_os = "android",
|
||||
test
|
||||
))]
|
||||
mod rnode_capability_preflight;
|
||||
#[cfg(feature = "serial")]
|
||||
pub mod rnode_multi;
|
||||
pub mod rnode_protocol;
|
||||
#[cfg(feature = "serial")]
|
||||
pub mod serial;
|
||||
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
|
||||
#[cfg(feature = "serial")]
|
||||
mod serial_io;
|
||||
pub mod socket_tuning;
|
||||
pub mod tcp;
|
||||
|
||||
@@ -9,7 +9,9 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const LOCAL_MTU: u32 = 262_144;
|
||||
@@ -28,6 +30,18 @@ pub fn socket_path(data_dir: Option<&std::path::Path>) -> std::path::PathBuf {
|
||||
}
|
||||
|
||||
pub const FALLBACK_TCP_PORT: u16 = 37428;
|
||||
#[cfg(unix)]
|
||||
const LOCAL_RECONNECT_WAIT_SECS: u64 = 8;
|
||||
|
||||
#[cfg(all(unix, not(test)))]
|
||||
fn local_reconnect_wait() -> std::time::Duration {
|
||||
std::time::Duration::from_secs(LOCAL_RECONNECT_WAIT_SECS)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, test))]
|
||||
fn local_reconnect_wait() -> std::time::Duration {
|
||||
std::time::Duration::from_millis(50)
|
||||
}
|
||||
|
||||
pub fn socket_path_for(instance_name: &str) -> String {
|
||||
format!("/tmp/rns_{}.sock", instance_name)
|
||||
@@ -148,6 +162,81 @@ async fn local_write_loop<W: AsyncWriteExt + Unpin>(
|
||||
online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
enum LocalClientConnectionEnd {
|
||||
Disconnected,
|
||||
Detached,
|
||||
}
|
||||
|
||||
/// Drive both halves of one initiating local-client connection in a single
|
||||
/// task. Keeping the persistent outbound receiver here lets the Unix client
|
||||
/// retain one stable `InterfaceHandle` while replacing only the socket after a
|
||||
/// shared-instance restart.
|
||||
#[cfg(unix)]
|
||||
async fn run_local_client_connection<R, W>(
|
||||
mut reader: R,
|
||||
mut writer: W,
|
||||
rx: &mut mpsc::Receiver<Bytes>,
|
||||
interface_id: InterfaceId,
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
rxb: &AtomicU64,
|
||||
txb: &AtomicU64,
|
||||
) -> LocalClientConnectionEnd
|
||||
where
|
||||
R: AsyncReadExt + Unpin,
|
||||
W: AsyncWriteExt + Unpin,
|
||||
{
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut deframer = hdlc::HdlcDeframer::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
read = reader.read(&mut buf) => {
|
||||
match read {
|
||||
Ok(0) => {
|
||||
tracing::info!(interface_id, "local client read: EOF");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
Ok(n) => {
|
||||
rxb.fetch_add(n as u64, Ordering::Relaxed);
|
||||
for frame in deframer.feed(&buf[..n]) {
|
||||
if frame.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let msg = TransportMessage::Inbound(InboundPacket {
|
||||
raw: Bytes::from(frame),
|
||||
interface_id,
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
});
|
||||
if transport_tx.send(msg).await.is_err() {
|
||||
tracing::warn!(interface_id, "transport channel closed");
|
||||
return LocalClientConnectionEnd::Detached;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(interface_id, %error, "local client read error");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
}
|
||||
}
|
||||
outbound = rx.recv() => {
|
||||
let Some(data) = outbound else {
|
||||
return LocalClientConnectionEnd::Detached;
|
||||
};
|
||||
let framed = hdlc::frame(&data);
|
||||
if let Err(error) = writer.write_all(&framed).await {
|
||||
tracing::warn!(interface_id, %error, "local client write error");
|
||||
return LocalClientConnectionEnd::Disconnected;
|
||||
}
|
||||
txb.fetch_add(framed.len() as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-stream wiring shared by both platform variants: write loop, read task,
|
||||
/// and the connection's `InterfaceHandle`. `dereg_on_disconnect` is set for
|
||||
/// accepted server-side clients so transport drops them immediately on EOF.
|
||||
@@ -202,6 +291,7 @@ where
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -231,6 +321,7 @@ fn server_listener_handle(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -336,7 +427,10 @@ mod platform {
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -358,19 +452,97 @@ mod platform {
|
||||
id: InterfaceId,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let stream = connect_unix_stream(&config.socket_path).await?;
|
||||
let initial_stream = connect_unix_stream(&config.socket_path).await?;
|
||||
tracing::info!(name = %config.name, path = %display_socket_path(&config.socket_path), "local client connected");
|
||||
|
||||
let (reader, writer) = stream.into_split();
|
||||
Ok(wire_local_stream(
|
||||
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>(256);
|
||||
|
||||
let task_online = online.clone();
|
||||
let task_rxb = rxb.clone();
|
||||
let task_txb = txb.clone();
|
||||
let task_name = config.name.clone();
|
||||
let task_socket_path = config.socket_path.clone();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let mut stream = initial_stream;
|
||||
loop {
|
||||
let (reader, writer) = stream.into_split();
|
||||
let end = run_local_client_connection(
|
||||
reader,
|
||||
writer,
|
||||
&mut rx,
|
||||
id,
|
||||
&transport_tx,
|
||||
&task_rxb,
|
||||
&task_txb,
|
||||
)
|
||||
.await;
|
||||
task_online.store(false, Ordering::SeqCst);
|
||||
|
||||
if matches!(end, LocalClientConnectionEnd::Detached)
|
||||
|| transport_tx.is_closed()
|
||||
|| rx.is_closed()
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
wait_seconds = LOCAL_RECONNECT_WAIT_SECS,
|
||||
"local shared-instance connection lost; reconnecting"
|
||||
);
|
||||
loop {
|
||||
tokio::time::sleep(local_reconnect_wait()).await;
|
||||
if transport_tx.is_closed() || rx.is_closed() {
|
||||
return;
|
||||
}
|
||||
match connect_unix_stream(&task_socket_path).await {
|
||||
Ok(connected) => {
|
||||
stream = connected;
|
||||
task_online.store(true, Ordering::SeqCst);
|
||||
tracing::info!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
"local shared-instance client reconnected"
|
||||
);
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
name = %task_name,
|
||||
path = %display_socket_path(&task_socket_path),
|
||||
%error,
|
||||
"local shared-instance reconnect failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(InterfaceHandle {
|
||||
id,
|
||||
config.name.clone(),
|
||||
None,
|
||||
reader,
|
||||
writer,
|
||||
transport_tx,
|
||||
false,
|
||||
))
|
||||
parent_id: None,
|
||||
name: config.name,
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection {
|
||||
inbound: true,
|
||||
outbound: true,
|
||||
forward: false,
|
||||
repeat: false,
|
||||
},
|
||||
bitrate: 1_000_000_000,
|
||||
mtu: crate::traits::optimise_mtu(1_000_000_000).unwrap_or(LOCAL_MTU),
|
||||
online,
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,7 +596,10 @@ mod platform {
|
||||
transport_tx.clone(),
|
||||
true,
|
||||
);
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("local handle registry closed");
|
||||
break;
|
||||
}
|
||||
@@ -678,4 +853,86 @@ mod tests {
|
||||
server_handle.read_task.abort();
|
||||
let _ = std::fs::remove_file(&socket_path);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn test_local_client_reconnects_after_server_restart() {
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(64);
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel::<InterfaceHandle>(8);
|
||||
let id_gen = Arc::new(AtomicU64::new(900));
|
||||
let socket_path = unique_test_socket_path("reticulum_reconnect_test");
|
||||
|
||||
let server_config = || LocalServerConfig {
|
||||
socket_path: socket_path.clone(),
|
||||
name: "restartable-local-server".to_string(),
|
||||
};
|
||||
let server_handle = spawn_local_server(
|
||||
server_config(),
|
||||
id_gen.clone(),
|
||||
transport_tx.clone(),
|
||||
handle_tx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let client_handle = spawn_local_client(
|
||||
LocalClientConfig {
|
||||
socket_path: socket_path.clone(),
|
||||
name: "persistent-local-client".to_string(),
|
||||
},
|
||||
88,
|
||||
transport_tx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let first_accepted =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
|
||||
.await
|
||||
.expect("timeout waiting for first accepted client")
|
||||
.expect("handle channel closed");
|
||||
|
||||
server_handle.read_task.abort();
|
||||
first_accepted.read_task.abort();
|
||||
drop(first_accepted.tx);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), async {
|
||||
while client_handle.online.load(Ordering::SeqCst) {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("client did not observe server shutdown");
|
||||
|
||||
let restarted_server =
|
||||
spawn_local_server(server_config(), id_gen, transport_tx.clone(), handle_tx)
|
||||
.await
|
||||
.unwrap();
|
||||
let second_accepted =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), handle_rx.recv())
|
||||
.await
|
||||
.expect("client did not reconnect to restarted server")
|
||||
.expect("handle channel closed");
|
||||
assert!(
|
||||
client_handle.online.load(Ordering::SeqCst),
|
||||
"stable client handle must return online after reconnect"
|
||||
);
|
||||
|
||||
let payload = Bytes::from_static(b"after shared restart");
|
||||
second_accepted.tx.send(payload.clone()).await.unwrap();
|
||||
let inbound = tokio::time::timeout(std::time::Duration::from_secs(3), transport_rx.recv())
|
||||
.await
|
||||
.expect("timeout waiting for post-restart frame")
|
||||
.expect("transport channel closed");
|
||||
match inbound {
|
||||
TransportMessage::Inbound(packet) => {
|
||||
assert_eq!(packet.interface_id, 88);
|
||||
assert_eq!(packet.raw, payload);
|
||||
}
|
||||
other => panic!("unexpected post-restart message: {other:?}"),
|
||||
}
|
||||
|
||||
restarted_server.read_task.abort();
|
||||
second_accepted.read_task.abort();
|
||||
drop(second_accepted.tx);
|
||||
client_handle.read_task.abort();
|
||||
let _ = std::fs::remove_file(&socket_path);
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,7 @@ pub async fn spawn_pipe_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
+6510
-216
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,978 @@
|
||||
//! Privacy-bounded, read-only RNode capability parsing.
|
||||
//!
|
||||
//! RNode EEPROM identity information contains serial, manufacturing, checksum,
|
||||
//! signature, and other device-specific bytes. This module validates the
|
||||
//! immutable identity prefix in place, then returns only copyable product/model
|
||||
//! codes and reviewed radio limits. It never retains the source image or
|
||||
//! exposes identity, signature, configuration, or raw EEPROM fields.
|
||||
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
use crate::rnode::{RNodeConfigValidationError, RNodeRadioSettings};
|
||||
|
||||
const PRODUCT_ADDRESS: usize = 0x00;
|
||||
const MODEL_ADDRESS: usize = 0x01;
|
||||
const IDENTITY_CHECKSUM_INPUT_END: usize = 0x0B;
|
||||
const CHECKSUM_ADDRESS: usize = 0x0B;
|
||||
const CHECKSUM_END: usize = 0x1B;
|
||||
const INFO_LOCK_ADDRESS: usize = 0x9B;
|
||||
const REQUIRED_EEPROM_LEN: usize = INFO_LOCK_ADDRESS + 1;
|
||||
const INFO_LOCK_BYTE: u8 = 0x73;
|
||||
|
||||
/// A validated, privacy-bounded RNode capability description.
|
||||
///
|
||||
/// The value owns no EEPROM bytes and contains no stable device identifier.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RNodeCapabilities {
|
||||
product_code: u8,
|
||||
model_code: u8,
|
||||
radio: RNodeRadioCapabilities,
|
||||
}
|
||||
|
||||
impl RNodeCapabilities {
|
||||
/// The RNode product code stored in the validated identity prefix.
|
||||
pub const fn product_code(self) -> u8 {
|
||||
self.product_code
|
||||
}
|
||||
|
||||
/// A reviewed display name for the product code, when one is known.
|
||||
///
|
||||
/// This is a static code-table lookup; no label is read from or retained
|
||||
/// from the EEPROM image.
|
||||
pub const fn product_name(self) -> Option<&'static str> {
|
||||
rnode_product_name(self.product_code)
|
||||
}
|
||||
|
||||
/// The exact, unnormalised RNode model code stored in the identity prefix.
|
||||
pub const fn model_code(self) -> u8 {
|
||||
self.model_code
|
||||
}
|
||||
|
||||
/// Reviewed radio limits for the model, or [`RNodeRadioCapabilities::Unknown`].
|
||||
pub const fn radio(self) -> RNodeRadioCapabilities {
|
||||
self.radio
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a validated model has a reviewed radio capability profile.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioCapabilities {
|
||||
/// The model maps to a reviewed, internally consistent numeric profile.
|
||||
Known(RNodeKnownRadioCapabilities),
|
||||
/// The model is unknown, ambiguous, or deliberately quarantined.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Reviewed numeric limits for a known RNode radio model.
|
||||
///
|
||||
/// For a dual-radio product, these limits describe the reviewed generic/main
|
||||
/// RNode radio profile. They do not claim to span every band supported by each
|
||||
/// physically present secondary radio.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RNodeKnownRadioCapabilities {
|
||||
family: RNodeRadioFamily,
|
||||
min_frequency_hz: u32,
|
||||
max_frequency_hz: u32,
|
||||
max_tx_power_dbm: u8,
|
||||
}
|
||||
|
||||
impl RNodeKnownRadioCapabilities {
|
||||
/// The radio family associated with the model.
|
||||
pub const fn family(self) -> RNodeRadioFamily {
|
||||
self.family
|
||||
}
|
||||
|
||||
/// The inclusive lower frequency bound in hertz.
|
||||
pub const fn min_frequency_hz(self) -> u32 {
|
||||
self.min_frequency_hz
|
||||
}
|
||||
|
||||
/// The inclusive upper frequency bound in hertz.
|
||||
pub const fn max_frequency_hz(self) -> u32 {
|
||||
self.max_frequency_hz
|
||||
}
|
||||
|
||||
/// The inclusive maximum transmit power in dBm.
|
||||
pub const fn max_tx_power_dbm(self) -> u8 {
|
||||
self.max_tx_power_dbm
|
||||
}
|
||||
|
||||
/// Whether `frequency_hz` lies within the inclusive reviewed bounds.
|
||||
pub const fn supports_frequency(self, frequency_hz: u32) -> bool {
|
||||
frequency_hz >= self.min_frequency_hz && frequency_hz <= self.max_frequency_hz
|
||||
}
|
||||
|
||||
/// Whether `tx_power_dbm` is at or below the inclusive reviewed maximum.
|
||||
pub const fn supports_tx_power(self, tx_power_dbm: u8) -> bool {
|
||||
tx_power_dbm <= self.max_tx_power_dbm
|
||||
}
|
||||
}
|
||||
|
||||
/// Radio families represented by reviewed RNode model profiles.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioFamily {
|
||||
Sx1262,
|
||||
Sx1268,
|
||||
Sx1276,
|
||||
Sx1278,
|
||||
Sx1280,
|
||||
/// A dual-radio product.
|
||||
///
|
||||
/// Its numeric capability bounds describe the reviewed generic/main radio
|
||||
/// profile, not every band of the physically present secondary radio.
|
||||
Sx1262AndSx1280,
|
||||
}
|
||||
|
||||
/// Why a capability image could not be accepted.
|
||||
///
|
||||
/// Errors intentionally contain no EEPROM contents, hashes, or identity
|
||||
/// values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeCapabilityParseError {
|
||||
#[error("RNode EEPROM image is too short (need {required} bytes, got {actual})")]
|
||||
TooShort { required: usize, actual: usize },
|
||||
#[error("RNode identity information is not locked")]
|
||||
InfoNotLocked,
|
||||
#[error("RNode identity checksum is invalid")]
|
||||
ChecksumMismatch,
|
||||
}
|
||||
|
||||
/// Model-specific classification for a validated RNode capability image.
|
||||
///
|
||||
/// `Verified` means the exact model has a reviewed capability profile.
|
||||
/// `Unverified` means the exact stored model is unknown or quarantined, so no
|
||||
/// model profile was inferred. `Unprovisioned` means the device presented no
|
||||
/// locked EEPROM identity at all, so no product or model claim exists and only
|
||||
/// generic validation was applied. A `Verified` classification alone does not
|
||||
/// admit radio settings; use [`admit_rnode_radio_settings`] for that.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioAdmission {
|
||||
Verified { product_code: u8, model_code: u8 },
|
||||
Unverified { product_code: u8, model_code: u8 },
|
||||
Unprovisioned,
|
||||
}
|
||||
|
||||
impl RNodeRadioAdmission {
|
||||
/// Validated EEPROM product code, when a locked identity supplied one.
|
||||
pub const fn product_code(self) -> Option<u8> {
|
||||
match self {
|
||||
Self::Verified { product_code, .. } | Self::Unverified { product_code, .. } => {
|
||||
Some(product_code)
|
||||
}
|
||||
Self::Unprovisioned => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact, unnormalised EEPROM model code, when a locked identity supplied one.
|
||||
pub const fn model_code(self) -> Option<u8> {
|
||||
match self {
|
||||
Self::Verified { model_code, .. } | Self::Unverified { model_code, .. } => {
|
||||
Some(model_code)
|
||||
}
|
||||
Self::Unprovisioned => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reviewed model-specific profile was available.
|
||||
pub const fn is_verified(self) -> bool {
|
||||
matches!(self, Self::Verified { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed failure from model-specific RNode radio admission.
|
||||
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeRadioAdmissionError {
|
||||
#[error("generic RNode radio settings are invalid: {0}")]
|
||||
GenericValidation(#[source] RNodeConfigValidationError),
|
||||
#[error("frequency {requested_hz} Hz is outside verified model range {min_hz}..={max_hz} Hz")]
|
||||
FrequencyOutOfRange {
|
||||
requested_hz: u32,
|
||||
min_hz: u32,
|
||||
max_hz: u32,
|
||||
},
|
||||
#[error("TX power {requested_dbm} dBm exceeds verified model maximum {max_dbm} dBm")]
|
||||
TxPowerExceedsMaximum { requested_dbm: u8, max_dbm: u8 },
|
||||
}
|
||||
|
||||
/// Bounded classification of a full-length RNode EEPROM image.
|
||||
///
|
||||
/// `Provisioned` carries validated capabilities from a locked, checksummed
|
||||
/// identity. `Unprovisioned` means the info lock at `0x9b` is absent: the
|
||||
/// device carries no attested identity, so product, model, and checksum bytes
|
||||
/// are deliberately never read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum RNodeEepromImage {
|
||||
Provisioned(RNodeCapabilities),
|
||||
Unprovisioned,
|
||||
}
|
||||
|
||||
/// Classify an EEPROM image, admitting unprovisioned devices as a typed state.
|
||||
///
|
||||
/// The image must still span the identity-information lock at `0x9b`. An
|
||||
/// unlocked image classifies as [`RNodeEepromImage::Unprovisioned`] without
|
||||
/// consulting the checksum or identity bytes — an unattested model byte must
|
||||
/// never impose or relax model-specific limits. A locked image validates the
|
||||
/// MD5 checksum over the exact stored bytes `0x00..0x0b` (model aliases are
|
||||
/// deliberately not normalised first); bytes after the identity prefix,
|
||||
/// including the signature region, are ignored.
|
||||
pub fn classify_rnode_eeprom_image(
|
||||
eeprom: &[u8],
|
||||
) -> Result<RNodeEepromImage, RNodeCapabilityParseError> {
|
||||
if eeprom.len() < REQUIRED_EEPROM_LEN {
|
||||
return Err(RNodeCapabilityParseError::TooShort {
|
||||
required: REQUIRED_EEPROM_LEN,
|
||||
actual: eeprom.len(),
|
||||
});
|
||||
}
|
||||
if eeprom[INFO_LOCK_ADDRESS] != INFO_LOCK_BYTE {
|
||||
return Ok(RNodeEepromImage::Unprovisioned);
|
||||
}
|
||||
|
||||
let calculated: [u8; 16] = Md5::digest(&eeprom[..IDENTITY_CHECKSUM_INPUT_END]).into();
|
||||
if calculated != eeprom[CHECKSUM_ADDRESS..CHECKSUM_END] {
|
||||
return Err(RNodeCapabilityParseError::ChecksumMismatch);
|
||||
}
|
||||
|
||||
let product_code = eeprom[PRODUCT_ADDRESS];
|
||||
let model_code = eeprom[MODEL_ADDRESS];
|
||||
let radio = rnode_model_capabilities(model_code);
|
||||
|
||||
Ok(RNodeEepromImage::Provisioned(RNodeCapabilities {
|
||||
product_code,
|
||||
model_code,
|
||||
radio,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Validate an EEPROM image and retain only non-identifying capability data.
|
||||
///
|
||||
/// Strict form of [`classify_rnode_eeprom_image`] for callers that require a
|
||||
/// provisioned identity (for example rnodeconf mutation preflights): an
|
||||
/// unlocked image is an [`RNodeCapabilityParseError::InfoNotLocked`] error
|
||||
/// here rather than a typed classification.
|
||||
pub fn parse_rnode_capabilities(
|
||||
eeprom: &[u8],
|
||||
) -> Result<RNodeCapabilities, RNodeCapabilityParseError> {
|
||||
match classify_rnode_eeprom_image(eeprom)? {
|
||||
RNodeEepromImage::Provisioned(capabilities) => Ok(capabilities),
|
||||
RNodeEepromImage::Unprovisioned => Err(RNodeCapabilityParseError::InfoNotLocked),
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify a validated model without admitting radio settings.
|
||||
///
|
||||
/// `capabilities` can only be obtained from a successfully validated EEPROM
|
||||
/// image. Unknown, aliased, ambiguous, and quarantined model codes return
|
||||
/// [`RNodeRadioAdmission::Unverified`] without normalisation or an inferred
|
||||
/// profile.
|
||||
pub fn classify_rnode_radio_capabilities(capabilities: RNodeCapabilities) -> RNodeRadioAdmission {
|
||||
let product_code = capabilities.product_code();
|
||||
let model_code = capabilities.model_code();
|
||||
match capabilities.radio() {
|
||||
RNodeRadioCapabilities::Known(_) => RNodeRadioAdmission::Verified {
|
||||
product_code,
|
||||
model_code,
|
||||
},
|
||||
RNodeRadioCapabilities::Unknown => RNodeRadioAdmission::Unverified {
|
||||
product_code,
|
||||
model_code,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the sole lower-layer RF admission policy to validated capabilities.
|
||||
///
|
||||
/// Generic RNode validation runs first. Known exact model codes then enforce
|
||||
/// their inclusive frequency range and maximum TX power. Unknown, aliased,
|
||||
/// ambiguous, and quarantined model codes continue as an explicit
|
||||
/// [`RNodeRadioAdmission::Unverified`] result without normalisation or an
|
||||
/// inferred profile.
|
||||
pub fn admit_rnode_radio_settings(
|
||||
capabilities: RNodeCapabilities,
|
||||
settings: RNodeRadioSettings,
|
||||
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
|
||||
settings
|
||||
.validate()
|
||||
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
|
||||
|
||||
if let RNodeRadioCapabilities::Known(radio) = capabilities.radio() {
|
||||
if !radio.supports_frequency(settings.frequency) {
|
||||
return Err(RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: settings.frequency,
|
||||
min_hz: radio.min_frequency_hz(),
|
||||
max_hz: radio.max_frequency_hz(),
|
||||
});
|
||||
}
|
||||
if !radio.supports_tx_power(settings.tx_power) {
|
||||
return Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
|
||||
requested_dbm: settings.tx_power,
|
||||
max_dbm: radio.max_tx_power_dbm(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(classify_rnode_radio_capabilities(capabilities))
|
||||
}
|
||||
|
||||
/// Admit radio settings for a device that presented no locked EEPROM identity.
|
||||
///
|
||||
/// Only generic RNode validation applies: with no attested model there are no
|
||||
/// model-specific limits to consult, matching the treatment of unknown and
|
||||
/// quarantined model codes.
|
||||
pub fn admit_unprovisioned_rnode_radio_settings(
|
||||
settings: RNodeRadioSettings,
|
||||
) -> Result<RNodeRadioAdmission, RNodeRadioAdmissionError> {
|
||||
settings
|
||||
.validate()
|
||||
.map_err(RNodeRadioAdmissionError::GenericValidation)?;
|
||||
Ok(RNodeRadioAdmission::Unprovisioned)
|
||||
}
|
||||
|
||||
/// Return the reviewed display name for an RNode product code.
|
||||
///
|
||||
/// Unknown product codes return `None`. Names are static code-table values and
|
||||
/// are never read from device-controlled EEPROM data.
|
||||
pub const fn rnode_product_name(product_code: u8) -> Option<&'static str> {
|
||||
Some(match product_code {
|
||||
0x03 => "RNode",
|
||||
0x10 => "RAK4631",
|
||||
0x15 => "LilyGO T-Echo",
|
||||
0x20 => "openCom XL",
|
||||
0xB0 => "LilyGO LoRa32 v2.0",
|
||||
0xB1 => "LilyGO LoRa32 v2.1",
|
||||
0xB2 => "LilyGO LoRa32 v1.0",
|
||||
0xC0 => "Heltec LoRa32 v2",
|
||||
0xC1 => "Heltec LoRa32 v3",
|
||||
0xC2 => "Heltec Mesh Node T114",
|
||||
0xC3 => "Heltec LoRa32 v4",
|
||||
0xD0 => "LilyGO T-Deck",
|
||||
0xE0 => "LilyGO T-Beam",
|
||||
0xEA => "LilyGO T-Beam Supreme",
|
||||
0xEB => "Seeed XIAO ESP32S3 Wio-SX1262",
|
||||
0xF0 => "Hombrew RNode",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Return the reviewed radio capabilities for an exact RNode model code.
|
||||
///
|
||||
/// Unknown, ambiguous, and quarantined model codes return
|
||||
/// [`RNodeRadioCapabilities::Unknown`]. In particular, EEPROM aliases are not
|
||||
/// normalised by this lookup. Model codes `0xA6`, `0xAA`, and `0xC8` remain
|
||||
/// quarantined because the trusted Rust sources do not establish a single,
|
||||
/// internally consistent numeric capability profile for them.
|
||||
pub fn rnode_model_capabilities(model_code: u8) -> RNodeRadioCapabilities {
|
||||
KNOWN_RADIOS
|
||||
.iter()
|
||||
.find_map(|(candidate, profile)| (*candidate == model_code).then_some(*profile))
|
||||
.map(RNodeRadioCapabilities::Known)
|
||||
.unwrap_or(RNodeRadioCapabilities::Unknown)
|
||||
}
|
||||
|
||||
const fn known(
|
||||
family: RNodeRadioFamily,
|
||||
min_frequency_hz: u32,
|
||||
max_frequency_hz: u32,
|
||||
max_tx_power_dbm: u8,
|
||||
) -> RNodeKnownRadioCapabilities {
|
||||
RNodeKnownRadioCapabilities {
|
||||
family,
|
||||
min_frequency_hz,
|
||||
max_frequency_hz,
|
||||
max_tx_power_dbm,
|
||||
}
|
||||
}
|
||||
|
||||
// Reviewed numeric profiles owned by this lower-core module. Firmware
|
||||
// filenames and human labels intentionally do not cross this boundary.
|
||||
// Models with aliases, contradictory ranges, ambiguous evidence, or explicitly
|
||||
// unknown limits are absent and therefore resolve to Unknown.
|
||||
const KNOWN_RADIOS: &[(u8, RNodeKnownRadioCapabilities)] = &[
|
||||
(
|
||||
0xA4,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 14),
|
||||
),
|
||||
(
|
||||
0xA9,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA1,
|
||||
known(RNodeRadioFamily::Sx1268, 410_000_000, 525_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xA5,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xAC,
|
||||
known(RNodeRadioFamily::Sx1280, 2_400_000_000, 2_500_000_000, 20),
|
||||
),
|
||||
(
|
||||
0xA2,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA7,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA3,
|
||||
known(RNodeRadioFamily::Sx1278, 410_000_000, 525_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xA8,
|
||||
known(RNodeRadioFamily::Sx1276, 820_000_000, 1_020_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB3,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB8,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xB9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xBA,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xBB,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xC5,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xCA,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xC6,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xC7,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE4,
|
||||
known(RNodeRadioFamily::Sx1278, 420_000_000, 520_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xE9,
|
||||
known(RNodeRadioFamily::Sx1276, 850_000_000, 950_000_000, 17),
|
||||
),
|
||||
(
|
||||
0xD4,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xD9,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDB,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDC,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE3,
|
||||
known(RNodeRadioFamily::Sx1268, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xE8,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x11,
|
||||
known(RNodeRadioFamily::Sx1262, 430_000_000, 510_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x12,
|
||||
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x13,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
430_000_000,
|
||||
510_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0x14,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
779_000_000,
|
||||
928_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0x17,
|
||||
known(RNodeRadioFamily::Sx1262, 779_000_000, 928_000_000, 22),
|
||||
),
|
||||
(
|
||||
0x21,
|
||||
known(
|
||||
RNodeRadioFamily::Sx1262AndSx1280,
|
||||
820_000_000,
|
||||
960_000_000,
|
||||
22,
|
||||
),
|
||||
),
|
||||
(
|
||||
0xDE,
|
||||
known(RNodeRadioFamily::Sx1262, 420_000_000, 520_000_000, 22),
|
||||
),
|
||||
(
|
||||
0xDD,
|
||||
known(RNodeRadioFamily::Sx1262, 850_000_000, 950_000_000, 22),
|
||||
),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PRODUCT: u8 = 0x03;
|
||||
const QUARANTINED_MODELS: &[u8] = &[0x04, 0x09, 0x16, 0xA6, 0xAA, 0xC8, 0xFE, 0xFF];
|
||||
|
||||
fn image(model: u8) -> [u8; REQUIRED_EEPROM_LEN] {
|
||||
let mut bytes = [0xA5; REQUIRED_EEPROM_LEN];
|
||||
bytes[PRODUCT_ADDRESS] = PRODUCT;
|
||||
bytes[MODEL_ADDRESS] = model;
|
||||
bytes[0x02] = 0x07;
|
||||
bytes[0x03..0x07].copy_from_slice(&0x1122_3344_u32.to_be_bytes());
|
||||
bytes[0x07..0x0B].copy_from_slice(&0x5566_7788_u32.to_be_bytes());
|
||||
let checksum: [u8; 16] = Md5::digest(&bytes[..IDENTITY_CHECKSUM_INPUT_END]).into();
|
||||
bytes[CHECKSUM_ADDRESS..CHECKSUM_END].copy_from_slice(&checksum);
|
||||
bytes[INFO_LOCK_ADDRESS] = INFO_LOCK_BYTE;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
|
||||
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_every_byte_through_info_lock() {
|
||||
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(short),
|
||||
Err(RNodeCapabilityParseError::TooShort {
|
||||
required: 156,
|
||||
actual: 155,
|
||||
})
|
||||
);
|
||||
|
||||
let exact = image(0xA4);
|
||||
assert!(parse_rnode_capabilities(&exact).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unlocked_identity_information_before_checksum_validation() {
|
||||
let mut bytes = image(0xA4);
|
||||
bytes[INFO_LOCK_ADDRESS] = 0x00;
|
||||
bytes[CHECKSUM_ADDRESS] ^= 0xFF;
|
||||
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::InfoNotLocked)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_images_classify_unprovisioned_without_reading_identity() {
|
||||
// Both fresh-erase (0xFF) and zeroed lock bytes count as unlocked, and
|
||||
// neither the checksum nor the identity bytes may be consulted.
|
||||
for lock in [0x00, 0xFF] {
|
||||
let mut bytes = image(0x11);
|
||||
bytes[INFO_LOCK_ADDRESS] = lock;
|
||||
for byte in &mut bytes[CHECKSUM_ADDRESS..CHECKSUM_END] {
|
||||
*byte = 0xA5;
|
||||
}
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&bytes),
|
||||
Ok(RNodeEepromImage::Unprovisioned),
|
||||
"lock byte {lock:#04x} must classify unprovisioned"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classification_preserves_strict_short_and_checksum_failures() {
|
||||
let short = &image(0xA4)[..REQUIRED_EEPROM_LEN - 1];
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(short),
|
||||
Err(RNodeCapabilityParseError::TooShort {
|
||||
required: 156,
|
||||
actual: 155,
|
||||
})
|
||||
);
|
||||
|
||||
let mut corrupt = image(0xA4);
|
||||
corrupt[CHECKSUM_ADDRESS] ^= 0x01;
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&corrupt),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
classify_rnode_eeprom_image(&image(0x11)),
|
||||
Ok(RNodeEepromImage::Provisioned(
|
||||
parse_rnode_capabilities(&image(0x11)).expect("valid image")
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unprovisioned_admission_applies_generic_validation_only() {
|
||||
assert_eq!(
|
||||
admit_unprovisioned_rnode_radio_settings(settings(868_000_000, 37)),
|
||||
Ok(RNodeRadioAdmission::Unprovisioned)
|
||||
);
|
||||
assert!(matches!(
|
||||
admit_unprovisioned_rnode_radio_settings(settings(1, 14)),
|
||||
Err(RNodeRadioAdmissionError::GenericValidation(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_codes_are_present_only_for_locked_identities() {
|
||||
let verified = RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
};
|
||||
assert_eq!(verified.product_code(), Some(PRODUCT));
|
||||
assert_eq!(verified.model_code(), Some(0x11));
|
||||
assert!(verified.is_verified());
|
||||
|
||||
assert_eq!(RNodeRadioAdmission::Unprovisioned.product_code(), None);
|
||||
assert_eq!(RNodeRadioAdmission::Unprovisioned.model_code(), None);
|
||||
assert!(!RNodeRadioAdmission::Unprovisioned.is_verified());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_covers_exact_identity_prefix_without_model_normalisation() {
|
||||
let mut bytes = image(0x04);
|
||||
let parsed = parse_rnode_capabilities(&bytes).expect("raw model checksum should validate");
|
||||
assert_eq!(parsed.model_code(), 0x04);
|
||||
assert_eq!(parsed.radio(), RNodeRadioCapabilities::Unknown);
|
||||
|
||||
// Replacing the raw alias with its nominal model invalidates the exact
|
||||
// stored checksum; the parser must not normalise it first.
|
||||
bytes[MODEL_ADDRESS] = 0xB4;
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_any_identity_prefix_checksum_mismatch() {
|
||||
for address in 0..IDENTITY_CHECKSUM_INPUT_END {
|
||||
let mut bytes = image(0xA4);
|
||||
bytes[address] ^= 0x01;
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&bytes),
|
||||
Err(RNodeCapabilityParseError::ChecksumMismatch),
|
||||
"identity byte {address:#04x} was not covered"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_only_reviewed_codes_and_known_numeric_bounds() {
|
||||
let parsed = parse_rnode_capabilities(&image(0xAC)).expect("valid known model");
|
||||
assert_eq!(parsed.product_code(), PRODUCT);
|
||||
assert_eq!(parsed.product_name(), Some("RNode"));
|
||||
assert_eq!(parsed.model_code(), 0xAC);
|
||||
assert_eq!(
|
||||
parsed.radio(),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1280,
|
||||
2_400_000_000,
|
||||
2_500_000_000,
|
||||
20,
|
||||
))
|
||||
);
|
||||
|
||||
let low_band = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
assert_eq!(
|
||||
low_band.radio(),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1262,
|
||||
430_000_000,
|
||||
510_000_000,
|
||||
22,
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_support_helpers_include_both_boundaries() {
|
||||
let parsed = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
let RNodeRadioCapabilities::Known(radio) = parsed.radio() else {
|
||||
panic!("model 0x11 must have a reviewed profile");
|
||||
};
|
||||
|
||||
assert!(radio.supports_frequency(430_000_000));
|
||||
assert!(radio.supports_frequency(510_000_000));
|
||||
assert!(!radio.supports_frequency(429_999_999));
|
||||
assert!(!radio.supports_frequency(510_000_001));
|
||||
|
||||
assert!(radio.supports_tx_power(0));
|
||||
assert!(radio.supports_tx_power(22));
|
||||
assert!(!radio.supports_tx_power(23));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_admission_includes_frequency_and_power_boundaries() {
|
||||
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(430_000_000, 0)),
|
||||
Ok(RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(510_000_000, 22)),
|
||||
Ok(RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
classify_rnode_radio_capabilities(capabilities),
|
||||
RNodeRadioAdmission::Verified {
|
||||
product_code: PRODUCT,
|
||||
model_code: 0x11,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_admission_returns_typed_frequency_and_power_mismatches() {
|
||||
let capabilities = parse_rnode_capabilities(&image(0x11)).expect("valid known model");
|
||||
|
||||
for (frequency, expected) in [
|
||||
(
|
||||
429_999_999,
|
||||
RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: 429_999_999,
|
||||
min_hz: 430_000_000,
|
||||
max_hz: 510_000_000,
|
||||
},
|
||||
),
|
||||
(
|
||||
510_000_001,
|
||||
RNodeRadioAdmissionError::FrequencyOutOfRange {
|
||||
requested_hz: 510_000_001,
|
||||
min_hz: 430_000_000,
|
||||
max_hz: 510_000_000,
|
||||
},
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(frequency, 22)),
|
||||
Err(expected)
|
||||
);
|
||||
}
|
||||
|
||||
let error = admit_rnode_radio_settings(capabilities, settings(430_000_000, 23));
|
||||
assert_eq!(
|
||||
error,
|
||||
Err(RNodeRadioAdmissionError::TxPowerExceedsMaximum {
|
||||
requested_dbm: 23,
|
||||
max_dbm: 22,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_quarantined_admission_is_explicitly_unverified() {
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
let capabilities =
|
||||
parse_rnode_capabilities(&image(model)).expect("valid identity image");
|
||||
assert_eq!(
|
||||
classify_rnode_radio_capabilities(capabilities),
|
||||
RNodeRadioAdmission::Unverified {
|
||||
product_code: PRODUCT,
|
||||
model_code: model,
|
||||
},
|
||||
"model {model:#04x} classification must remain unverified"
|
||||
);
|
||||
assert_eq!(
|
||||
admit_rnode_radio_settings(capabilities, settings(868_000_000, 37)),
|
||||
Ok(RNodeRadioAdmission::Unverified {
|
||||
product_code: PRODUCT,
|
||||
model_code: model,
|
||||
}),
|
||||
"model {model:#04x} must remain unverified"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_validation_precedes_known_and_unverified_model_policy() {
|
||||
for model in [0x11, 0xA6] {
|
||||
let capabilities = parse_rnode_capabilities(&image(model)).expect("valid identity");
|
||||
let error = admit_rnode_radio_settings(capabilities, settings(1, 23))
|
||||
.expect_err("model policy must not bypass generic validation");
|
||||
assert!(
|
||||
matches!(error, RNodeRadioAdmissionError::GenericValidation(_)),
|
||||
"model {model:#04x} did not fail generic validation first: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn product_names_are_closed_static_lookups() {
|
||||
const PRODUCTS: &[(u8, &str)] = &[
|
||||
(0x03, "RNode"),
|
||||
(0x10, "RAK4631"),
|
||||
(0x15, "LilyGO T-Echo"),
|
||||
(0x20, "openCom XL"),
|
||||
(0xB0, "LilyGO LoRa32 v2.0"),
|
||||
(0xB1, "LilyGO LoRa32 v2.1"),
|
||||
(0xB2, "LilyGO LoRa32 v1.0"),
|
||||
(0xC0, "Heltec LoRa32 v2"),
|
||||
(0xC1, "Heltec LoRa32 v3"),
|
||||
(0xC2, "Heltec Mesh Node T114"),
|
||||
(0xC3, "Heltec LoRa32 v4"),
|
||||
(0xD0, "LilyGO T-Deck"),
|
||||
(0xE0, "LilyGO T-Beam"),
|
||||
(0xEA, "LilyGO T-Beam Supreme"),
|
||||
(0xEB, "Seeed XIAO ESP32S3 Wio-SX1262"),
|
||||
(0xF0, "Hombrew RNode"),
|
||||
];
|
||||
|
||||
for (index, (code, name)) in PRODUCTS.iter().enumerate() {
|
||||
assert_eq!(rnode_product_name(*code), Some(*name));
|
||||
assert!(
|
||||
!PRODUCTS[..index].iter().any(|(earlier, _)| earlier == code),
|
||||
"duplicate product code {code:#04x}"
|
||||
);
|
||||
}
|
||||
assert_eq!(rnode_product_name(0x00), None);
|
||||
assert_eq!(rnode_product_name(0xFF), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_and_quarantined_models_never_invent_limits() {
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
let parsed = parse_rnode_capabilities(&image(model)).expect("valid identity image");
|
||||
assert_eq!(parsed.model_code(), model);
|
||||
assert_eq!(
|
||||
parsed.radio(),
|
||||
RNodeRadioCapabilities::Unknown,
|
||||
"model {model:#04x} must remain unknown"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_model_lookup_is_closed_and_does_not_normalise_quarantine() {
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(0xA4),
|
||||
RNodeRadioCapabilities::Known(known(
|
||||
RNodeRadioFamily::Sx1278,
|
||||
410_000_000,
|
||||
525_000_000,
|
||||
14,
|
||||
))
|
||||
);
|
||||
|
||||
for model in std::iter::once(0x00).chain(QUARANTINED_MODELS.iter().copied()) {
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(model),
|
||||
RNodeRadioCapabilities::Unknown,
|
||||
"model {model:#04x} must remain unknown"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_and_other_ignored_bytes_do_not_affect_result() {
|
||||
let baseline_image = image(0xA4);
|
||||
let baseline = parse_rnode_capabilities(&baseline_image).expect("valid image");
|
||||
let mut mutated = baseline_image;
|
||||
|
||||
for (index, byte) in mutated[CHECKSUM_END..INFO_LOCK_ADDRESS]
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
{
|
||||
*byte = index as u8;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
parse_rnode_capabilities(&mutated),
|
||||
Ok(baseline),
|
||||
"signature and non-capability bytes must be ignored"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_table_is_unique_valid_and_excludes_quarantine() {
|
||||
assert_eq!(KNOWN_RADIOS.len(), 37);
|
||||
|
||||
for (index, (model, profile)) in KNOWN_RADIOS.iter().enumerate() {
|
||||
assert!(
|
||||
!QUARANTINED_MODELS.contains(model),
|
||||
"quarantined model {model:#04x} entered the known table"
|
||||
);
|
||||
assert!(
|
||||
profile.min_frequency_hz() < profile.max_frequency_hz(),
|
||||
"model {model:#04x} has inverted frequency limits"
|
||||
);
|
||||
assert!(
|
||||
profile.max_tx_power_dbm() > 0,
|
||||
"model {model:#04x} has a non-positive maximum TX power"
|
||||
);
|
||||
assert!(
|
||||
!KNOWN_RADIOS[..index]
|
||||
.iter()
|
||||
.any(|(earlier, _)| earlier == model),
|
||||
"duplicate model {model:#04x}"
|
||||
);
|
||||
assert_eq!(
|
||||
rnode_model_capabilities(*model),
|
||||
RNodeRadioCapabilities::Known(*profile),
|
||||
"model {model:#04x} did not round-trip through lookup"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
//! Bounded, transport-independent RNode capability preflight state.
|
||||
//!
|
||||
//! Transport owners retain their stream, writer, clock, and cancellation
|
||||
//! policy. This module owns only strict framing, bounded admission state, and
|
||||
//! privacy-safe errors so serial/TCP, BLE, and USB can share one policy without
|
||||
//! sharing transport lifecycle machinery.
|
||||
|
||||
use crate::kiss;
|
||||
use crate::rnode::{CMD_ERROR, CMD_ROM_READ, RNodeCapabilityAdmissionError, RNodeRadioSettings};
|
||||
use crate::rnode_capabilities::{
|
||||
RNodeEepromImage, RNodeRadioAdmission, admit_rnode_radio_settings,
|
||||
admit_unprovisioned_rnode_radio_settings, classify_rnode_eeprom_image,
|
||||
};
|
||||
use crate::rnode_protocol::{
|
||||
RNodeFrameRejection, RNodeProtocolEffect, RNodeProtocolState, RNodeProtocolTarget,
|
||||
};
|
||||
|
||||
#[cfg(all(not(test), any(feature = "serial", feature = "rnode-tcp")))]
|
||||
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
|
||||
std::time::Duration::from_secs(5);
|
||||
#[cfg(all(test, any(feature = "serial", feature = "rnode-tcp")))]
|
||||
pub(crate) const RNODE_CAPABILITY_PREFLIGHT_DEADLINE: std::time::Duration =
|
||||
std::time::Duration::from_secs(1);
|
||||
pub(crate) const RNODE_CAPABILITY_READ_BUFFER_BYTES: usize = 1024;
|
||||
const RNODE_CAPABILITY_MAX_READS: usize = 128;
|
||||
const RNODE_CAPABILITY_MAX_INPUT_BYTES: usize = 4 * 1024;
|
||||
const RNODE_CAPABILITY_MAX_FRAMES: usize = 128;
|
||||
|
||||
pub(crate) fn build_rnode_capability_request() -> Vec<u8> {
|
||||
kiss::frame_with_command(CMD_ROM_READ, &[0])
|
||||
}
|
||||
|
||||
pub(crate) struct RNodeCapabilityPreflight {
|
||||
deframer: kiss::RawKissDeframer,
|
||||
protocol_state: RNodeProtocolState,
|
||||
settings: RNodeRadioSettings,
|
||||
admission: Option<RNodeRadioAdmission>,
|
||||
read_count: usize,
|
||||
input_bytes: usize,
|
||||
frame_count: usize,
|
||||
}
|
||||
|
||||
impl RNodeCapabilityPreflight {
|
||||
pub(crate) fn new(settings: RNodeRadioSettings) -> Self {
|
||||
Self {
|
||||
deframer: kiss::RawKissDeframer::new(),
|
||||
protocol_state: RNodeProtocolState::new(RNodeProtocolTarget::new(
|
||||
settings.frequency,
|
||||
settings.bandwidth,
|
||||
settings.spreading_factor,
|
||||
settings.coding_rate,
|
||||
settings.tx_power,
|
||||
)),
|
||||
settings,
|
||||
admission: None,
|
||||
read_count: 0,
|
||||
input_bytes: 0,
|
||||
frame_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume one bounded transport read.
|
||||
///
|
||||
/// `CMD_DATA` and EEPROM payloads never leave this state machine. Unknown
|
||||
/// non-data controls are ignored after strict deframing; supported generic
|
||||
/// controls are reduced into the generation-private protocol state.
|
||||
pub(crate) fn observe_read(
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
|
||||
self.read_count = self.read_count.saturating_add(1);
|
||||
if self.read_count > RNODE_CAPABILITY_MAX_READS {
|
||||
return Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_READS,
|
||||
});
|
||||
}
|
||||
if bytes.len() > RNODE_CAPABILITY_READ_BUFFER_BYTES {
|
||||
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_READ_BUFFER_BYTES,
|
||||
});
|
||||
}
|
||||
self.input_bytes = self.input_bytes.saturating_add(bytes.len());
|
||||
if self.input_bytes > RNODE_CAPABILITY_MAX_INPUT_BYTES {
|
||||
return Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
for (command, payload) in self.deframer.feed(bytes) {
|
||||
self.frame_count = self.frame_count.saturating_add(1);
|
||||
if self.frame_count > RNODE_CAPABILITY_MAX_FRAMES {
|
||||
return Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_FRAMES,
|
||||
});
|
||||
}
|
||||
|
||||
if command == kiss::CMD_DATA {
|
||||
continue;
|
||||
}
|
||||
if command == CMD_ROM_READ {
|
||||
if self.admission.is_some() {
|
||||
return Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse);
|
||||
}
|
||||
let admission = match classify_rnode_eeprom_image(&payload)
|
||||
.map_err(RNodeCapabilityAdmissionError::CapabilityImage)?
|
||||
{
|
||||
RNodeEepromImage::Provisioned(capabilities) => {
|
||||
admit_rnode_radio_settings(capabilities, self.settings)
|
||||
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
|
||||
}
|
||||
RNodeEepromImage::Unprovisioned => {
|
||||
admit_unprovisioned_rnode_radio_settings(self.settings)
|
||||
.map_err(RNodeCapabilityAdmissionError::RadioSettings)?
|
||||
}
|
||||
};
|
||||
self.admission = Some(admission);
|
||||
continue;
|
||||
}
|
||||
if command == CMD_ERROR {
|
||||
return Err(RNodeCapabilityAdmissionError::DeviceError);
|
||||
}
|
||||
|
||||
match self.protocol_state.apply_frame(command, &payload) {
|
||||
RNodeProtocolEffect::Rejected(RNodeFrameRejection::UnknownCommand) => {}
|
||||
RNodeProtocolEffect::Rejected(rejection) => {
|
||||
return Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame {
|
||||
rejection,
|
||||
});
|
||||
}
|
||||
RNodeProtocolEffect::RadioInitialisationFault => {
|
||||
unreachable!("CMD_ERROR is rejected before protocol reduction")
|
||||
}
|
||||
RNodeProtocolEffect::EvidenceChanged(_)
|
||||
| RNodeProtocolEffect::FlowPermissionChanged(_)
|
||||
| RNodeProtocolEffect::Reset
|
||||
| RNodeProtocolEffect::NoChange => {}
|
||||
}
|
||||
}
|
||||
|
||||
let evidence = self.protocol_state.evidence();
|
||||
if self.protocol_state.detection_observed() && !evidence.detected {
|
||||
return Err(RNodeCapabilityAdmissionError::DetectionRejected);
|
||||
}
|
||||
if evidence
|
||||
.firmware
|
||||
.is_some_and(|firmware| !firmware.is_supported())
|
||||
{
|
||||
return Err(RNodeCapabilityAdmissionError::UnsupportedFirmware);
|
||||
}
|
||||
Ok((evidence.detected && evidence.firmware.is_some())
|
||||
.then_some(self.admission)
|
||||
.flatten())
|
||||
}
|
||||
|
||||
/// Return the only preflight evidence that may seed active readiness.
|
||||
///
|
||||
/// Configuration, radio, and flow frames observed before the runtime sends
|
||||
/// its admitted init sequence may be stale. They remain reduced privately
|
||||
/// during preflight but never cross the admission boundary.
|
||||
pub(crate) fn into_protocol_state(self) -> RNodeProtocolState {
|
||||
let target = self.protocol_state.target();
|
||||
let evidence = self.protocol_state.evidence();
|
||||
let mut admitted = RNodeProtocolState::new(target);
|
||||
if evidence.detected {
|
||||
admitted.apply_frame(crate::rnode::CMD_DETECT, &[crate::rnode::DETECT_RESP]);
|
||||
}
|
||||
if let Some(firmware) = evidence.firmware {
|
||||
admitted.apply_frame(
|
||||
crate::rnode::CMD_FW_VERSION,
|
||||
&[firmware.major, firmware.minor],
|
||||
);
|
||||
}
|
||||
admitted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
use super::*;
|
||||
use crate::rnode::{
|
||||
CMD_DETECT, CMD_FW_VERSION, DETECT_RESP, REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN,
|
||||
};
|
||||
|
||||
fn settings(frequency: u32, tx_power: u8) -> RNodeRadioSettings {
|
||||
RNodeRadioSettings::new(frequency, 125_000, 7, 5, tx_power)
|
||||
}
|
||||
|
||||
fn eeprom(model: u8) -> Vec<u8> {
|
||||
let mut bytes = vec![0xFF; 1024];
|
||||
bytes[0] = 0x03;
|
||||
bytes[1] = model;
|
||||
bytes[2..11].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
let checksum: [u8; 16] = Md5::digest(&bytes[..11]).into();
|
||||
bytes[11..27].copy_from_slice(&checksum);
|
||||
// Exercise both extended-KISS escape forms outside the validated
|
||||
// identity prefix.
|
||||
bytes[100] = kiss::FEND;
|
||||
bytes[101] = kiss::FESC;
|
||||
bytes[0x9B] = 0x73;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn observe_chunked(
|
||||
preflight: &mut RNodeCapabilityPreflight,
|
||||
bytes: &[u8],
|
||||
) -> Result<Option<RNodeRadioAdmission>, RNodeCapabilityAdmissionError> {
|
||||
let mut admission = None;
|
||||
for chunk in bytes.chunks(257) {
|
||||
admission = preflight.observe_read(chunk)?.or(admission);
|
||||
}
|
||||
Ok(admission)
|
||||
}
|
||||
|
||||
fn admitted_frames(model: u8) -> Vec<u8> {
|
||||
let mut frames = Vec::new();
|
||||
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
|
||||
kiss::frame_with_command_into(
|
||||
CMD_FW_VERSION,
|
||||
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
|
||||
&mut frames,
|
||||
);
|
||||
kiss::frame_with_command_into(CMD_ROM_READ, &eeprom(model), &mut frames);
|
||||
frames
|
||||
}
|
||||
|
||||
fn unlocked_eeprom(model: u8) -> Vec<u8> {
|
||||
let mut bytes = eeprom(model);
|
||||
bytes[0x9B] = 0xFF;
|
||||
// Corrupt the checksum region too: unlocked images must admit without
|
||||
// consulting it.
|
||||
for byte in &mut bytes[11..27] {
|
||||
*byte = 0x5A;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn unprovisioned_frames(model: u8) -> Vec<u8> {
|
||||
let mut frames = Vec::new();
|
||||
kiss::frame_with_command_into(CMD_DETECT, &[DETECT_RESP], &mut frames);
|
||||
kiss::frame_with_command_into(
|
||||
CMD_FW_VERSION,
|
||||
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN],
|
||||
&mut frames,
|
||||
);
|
||||
kiss::frame_with_command_into(CMD_ROM_READ, &unlocked_eeprom(model), &mut frames);
|
||||
frames
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_eeprom_admits_unprovisioned_and_never_consults_model_bounds() {
|
||||
// Model 0xB4 at 868 MHz is a typed FrequencyOutOfRange when locked
|
||||
// (see known_model_mismatch_and_bounds_are_typed); unlocked, the model
|
||||
// byte is unattested and must impose nothing.
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut preflight, &unprovisioned_frames(0xB4)).unwrap();
|
||||
assert_eq!(result, Some(RNodeRadioAdmission::Unprovisioned));
|
||||
|
||||
let seed = preflight.into_protocol_state();
|
||||
assert!(seed.evidence().detected);
|
||||
assert!(seed.evidence().firmware.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_eeprom_still_fails_generic_radio_validation() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(1, 14));
|
||||
assert!(matches!(
|
||||
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)),
|
||||
Err(RNodeCapabilityAdmissionError::RadioSettings(
|
||||
crate::rnode_capabilities::RNodeRadioAdmissionError::GenericValidation(_)
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlocked_then_duplicate_rom_response_remains_fatal() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(&mut preflight, &unprovisioned_frames(0xB8)).unwrap(),
|
||||
Some(RNodeRadioAdmission::Unprovisioned)
|
||||
);
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut preflight,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &unlocked_eeprom(0xB8)),
|
||||
),
|
||||
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_request_is_one_standalone_rom_read_zero_frame() {
|
||||
assert_eq!(
|
||||
build_rnode_capability_request(),
|
||||
kiss::frame_with_command(CMD_ROM_READ, &[0])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragmented_and_escaped_eeprom_admits_verified_model() {
|
||||
let bytes = admitted_frames(0xB8);
|
||||
assert!(bytes.contains(&kiss::FESC));
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut preflight, &bytes).unwrap();
|
||||
assert!(matches!(result, Some(RNodeRadioAdmission::Verified { .. })));
|
||||
assert!(preflight.into_protocol_state().evidence().detected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validated_unknown_model_is_explicitly_unverified() {
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert!(matches!(
|
||||
observe_chunked(&mut preflight, &admitted_frames(0xFE)).unwrap(),
|
||||
Some(RNodeRadioAdmission::Unverified {
|
||||
model_code: 0xFE,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_and_wrong_commands_do_not_satisfy_or_escape_preflight() {
|
||||
let mut bytes = Vec::new();
|
||||
kiss::frame_with_command_into(kiss::CMD_DATA, b"private packet", &mut bytes);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0x80], &mut bytes);
|
||||
kiss::frame_with_command_into(CMD_ROM_READ.wrapping_add(1), &eeprom(0xB8), &mut bytes);
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(observe_chunked(&mut preflight, &bytes).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_control_device_error_and_invalid_image_fail_closed() {
|
||||
let mut malformed = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let malformed_frame = kiss::frame_with_command(CMD_FW_VERSION, &[1]);
|
||||
assert!(matches!(
|
||||
malformed.observe_read(&malformed_frame),
|
||||
Err(RNodeCapabilityAdmissionError::MalformedProtocolFrame { .. })
|
||||
));
|
||||
|
||||
let mut device_error = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
device_error.observe_read(&kiss::frame_with_command(CMD_ERROR, &[0x7F])),
|
||||
Err(RNodeCapabilityAdmissionError::DeviceError)
|
||||
);
|
||||
|
||||
let mut invalid = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert!(matches!(
|
||||
invalid.observe_read(&kiss::frame_with_command(CMD_ROM_READ, &[0; 8])),
|
||||
Err(RNodeCapabilityAdmissionError::CapabilityImage(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_model_mismatch_and_bounds_are_typed() {
|
||||
let mut mismatch = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let result = observe_chunked(&mut mismatch, &admitted_frames(0xB4));
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RNodeCapabilityAdmissionError::RadioSettings(
|
||||
crate::rnode_capabilities::RNodeRadioAdmissionError::FrequencyOutOfRange { .. }
|
||||
))
|
||||
));
|
||||
|
||||
let mut bounded = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
for _ in 0..RNODE_CAPABILITY_MAX_READS {
|
||||
assert_eq!(bounded.observe_read(&[]).unwrap(), None);
|
||||
}
|
||||
assert_eq!(
|
||||
bounded.observe_read(&[]),
|
||||
Err(RNodeCapabilityAdmissionError::ReadLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_READS
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_detection_unsupported_firmware_and_duplicate_rom_are_typed() {
|
||||
let mut detection = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
detection.observe_read(&kiss::frame_with_command(CMD_DETECT, &[0])),
|
||||
Err(RNodeCapabilityAdmissionError::DetectionRejected)
|
||||
);
|
||||
|
||||
let mut firmware = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
firmware.observe_read(&kiss::frame_with_command(
|
||||
CMD_FW_VERSION,
|
||||
&[REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN - 1],
|
||||
)),
|
||||
Err(RNodeCapabilityAdmissionError::UnsupportedFirmware)
|
||||
);
|
||||
|
||||
let mut duplicate = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut duplicate,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
|
||||
)
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
observe_chunked(
|
||||
&mut duplicate,
|
||||
&kiss::frame_with_command(CMD_ROM_READ, &eeprom(0xB8)),
|
||||
),
|
||||
Err(RNodeCapabilityAdmissionError::DuplicateEepromResponse)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cumulative_input_and_frame_limits_fail_closed() {
|
||||
let mut input = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
let chunk = vec![0; RNODE_CAPABILITY_READ_BUFFER_BYTES];
|
||||
for _ in 0..(RNODE_CAPABILITY_MAX_INPUT_BYTES / chunk.len()) {
|
||||
assert_eq!(input.observe_read(&chunk).unwrap(), None);
|
||||
}
|
||||
assert_eq!(
|
||||
input.observe_read(&[0]),
|
||||
Err(RNodeCapabilityAdmissionError::InputLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_INPUT_BYTES
|
||||
})
|
||||
);
|
||||
|
||||
let mut frame_bytes = Vec::new();
|
||||
for _ in 0..=RNODE_CAPABILITY_MAX_FRAMES {
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_PLATFORM, &[0], &mut frame_bytes);
|
||||
}
|
||||
let mut frames = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
frames.observe_read(&frame_bytes),
|
||||
Err(RNodeCapabilityAdmissionError::FrameLimitExceeded {
|
||||
limit: RNODE_CAPABILITY_MAX_FRAMES
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_frame_never_admits_and_is_not_replayed() {
|
||||
let bytes = admitted_frames(0xB8);
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings(868_000_000, 14));
|
||||
assert_eq!(
|
||||
observe_chunked(&mut preflight, &bytes[..bytes.len() - 1]).unwrap(),
|
||||
None
|
||||
);
|
||||
drop(preflight);
|
||||
|
||||
let mut fresh = kiss::RawKissDeframer::new();
|
||||
assert!(fresh.feed(&bytes[bytes.len() - 1..]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_pre_init_radio_evidence_cannot_make_admitted_seed_ready() {
|
||||
let settings = settings(868_000_000, 14);
|
||||
let mut bytes = Vec::new();
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_FREQUENCY,
|
||||
&settings.frequency.to_be_bytes(),
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_BANDWIDTH,
|
||||
&settings.bandwidth.to_be_bytes(),
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_SF,
|
||||
&[settings.spreading_factor],
|
||||
&mut bytes,
|
||||
);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_CR, &[settings.coding_rate], &mut bytes);
|
||||
kiss::frame_with_command_into(crate::rnode::CMD_TXPOWER, &[settings.tx_power], &mut bytes);
|
||||
kiss::frame_with_command_into(
|
||||
crate::rnode::CMD_RADIO_STATE,
|
||||
&[crate::rnode::RADIO_STATE_ON],
|
||||
&mut bytes,
|
||||
);
|
||||
bytes.extend_from_slice(&admitted_frames(0xB8));
|
||||
|
||||
let mut preflight = RNodeCapabilityPreflight::new(settings);
|
||||
assert!(observe_chunked(&mut preflight, &bytes).unwrap().is_some());
|
||||
let seed = preflight.into_protocol_state();
|
||||
assert!(seed.evidence().detected);
|
||||
assert!(seed.evidence().firmware.is_some());
|
||||
assert_eq!(seed.evidence().frequency, None);
|
||||
assert_eq!(seed.evidence().radio_state, None);
|
||||
assert!(matches!(
|
||||
seed.readiness(),
|
||||
crate::rnode_protocol::RNodeReadiness::Blocked(
|
||||
crate::rnode_protocol::RNodeReadinessBlocker::Missing(
|
||||
crate::rnode_protocol::RNodeReadinessEvidence::Frequency
|
||||
)
|
||||
)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
//! Multi-radio RNode: up to 11 sub-interfaces on one serial connection.
|
||||
//! One read task demuxes by per-vport command byte; one write task prepends
|
||||
//! `CMD_SEL_INT` so the device picks the right radio.
|
||||
//! One read task demuxes canonical `CMD_DATA` frames by the most recently
|
||||
//! selected virtual port; one write task prepends `CMD_SEL_INT` so the device
|
||||
//! picks the right radio.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
@@ -29,8 +32,12 @@ pub const CMD_ERROR: u8 = 0x90;
|
||||
pub const ERROR_INITRADIO: u8 = 0x01;
|
||||
pub const ERROR_TXFAILED: u8 = 0x02;
|
||||
|
||||
/// Per-sub-interface data command bytes. NOT port-nibble; some collide
|
||||
/// (e.g. `CMD_INT5_DATA == CMD_ERROR`) — demux by vport index, not byte.
|
||||
/// Legacy per-interface constants exposed by the firmware protocol.
|
||||
///
|
||||
/// Live RNodeMulti traffic is not demultiplexed with this table. The canonical
|
||||
/// wire form selects a vport with [`CMD_SEL_INT`] and then sends one ordinary
|
||||
/// [`kiss::CMD_DATA`] frame. Treating these values as inbound data commands
|
||||
/// makes `0x90` indistinguishable from [`CMD_ERROR`].
|
||||
pub const CMD_INT_DATA: [u8; 12] = [
|
||||
0x00, 0x10, 0x20, 0x70, 0x75, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
|
||||
];
|
||||
@@ -83,7 +90,7 @@ impl RadioType {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SubInterfaceConfig {
|
||||
pub name: String,
|
||||
/// vport index on RNode (0..MAX_SUBINTERFACES).
|
||||
/// vport index on RNode (`0..MAX_SUBINTERFACES`).
|
||||
pub vport: u8,
|
||||
pub frequency: u32,
|
||||
pub bandwidth: u32,
|
||||
@@ -158,10 +165,12 @@ impl SubInterfaceConfig {
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.vport as usize > MAX_SUBINTERFACES {
|
||||
if self.vport as usize >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
"Virtual port {} exceeds max {} for sub-interface {}",
|
||||
self.vport, MAX_SUBINTERFACES, self.name
|
||||
"Virtual port {} is outside 0..{} for sub-interface {}",
|
||||
self.vport,
|
||||
MAX_SUBINTERFACES - 1,
|
||||
self.name
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -249,6 +258,14 @@ pub fn build_subinterface_data_frame(index: u8, data: &[u8]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Map a legacy `CMD_INTn_DATA` constant to its nominal vport.
|
||||
///
|
||||
/// This helper is retained for protocol inspection and compatibility only.
|
||||
/// It must not be used to route live RNodeMulti input; use `CMD_SEL_INT`
|
||||
/// followed by `CMD_DATA` instead.
|
||||
#[deprecated(
|
||||
note = "legacy constants collide with control commands; route CMD_DATA by CMD_SEL_INT"
|
||||
)]
|
||||
pub fn command_to_subinterface(cmd_byte: u8) -> Option<usize> {
|
||||
for (i, &port_cmd) in CMD_INT_DATA.iter().enumerate() {
|
||||
if cmd_byte == port_cmd {
|
||||
@@ -258,6 +275,345 @@ pub fn command_to_subinterface(cmd_byte: u8) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
|
||||
const RNODE_HW_MTU: u32 = 508;
|
||||
const RNODE_OPEN_SETTLE: Duration = Duration::from_secs(2);
|
||||
const RNODE_SUBINTERFACE_SETTLE: Duration = Duration::from_secs(2);
|
||||
const RNODE_SUBINTERFACE_READY_SETTLE: Duration = Duration::from_millis(300);
|
||||
const RNODE_DISCOVERY_DEADLINE: Duration = Duration::from_secs(2);
|
||||
const RNODE_CONFIGURATION_DEADLINE: Duration = Duration::from_secs(2);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
struct RadioEvidence {
|
||||
frequency: Option<u32>,
|
||||
bandwidth: Option<u32>,
|
||||
spreading_factor: Option<u8>,
|
||||
coding_rate: Option<u8>,
|
||||
tx_power: Option<u8>,
|
||||
radio_state: Option<u8>,
|
||||
}
|
||||
|
||||
impl RadioEvidence {
|
||||
fn complete(self) -> bool {
|
||||
self.frequency.is_some()
|
||||
&& self.bandwidth.is_some()
|
||||
&& self.spreading_factor.is_some()
|
||||
&& self.coding_rate.is_some()
|
||||
&& self.tx_power.is_some()
|
||||
&& self.radio_state.is_some()
|
||||
}
|
||||
|
||||
fn validate(self, config: &SubInterfaceConfig) -> Result<(), String> {
|
||||
let frequency = self
|
||||
.frequency
|
||||
.ok_or_else(|| format!("{} did not report frequency", config.name))?;
|
||||
if frequency.abs_diff(config.frequency) > crate::rnode_protocol::FREQUENCY_TOLERANCE_HZ {
|
||||
return Err(format!("{} reported a different frequency", config.name));
|
||||
}
|
||||
if self.bandwidth != Some(config.bandwidth) {
|
||||
return Err(format!("{} reported a different bandwidth", config.name));
|
||||
}
|
||||
if self.spreading_factor != Some(config.spreading_factor) {
|
||||
return Err(format!(
|
||||
"{} reported a different spreading factor",
|
||||
config.name
|
||||
));
|
||||
}
|
||||
if self.coding_rate != Some(config.coding_rate) {
|
||||
return Err(format!("{} reported a different coding rate", config.name));
|
||||
}
|
||||
if self.tx_power != Some(config.tx_power) {
|
||||
return Err(format!("{} reported a different TX power", config.name));
|
||||
}
|
||||
if self.radio_state != Some(rnode::RADIO_STATE_ON) {
|
||||
return Err(format!("{} did not report its radio online", config.name));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StartupEvidence {
|
||||
detected: bool,
|
||||
firmware: Option<(u8, u8)>,
|
||||
interfaces: [Option<RadioType>; MAX_SUBINTERFACES],
|
||||
selected_vport: Option<u8>,
|
||||
radios: [RadioEvidence; MAX_SUBINTERFACES],
|
||||
}
|
||||
|
||||
impl Default for StartupEvidence {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
detected: false,
|
||||
firmware: None,
|
||||
interfaces: [None; MAX_SUBINTERFACES],
|
||||
selected_vport: None,
|
||||
radios: [RadioEvidence::default(); MAX_SUBINTERFACES],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StartupEvidence {
|
||||
fn apply_frame(&mut self, command: u8, payload: &[u8]) -> Result<(), String> {
|
||||
match command {
|
||||
rnode::CMD_DETECT => {
|
||||
if payload.len() != 1 {
|
||||
return Err("RNodeMulti returned malformed detection evidence".into());
|
||||
}
|
||||
self.detected = payload[0] == rnode::DETECT_RESP;
|
||||
}
|
||||
rnode::CMD_FW_VERSION => {
|
||||
if payload.len() != 2 {
|
||||
return Err("RNodeMulti returned malformed firmware evidence".into());
|
||||
}
|
||||
self.firmware = Some((payload[0], payload[1]));
|
||||
}
|
||||
CMD_INTERFACES => {
|
||||
if payload.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if payload.len() % 2 != 0 {
|
||||
return Err("RNodeMulti returned a malformed interface list".into());
|
||||
}
|
||||
for pair in payload.chunks_exact(2) {
|
||||
let vport = pair[0] as usize;
|
||||
if vport >= MAX_SUBINTERFACES {
|
||||
return Err(format!(
|
||||
"RNodeMulti reported unsupported virtual port {}",
|
||||
pair[0]
|
||||
));
|
||||
}
|
||||
let radio_type = RadioType::from_u8(pair[1]).ok_or_else(|| {
|
||||
format!(
|
||||
"RNodeMulti reported unknown radio type 0x{:02X} on virtual port {}",
|
||||
pair[1], pair[0]
|
||||
)
|
||||
})?;
|
||||
if self.interfaces[vport].is_some_and(|known| known != radio_type) {
|
||||
return Err(format!(
|
||||
"RNodeMulti changed the radio type reported for virtual port {}",
|
||||
pair[0]
|
||||
));
|
||||
}
|
||||
self.interfaces[vport] = Some(radio_type);
|
||||
}
|
||||
}
|
||||
CMD_SEL_INT => {
|
||||
if payload.len() != 1 || payload[0] as usize >= MAX_SUBINTERFACES {
|
||||
self.selected_vport = None;
|
||||
return Err("RNodeMulti returned an invalid virtual-port selection".into());
|
||||
}
|
||||
self.selected_vport = Some(payload[0]);
|
||||
}
|
||||
rnode::CMD_FREQUENCY => {
|
||||
if payload.len() != 4 {
|
||||
return Err("RNodeMulti returned malformed frequency evidence".into());
|
||||
}
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.frequency = Some(u32::from_be_bytes(
|
||||
payload.try_into().expect("length checked"),
|
||||
));
|
||||
}
|
||||
}
|
||||
rnode::CMD_BANDWIDTH => {
|
||||
if payload.len() != 4 {
|
||||
return Err("RNodeMulti returned malformed bandwidth evidence".into());
|
||||
}
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.bandwidth = Some(u32::from_be_bytes(
|
||||
payload.try_into().expect("length checked"),
|
||||
));
|
||||
}
|
||||
}
|
||||
rnode::CMD_SF => {
|
||||
let value = one_byte(payload, "spreading factor")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.spreading_factor = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_CR => {
|
||||
let value = one_byte(payload, "coding rate")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.coding_rate = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_TXPOWER => {
|
||||
let value = one_byte(payload, "TX power")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.tx_power = Some(value);
|
||||
}
|
||||
}
|
||||
rnode::CMD_RADIO_STATE => {
|
||||
let value = one_byte(payload, "radio state")?;
|
||||
if let Some(radio) = self.selected_radio_mut() {
|
||||
radio.radio_state = Some(value);
|
||||
}
|
||||
}
|
||||
CMD_ERROR => {
|
||||
let class = match payload.first().copied() {
|
||||
Some(ERROR_INITRADIO) => "radio initialisation",
|
||||
Some(ERROR_TXFAILED) => "radio transmission",
|
||||
_ => "unknown hardware",
|
||||
};
|
||||
return Err(format!("RNodeMulti reported a {class} error"));
|
||||
}
|
||||
rnode::CMD_RESET if payload.first().copied() == Some(0xF8) => {
|
||||
return Err("RNodeMulti reset during startup".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn selected_radio_mut(&mut self) -> Option<&mut RadioEvidence> {
|
||||
self.selected_vport
|
||||
.and_then(|vport| self.radios.get_mut(vport as usize))
|
||||
}
|
||||
|
||||
fn discovery_complete(&self, config: &RNodeMultiConfig) -> bool {
|
||||
self.detected
|
||||
&& self.firmware.is_some()
|
||||
&& config
|
||||
.subinterfaces
|
||||
.iter()
|
||||
.all(|sub| self.interfaces[sub.vport as usize].is_some())
|
||||
}
|
||||
|
||||
fn validate_discovery(&self, config: &RNodeMultiConfig) -> Result<(), String> {
|
||||
if !self.detected {
|
||||
return Err("RNodeMulti device did not answer detection".into());
|
||||
}
|
||||
let (major, minor) = self
|
||||
.firmware
|
||||
.ok_or_else(|| "RNodeMulti did not report its firmware version".to_string())?;
|
||||
if (major, minor) < (REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN) {
|
||||
return Err(format!(
|
||||
"RNodeMulti firmware {major}.{minor} is below required {}.{}",
|
||||
REQUIRED_FW_VER_MAJ, REQUIRED_FW_VER_MIN
|
||||
));
|
||||
}
|
||||
for sub in &config.subinterfaces {
|
||||
let radio_type = self.interfaces[sub.vport as usize].ok_or_else(|| {
|
||||
format!(
|
||||
"virtual port {} for {} was not reported by the RNodeMulti device",
|
||||
sub.vport, sub.name
|
||||
)
|
||||
})?;
|
||||
if !radio_type.validate_frequency(sub.frequency) {
|
||||
return Err(format!(
|
||||
"frequency {} is outside the {} range reported for {}",
|
||||
sub.frequency,
|
||||
radio_type.family_name(),
|
||||
sub.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reset_radio(&mut self, vport: u8) {
|
||||
self.radios[vport as usize] = RadioEvidence::default();
|
||||
self.selected_vport = None;
|
||||
}
|
||||
|
||||
fn radio_complete(&self, vport: u8) -> bool {
|
||||
self.radios[vport as usize].complete()
|
||||
}
|
||||
}
|
||||
|
||||
fn one_byte(payload: &[u8], field: &str) -> Result<u8, String> {
|
||||
if payload.len() != 1 {
|
||||
return Err(format!("RNodeMulti returned malformed {field} evidence"));
|
||||
}
|
||||
Ok(payload[0])
|
||||
}
|
||||
|
||||
fn read_startup_until(
|
||||
port: &mut dyn serialport::SerialPort,
|
||||
deframer: &mut kiss::RawKissDeframer,
|
||||
evidence: &mut StartupEvidence,
|
||||
deadline: Instant,
|
||||
ready: impl Fn(&StartupEvidence) -> bool,
|
||||
) -> Result<(), String> {
|
||||
let mut buffer = [0u8; 1024];
|
||||
while Instant::now() < deadline {
|
||||
match port.read(&mut buffer) {
|
||||
Ok(0) => {}
|
||||
Ok(read) => {
|
||||
for (command, payload) in deframer.feed(&buffer[..read]) {
|
||||
evidence.apply_frame(command, &payload)?;
|
||||
if ready(evidence) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {}
|
||||
Err(error) => return Err(format!("RNodeMulti startup read failed: {error}")),
|
||||
}
|
||||
}
|
||||
Err("RNodeMulti startup validation timed out".into())
|
||||
}
|
||||
|
||||
fn initialise_rnode_multi(
|
||||
mut port: Box<dyn serialport::SerialPort>,
|
||||
config: &RNodeMultiConfig,
|
||||
) -> Result<Box<dyn serialport::SerialPort>, String> {
|
||||
std::thread::sleep(RNODE_OPEN_SETTLE);
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let mut evidence = StartupEvidence::default();
|
||||
|
||||
port.write_all(&build_detect_sequence())
|
||||
.map_err(|error| format!("RNodeMulti detect write failed: {error}"))?;
|
||||
port.flush()
|
||||
.map_err(|error| format!("RNodeMulti detect flush failed: {error}"))?;
|
||||
read_startup_until(
|
||||
port.as_mut(),
|
||||
&mut deframer,
|
||||
&mut evidence,
|
||||
Instant::now() + RNODE_DISCOVERY_DEADLINE,
|
||||
|state| state.discovery_complete(config),
|
||||
)?;
|
||||
evidence.validate_discovery(config)?;
|
||||
|
||||
for sub in &config.subinterfaces {
|
||||
// RNode firmware configures one physical radio at a time. Match the
|
||||
// established RNodeMulti startup cadence and let the selected radio
|
||||
// settle before sending its reset/init sequence.
|
||||
std::thread::sleep(RNODE_SUBINTERFACE_SETTLE);
|
||||
evidence.reset_radio(sub.vport);
|
||||
port.write_all(&build_subinterface_init(sub.vport, sub))
|
||||
.map_err(|error| format!("RNodeMulti {} init write failed: {error}", sub.name))?;
|
||||
port.flush()
|
||||
.map_err(|error| format!("RNodeMulti {} init flush failed: {error}", sub.name))?;
|
||||
read_startup_until(
|
||||
port.as_mut(),
|
||||
&mut deframer,
|
||||
&mut evidence,
|
||||
Instant::now() + RNODE_CONFIGURATION_DEADLINE,
|
||||
|state| state.radio_complete(sub.vport),
|
||||
)?;
|
||||
evidence.radios[sub.vport as usize].validate(sub)?;
|
||||
// Match upstream's brief post-validation pause before exposing this
|
||||
// radio or beginning configuration of the next physical radio.
|
||||
std::thread::sleep(RNODE_SUBINTERFACE_READY_SETTLE);
|
||||
}
|
||||
|
||||
Ok(port)
|
||||
}
|
||||
|
||||
fn selected_data_target(
|
||||
command: u8,
|
||||
selected_vport: Option<u8>,
|
||||
vport_map: &[Option<usize>; MAX_SUBINTERFACES],
|
||||
) -> Option<usize> {
|
||||
if command != kiss::CMD_DATA {
|
||||
return None;
|
||||
}
|
||||
selected_vport
|
||||
.and_then(|vport| vport_map.get(vport as usize))
|
||||
.copied()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
struct WriteRequest {
|
||||
index: u8,
|
||||
/// Raw payload, not yet KISS-escaped.
|
||||
@@ -334,6 +690,15 @@ pub async fn spawn_rnode_multi_interface(
|
||||
sub.validate()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti config: {}", e)))?;
|
||||
}
|
||||
let mut configured_vports = HashSet::with_capacity(config.subinterfaces.len());
|
||||
for sub in &config.subinterfaces {
|
||||
if !configured_vports.insert(sub.vport) {
|
||||
return Err(InterfaceError::SendFailed(format!(
|
||||
"RNodeMulti config: virtual port {} is configured more than once",
|
||||
sub.vport
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let port = serialport::new(&config.port, config.baud_rate)
|
||||
.timeout(Duration::from_millis(RNODE_READ_TIMEOUT_MS))
|
||||
@@ -347,36 +712,13 @@ pub async fn spawn_rnode_multi_interface(
|
||||
"RNodeMulti interface opened"
|
||||
);
|
||||
|
||||
{
|
||||
let mut detect_port = port
|
||||
.try_clone()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
|
||||
let detect_seq = build_detect_sequence();
|
||||
use std::io::Write;
|
||||
detect_port
|
||||
.write_all(&detect_seq)
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect write: {}", e)))?;
|
||||
detect_port
|
||||
.flush()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti detect flush: {}", e)))?;
|
||||
}
|
||||
|
||||
{
|
||||
let mut init_port = port
|
||||
.try_clone()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti clone: {}", e)))?;
|
||||
let mut init_seq = Vec::new();
|
||||
for sub in &config.subinterfaces {
|
||||
init_seq.extend_from_slice(&build_subinterface_init(sub.vport, sub));
|
||||
}
|
||||
use std::io::Write;
|
||||
init_port
|
||||
.write_all(&init_seq)
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init write: {}", e)))?;
|
||||
init_port
|
||||
.flush()
|
||||
.map_err(|e| InterfaceError::SendFailed(format!("RNodeMulti init flush: {}", e)))?;
|
||||
}
|
||||
let startup_config = config.clone();
|
||||
let port = tokio::task::spawn_blocking(move || initialise_rnode_multi(port, &startup_config))
|
||||
.await
|
||||
.map_err(|error| {
|
||||
InterfaceError::SendFailed(format!("RNodeMulti startup worker failed: {error}"))
|
||||
})?
|
||||
.map_err(|error| InterfaceError::SendFailed(format!("RNodeMulti startup: {error}")))?;
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
|
||||
@@ -478,10 +820,11 @@ pub async fn spawn_rnode_multi_interface(
|
||||
repeat: false,
|
||||
},
|
||||
bitrate,
|
||||
mtu: rns_wire::constants::MTU as u32,
|
||||
mtu: RNODE_HW_MTU,
|
||||
online: sub_onlines[i].clone(),
|
||||
rxb: Some(rxb),
|
||||
txb: Some(txb),
|
||||
inspection: None,
|
||||
tx: sub_tx,
|
||||
read_task: sub_read_task,
|
||||
});
|
||||
@@ -601,13 +944,11 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let parent_name = config.name.clone();
|
||||
|
||||
// `vport_map[vport] -> Some(local_index)` for configured sub-interfaces.
|
||||
let mut vport_map: [Option<usize>; 12] = [None; 12];
|
||||
let mut vport_map: [Option<usize>; MAX_SUBINTERFACES] = [None; MAX_SUBINTERFACES];
|
||||
let mut sub_ids: Vec<InterfaceId> = Vec::with_capacity(num_subs);
|
||||
for (i, sub_cfg) in config.subinterfaces.iter().enumerate() {
|
||||
let vp = sub_cfg.vport as usize;
|
||||
if vp < 12 {
|
||||
vport_map[vp] = Some(i);
|
||||
}
|
||||
vport_map[vp] = Some(i);
|
||||
sub_ids.push(ids[i]);
|
||||
}
|
||||
|
||||
@@ -621,10 +962,8 @@ pub async fn spawn_rnode_multi_interface(
|
||||
.collect();
|
||||
|
||||
// Which sub-interface the device is currently addressing via
|
||||
// CMD_SEL_INT; status commands below target this index.
|
||||
let mut selected_index: usize = 0;
|
||||
|
||||
let mut interfaces_buf: Vec<u8> = Vec::new();
|
||||
// CMD_SEL_INT; status and canonical CMD_DATA frames target this vport.
|
||||
let mut selected_vport: Option<u8> = Some(0);
|
||||
|
||||
loop {
|
||||
if !flags_r.device_running() {
|
||||
@@ -640,11 +979,13 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
for (raw_cmd, frame) in deframer.feed(&buf[..n]) {
|
||||
if let Some(vport) = command_to_subinterface(raw_cmd) {
|
||||
if raw_cmd == kiss::CMD_DATA {
|
||||
if frame.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(local_idx) = vport_map[vport] {
|
||||
if let Some(local_idx) =
|
||||
selected_data_target(raw_cmd, selected_vport, &vport_map)
|
||||
{
|
||||
sub_rxb[local_idx].fetch_add(frame.len() as u64, Ordering::Relaxed);
|
||||
|
||||
let rssi = signals[local_idx].last_rssi.take();
|
||||
@@ -668,7 +1009,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
} else {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport,
|
||||
vport = ?selected_vport,
|
||||
"data for unconfigured sub-interface, dropping"
|
||||
);
|
||||
}
|
||||
@@ -680,7 +1021,15 @@ pub async fn spawn_rnode_multi_interface(
|
||||
// Device echoes selection before emitting any
|
||||
// status/config responses for that sub-interface.
|
||||
if let Some(&idx) = frame.first() {
|
||||
selected_index = idx as usize;
|
||||
selected_vport =
|
||||
((idx as usize) < MAX_SUBINTERFACES).then_some(idx);
|
||||
if selected_vport.is_none() {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
vport = idx,
|
||||
"RNodeMulti selected an invalid virtual port"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,7 +1037,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
let rssi = rnode::decode_rssi_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
signals[local_idx].last_rssi = Some(rssi);
|
||||
}
|
||||
@@ -698,7 +1047,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
let snr = rnode::decode_snr_byte(frame[0]);
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
signals[local_idx].last_snr = Some(snr);
|
||||
}
|
||||
@@ -745,20 +1094,20 @@ pub async fn spawn_rnode_multi_interface(
|
||||
|
||||
rnode::CMD_RADIO_STATE => {
|
||||
if let Some(local_idx) =
|
||||
vport_map.get(selected_index).copied().flatten()
|
||||
selected_vport.and_then(|vport| vport_map[vport as usize])
|
||||
{
|
||||
if frame.first().copied() == Some(rnode::RADIO_STATE_ON) {
|
||||
tracing::info!(
|
||||
parent = %parent_name,
|
||||
subinterface = local_idx,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti sub-interface radio online"
|
||||
);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
subinterface = local_idx,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti sub-interface radio offline"
|
||||
);
|
||||
}
|
||||
@@ -772,7 +1121,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
]);
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
freq_mhz = format!("{:.3}", freq as f64 / 1_000_000.0),
|
||||
"Radio reporting frequency"
|
||||
);
|
||||
@@ -786,7 +1135,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
]);
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
bw_khz = format!("{:.1}", bw as f64 / 1000.0),
|
||||
"Radio reporting bandwidth"
|
||||
);
|
||||
@@ -797,7 +1146,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
sf = frame[0],
|
||||
"Radio reporting spreading factor"
|
||||
);
|
||||
@@ -808,7 +1157,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
if !frame.is_empty() {
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
cr = frame[0],
|
||||
"Radio reporting coding rate"
|
||||
);
|
||||
@@ -820,7 +1169,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let txp = frame[0] as i8;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
txpower_dbm = txp,
|
||||
"Radio reporting TX power"
|
||||
);
|
||||
@@ -833,7 +1182,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let pct = at as f32 / 100.0;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti short-term airtime limit: {:.2}%", pct,
|
||||
);
|
||||
}
|
||||
@@ -845,7 +1194,7 @@ pub async fn spawn_rnode_multi_interface(
|
||||
let pct = at as f32 / 100.0;
|
||||
tracing::debug!(
|
||||
parent = %parent_name,
|
||||
vport = selected_index,
|
||||
vport = ?selected_vport,
|
||||
"RNodeMulti long-term airtime limit: {:.2}%", pct,
|
||||
);
|
||||
}
|
||||
@@ -872,12 +1221,10 @@ pub async fn spawn_rnode_multi_interface(
|
||||
}
|
||||
|
||||
CMD_INTERFACES => {
|
||||
// Reply is a stream of 2-byte `[vport, radio_type]`
|
||||
// pairs, one per radio module; accumulate then pop.
|
||||
interfaces_buf.extend_from_slice(&frame);
|
||||
if interfaces_buf.len() >= 2 {
|
||||
let vp = interfaces_buf[0];
|
||||
let rt = interfaces_buf[1];
|
||||
// Reply is one or more `[vport, radio_type]` pairs.
|
||||
for pair in frame.chunks_exact(2) {
|
||||
let vp = pair[0];
|
||||
let rt = pair[1];
|
||||
let rtype = RadioType::from_u8(rt)
|
||||
.map(|r| r.family_name().to_string())
|
||||
.unwrap_or_else(|| format!("unknown(0x{:02X})", rt));
|
||||
@@ -887,13 +1234,30 @@ pub async fn spawn_rnode_multi_interface(
|
||||
radio_type = %rtype,
|
||||
"RNodeMulti radio module reported"
|
||||
);
|
||||
interfaces_buf.clear();
|
||||
}
|
||||
if frame.len() % 2 != 0 {
|
||||
tracing::warn!(
|
||||
parent = %parent_name,
|
||||
"RNodeMulti returned a malformed interface list"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// No CMD_ERROR arm: 0x90 collides with CMD_INT5_DATA
|
||||
// and is consumed by the vport demux above — same
|
||||
// collision as Python RNodeMultiInterface.
|
||||
CMD_ERROR => {
|
||||
let class = match frame.first().copied() {
|
||||
Some(ERROR_INITRADIO) => "radio initialisation",
|
||||
Some(ERROR_TXFAILED) => "radio transmission",
|
||||
_ => "unknown hardware",
|
||||
};
|
||||
tracing::error!(
|
||||
parent = %parent_name,
|
||||
class,
|
||||
"RNodeMulti hardware error"
|
||||
);
|
||||
flags_r.trip_device();
|
||||
return;
|
||||
}
|
||||
|
||||
rnode::CMD_RESET => {
|
||||
if frame.first().copied() == Some(0xF8) {
|
||||
tracing::error!(
|
||||
@@ -1018,25 +1382,6 @@ mod tests {
|
||||
assert_eq!(frames.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_command_to_subinterface() {
|
||||
assert_eq!(command_to_subinterface(0x00), Some(0));
|
||||
assert_eq!(command_to_subinterface(0x10), Some(1));
|
||||
assert_eq!(command_to_subinterface(0x20), Some(2));
|
||||
assert_eq!(command_to_subinterface(0x70), Some(3));
|
||||
assert_eq!(command_to_subinterface(0x75), Some(4));
|
||||
assert_eq!(command_to_subinterface(0x90), Some(5));
|
||||
assert_eq!(command_to_subinterface(0xA0), Some(6));
|
||||
assert_eq!(command_to_subinterface(0xB0), Some(7));
|
||||
assert_eq!(command_to_subinterface(0xC0), Some(8));
|
||||
assert_eq!(command_to_subinterface(0xD0), Some(9));
|
||||
assert_eq!(command_to_subinterface(0xE0), Some(10));
|
||||
assert_eq!(command_to_subinterface(0xF0), Some(11));
|
||||
assert_eq!(command_to_subinterface(0x55), None);
|
||||
assert_eq!(command_to_subinterface(0xFF), None);
|
||||
assert_eq!(command_to_subinterface(0x01), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_radio_type() {
|
||||
assert_eq!(RadioType::from_u8(0x00), Some(RadioType::SX127X));
|
||||
@@ -1067,7 +1412,12 @@ mod tests {
|
||||
#[test]
|
||||
fn test_max_subinterfaces() {
|
||||
assert_eq!(MAX_SUBINTERFACES, 11);
|
||||
assert_eq!(CMD_INT_DATA.len(), 12);
|
||||
assert_eq!(RNODE_HW_MTU, 508);
|
||||
|
||||
let highest = SubInterfaceConfig::new("radio10", 10, 868_000_000);
|
||||
assert!(highest.validate().is_ok());
|
||||
let outside = SubInterfaceConfig::new("radio11", 11, 868_000_000);
|
||||
assert!(outside.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1098,9 +1448,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_raw_kiss_deframer_preserves_command() {
|
||||
// CMD_INT5_DATA = 0x90 collides with CMD_ERROR after masking; the raw
|
||||
// deframer must keep the high nibble intact.
|
||||
let payload = b"test data";
|
||||
// CMD_ERROR is 0x90. The raw deframer must retain that exact command
|
||||
// so it can never be mistaken for vport-5 packet data.
|
||||
let payload = &[ERROR_INITRADIO];
|
||||
let mut raw_frame = Vec::new();
|
||||
raw_frame.push(kiss::FEND);
|
||||
raw_frame.push(0x90);
|
||||
@@ -1110,10 +1460,12 @@ mod tests {
|
||||
let mut deframer = kiss::RawKissDeframer::new();
|
||||
let frames = deframer.feed(&raw_frame);
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0].0, 0x90);
|
||||
assert_eq!(frames[0].0, CMD_ERROR);
|
||||
assert_eq!(frames[0].1, payload);
|
||||
|
||||
assert_eq!(command_to_subinterface(0x90), Some(5));
|
||||
let mut vport_map = [None; MAX_SUBINTERFACES];
|
||||
vport_map[5] = Some(0);
|
||||
assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1213,7 +1565,7 @@ mod tests {
|
||||
bad.st_alock = Some(101.0);
|
||||
assert!(bad.validate().is_err());
|
||||
|
||||
let bad = SubInterfaceConfig::new("radio0", 12, 868_000_000);
|
||||
let bad = SubInterfaceConfig::new("radio0", 11, 868_000_000);
|
||||
assert!(bad.validate().is_err());
|
||||
}
|
||||
|
||||
@@ -1283,55 +1635,118 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_subinterface_data_commands_unique() {
|
||||
for (i, lhs) in CMD_INT_DATA.iter().enumerate() {
|
||||
for (j, rhs) in CMD_INT_DATA.iter().enumerate().skip(i + 1) {
|
||||
assert_ne!(
|
||||
lhs, rhs,
|
||||
"CMD_INT_DATA[{}] == CMD_INT_DATA[{}] == 0x{:02X}",
|
||||
i, j, *lhs
|
||||
);
|
||||
}
|
||||
}
|
||||
fn canonical_data_routing_uses_selected_vport_only() {
|
||||
let mut vport_map = [None; MAX_SUBINTERFACES];
|
||||
vport_map[0] = Some(0);
|
||||
vport_map[5] = Some(1);
|
||||
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(5), &vport_map),
|
||||
Some(1)
|
||||
);
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(0), &vport_map),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
selected_data_target(kiss::CMD_DATA, Some(4), &vport_map),
|
||||
None
|
||||
);
|
||||
assert_eq!(selected_data_target(CMD_ERROR, Some(5), &vport_map), None);
|
||||
assert_eq!(selected_data_target(0xA0, Some(5), &vport_map), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_commands_dont_collide_with_control_commands() {
|
||||
let control_cmds = [
|
||||
CMD_SEL_INT,
|
||||
rnode::CMD_STAT_RSSI,
|
||||
rnode::CMD_STAT_SNR,
|
||||
rnode::CMD_READY,
|
||||
rnode::CMD_DETECT,
|
||||
rnode::CMD_FW_VERSION,
|
||||
rnode::CMD_RADIO_STATE,
|
||||
rnode::CMD_FREQUENCY,
|
||||
rnode::CMD_BANDWIDTH,
|
||||
rnode::CMD_SF,
|
||||
rnode::CMD_CR,
|
||||
rnode::CMD_TXPOWER,
|
||||
rnode::CMD_ST_ALOCK,
|
||||
rnode::CMD_LT_ALOCK,
|
||||
rnode::CMD_PLATFORM,
|
||||
rnode::CMD_MCU,
|
||||
CMD_INTERFACES,
|
||||
rnode::CMD_RESET,
|
||||
];
|
||||
fn startup_discovery_validates_firmware_interface_types_and_ranges() {
|
||||
let mut config = RNodeMultiConfig::new("multi0", "/dev/null");
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("low", 0, 868_000_000));
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("high", 3, 2_400_000_000));
|
||||
|
||||
for &data_cmd in &CMD_INT_DATA {
|
||||
for &ctrl_cmd in &control_cmds {
|
||||
// CMD_INT0_DATA == CMD_DATA (0x00) and CMD_INT5_DATA ==
|
||||
// CMD_ERROR (0x90) are known, intentional overlaps; the read
|
||||
// loop disambiguates by checking data commands first.
|
||||
if data_cmd == 0x00 || data_cmd == 0x90 {
|
||||
continue;
|
||||
}
|
||||
assert_ne!(
|
||||
data_cmd, ctrl_cmd,
|
||||
"CMD_INT_DATA 0x{:02X} collides with control cmd 0x{:02X}",
|
||||
data_cmd, ctrl_cmd
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut state = StartupEvidence::default();
|
||||
state
|
||||
.apply_frame(rnode::CMD_DETECT, &[rnode::DETECT_RESP])
|
||||
.unwrap();
|
||||
// Lexicographic comparison accepts newer major versions.
|
||||
state.apply_frame(rnode::CMD_FW_VERSION, &[2, 0]).unwrap();
|
||||
state
|
||||
.apply_frame(
|
||||
CMD_INTERFACES,
|
||||
&[0, RadioType::SX1276 as u8, 3, RadioType::SX1280 as u8],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(state.discovery_complete(&config));
|
||||
assert!(state.validate_discovery(&config).is_ok());
|
||||
|
||||
config.subinterfaces[1].frequency = 915_000_000;
|
||||
assert!(state.validate_discovery(&config).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_discovery_rejects_malformed_or_unknown_interfaces() {
|
||||
let mut state = StartupEvidence::default();
|
||||
assert!(state.apply_frame(CMD_INTERFACES, &[0]).is_err());
|
||||
assert!(state.apply_frame(CMD_INTERFACES, &[0, 0xFF]).is_err());
|
||||
assert!(
|
||||
state
|
||||
.apply_frame(CMD_INTERFACES, &[MAX_SUBINTERFACES as u8, 0x00])
|
||||
.is_err()
|
||||
);
|
||||
assert!(state.apply_frame(CMD_ERROR, &[ERROR_INITRADIO]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_requires_matching_echoes_before_radio_is_ready() {
|
||||
let config = SubInterfaceConfig::new("radio0", 0, 868_000_000);
|
||||
let mut state = StartupEvidence::default();
|
||||
state.apply_frame(CMD_SEL_INT, &[0]).unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_FREQUENCY, &config.frequency.to_be_bytes())
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_BANDWIDTH, &config.bandwidth.to_be_bytes())
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_SF, &[config.spreading_factor])
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_CR, &[config.coding_rate])
|
||||
.unwrap();
|
||||
state
|
||||
.apply_frame(rnode::CMD_TXPOWER, &[config.tx_power])
|
||||
.unwrap();
|
||||
assert!(!state.radio_complete(0));
|
||||
state
|
||||
.apply_frame(rnode::CMD_RADIO_STATE, &[rnode::RADIO_STATE_ON])
|
||||
.unwrap();
|
||||
|
||||
assert!(state.radio_complete(0));
|
||||
assert!(state.radios[0].validate(&config).is_ok());
|
||||
|
||||
let mut mismatch = state.radios[0];
|
||||
mismatch.coding_rate = Some(config.coding_rate + 1);
|
||||
assert!(mismatch.validate(&config).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_vports_are_rejected_before_opening_serial() {
|
||||
let mut config = RNodeMultiConfig::new("multi0", "/does/not/exist");
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("first", 0, 868_000_000));
|
||||
config
|
||||
.subinterfaces
|
||||
.push(SubInterfaceConfig::new("second", 0, 915_000_000));
|
||||
let (transport_tx, _transport_rx) = mpsc::channel(1);
|
||||
let result = spawn_rnode_multi_interface(config, &[1, 2], transport_tx).await;
|
||||
let error = match result {
|
||||
Ok(_) => panic!("duplicate vports must fail before serial open"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.to_string().contains("configured more than once"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -188,6 +188,7 @@ pub async fn spawn_serial_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
/// One bounded blocking read. Serial idle timeouts surface as `n == 0` so
|
||||
/// the caller's loop can re-check its exit flag. A panicked blocking task
|
||||
/// folds into an `io::Error`.
|
||||
#[cfg(feature = "serial")]
|
||||
pub(crate) async fn poll_read<P>(
|
||||
mut port: P,
|
||||
mut buf: [u8; 1024],
|
||||
|
||||
@@ -8,7 +8,9 @@ use tokio::sync::mpsc;
|
||||
|
||||
use crate::hdlc;
|
||||
use crate::kiss;
|
||||
use crate::traits::{InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode};
|
||||
use crate::traits::{
|
||||
InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, handoff_accepted_interface,
|
||||
};
|
||||
use rns_transport::messages::{InboundPacket, TransportMessage};
|
||||
|
||||
pub const RECONNECT_WAIT_INITIAL: u64 = 5;
|
||||
@@ -100,8 +102,10 @@ 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 && let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
if prefer_ipv6 {
|
||||
if let Some(v6) = on_dev.iter().find(|ip| ip.is_ipv6()) {
|
||||
return Some(*v6);
|
||||
}
|
||||
}
|
||||
on_dev
|
||||
.iter()
|
||||
@@ -285,12 +289,12 @@ async fn tcp_write_loop(
|
||||
state.online.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Spawn an auto-reconnecting TCP client interface.
|
||||
/// Spawn an auto-reconnecting TCP client interface. IFAC masking, when
|
||||
/// configured, is applied by the transport actor, not the driver.
|
||||
pub async fn spawn_tcp_client(
|
||||
config: TcpClientConfig,
|
||||
id: InterfaceId,
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
_ifac: Option<crate::traits::IfacConfig>,
|
||||
) -> Result<InterfaceHandle, crate::traits::InterfaceError> {
|
||||
let online = Arc::new(AtomicBool::new(false));
|
||||
let online2 = online.clone();
|
||||
@@ -437,6 +441,7 @@ pub async fn spawn_tcp_client(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -505,6 +510,7 @@ async fn spawn_tcp_accepted(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
}
|
||||
@@ -560,7 +566,10 @@ pub async fn spawn_tcp_server(
|
||||
mode,
|
||||
)
|
||||
.await;
|
||||
if handle_tx.send(handle).await.is_err() {
|
||||
if handoff_accepted_interface(&handle_tx, handle)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("handle registry channel closed, stopping accept loop");
|
||||
break;
|
||||
}
|
||||
@@ -591,6 +600,7 @@ pub async fn spawn_tcp_server(
|
||||
online,
|
||||
rxb: Some(Arc::new(AtomicU64::new(0))),
|
||||
txb: Some(Arc::new(AtomicU64::new(0))),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
@@ -691,9 +701,7 @@ mod tests {
|
||||
config.max_reconnect_tries = Some(1);
|
||||
config.connect_timeout_secs = 2;
|
||||
|
||||
let handle = spawn_tcp_client(config, 77, transport_tx, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let handle = spawn_tcp_client(config, 77, transport_tx).await.unwrap();
|
||||
|
||||
let msg = tokio::time::timeout(std::time::Duration::from_secs(10), transport_rx.recv())
|
||||
.await
|
||||
@@ -767,7 +775,7 @@ mod tests {
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
};
|
||||
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone(), None)
|
||||
let client_handle = spawn_tcp_client(client_cfg, 1, transport_tx.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -853,9 +861,7 @@ mod tests {
|
||||
fixed_mtu: None,
|
||||
};
|
||||
|
||||
let handle = spawn_tcp_client(config, 99, transport_tx, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let handle = spawn_tcp_client(config, 99, transport_tx).await.unwrap();
|
||||
|
||||
// Two failed tries with 5s waits each; 20s headroom.
|
||||
let result =
|
||||
@@ -896,7 +902,7 @@ mod tests {
|
||||
mode: InterfaceMode::Full,
|
||||
fixed_mtu: None,
|
||||
};
|
||||
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone(), None)
|
||||
let client_handle = spawn_tcp_client(client_cfg, 321, transport_tx.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
||||
@@ -20,14 +20,34 @@ pub struct InterfaceHandle {
|
||||
pub online: Arc<AtomicBool>,
|
||||
pub rxb: Option<Arc<AtomicU64>>,
|
||||
pub txb: Option<Arc<AtomicU64>>,
|
||||
/// Optional live aggregate inspection source carried into the transport
|
||||
/// actor. This field intentionally makes pre-freeze struct literals update
|
||||
/// explicitly so new interface drivers choose whether they expose stats.
|
||||
pub inspection: Option<rns_transport::messages::InterfaceInspectionSource>,
|
||||
pub tx: mpsc::Sender<Bytes>,
|
||||
pub read_task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
/// Optional per-interface IFAC (Interface Authentication Code) configuration.
|
||||
pub struct IfacConfig {
|
||||
pub ifac_key: [u8; 64],
|
||||
pub ifac_size: usize,
|
||||
/// Deliver a dynamically accepted interface to its owner.
|
||||
///
|
||||
/// A failed handoff returns the handle to this producer. The producer must
|
||||
/// finish disposing of the exact child it created rather than detaching its
|
||||
/// read task when the receiving runtime has gone away.
|
||||
pub(crate) async fn handoff_accepted_interface(
|
||||
handle_tx: &mpsc::Sender<InterfaceHandle>,
|
||||
handle: InterfaceHandle,
|
||||
) -> Result<(), ()> {
|
||||
match handle_tx.send(handle).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(mpsc::error::SendError(handle)) => {
|
||||
handle
|
||||
.online
|
||||
.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
handle.read_task.abort();
|
||||
let _ = handle.read_task.await;
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface operating mode. Byte values are on-wire constants.
|
||||
@@ -42,6 +62,8 @@ pub enum InterfaceMode {
|
||||
Roaming = 0x04,
|
||||
Boundary = 0x05,
|
||||
Gateway = 0x06,
|
||||
/// Python 1.3.8 `MODE_INTERNAL` (Interface.py:51) — local/shared-instance interfaces.
|
||||
Internal = 0x07,
|
||||
}
|
||||
|
||||
pub const MODE_FULL: InterfaceMode = InterfaceMode::Full;
|
||||
@@ -57,6 +79,7 @@ pub const DISCOVER_PATHS_FOR: &[InterfaceMode] = &[
|
||||
InterfaceMode::AccessPoint,
|
||||
InterfaceMode::Gateway,
|
||||
InterfaceMode::Roaming,
|
||||
InterfaceMode::Internal,
|
||||
];
|
||||
|
||||
impl InterfaceMode {
|
||||
@@ -68,6 +91,7 @@ impl InterfaceMode {
|
||||
0x04 => Some(Self::Roaming),
|
||||
0x05 => Some(Self::Boundary),
|
||||
0x06 => Some(Self::Gateway),
|
||||
0x07 => Some(Self::Internal),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -162,6 +186,19 @@ pub enum InterfaceError {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
struct TaskExitGuard {
|
||||
exited: Option<tokio::sync::oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl Drop for TaskExitGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(exited) = self.exited.take() {
|
||||
let _ = exited.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_optimise_mtu() {
|
||||
@@ -180,6 +217,7 @@ mod tests {
|
||||
assert_eq!(InterfaceMode::Roaming as u8, 0x04);
|
||||
assert_eq!(InterfaceMode::Boundary as u8, 0x05);
|
||||
assert_eq!(InterfaceMode::Gateway as u8, 0x06);
|
||||
assert_eq!(InterfaceMode::Internal as u8, 0x07);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -190,7 +228,9 @@ mod tests {
|
||||
Some(InterfaceMode::PointToPoint)
|
||||
);
|
||||
assert_eq!(InterfaceMode::from_u8(0x06), Some(InterfaceMode::Gateway));
|
||||
assert_eq!(InterfaceMode::from_u8(0x07), Some(InterfaceMode::Internal));
|
||||
assert_eq!(InterfaceMode::from_u8(0x00), None);
|
||||
assert_eq!(InterfaceMode::from_u8(0x08), None);
|
||||
assert_eq!(InterfaceMode::from_u8(0xFF), None);
|
||||
}
|
||||
|
||||
@@ -205,6 +245,7 @@ mod tests {
|
||||
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::AccessPoint));
|
||||
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Gateway));
|
||||
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Roaming));
|
||||
assert!(DISCOVER_PATHS_FOR.contains(&InterfaceMode::Internal));
|
||||
assert!(!DISCOVER_PATHS_FOR.contains(&InterfaceMode::Full));
|
||||
}
|
||||
|
||||
@@ -237,4 +278,90 @@ mod tests {
|
||||
assert_eq!(EC_PR_FREQ, 5.0);
|
||||
const { assert!(!EGRESS_CONTROL) };
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_accepted_interface_is_stopped_and_disposed() {
|
||||
let (handle_tx, handle_rx) = mpsc::channel(1);
|
||||
drop(handle_rx);
|
||||
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let (interface_tx, mut interface_rx) = mpsc::channel(1);
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let (exited_tx, exited_rx) = tokio::sync::oneshot::channel();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let _exit_guard = TaskExitGuard {
|
||||
exited: Some(exited_tx),
|
||||
};
|
||||
let _ = started_tx.send(());
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
started_rx.await.expect("read task should start");
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: 1,
|
||||
parent_id: Some(0),
|
||||
name: "rejected-child".to_string(),
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection::default(),
|
||||
bitrate: 1,
|
||||
mtu: 1,
|
||||
online: Arc::clone(&online),
|
||||
rxb: None,
|
||||
txb: None,
|
||||
inspection: None,
|
||||
tx: interface_tx,
|
||||
read_task,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
handoff_accepted_interface(&handle_tx, handle).await,
|
||||
Err(())
|
||||
);
|
||||
assert!(!online.load(Ordering::SeqCst));
|
||||
exited_rx
|
||||
.await
|
||||
.expect("helper should await exact read-task termination");
|
||||
assert_eq!(
|
||||
interface_rx.recv().await,
|
||||
None,
|
||||
"rejected handle resources should be dropped"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accepted_interface_handoff_preserves_live_handle() {
|
||||
let (handle_tx, mut handle_rx) = mpsc::channel(1);
|
||||
let online = Arc::new(AtomicBool::new(true));
|
||||
let (interface_tx, _interface_rx) = mpsc::channel(1);
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let read_task = tokio::spawn(async move {
|
||||
let _ = started_tx.send(());
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
started_rx.await.expect("read task should start");
|
||||
|
||||
let handle = InterfaceHandle {
|
||||
id: 2,
|
||||
parent_id: Some(0),
|
||||
name: "accepted-child".to_string(),
|
||||
mode: InterfaceMode::Full,
|
||||
direction: InterfaceDirection::default(),
|
||||
bitrate: 1,
|
||||
mtu: 1,
|
||||
online: Arc::clone(&online),
|
||||
rxb: None,
|
||||
txb: None,
|
||||
inspection: None,
|
||||
tx: interface_tx,
|
||||
read_task,
|
||||
};
|
||||
|
||||
assert_eq!(handoff_accepted_interface(&handle_tx, handle).await, Ok(()));
|
||||
let delivered = handle_rx.recv().await.expect("handle should be delivered");
|
||||
assert!(online.load(Ordering::SeqCst));
|
||||
assert!(!delivered.read_task.is_finished());
|
||||
|
||||
delivered.read_task.abort();
|
||||
let _ = delivered.read_task.await;
|
||||
}
|
||||
}
|
||||
@@ -180,6 +180,7 @@ pub async fn spawn_udp_interface(
|
||||
online,
|
||||
rxb: Some(shared_rxb),
|
||||
txb: Some(shared_txb),
|
||||
inspection: None,
|
||||
tx,
|
||||
read_task,
|
||||
})
|
||||
|
||||
@@ -58,6 +58,8 @@ pub const CMD_REMOTE_INPUT: u16 = 0x0A01;
|
||||
pub const EVT_MSG: u16 = 0x0000;
|
||||
pub const EVT_SYSTEM_BOOT: u16 = 0x0001;
|
||||
pub const EVT_CORE_INIT: u16 = 0x0002;
|
||||
// "Board hardware initialization" (1.3.8 WeaveInterface.py:342, newer firmware boot event)
|
||||
pub const EVT_BOARD_INIT: u16 = 0x0003;
|
||||
|
||||
// Driver events (0x1xxx)
|
||||
pub const EVT_DRV_UART_INIT: u16 = 0x1000;
|
||||
@@ -112,6 +114,7 @@ pub const EVT_STAT_UPTIME: u16 = 0xE001;
|
||||
pub const EVT_STAT_TIMEBASE: u16 = 0xE002;
|
||||
pub const EVT_STAT_CPU: u16 = 0xE003;
|
||||
pub const EVT_STAT_TASK_CPU: u16 = 0xE004;
|
||||
// EVT_STAT_MEMORY data = [free u32 BE][total u32 BE] (1.3.8 WeaveInterface.py:760-761)
|
||||
pub const EVT_STAT_MEMORY: u16 = 0xE005;
|
||||
pub const EVT_STAT_STORAGE: u16 = 0xE006;
|
||||
|
||||
@@ -333,7 +336,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_weave_constants() {
|
||||
assert_eq!(HW_MTU, 1024);
|
||||
const { assert!(FIXED_MTU) };
|
||||
assert_eq!(PEERING_TIMEOUT, 20.0);
|
||||
assert_eq!(BITRATE_GUESS, 250_000);
|
||||
assert_eq!(DEFAULT_IFAC_SIZE, 16);
|
||||
@@ -442,6 +444,24 @@ mod tests {
|
||||
assert_eq!(frame.data, b"ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_boot_event_codes() {
|
||||
assert_eq!(EVT_MSG, 0x0000);
|
||||
assert_eq!(EVT_SYSTEM_BOOT, 0x0001);
|
||||
assert_eq!(EVT_CORE_INIT, 0x0002);
|
||||
assert_eq!(EVT_BOARD_INIT, 0x0003);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_log_frame_board_init() {
|
||||
// flags=0, ts=42ms, level=NOTICE, event=EVT_BOARD_INIT, no data
|
||||
let payload = [0x00, 0x00, 0x00, 0x00, 0x2A, 0x04, 0x00, 0x03];
|
||||
let frame = parse_log_frame(&payload).unwrap();
|
||||
assert_eq!(frame.timestamp_ms, 42);
|
||||
assert_eq!(frame.event, EVT_BOARD_INIT);
|
||||
assert!(frame.data.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_log_frame_too_short() {
|
||||
assert!(parse_log_frame(&[0; 7]).is_none());
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-link"
|
||||
description = "Link layer and encrypted channel for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
|
||||
@@ -89,6 +89,10 @@ impl KeepaliveState {
|
||||
|
||||
/// Whether the initiator should emit a keepalive now (jitter applied).
|
||||
pub fn should_send_keepalive(&self) -> bool {
|
||||
self.should_send_keepalive_at(Instant::now())
|
||||
}
|
||||
|
||||
pub(crate) fn should_send_keepalive_at(&self, now: Instant) -> bool {
|
||||
let jittered = if self.jitter_negative {
|
||||
self.keepalive_interval
|
||||
.saturating_sub(self.jitter_offset)
|
||||
@@ -97,37 +101,53 @@ impl KeepaliveState {
|
||||
self.keepalive_interval + self.jitter_offset
|
||||
};
|
||||
|
||||
let inbound_elapsed = self.last_inbound.elapsed();
|
||||
let inbound_elapsed = now.saturating_duration_since(self.last_inbound);
|
||||
let outbound_elapsed = self
|
||||
.last_outbound
|
||||
.or(self.activated_at)
|
||||
.map(|baseline| now.saturating_duration_since(baseline))
|
||||
.unwrap_or(inbound_elapsed);
|
||||
let keepalive_elapsed = self
|
||||
.last_keepalive_sent
|
||||
.map(|t| t.elapsed())
|
||||
.map(|last_keepalive| now.saturating_duration_since(last_keepalive))
|
||||
.unwrap_or(Duration::MAX);
|
||||
|
||||
self.is_initiator && inbound_elapsed >= jittered && keepalive_elapsed >= jittered
|
||||
self.is_initiator
|
||||
&& (inbound_elapsed >= jittered || outbound_elapsed >= jittered)
|
||||
&& keepalive_elapsed >= jittered
|
||||
}
|
||||
|
||||
pub(crate) fn should_respond_to_keepalive_at(&self, now: Instant) -> bool {
|
||||
!self.is_initiator
|
||||
&& self
|
||||
.last_outbound
|
||||
.map(|last_outbound| {
|
||||
now.saturating_duration_since(last_outbound) >= self.keepalive_interval
|
||||
})
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Whether the link should transition to STALE.
|
||||
///
|
||||
/// Uses the most recent of inbound, proof, or activation as the baseline so a
|
||||
/// link that just came up isn't immediately flagged stale on a quiet channel.
|
||||
/// Uses only peer evidence — inbound traffic, proof, or activation — as the
|
||||
/// baseline. Local outbound traffic cannot prove that the peer remains alive.
|
||||
pub fn is_stale(&self) -> bool {
|
||||
self.is_stale_at(Instant::now())
|
||||
}
|
||||
|
||||
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(outbound) = self.last_outbound {
|
||||
if outbound > latest {
|
||||
latest = outbound;
|
||||
}
|
||||
}
|
||||
if let Some(activated) = self.activated_at {
|
||||
if activated > latest {
|
||||
latest = activated;
|
||||
}
|
||||
}
|
||||
latest.elapsed() >= self.stale_time
|
||||
now.saturating_duration_since(latest) >= self.stale_time
|
||||
}
|
||||
|
||||
/// How long to wait in STALE before tearing the link down.
|
||||
@@ -139,6 +159,16 @@ impl KeepaliveState {
|
||||
self.last_keepalive_sent = Some(Instant::now());
|
||||
}
|
||||
|
||||
pub(crate) fn mark_keepalive_sent_at(&mut self, now: Instant) {
|
||||
self.last_keepalive_sent = Some(now);
|
||||
}
|
||||
|
||||
pub(crate) fn record_keepalive_outbound(&mut self) {
|
||||
let now = Instant::now();
|
||||
self.last_outbound = Some(now);
|
||||
self.last_keepalive_sent = Some(now);
|
||||
}
|
||||
|
||||
pub fn since_inbound(&self) -> Duration {
|
||||
self.last_inbound.elapsed()
|
||||
}
|
||||
@@ -220,6 +250,60 @@ mod tests {
|
||||
assert!(!ks2.should_send_keepalive());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_inbound_still_schedules_keepalive_when_outbound_is_quiet() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.jitter_offset = Duration::ZERO;
|
||||
state.jitter_negative = false;
|
||||
state.last_inbound = now;
|
||||
state.last_outbound = None;
|
||||
state.activated_at = Some(now - Duration::from_secs(6));
|
||||
state.last_keepalive_sent = Some(now - Duration::from_secs(6));
|
||||
|
||||
assert!(state.should_send_keepalive_at(now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_keepalive_suppresses_duplicate_at_exact_tick_time() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.jitter_offset = Duration::ZERO;
|
||||
state.jitter_negative = false;
|
||||
state.last_inbound = now - Duration::from_secs(6);
|
||||
state.last_outbound = Some(now - Duration::from_secs(6));
|
||||
state.last_keepalive_sent = Some(now - Duration::from_secs(4));
|
||||
|
||||
assert!(!state.should_send_keepalive_at(now));
|
||||
assert!(state.should_send_keepalive_at(now + Duration::from_secs(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_outbound_traffic_does_not_mask_a_stale_peer() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(true);
|
||||
state.stale_time = Duration::from_secs(5);
|
||||
state.last_inbound = now - Duration::from_secs(6);
|
||||
state.last_outbound = Some(now);
|
||||
state.last_proof = None;
|
||||
state.activated_at = None;
|
||||
|
||||
assert!(state.is_stale_at(now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responder_suppresses_keepalive_reply_after_recent_outbound() {
|
||||
let now = Instant::now();
|
||||
let mut state = KeepaliveState::new(false);
|
||||
state.keepalive_interval = Duration::from_secs(5);
|
||||
state.last_outbound = Some(now);
|
||||
|
||||
assert!(!state.should_respond_to_keepalive_at(now));
|
||||
assert!(state.should_respond_to_keepalive_at(now + Duration::from_secs(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stale_detection() {
|
||||
let mut ks = KeepaliveState::new(true);
|
||||
|
||||
+449
-27
@@ -12,7 +12,7 @@ use crate::handshake::{
|
||||
use crate::keepalive::KeepaliveState;
|
||||
use crate::key_derivation::LinkKeys;
|
||||
use crate::mtu_discovery::SignallingData;
|
||||
use crate::request::{RequestReceipt, RequestState};
|
||||
use crate::request::RequestReceipt;
|
||||
|
||||
/// Link lifecycle states.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -37,6 +37,14 @@ pub enum CloseReason {
|
||||
DestinationClosed,
|
||||
}
|
||||
|
||||
/// Latest physical-layer measurements observed for a Link.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct LinkPhyStats {
|
||||
pub rssi: Option<f64>,
|
||||
pub snr: Option<f64>,
|
||||
pub q: Option<f64>,
|
||||
}
|
||||
|
||||
/// Resource acceptance strategy.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum ResourceStrategy {
|
||||
@@ -107,6 +115,9 @@ pub struct Link {
|
||||
/// Truncated SHA-256 of the request's hashable part.
|
||||
pub link_id: [u8; 16],
|
||||
pub state: LinkState,
|
||||
/// Terminal close reason, retained after keys and transient state are
|
||||
/// purged. Remains `None` until an orderly or timeout close occurs.
|
||||
pub teardown_reason: Option<CloseReason>,
|
||||
pub is_initiator: bool,
|
||||
pub mode: u8,
|
||||
|
||||
@@ -145,6 +156,9 @@ pub struct Link {
|
||||
pub establishment_rate: Option<f64>,
|
||||
/// Expected in-flight data rate (bits/sec), refreshed after each resource transfer.
|
||||
pub expected_rate: Option<f64>,
|
||||
/// Path length in hops: initiator sets it at creation (Link.py:282), the
|
||||
/// destination side from the LRRTT packet at activation (Link.py:525).
|
||||
pub expected_hops: Option<u8>,
|
||||
|
||||
pub destination_hash: [u8; 16],
|
||||
|
||||
@@ -162,6 +176,7 @@ pub struct Link {
|
||||
pub snr: Option<f64>,
|
||||
/// Link quality indicator in `[0.0, 1.0]`.
|
||||
pub q: Option<f64>,
|
||||
track_phy_stats: bool,
|
||||
|
||||
pub has_channel: bool,
|
||||
|
||||
@@ -213,6 +228,7 @@ impl Link {
|
||||
let link = Self {
|
||||
link_id,
|
||||
state: LinkState::Pending,
|
||||
teardown_reason: None,
|
||||
is_initiator: true,
|
||||
mode: DEFAULT_MODE,
|
||||
ephemeral_keys: Some(ephemeral_keys),
|
||||
@@ -228,7 +244,7 @@ impl Link {
|
||||
stale_since: None,
|
||||
keepalive: KeepaliveState::new(true),
|
||||
mtu: rns_wire::constants::MTU as u32,
|
||||
mdu: rns_wire::constants::ENCRYPTED_MDU,
|
||||
mdu: rns_wire::constants::LINK_MDU,
|
||||
resource_strategy: ResourceStrategy::default(),
|
||||
pending_requests: Vec::new(),
|
||||
incoming_resources: Vec::new(),
|
||||
@@ -238,6 +254,7 @@ impl Link {
|
||||
establishment_cost,
|
||||
establishment_rate: None,
|
||||
expected_rate: None,
|
||||
expected_hops: Some(hops),
|
||||
destination_hash,
|
||||
remote_identity_pub: None,
|
||||
identified: false,
|
||||
@@ -248,6 +265,7 @@ impl Link {
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
track_phy_stats: false,
|
||||
has_channel: false,
|
||||
packet_callback: None,
|
||||
resource_callback: None,
|
||||
@@ -472,6 +490,7 @@ impl Link {
|
||||
let link = Self {
|
||||
link_id,
|
||||
state: LinkState::Handshake,
|
||||
teardown_reason: None,
|
||||
is_initiator: false,
|
||||
mode: request.signalling.mode,
|
||||
ephemeral_keys: Some(responder_keys),
|
||||
@@ -486,7 +505,7 @@ impl Link {
|
||||
stale_since: None,
|
||||
keepalive: KeepaliveState::new(false),
|
||||
mtu: request.signalling.mtu.min(rns_wire::constants::MTU as u32),
|
||||
mdu: rns_wire::constants::ENCRYPTED_MDU,
|
||||
mdu: rns_wire::constants::LINK_MDU,
|
||||
resource_strategy: ResourceStrategy::default(),
|
||||
pending_requests: Vec::new(),
|
||||
incoming_resources: Vec::new(),
|
||||
@@ -496,6 +515,8 @@ impl Link {
|
||||
establishment_cost,
|
||||
establishment_rate: None,
|
||||
expected_rate: None,
|
||||
// Populated by the runtime from the LRRTT packet hops (Link.py:525).
|
||||
expected_hops: None,
|
||||
destination_hash,
|
||||
remote_identity_pub: None,
|
||||
identified: false,
|
||||
@@ -506,6 +527,7 @@ impl Link {
|
||||
rssi: None,
|
||||
snr: None,
|
||||
q: None,
|
||||
track_phy_stats: false,
|
||||
has_channel: false,
|
||||
packet_callback: None,
|
||||
resource_callback: None,
|
||||
@@ -665,6 +687,14 @@ impl Link {
|
||||
return Err(LinkCryptoError::DecryptionFailed);
|
||||
}
|
||||
|
||||
// First-identity-wins (Reticulum 1.3.9): once a verified identity is
|
||||
// recorded it is immutable — a later, even validly-signed, identification
|
||||
// is ignored rather than overwriting the peer. Callers detect the repeat
|
||||
// via `self.identified` being already set and skip re-tracking/callbacks.
|
||||
if let Some(existing) = self.remote_identity_pub {
|
||||
return Ok(existing);
|
||||
}
|
||||
|
||||
self.remote_identity_pub = Some(public_key);
|
||||
self.identified = true;
|
||||
|
||||
@@ -686,11 +716,31 @@ impl Link {
|
||||
path: &str,
|
||||
data: Option<&[u8]>,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
let (packed, request_id) = self.prepare_request(path, data, timeout)?;
|
||||
match self.encrypt(&packed) {
|
||||
Ok(encrypted) => Ok((encrypted, request_id)),
|
||||
Err(error) => {
|
||||
self.discard_pending_request(&request_id);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the plaintext MsgPack request body and register its receipt.
|
||||
///
|
||||
/// Packet-sized callers encrypt the returned body directly. Bodies larger
|
||||
/// than the Link MDU are passed to Resource with the returned request ID.
|
||||
pub fn prepare_request(
|
||||
&mut self,
|
||||
path: &str,
|
||||
data: Option<&[u8]>,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
let data_value = data
|
||||
.map(msgpack_value_from_bytes_or_binary)
|
||||
.unwrap_or(rmpv::Value::Nil);
|
||||
self.request_value(path, data_value, timeout)
|
||||
self.prepare_request_value(path, data_value, timeout)
|
||||
}
|
||||
|
||||
/// Build a REQUEST payload with a MsgPack string body.
|
||||
@@ -703,10 +753,18 @@ impl Link {
|
||||
data: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, [u8; 16]), LinkCryptoError> {
|
||||
self.request_value(path, rmpv::Value::String(data.into()), timeout)
|
||||
let (packed, request_id) =
|
||||
self.prepare_request_value(path, rmpv::Value::String(data.into()), timeout)?;
|
||||
match self.encrypt(&packed) {
|
||||
Ok(encrypted) => Ok((encrypted, request_id)),
|
||||
Err(error) => {
|
||||
self.discard_pending_request(&request_id);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_value(
|
||||
fn prepare_request_value(
|
||||
&mut self,
|
||||
path: &str,
|
||||
data_value: rmpv::Value,
|
||||
@@ -731,8 +789,6 @@ impl Link {
|
||||
rmpv::encode::write_value(&mut packed, &array)
|
||||
.map_err(|_| LinkCryptoError::EncryptionFailed)?;
|
||||
|
||||
let encrypted = self.encrypt(&packed)?;
|
||||
|
||||
// request_id is a truncated SHA-256 of the plaintext, so both sides derive
|
||||
// the same ID without exchanging it.
|
||||
let request_id = truncated_hash(&packed);
|
||||
@@ -742,7 +798,53 @@ impl Link {
|
||||
let receipt = RequestReceipt::new(receipt_id, self.link_id, timeout);
|
||||
self.pending_requests.push(receipt);
|
||||
|
||||
Ok((encrypted, request_id))
|
||||
Ok((packed, request_id))
|
||||
}
|
||||
|
||||
/// Suspend a request's response timeout while its body is sent by Resource.
|
||||
pub fn mark_request_resource_sending(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.mark_resource_sending();
|
||||
true
|
||||
}
|
||||
|
||||
/// Start a Resource-backed request's response timeout after send proof.
|
||||
pub fn mark_request_resource_sent(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.mark_resource_sent();
|
||||
true
|
||||
}
|
||||
|
||||
/// Fail and remove a pending request by its truncated request ID.
|
||||
pub fn fail_pending_request(&mut self, request_id: &[u8; 16]) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|receipt| receipt.request_id[..16] == request_id[..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.fail();
|
||||
self.pending_requests
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
true
|
||||
}
|
||||
|
||||
fn discard_pending_request(&mut self, request_id: &[u8; 16]) {
|
||||
self.pending_requests
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
}
|
||||
|
||||
/// Replace the initial request id with the packet-hash id used by
|
||||
@@ -771,9 +873,17 @@ impl Link {
|
||||
encrypted_data: &[u8],
|
||||
) -> Result<ParsedRequestData, LinkCryptoError> {
|
||||
let plaintext = self.decrypt(encrypted_data)?;
|
||||
Self::parse_request(&plaintext)
|
||||
}
|
||||
|
||||
/// Parse an already-decrypted Link request.
|
||||
///
|
||||
/// Packet requests use [`Self::handle_request`]. Request Resources are
|
||||
/// decrypted by the Resource transfer before reaching the Link runtime,
|
||||
/// so they use this parser directly.
|
||||
pub fn parse_request(plaintext: &[u8]) -> Result<ParsedRequestData, LinkCryptoError> {
|
||||
// request_id = SHA-256(packed_request)[:16]
|
||||
let request_id = truncated_hash(&plaintext);
|
||||
let request_id = truncated_hash(plaintext);
|
||||
|
||||
// Unpack msgpack array: [timestamp, path_hash, data]
|
||||
let value = rmpv::decode::read_value(&mut &plaintext[..])
|
||||
@@ -847,6 +957,16 @@ impl Link {
|
||||
pub fn handle_response_plaintext(
|
||||
&mut self,
|
||||
plaintext: &[u8],
|
||||
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
|
||||
let (request_id, response_data) = Self::parse_response_plaintext(plaintext)?;
|
||||
self.deliver_response_data(&request_id, response_data.clone());
|
||||
Ok((request_id, response_data))
|
||||
}
|
||||
|
||||
/// Parse plaintext MsgPack `[request_id, response_data]` without mutating
|
||||
/// pending request state.
|
||||
pub fn parse_response_plaintext(
|
||||
plaintext: &[u8],
|
||||
) -> Result<([u8; 16], Vec<u8>), LinkCryptoError> {
|
||||
let value = rmpv::decode::read_value(&mut &plaintext[..])
|
||||
.map_err(|_| LinkCryptoError::DecryptionFailed)?;
|
||||
@@ -867,18 +987,23 @@ impl Link {
|
||||
|
||||
let response_data = msgpack_value_to_bytes(&array[1])?;
|
||||
|
||||
if let Some(receipt) = self
|
||||
Ok((request_id, response_data))
|
||||
}
|
||||
|
||||
/// Deliver already-decoded response bytes to a pending request.
|
||||
pub fn deliver_response_data(&mut self, request_id: &[u8; 16], response_data: Vec<u8>) -> bool {
|
||||
let Some(receipt) = self
|
||||
.pending_requests
|
||||
.iter_mut()
|
||||
.find(|r| r.request_id[..16] == request_id[..])
|
||||
{
|
||||
receipt.receive_response(response_data.clone());
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
receipt.receive_response(response_data);
|
||||
|
||||
self.pending_requests
|
||||
.retain(|r| r.state == RequestState::Sent);
|
||||
|
||||
Ok((request_id, response_data))
|
||||
.retain(|receipt| receipt.request_id[..16] != request_id[..]);
|
||||
true
|
||||
}
|
||||
|
||||
/// Update RTT from an LRRTT packet (context 0xFE) received after handshake.
|
||||
@@ -965,7 +1090,13 @@ impl Link {
|
||||
where
|
||||
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
|
||||
{
|
||||
if self.state != LinkState::Active && self.state != LinkState::Stale {
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -1038,12 +1169,34 @@ impl Link {
|
||||
self.outgoing_resources.retain(|h| h != resource_hash);
|
||||
}
|
||||
|
||||
/// `bytes` is the link payload after the context byte (ciphertext), the
|
||||
/// same unit as `record_rx` — Packet.py:291 txbytes += len(ciphertext).
|
||||
pub fn record_tx(&mut self, bytes: usize) {
|
||||
self.tx_bytes += bytes as u64;
|
||||
self.tx_count += 1;
|
||||
self.keepalive.record_outbound();
|
||||
}
|
||||
|
||||
/// Count an outbound keepalive beat and retain its send time.
|
||||
///
|
||||
/// Stale detection deliberately ignores local outbound activity, while the
|
||||
/// retained timestamp prevents redundant keepalive traffic.
|
||||
pub fn record_tx_keepalive(&mut self, bytes: usize) {
|
||||
self.tx_bytes += bytes as u64;
|
||||
self.tx_count += 1;
|
||||
self.keepalive.record_keepalive_outbound();
|
||||
}
|
||||
|
||||
/// Whether this responder should answer a keepalive request.
|
||||
///
|
||||
/// Recent outbound traffic already proves the responder can transmit, so
|
||||
/// an immediate extra reply would only duplicate that traffic.
|
||||
pub fn should_respond_to_keepalive(&self) -> bool {
|
||||
self.keepalive
|
||||
.should_respond_to_keepalive_at(Instant::now())
|
||||
}
|
||||
|
||||
/// `bytes` is the link payload after the context byte (Link.py:929).
|
||||
pub fn record_rx(&mut self, bytes: usize) {
|
||||
self.rx_bytes += bytes as u64;
|
||||
self.rx_count += 1;
|
||||
@@ -1054,9 +1207,28 @@ impl Link {
|
||||
(self.tx_bytes, self.rx_bytes, self.tx_count, self.rx_count)
|
||||
}
|
||||
|
||||
/// Merge PHY measurements from the receiving interface; `None` values leave
|
||||
/// the current reading intact.
|
||||
/// Enable or disable per-packet physical-layer measurement tracking.
|
||||
pub fn track_phy_stats(&mut self, track: bool) {
|
||||
self.track_phy_stats = track;
|
||||
}
|
||||
|
||||
pub fn phy_stats_tracking_enabled(&self) -> bool {
|
||||
self.track_phy_stats
|
||||
}
|
||||
|
||||
/// Merge measurements when tracking is enabled.
|
||||
pub fn update_phy_stats(&mut self, rssi: Option<f64>, snr: Option<f64>, q: Option<f64>) {
|
||||
if !self.track_phy_stats {
|
||||
return;
|
||||
}
|
||||
self.update_phy_stats_force(rssi, snr, q);
|
||||
}
|
||||
|
||||
/// Merge measurements regardless of the tracking gate.
|
||||
///
|
||||
/// Responder Links use this to retain the establishment packet's
|
||||
/// measurements, matching Python's forced initial update.
|
||||
pub fn update_phy_stats_force(&mut self, rssi: Option<f64>, snr: Option<f64>, q: Option<f64>) {
|
||||
if rssi.is_some() {
|
||||
self.rssi = rssi;
|
||||
}
|
||||
@@ -1070,7 +1242,32 @@ impl Link {
|
||||
|
||||
/// Current PHY measurements as `(rssi, snr, q)`.
|
||||
pub fn phy_stats(&self) -> (Option<f64>, Option<f64>, Option<f64>) {
|
||||
(self.rssi, self.snr, self.q)
|
||||
let stats = self.phy_stats_snapshot();
|
||||
(stats.rssi, stats.snr, stats.q)
|
||||
}
|
||||
|
||||
pub fn phy_stats_snapshot(&self) -> LinkPhyStats {
|
||||
if self.track_phy_stats {
|
||||
LinkPhyStats {
|
||||
rssi: self.rssi,
|
||||
snr: self.snr,
|
||||
q: self.q,
|
||||
}
|
||||
} else {
|
||||
LinkPhyStats::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_rssi(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.rssi).flatten()
|
||||
}
|
||||
|
||||
pub fn get_snr(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.snr).flatten()
|
||||
}
|
||||
|
||||
pub fn get_q(&self) -> Option<f64> {
|
||||
self.track_phy_stats.then_some(self.q).flatten()
|
||||
}
|
||||
|
||||
/// Clone of the session keys, for handing to a Channel or Resource.
|
||||
@@ -1093,9 +1290,15 @@ impl Link {
|
||||
),
|
||||
)]
|
||||
pub fn tick(&mut self) -> LinkAction {
|
||||
let now = Instant::now();
|
||||
for receipt in &mut self.pending_requests {
|
||||
receipt.check_timeout();
|
||||
}
|
||||
self.pending_requests.retain(|receipt| !receipt.concluded());
|
||||
|
||||
match self.state {
|
||||
LinkState::Pending | LinkState::Handshake => {
|
||||
if self.request_time.elapsed() > self.establishment_timeout {
|
||||
if now.saturating_duration_since(self.request_time) > self.establishment_timeout {
|
||||
self.close(CloseReason::Timeout);
|
||||
return LinkAction::Closed(CloseReason::Timeout);
|
||||
}
|
||||
@@ -1104,13 +1307,13 @@ impl Link {
|
||||
LinkState::Active => {
|
||||
// Emit any pending keepalive before checking staleness so a final
|
||||
// beat goes out on the same tick the link transitions to STALE.
|
||||
if self.keepalive.should_send_keepalive() {
|
||||
self.keepalive.mark_keepalive_sent();
|
||||
if self.keepalive.should_send_keepalive_at(now) {
|
||||
self.keepalive.mark_keepalive_sent_at(now);
|
||||
return LinkAction::SendKeepalive;
|
||||
}
|
||||
if self.keepalive.is_stale() {
|
||||
if self.keepalive.is_stale_at(now) {
|
||||
self.state = LinkState::Stale;
|
||||
self.stale_since = Some(Instant::now());
|
||||
self.stale_since = Some(now);
|
||||
tracing::debug!(link_id = ?self.link_id, "link state -> Stale");
|
||||
return LinkAction::TransitionedToStale;
|
||||
}
|
||||
@@ -1122,7 +1325,7 @@ impl Link {
|
||||
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 stale_since.elapsed() >= grace {
|
||||
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);
|
||||
@@ -1174,6 +1377,11 @@ impl Link {
|
||||
|
||||
fn close(&mut self, reason: CloseReason) {
|
||||
tracing::debug!(link_id = ?self.link_id, ?reason, "link state -> Closed");
|
||||
self.teardown_reason = Some(reason);
|
||||
for receipt in &mut self.pending_requests {
|
||||
receipt.fail();
|
||||
}
|
||||
self.pending_requests.clear();
|
||||
self.state = LinkState::Closed;
|
||||
self.purge_keys();
|
||||
}
|
||||
@@ -1313,6 +1521,31 @@ impl Link {
|
||||
self.establishment_rate.map(|rate| rate * 8.0)
|
||||
}
|
||||
|
||||
/// Negotiated MTU for an active Link.
|
||||
pub fn get_mtu(&self) -> Option<u32> {
|
||||
(self.state == LinkState::Active).then_some(self.mtu)
|
||||
}
|
||||
|
||||
/// Negotiated encrypted-payload MDU for an active Link.
|
||||
pub fn get_mdu(&self) -> Option<usize> {
|
||||
(self.state == LinkState::Active).then_some(self.mdu)
|
||||
}
|
||||
|
||||
/// Negotiated Link mode.
|
||||
pub const fn get_mode(&self) -> u8 {
|
||||
self.mode
|
||||
}
|
||||
|
||||
/// Duration since activation, or `None` before the Link is established.
|
||||
pub fn age(&self) -> Option<Duration> {
|
||||
self.activated_at.map(|activated| activated.elapsed())
|
||||
}
|
||||
|
||||
/// Python-compatible Link age in seconds.
|
||||
pub fn get_age(&self) -> Option<f64> {
|
||||
self.age().map(|age| age.as_secs_f64())
|
||||
}
|
||||
|
||||
/// Expected in-flight rate in bits/sec for an active link; `None` until the
|
||||
/// first resource transfer completes.
|
||||
pub fn get_expected_rate(&self) -> Option<f64> {
|
||||
@@ -1471,6 +1704,25 @@ mod tests {
|
||||
assert_eq!(pt2, msg2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responder_can_prove_packet_before_lrrtt_activation() {
|
||||
let dest_hash = [0xAB; 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();
|
||||
let _rtt_data = initiator
|
||||
.validate_proof(&proof_data, &identity_pub, &identity_pub.to_bytes())
|
||||
.unwrap();
|
||||
|
||||
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();
|
||||
assert!(initiator.validate_packet_proof(&packet_hash, &packet_proof));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_teardown() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
@@ -1488,11 +1740,19 @@ mod tests {
|
||||
|
||||
let teardown_data = initiator.teardown(CloseReason::InitiatorClosed);
|
||||
assert_eq!(initiator.state, LinkState::Closed);
|
||||
assert_eq!(
|
||||
initiator.teardown_reason,
|
||||
Some(CloseReason::InitiatorClosed)
|
||||
);
|
||||
assert!(teardown_data.is_some());
|
||||
|
||||
let accepted = responder.receive_teardown(&teardown_data.unwrap());
|
||||
assert!(accepted);
|
||||
assert_eq!(responder.state, LinkState::Closed);
|
||||
assert_eq!(
|
||||
responder.teardown_reason,
|
||||
Some(CloseReason::DestinationClosed)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1792,6 +2052,29 @@ mod tests {
|
||||
assert!((initiator_rate_bps - initiator_rate_bytes * 8.0).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_link_metric_accessors_gate_negotiated_sizes_and_report_age() {
|
||||
let (mut link, _) = Link::new_initiator([0xA4; 16], 1);
|
||||
assert_eq!(link.get_mtu(), None);
|
||||
assert_eq!(link.get_mdu(), None);
|
||||
assert_eq!(link.get_age(), None);
|
||||
assert_eq!(link.get_mode(), link.mode);
|
||||
|
||||
link.state = LinkState::Active;
|
||||
link.activated_at = Instant::now().checked_sub(Duration::from_millis(10));
|
||||
assert_eq!(link.get_mtu(), Some(link.mtu));
|
||||
assert_eq!(link.get_mdu(), Some(link.mdu));
|
||||
assert!(
|
||||
link.age()
|
||||
.is_some_and(|age| age >= Duration::from_millis(10))
|
||||
);
|
||||
assert!(link.get_age().is_some_and(|age| age >= 0.01));
|
||||
|
||||
link.state = LinkState::Stale;
|
||||
assert_eq!(link.get_mtu(), None);
|
||||
assert_eq!(link.get_mdu(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expected_rate_computed_on_resource_concluded() {
|
||||
let dest_hash = [0xAA; 16];
|
||||
@@ -2006,6 +2289,37 @@ mod tests {
|
||||
assert_eq!(responder.remote_identity().unwrap(), &identity_pub);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_identify_first_wins_ignores_later_identity() {
|
||||
// First-identity-wins (Reticulum 1.3.9): once a verified identity is
|
||||
// recorded, a second validly-signed LinkIdentify for a DIFFERENT identity
|
||||
// must not overwrite the first.
|
||||
let (initiator, mut responder, _dest_identity) = make_active_link();
|
||||
|
||||
let first_identity = Ed25519PrivateKey::generate();
|
||||
let mut first_pub = [0u8; 64];
|
||||
first_pub[..32].copy_from_slice(&[0x11; 32]);
|
||||
first_pub[32..].copy_from_slice(&first_identity.public_key().to_bytes());
|
||||
let first_data = initiator.identify(&first_pub, &first_identity).unwrap();
|
||||
|
||||
let recorded = responder.handle_identification(&first_data).unwrap();
|
||||
assert_eq!(recorded, first_pub);
|
||||
assert_eq!(responder.remote_identity().unwrap(), &first_pub);
|
||||
|
||||
// A second, independently valid identification for a different identity.
|
||||
let second_identity = Ed25519PrivateKey::generate();
|
||||
let mut second_pub = [0u8; 64];
|
||||
second_pub[..32].copy_from_slice(&[0x22; 32]);
|
||||
second_pub[32..].copy_from_slice(&second_identity.public_key().to_bytes());
|
||||
let second_data = initiator.identify(&second_pub, &second_identity).unwrap();
|
||||
assert_ne!(first_pub, second_pub);
|
||||
|
||||
// The recorded identity stays the first one; the repeat is ignored.
|
||||
let returned = responder.handle_identification(&second_data).unwrap();
|
||||
assert_eq!(returned, first_pub);
|
||||
assert_eq!(responder.remote_identity().unwrap(), &first_pub);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_identify_non_initiator_fails() {
|
||||
let (_initiator, responder, _identity) = make_active_link();
|
||||
@@ -2060,6 +2374,72 @@ mod tests {
|
||||
assert!(initiator.pending_requests.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_plaintext_request_resource_payload() {
|
||||
let (mut initiator, responder, _) = make_active_link();
|
||||
|
||||
let (encrypted, request_id) = initiator
|
||||
.request(
|
||||
"resource.path",
|
||||
Some(b"resource request data"),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.unwrap();
|
||||
let plaintext = responder.decrypt(&encrypted).unwrap();
|
||||
|
||||
let (parsed_id, path_hash, _timestamp, data) = Link::parse_request(&plaintext).unwrap();
|
||||
assert_eq!(parsed_id, request_id);
|
||||
assert_eq!(path_hash, truncated_hash(b"resource.path"));
|
||||
assert_eq!(data, b"resource request data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tick_expires_pending_request_and_fires_callback() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let (mut initiator, _responder, _) = make_active_link();
|
||||
initiator
|
||||
.request("test.timeout", None, Duration::ZERO)
|
||||
.unwrap();
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
initiator.pending_requests[0].set_failed_callback(move |_| {
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
initiator.tick();
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(
|
||||
initiator.pending_requests.is_empty(),
|
||||
"owning runtime tick must reap concluded request receipts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_close_fails_pending_request() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let (mut initiator, _responder, _) = make_active_link();
|
||||
initiator
|
||||
.request("test.close", None, Duration::from_secs(30))
|
||||
.unwrap();
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
initiator.pending_requests[0].set_failed_callback(move |_| {
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
initiator.mark_closed(CloseReason::DestinationClosed);
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(initiator.pending_requests.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_response_preserves_msgpack_object_bodies() {
|
||||
use rmpv::Value;
|
||||
@@ -2198,12 +2578,45 @@ mod tests {
|
||||
assert_eq!(rx_c, 1);
|
||||
}
|
||||
|
||||
/// Keepalive beats count into traffic stats and refresh the outbound
|
||||
/// keepalive clock. Peer-liveness detection remains inbound-only.
|
||||
#[test]
|
||||
fn test_record_tx_keepalive_counts_and_refreshes_outbound() {
|
||||
let (mut link, _, _) = make_active_link();
|
||||
assert!(link.keepalive.last_outbound.is_none());
|
||||
|
||||
link.record_tx_keepalive(1);
|
||||
|
||||
let (tx_b, _, tx_c, _) = link.traffic_stats();
|
||||
assert_eq!(tx_b, 1);
|
||||
assert_eq!(tx_c, 1);
|
||||
assert!(link.keepalive.last_outbound.is_some());
|
||||
assert!(link.keepalive.last_keepalive_sent.is_some());
|
||||
}
|
||||
|
||||
/// Initiator knows expected_hops at creation (Link.py:282); the responder
|
||||
/// side stays unset until the runtime observes the LRRTT hops (Link.py:525).
|
||||
#[test]
|
||||
fn test_expected_hops_initiator_only_at_creation() {
|
||||
let dest_hash = [0xAB; 16];
|
||||
let identity_key = Ed25519PrivateKey::generate();
|
||||
let (initiator, request_data) = Link::new_initiator(dest_hash, 3);
|
||||
let (responder, _proof) =
|
||||
Link::new_responder(&request_data, &identity_key, dest_hash, 3).unwrap();
|
||||
|
||||
assert_eq!(initiator.expected_hops, Some(3));
|
||||
assert_eq!(responder.expected_hops, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_phy_stats() {
|
||||
let (mut link, _, _) = make_active_link();
|
||||
|
||||
assert_eq!(link.phy_stats(), (None, None, None));
|
||||
link.update_phy_stats(Some(-90.0), Some(5.0), Some(0.5));
|
||||
assert_eq!(link.rssi, None);
|
||||
|
||||
link.track_phy_stats(true);
|
||||
link.update_phy_stats(Some(-80.0), Some(12.5), Some(0.95));
|
||||
assert_eq!(link.rssi, Some(-80.0));
|
||||
assert_eq!(link.snr, Some(12.5));
|
||||
@@ -2213,6 +2626,15 @@ mod tests {
|
||||
link.update_phy_stats(Some(-75.0), None, None);
|
||||
assert_eq!(link.rssi, Some(-75.0));
|
||||
assert_eq!(link.snr, Some(12.5));
|
||||
assert_eq!(link.get_rssi(), Some(-75.0));
|
||||
|
||||
link.track_phy_stats(false);
|
||||
assert_eq!(link.phy_stats(), (None, None, None));
|
||||
assert_eq!(link.get_rssi(), None);
|
||||
|
||||
link.update_phy_stats_force(Some(-60.0), None, None);
|
||||
link.track_phy_stats(true);
|
||||
assert_eq!(link.get_rssi(), Some(-60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+103
-10
@@ -4,6 +4,11 @@ use std::time::{Duration, Instant};
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RequestState {
|
||||
Sent,
|
||||
/// The request body itself is still being delivered as a Resource.
|
||||
///
|
||||
/// Resource transfer watchdogs own the send timeout in this state. The
|
||||
/// response timeout starts only after the Resource proof arrives.
|
||||
SendingResource,
|
||||
/// Response is arriving as a resource transfer rather than a single packet.
|
||||
Receiving,
|
||||
Delivered,
|
||||
@@ -59,7 +64,10 @@ impl RequestReceipt {
|
||||
|
||||
/// Record a response payload, transition to `Delivered`, and fire the response callback.
|
||||
pub fn deliver(&mut self, response: Vec<u8>) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.rtt = Some(self.sent_at.elapsed());
|
||||
self.response = Some(response);
|
||||
self.state = RequestState::Delivered;
|
||||
@@ -72,7 +80,10 @@ impl RequestReceipt {
|
||||
|
||||
/// Transition to `Failed` and fire the failure callback.
|
||||
pub fn fail(&mut self) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Receiving {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.state = RequestState::Failed;
|
||||
if let Some(cb) = self.callbacks.failed.take() {
|
||||
cb(self);
|
||||
@@ -81,11 +92,15 @@ impl RequestReceipt {
|
||||
}
|
||||
|
||||
pub fn is_timed_out(&self) -> bool {
|
||||
self.state == RequestState::Sent && self.sent_at.elapsed() > self.timeout
|
||||
matches!(self.state, RequestState::Sent | RequestState::Receiving)
|
||||
&& self.sent_at.elapsed() >= self.timeout
|
||||
}
|
||||
|
||||
pub fn is_pending(&self) -> bool {
|
||||
self.state == RequestState::Sent
|
||||
matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
)
|
||||
}
|
||||
|
||||
/// Store the response payload and advance to `ResponseReceived`.
|
||||
@@ -93,10 +108,20 @@ impl RequestReceipt {
|
||||
/// Distinct from `deliver()`: `receive_response` can fire after `mark_delivered()`
|
||||
/// for protocols that ack then stream the payload.
|
||||
pub fn receive_response(&mut self, data: Vec<u8>) {
|
||||
if self.state == RequestState::Sent || self.state == RequestState::Delivered {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent
|
||||
| RequestState::SendingResource
|
||||
| RequestState::Receiving
|
||||
| RequestState::Delivered
|
||||
) {
|
||||
self.rtt = Some(self.sent_at.elapsed());
|
||||
self.response = Some(data);
|
||||
self.state = RequestState::ResponseReceived;
|
||||
self.progress = 1.0;
|
||||
if let Some(cb) = self.callbacks.response.take() {
|
||||
cb(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,11 +134,30 @@ impl RequestReceipt {
|
||||
|
||||
/// Transition to `Failed` without firing the failure callback.
|
||||
pub fn mark_failed(&mut self) {
|
||||
if self.state == RequestState::Sent {
|
||||
if matches!(
|
||||
self.state,
|
||||
RequestState::Sent | RequestState::SendingResource | RequestState::Receiving
|
||||
) {
|
||||
self.state = RequestState::Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// Suspend the response deadline while the request body is sent as a
|
||||
/// Resource. The Resource transfer has its own watchdog.
|
||||
pub fn mark_resource_sending(&mut self) {
|
||||
if self.state == RequestState::Sent {
|
||||
self.state = RequestState::SendingResource;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the response deadline after a request Resource is proved.
|
||||
pub fn mark_resource_sent(&mut self) {
|
||||
if self.state == RequestState::SendingResource {
|
||||
self.state = RequestState::Sent;
|
||||
self.sent_at = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
/// True once the request has reached a terminal state (delivered, failed, or response received).
|
||||
pub fn concluded(&self) -> bool {
|
||||
matches!(
|
||||
@@ -152,10 +196,7 @@ impl RequestReceipt {
|
||||
/// Expire the request if past its deadline, firing the failure callback. Returns `true` if expired.
|
||||
pub fn check_timeout(&mut self) -> bool {
|
||||
if self.is_timed_out() {
|
||||
self.state = RequestState::Failed;
|
||||
if let Some(cb) = self.callbacks.failed.take() {
|
||||
cb(self);
|
||||
}
|
||||
self.fail();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
@@ -236,6 +277,19 @@ mod tests {
|
||||
assert!(!receipt.is_pending());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_send_suspends_and_restarts_response_timeout() {
|
||||
let mut receipt = RequestReceipt::new([0x12; 32], [0x34; 16], Duration::ZERO);
|
||||
|
||||
receipt.mark_resource_sending();
|
||||
assert_eq!(receipt.state, RequestState::SendingResource);
|
||||
assert!(!receipt.is_timed_out());
|
||||
|
||||
receipt.mark_resource_sent();
|
||||
assert_eq!(receipt.state, RequestState::Sent);
|
||||
assert!(receipt.is_timed_out());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cannot_receive_response_after_fail() {
|
||||
let mut receipt = RequestReceipt::new([0x33; 32], [0x44; 16], Duration::from_secs(10));
|
||||
@@ -245,4 +299,43 @@ mod tests {
|
||||
assert_eq!(receipt.state, RequestState::Failed);
|
||||
assert!(receipt.response.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_receive_response_fires_callback_from_receiving_state() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
let mut receipt = RequestReceipt::new([0x55; 32], [0x66; 16], Duration::from_secs(10));
|
||||
receipt.state = RequestState::Receiving;
|
||||
receipt.set_response_callback(move |receipt| {
|
||||
assert_eq!(receipt.state, RequestState::ResponseReceived);
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
receipt.receive_response(b"resource response".to_vec());
|
||||
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert_eq!(receipt.get_progress(), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_receiving_request_times_out_and_fires_failure_callback() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
let fired = Arc::new(AtomicBool::new(false));
|
||||
let callback_fired = fired.clone();
|
||||
let mut receipt = RequestReceipt::new([0x77; 32], [0x88; 16], Duration::ZERO);
|
||||
receipt.state = RequestState::Receiving;
|
||||
receipt.set_failed_callback(move |receipt| {
|
||||
assert_eq!(receipt.state, RequestState::Failed);
|
||||
callback_fired.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
assert!(receipt.check_timeout());
|
||||
assert!(fired.load(Ordering::SeqCst));
|
||||
assert!(!receipt.is_pending());
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ name = "rns-protocol"
|
||||
description = "Resource, Channel, and Buffer protocols for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -208,6 +208,10 @@ impl ChannelWindow {
|
||||
/// (subsequent handlers are skipped) or `false` to fall through.
|
||||
pub type MessageCallback = Box<dyn Fn(u16, &[u8]) -> bool + Send>;
|
||||
|
||||
/// Opaque token for removing one registered message handler.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct HandlerId(u64);
|
||||
|
||||
/// Sequenced, reliable message pipe over a Reticulum link.
|
||||
///
|
||||
/// The channel is passive: the owning runtime calls `send`/`receive`/
|
||||
@@ -221,12 +225,13 @@ pub struct Channel {
|
||||
rx_ring: VecDeque<Envelope>,
|
||||
pub window: ChannelWindow,
|
||||
pub active: bool,
|
||||
initial_rtt: f64,
|
||||
current_rtt: f64,
|
||||
/// When non-empty, only these types are accepted on `receive`.
|
||||
registered_types: Vec<u16>,
|
||||
/// Called in registration order on each delivered message; the first
|
||||
/// handler that returns `true` stops the chain.
|
||||
message_handlers: Vec<MessageCallback>,
|
||||
message_handlers: Vec<(HandlerId, MessageCallback)>,
|
||||
next_handler_id: u64,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
@@ -238,9 +243,10 @@ impl Channel {
|
||||
rx_ring: VecDeque::new(),
|
||||
window: ChannelWindow::new(rtt),
|
||||
active: true,
|
||||
initial_rtt: rtt,
|
||||
current_rtt: rtt,
|
||||
registered_types: Vec::new(),
|
||||
message_handlers: Vec::new(),
|
||||
next_handler_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,9 +271,26 @@ impl Channel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Append `handler` to the end of the callback chain.
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) {
|
||||
self.message_handlers.push(handler);
|
||||
/// Append `handler` to the end of the callback chain and return its token.
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
|
||||
let id = HandlerId(self.next_handler_id);
|
||||
self.next_handler_id = self.next_handler_id.wrapping_add(1);
|
||||
self.message_handlers.push((id, handler));
|
||||
id
|
||||
}
|
||||
|
||||
/// Remove exactly one previously registered handler.
|
||||
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
|
||||
let Some(index) = self
|
||||
.message_handlers
|
||||
.iter()
|
||||
.position(|(candidate, _)| *candidate == id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let (_id, handler) = self.message_handlers.remove(index);
|
||||
drop(handler);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn clear_message_handlers(&mut self) {
|
||||
@@ -275,19 +298,24 @@ impl Channel {
|
||||
}
|
||||
|
||||
fn run_callbacks(&self, msg_type: u16, payload: &[u8]) -> bool {
|
||||
for handler in &self.message_handlers {
|
||||
if handler(msg_type, payload) {
|
||||
for (_, handler) in &self.message_handlers {
|
||||
// Application callbacks must not prevent the channel from
|
||||
// advancing its receive sequence or starve handlers registered
|
||||
// after them. The process panic hook still reports the failure;
|
||||
// this boundary only isolates unwinding builds.
|
||||
let consumed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
handler(msg_type, payload)
|
||||
}))
|
||||
.unwrap_or(false);
|
||||
if consumed {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Empty registration list means "accept anything", matching the
|
||||
/// permissive behaviour of the Python reference before type filters were
|
||||
/// added.
|
||||
fn is_type_registered(&self, msg_type: u16) -> bool {
|
||||
self.registered_types.is_empty() || self.registered_types.contains(&msg_type)
|
||||
self.registered_types.contains(&msg_type)
|
||||
}
|
||||
|
||||
/// True when the channel has window headroom to accept a new outbound message.
|
||||
@@ -303,6 +331,11 @@ impl Channel {
|
||||
outstanding < self.window.window
|
||||
}
|
||||
|
||||
/// True when every outbound envelope has been acknowledged and removed.
|
||||
pub fn is_drained(&self) -> bool {
|
||||
self.tx_ring.is_empty()
|
||||
}
|
||||
|
||||
/// Pack `msg`, push it onto the TX ring, and return the raw envelope for
|
||||
/// the transport to send. Fails when the channel is closed or its window
|
||||
/// is already saturated.
|
||||
@@ -312,6 +345,14 @@ impl Channel {
|
||||
|
||||
/// As [`Self::send`], but also returns the assigned sequence number.
|
||||
pub fn send_tracked(&mut self, msg: &dyn MessageBase) -> Result<(u16, Vec<u8>), ChannelError> {
|
||||
self.send_tracked_with_max_envelope(msg, None)
|
||||
}
|
||||
|
||||
fn send_tracked_with_max_envelope(
|
||||
&mut self,
|
||||
msg: &dyn MessageBase,
|
||||
max_envelope_size: Option<usize>,
|
||||
) -> Result<(u16, Vec<u8>), ChannelError> {
|
||||
if !self.active {
|
||||
return Err(ChannelError::ChannelClosed);
|
||||
}
|
||||
@@ -320,9 +361,16 @@ impl Channel {
|
||||
}
|
||||
|
||||
let seq = self.next_tx_sequence;
|
||||
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.next_tx_sequence = ((self.next_tx_sequence as u32 + 1) % SEQ_MODULUS) as u16;
|
||||
envelope.state = MessageState::Sent;
|
||||
envelope.tries = 1;
|
||||
envelope.last_sent = Some(Instant::now());
|
||||
@@ -397,6 +445,9 @@ impl Channel {
|
||||
/// legitimate. Out-of-range or duplicate sequence numbers are silently
|
||||
/// dropped; registered callbacks fire in order on each delivered message.
|
||||
pub fn receive(&mut self, raw: &[u8]) -> Result<Vec<(u16, Vec<u8>)>, ChannelError> {
|
||||
if !self.active {
|
||||
return Err(ChannelError::ChannelClosed);
|
||||
}
|
||||
let envelope = Envelope::unpack(raw).map_err(|_| ChannelError::InvalidEnvelope)?;
|
||||
|
||||
if !self.is_type_registered(envelope.msg_type) {
|
||||
@@ -477,10 +528,10 @@ impl Channel {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Retransmit timeout: `1.5^(tries - 1) * max(rtt * 2.5, MIN_TIMEOUT_BASE)
|
||||
/// * (outstanding + 1.5)` seconds, using the RTT captured at construction.
|
||||
/// Retransmit timeout uses the Python-compatible exponential backoff,
|
||||
/// based on the latest Link RTT supplied by the owning runtime.
|
||||
pub fn compute_timeout(&self, tries: usize) -> f64 {
|
||||
let rtt = self.initial_rtt;
|
||||
let rtt = self.current_rtt;
|
||||
let backoff = 1.5_f64.powi(tries.saturating_sub(1) as i32);
|
||||
let base = (rtt * 2.5).max(MIN_TIMEOUT_BASE);
|
||||
let outstanding = self.outstanding_count() as f64 + 1.5;
|
||||
@@ -491,6 +542,13 @@ impl Channel {
|
||||
Duration::from_secs_f64(self.compute_timeout(tries).max(MIN_TIMEOUT_BASE))
|
||||
}
|
||||
|
||||
/// Update the live Link RTT used by subsequent retransmit deadlines.
|
||||
pub fn update_rtt(&mut self, rtt: f64) {
|
||||
if rtt.is_finite() && rtt >= 0.0 {
|
||||
self.current_rtt = rtt;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the channel inactive and drop every buffered envelope and
|
||||
/// handler. Idempotent.
|
||||
pub fn shutdown(&mut self) {
|
||||
@@ -522,6 +580,8 @@ pub enum ChannelError {
|
||||
UnknownMessageType(u16),
|
||||
#[error("invalid message type: 0x{0:04X} (reserved for system use)")]
|
||||
InvalidMessageType(u16),
|
||||
#[error("packed channel message is {actual} bytes; Link MDU is {max}")]
|
||||
MessageTooLarge { actual: usize, max: usize },
|
||||
}
|
||||
|
||||
/// A [`Channel`] paired with its link ID and (optionally) link session keys,
|
||||
@@ -530,6 +590,7 @@ pub enum ChannelError {
|
||||
pub struct LinkChannel {
|
||||
channel: Channel,
|
||||
link_id: [u8; 16],
|
||||
link_mdu: usize,
|
||||
session_keys: Option<rns_link::key_derivation::LinkKeys>,
|
||||
outbound_packet_hashes: HashMap<[u8; 32], u16>,
|
||||
}
|
||||
@@ -543,9 +604,15 @@ pub struct PreparedChannelData {
|
||||
impl LinkChannel {
|
||||
/// Plain-text channel (no transport-side encryption).
|
||||
pub fn new(link_id: [u8; 16], rtt: f64) -> Self {
|
||||
Self::new_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU)
|
||||
}
|
||||
|
||||
/// Plain-text channel with an explicit Link MDU.
|
||||
pub fn new_with_mdu(link_id: [u8; 16], rtt: f64, link_mdu: usize) -> Self {
|
||||
Self {
|
||||
channel: Channel::new(rtt),
|
||||
link_id,
|
||||
link_mdu,
|
||||
session_keys: None,
|
||||
outbound_packet_hashes: HashMap::new(),
|
||||
}
|
||||
@@ -557,10 +624,21 @@ impl LinkChannel {
|
||||
link_id: [u8; 16],
|
||||
rtt: f64,
|
||||
keys: rns_link::key_derivation::LinkKeys,
|
||||
) -> Self {
|
||||
Self::new_encrypted_with_mdu(link_id, rtt, rns_wire::constants::LINK_MDU, keys)
|
||||
}
|
||||
|
||||
/// Encrypted channel with an explicit Link MDU.
|
||||
pub fn new_encrypted_with_mdu(
|
||||
link_id: [u8; 16],
|
||||
rtt: f64,
|
||||
link_mdu: usize,
|
||||
keys: rns_link::key_derivation::LinkKeys,
|
||||
) -> Self {
|
||||
Self {
|
||||
channel: Channel::new(rtt),
|
||||
link_id,
|
||||
link_mdu,
|
||||
session_keys: Some(keys),
|
||||
outbound_packet_hashes: HashMap::new(),
|
||||
}
|
||||
@@ -578,7 +656,9 @@ impl LinkChannel {
|
||||
&mut self,
|
||||
msg: &dyn MessageBase,
|
||||
) -> Result<PreparedChannelData, ChannelError> {
|
||||
let (sequence, raw) = self.channel.send_tracked(msg)?;
|
||||
let (sequence, raw) = self
|
||||
.channel
|
||||
.send_tracked_with_max_envelope(msg, Some(self.link_mdu))?;
|
||||
if let Some(ref keys) = self.session_keys {
|
||||
let data = rns_link::encryption::link_encrypt(keys, &raw)
|
||||
.map_err(|_| ChannelError::ChannelClosed)?;
|
||||
@@ -604,6 +684,7 @@ impl LinkChannel {
|
||||
}
|
||||
|
||||
pub fn delivered(&mut self, sequence: u16, rtt: f64) {
|
||||
self.channel.update_rtt(rtt);
|
||||
self.channel.delivered(sequence, rtt);
|
||||
}
|
||||
|
||||
@@ -613,6 +694,8 @@ impl LinkChannel {
|
||||
|
||||
pub fn delivered_by_packet_hash(&mut self, packet_hash: &[u8; 32], rtt: f64) -> Option<u16> {
|
||||
let sequence = self.outbound_packet_hashes.remove(packet_hash)?;
|
||||
self.outbound_packet_hashes
|
||||
.retain(|_, tracked_sequence| *tracked_sequence != sequence);
|
||||
self.delivered(sequence, rtt);
|
||||
Some(sequence)
|
||||
}
|
||||
@@ -621,12 +704,42 @@ impl LinkChannel {
|
||||
self.channel.is_ready_to_send()
|
||||
}
|
||||
|
||||
pub fn is_drained(&self) -> bool {
|
||||
self.channel.is_drained()
|
||||
}
|
||||
|
||||
/// Maximum payload bytes available to one channel message.
|
||||
pub fn mdu(&self) -> usize {
|
||||
Channel::channel_mdu(self.link_mdu)
|
||||
}
|
||||
|
||||
pub fn register_message_type(&mut self, msg_type: u16) -> Result<(), ChannelError> {
|
||||
self.channel.register_message_type(msg_type)
|
||||
}
|
||||
|
||||
pub fn register_system_type(&mut self, msg_type: u16) {
|
||||
self.channel.register_system_type(msg_type);
|
||||
}
|
||||
|
||||
pub fn add_message_handler(&mut self, handler: MessageCallback) -> HandlerId {
|
||||
self.channel.add_message_handler(handler)
|
||||
}
|
||||
|
||||
pub fn remove_message_handler(&mut self, id: HandlerId) -> bool {
|
||||
self.channel.remove_message_handler(id)
|
||||
}
|
||||
|
||||
pub fn clear_message_handlers(&mut self) {
|
||||
self.channel.clear_message_handlers();
|
||||
}
|
||||
|
||||
pub fn link_id(&self) -> &[u8; 16] {
|
||||
&self.link_id
|
||||
}
|
||||
|
||||
pub fn shutdown(&mut self) {
|
||||
self.channel.shutdown();
|
||||
self.outbound_packet_hashes.clear();
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
@@ -657,6 +770,10 @@ impl LinkChannel {
|
||||
pub fn next_timeout_duration(&self) -> Option<Duration> {
|
||||
self.channel.next_timeout_duration()
|
||||
}
|
||||
|
||||
pub fn update_rtt(&mut self, rtt: f64) {
|
||||
self.channel.update_rtt(rtt);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -731,6 +848,7 @@ mod tests {
|
||||
fn test_channel_send_receive() {
|
||||
let mut tx_channel = Channel::new(0.1);
|
||||
let mut rx_channel = Channel::new(0.1);
|
||||
rx_channel.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"hello");
|
||||
let raw = tx_channel.send(&msg).unwrap();
|
||||
@@ -745,6 +863,7 @@ mod tests {
|
||||
fn test_channel_ordering() {
|
||||
let mut tx = Channel::new(0.1);
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg1 = TestMessage::new(b"first");
|
||||
let msg2 = TestMessage::new(b"second");
|
||||
@@ -776,6 +895,7 @@ mod tests {
|
||||
fn test_channel_flow_control() {
|
||||
let mut ch = Channel::new(0.1);
|
||||
assert!(ch.is_ready_to_send());
|
||||
assert!(ch.is_drained());
|
||||
|
||||
let msg = TestMessage::new(b"a");
|
||||
// `WINDOW_INITIAL` = 2 slots, so two sends saturate the window.
|
||||
@@ -783,9 +903,13 @@ mod tests {
|
||||
ch.send(&msg).unwrap();
|
||||
|
||||
assert!(!ch.is_ready_to_send());
|
||||
assert!(!ch.is_drained());
|
||||
|
||||
ch.delivered(0, 0.1);
|
||||
assert!(ch.is_ready_to_send());
|
||||
assert!(!ch.is_drained());
|
||||
ch.delivered(1, 0.1);
|
||||
assert!(ch.is_drained());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -808,6 +932,7 @@ mod tests {
|
||||
fn test_duplicate_rejection() {
|
||||
let mut tx = Channel::new(0.1);
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"once");
|
||||
let raw = tx.send(&msg).unwrap();
|
||||
@@ -907,6 +1032,10 @@ mod tests {
|
||||
ch.shutdown();
|
||||
assert!(!ch.active);
|
||||
assert!(ch.send(&msg).is_err());
|
||||
assert!(matches!(
|
||||
ch.receive(&Envelope::pack(&msg, 0).raw),
|
||||
Err(ChannelError::ChannelClosed)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -973,8 +1102,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_registered_types_allows_all() {
|
||||
// With an empty registry the channel must not filter inbound frames.
|
||||
fn test_no_registered_types_rejects_all() {
|
||||
// Python requires every inbound user or system type to be registered.
|
||||
let mut ch = Channel::new(0.1);
|
||||
|
||||
let mut raw = Vec::new();
|
||||
@@ -984,7 +1113,10 @@ mod tests {
|
||||
raw.extend_from_slice(b"test");
|
||||
|
||||
let result = ch.receive(&raw);
|
||||
assert!(result.is_ok());
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(ChannelError::UnknownMessageType(0x1234))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1031,6 +1163,7 @@ mod tests {
|
||||
let raw = ch.send(&msg).unwrap();
|
||||
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
let counter2 = counter.clone();
|
||||
let c4 = counter2.clone();
|
||||
rx.add_message_handler(Box::new(move |_msg_type, _payload| {
|
||||
@@ -1052,11 +1185,76 @@ mod tests {
|
||||
assert_eq!(counter2.load(Ordering::SeqCst), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panicking_handler_does_not_block_delivery_or_later_handlers() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
let mut tx = Channel::new(0.1);
|
||||
let raw = tx.send(&TestMessage::new(b"isolated")).unwrap();
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
rx.add_message_handler(Box::new(|_, _| panic!("consumer failed")));
|
||||
|
||||
let later_handler_ran = Arc::new(AtomicBool::new(false));
|
||||
let observed = later_handler_ran.clone();
|
||||
rx.add_message_handler(Box::new(move |_, _| {
|
||||
observed.store(true, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
|
||||
let delivered = rx.receive(&raw).unwrap();
|
||||
assert_eq!(delivered, vec![(0x0001, b"isolated".to_vec())]);
|
||||
assert!(later_handler_ran.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_message_handler_removes_only_its_token() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU32, Ordering},
|
||||
};
|
||||
|
||||
let mut tx = Channel::new(0.1);
|
||||
let raw = tx.send(&TestMessage::new(b"handler tokens")).unwrap();
|
||||
let mut rx = Channel::new(0.1);
|
||||
rx.register_message_type(0x0001).unwrap();
|
||||
let counter = Arc::new(AtomicU32::new(0));
|
||||
|
||||
let first_counter = counter.clone();
|
||||
let first = rx.add_message_handler(Box::new(move |_, _| {
|
||||
first_counter.fetch_add(1, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
let second_counter = counter.clone();
|
||||
let _second = rx.add_message_handler(Box::new(move |_, _| {
|
||||
second_counter.fetch_add(10, Ordering::SeqCst);
|
||||
false
|
||||
}));
|
||||
|
||||
assert!(rx.remove_message_handler(first));
|
||||
assert!(!rx.remove_message_handler(first));
|
||||
rx.receive(&raw).unwrap();
|
||||
assert_eq!(counter.load(Ordering::SeqCst), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_live_rtt_updates_retransmit_timeout() {
|
||||
let mut channel = Channel::new(0.1);
|
||||
channel.send(&TestMessage::new(b"rtt")).unwrap();
|
||||
let initial = channel.compute_timeout(1);
|
||||
channel.update_rtt(1.0);
|
||||
assert!(channel.compute_timeout(1) > initial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_channel_send_receive() {
|
||||
let link_id = [0xAA; 16];
|
||||
let mut tx_lc = LinkChannel::new(link_id, 0.1);
|
||||
let mut rx_lc = LinkChannel::new(link_id, 0.1);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
assert_eq!(*tx_lc.link_id(), link_id);
|
||||
assert!(tx_lc.is_active());
|
||||
@@ -1076,6 +1274,7 @@ mod tests {
|
||||
let link_id = [0xBB; 16];
|
||||
let mut tx_lc = LinkChannel::new(link_id, 0.1);
|
||||
let mut rx_lc = LinkChannel::new(link_id, 0.1);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
// Send two messages
|
||||
let msg1 = TestMessage::new(b"first");
|
||||
@@ -1095,6 +1294,7 @@ mod tests {
|
||||
tx_lc.delivered(0, 0.1);
|
||||
tx_lc.delivered(1, 0.1);
|
||||
assert_eq!(tx_lc.outstanding_count(), 0);
|
||||
assert!(tx_lc.is_drained());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1123,6 +1323,44 @@ mod tests {
|
||||
assert!(resend.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_channel_delivery_clears_retransmission_hashes_for_sequence() {
|
||||
let mut channel = LinkChannel::new([0xDF; 16], 0.1);
|
||||
channel
|
||||
.prepare_send_tracked(&TestMessage::new(b"tracked"))
|
||||
.unwrap();
|
||||
let first_hash = [1u8; 32];
|
||||
let retry_hash = [2u8; 32];
|
||||
channel.track_outbound_packet_hash(first_hash, 0);
|
||||
channel.track_outbound_packet_hash(retry_hash, 0);
|
||||
|
||||
assert_eq!(channel.delivered_by_packet_hash(&retry_hash, 0.1), Some(0));
|
||||
assert!(channel.outbound_packet_hashes.is_empty());
|
||||
assert_eq!(channel.delivered_by_packet_hash(&first_hash, 0.1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_channel_enforces_message_mdu_without_consuming_sequence() {
|
||||
let link_id = [0xDE; 16];
|
||||
let mut channel = LinkChannel::new_with_mdu(link_id, 0.1, 32);
|
||||
assert_eq!(channel.mdu(), 32 - ENVELOPE_HEADER_SIZE);
|
||||
|
||||
let oversized = TestMessage::new(&vec![0u8; channel.mdu() + 1]);
|
||||
assert!(matches!(
|
||||
channel.prepare_send_tracked(&oversized),
|
||||
Err(ChannelError::MessageTooLarge {
|
||||
actual: 33,
|
||||
max: 32
|
||||
})
|
||||
));
|
||||
assert_eq!(channel.outstanding_count(), 0);
|
||||
|
||||
let prepared = channel
|
||||
.prepare_send_tracked(&TestMessage::new(b"fits"))
|
||||
.unwrap();
|
||||
assert_eq!(prepared.sequence, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypted_link_channel_roundtrip() {
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
@@ -1140,6 +1378,7 @@ mod tests {
|
||||
|
||||
let mut tx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_a);
|
||||
let mut rx_lc = LinkChannel::new_encrypted(link_id, 0.1, keys_b);
|
||||
rx_lc.register_message_type(0x0001).unwrap();
|
||||
|
||||
let msg = TestMessage::new(b"encrypted hello");
|
||||
let raw = tx_lc.prepare_send(&msg).unwrap();
|
||||
|
||||
@@ -198,7 +198,9 @@ impl WindowState {
|
||||
pub fn grow(&mut self, rate: usize) {
|
||||
if self.window < self.window_max {
|
||||
self.window += 1;
|
||||
if (self.window - self.window_min) > (WINDOW_FLEXIBILITY - 1) {
|
||||
// saturating: a very-slow demotion can clamp `window` below `window_min` (Python's
|
||||
// signed comparison is false there; a plain sub underflows).
|
||||
if self.window.saturating_sub(self.window_min) > (WINDOW_FLEXIBILITY - 1) {
|
||||
self.window_min += 1;
|
||||
}
|
||||
}
|
||||
@@ -236,7 +238,7 @@ impl WindowState {
|
||||
if self.window_max > self.window_min {
|
||||
self.window_max -= 1;
|
||||
}
|
||||
if self.window_max - self.window > WINDOW_FLEXIBILITY - 1 {
|
||||
if self.window_max.saturating_sub(self.window) > WINDOW_FLEXIBILITY - 1 {
|
||||
self.window_max -= 1;
|
||||
}
|
||||
}
|
||||
@@ -562,6 +564,10 @@ impl InboundResource {
|
||||
initial_map_hashes: Vec<[u8; MAPHASH_LEN]>,
|
||||
link_sdu: Option<usize>,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if total_parts == 0 {
|
||||
return Err(ResourceError::InvalidAdvertisement);
|
||||
}
|
||||
|
||||
// `total_size` is post-encryption: max plaintext + random_hash +
|
||||
// TOKEN_OVERHEAD + worst-case PKCS7 pad.
|
||||
const MAX_AES_BLOCK_PAD: usize = 16;
|
||||
@@ -606,8 +612,8 @@ impl InboundResource {
|
||||
tracing::trace!(
|
||||
result = %format!("{:02x}{:02x}{:02x}{:02x}", mh[0], mh[1], mh[2], mh[3]),
|
||||
data_len = data.len(),
|
||||
data_first16 = %data.iter().take(16).map(|b| format!("{:02x}", b)).collect::<String>(),
|
||||
random_hash = %self.random_hash.iter().map(|b| format!("{:02x}", b)).collect::<String>(),
|
||||
data_first16 = %hex::encode(&data[..data.len().min(16)]),
|
||||
random_hash = %hex::encode(self.random_hash),
|
||||
random_len = self.random_hash.len(),
|
||||
"resource part map hash"
|
||||
);
|
||||
@@ -805,6 +811,39 @@ pub struct MultiSegmentOutbound {
|
||||
pub data_size: usize,
|
||||
}
|
||||
|
||||
/// Sender-side plan that materialises at most one split Resource segment at a
|
||||
/// time.
|
||||
///
|
||||
/// The signed/application payload remains owned by the plan, but plaintext,
|
||||
/// encrypted parts and hash maps for future segments are not allocated until
|
||||
/// [`Self::next_segment`] is called. This is the bounded primitive used by
|
||||
/// large LXMF Direct deliveries; the eager [`MultiSegmentOutbound`] facade is
|
||||
/// retained for callers that need random access to every segment.
|
||||
pub struct LazyMultiSegmentOutbound {
|
||||
data: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
metadata: Option<Vec<u8>>,
|
||||
metadata_wire_size: usize,
|
||||
request_id: Option<Vec<u8>>,
|
||||
is_response: bool,
|
||||
next_offset: usize,
|
||||
next_segment_index: usize,
|
||||
pub original_hash: [u8; 32],
|
||||
pub total_segments: usize,
|
||||
pub data_size: usize,
|
||||
}
|
||||
|
||||
fn required_segment_count(data_size: usize, metadata_wire_size: usize) -> usize {
|
||||
if data_size == 0 {
|
||||
return 1;
|
||||
}
|
||||
let first_payload_size = MAX_EFFICIENT_SIZE.saturating_sub(metadata_wire_size);
|
||||
let first_len = data_size.min(first_payload_size);
|
||||
1 + data_size
|
||||
.saturating_sub(first_len)
|
||||
.div_ceil(MAX_EFFICIENT_SIZE)
|
||||
}
|
||||
|
||||
impl MultiSegmentOutbound {
|
||||
/// Split `data` into `MAX_EFFICIENT_SIZE`-sized chunks, each wrapped in
|
||||
/// its own `OutboundResource` with `flags.split = true` and the correct
|
||||
@@ -834,64 +873,19 @@ impl MultiSegmentOutbound {
|
||||
is_response: bool,
|
||||
encrypt_fn: Option<&ResourceEncryptor<'_>>,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if data.len() > MAX_RESOURCE_SIZE {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
let data_size = data.len();
|
||||
|
||||
// `original_hash` covers the uncompressed concatenated payload so
|
||||
// the receiver can verify reassembly across all segments.
|
||||
let random_hash: [u8; RANDOM_HASH_SIZE] =
|
||||
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
|
||||
.try_into()
|
||||
.unwrap();
|
||||
let original_hash = compute_resource_hash(&data, &random_hash);
|
||||
|
||||
let metadata_wire_size = metadata.as_ref().map(|m| 3 + m.len()).unwrap_or(0);
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceError::MetadataTooLarge);
|
||||
}
|
||||
|
||||
let first_payload_max = MAX_EFFICIENT_SIZE - metadata_wire_size;
|
||||
let mut chunk_specs: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::new();
|
||||
|
||||
if data.is_empty() {
|
||||
chunk_specs.push((Vec::new(), metadata.clone()));
|
||||
} else {
|
||||
let first_len = data.len().min(first_payload_max);
|
||||
chunk_specs.push((data[..first_len].to_vec(), metadata.clone()));
|
||||
let mut offset = first_len;
|
||||
|
||||
while offset < data.len() {
|
||||
let end = (offset + MAX_EFFICIENT_SIZE).min(data.len());
|
||||
chunk_specs.push((data[offset..end].to_vec(), None));
|
||||
offset = end;
|
||||
}
|
||||
}
|
||||
|
||||
let total_segments = chunk_specs.len();
|
||||
let mut lazy = LazyMultiSegmentOutbound::with_options(
|
||||
data,
|
||||
auto_compress,
|
||||
metadata,
|
||||
request_id,
|
||||
is_response,
|
||||
)?;
|
||||
let original_hash = lazy.original_hash;
|
||||
let total_segments = lazy.total_segments;
|
||||
let data_size = lazy.data_size;
|
||||
let mut segments = Vec::with_capacity(total_segments);
|
||||
|
||||
for (i, (chunk, segment_metadata)) in chunk_specs.into_iter().enumerate() {
|
||||
let mut resource = OutboundResource::with_options(
|
||||
chunk,
|
||||
auto_compress,
|
||||
segment_metadata,
|
||||
None,
|
||||
encrypt_fn,
|
||||
)?;
|
||||
resource.flags.split = true;
|
||||
resource.flags.is_response = is_response;
|
||||
resource.segment_index = i + 1;
|
||||
resource.total_segments = total_segments;
|
||||
resource.request_id = request_id.clone();
|
||||
resource.advertisement_data_size = data_size + metadata_wire_size;
|
||||
// Stamps the shared `original_hash` onto each segment so the wire
|
||||
// ADV (built later via `create_advertisement`) carries the
|
||||
// coordinator key the receiver needs to reassemble.
|
||||
resource.original_hash = Some(original_hash);
|
||||
segments.push(resource);
|
||||
while let Some(segment) = lazy.next_segment(encrypt_fn)? {
|
||||
segments.push(segment);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -940,6 +934,120 @@ impl MultiSegmentOutbound {
|
||||
}
|
||||
}
|
||||
|
||||
impl LazyMultiSegmentOutbound {
|
||||
/// Create a sequential split-Resource plan without metadata or request
|
||||
/// flags.
|
||||
pub fn new(data: Vec<u8>, auto_compress: bool) -> Result<Self, ResourceError> {
|
||||
Self::with_options(data, auto_compress, None, None, false)
|
||||
}
|
||||
|
||||
/// Create a sequential split-Resource plan while preserving metadata and
|
||||
/// request flags. Metadata is moved into the first segment when it is
|
||||
/// materialised.
|
||||
pub fn with_options(
|
||||
data: Vec<u8>,
|
||||
auto_compress: bool,
|
||||
metadata: Option<Vec<u8>>,
|
||||
request_id: Option<Vec<u8>>,
|
||||
is_response: bool,
|
||||
) -> Result<Self, ResourceError> {
|
||||
if data.len() > MAX_RESOURCE_SIZE {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
let data_size = data.len();
|
||||
let metadata_wire_size = metadata.as_ref().map(|value| 3 + value.len()).unwrap_or(0);
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceError::MetadataTooLarge);
|
||||
}
|
||||
let total_segments = required_segment_count(data_size, metadata_wire_size);
|
||||
if total_segments > MAX_SEGMENTS {
|
||||
return Err(ResourceError::TooLarge);
|
||||
}
|
||||
|
||||
// `original_hash` covers the uncompressed concatenated payload so the
|
||||
// receiver can verify reassembly across all segments.
|
||||
let random_hash: [u8; RANDOM_HASH_SIZE] =
|
||||
rns_crypto::random::random_bytes(RANDOM_HASH_SIZE)
|
||||
.try_into()
|
||||
.expect("fixed random-hash length");
|
||||
let original_hash = compute_resource_hash(&data, &random_hash);
|
||||
|
||||
Ok(Self {
|
||||
data,
|
||||
auto_compress,
|
||||
metadata,
|
||||
metadata_wire_size,
|
||||
request_id,
|
||||
is_response,
|
||||
next_offset: 0,
|
||||
next_segment_index: 1,
|
||||
original_hash,
|
||||
total_segments,
|
||||
data_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of segments that have not yet been materialised.
|
||||
pub fn remaining_segments(&self) -> usize {
|
||||
self.total_segments
|
||||
.saturating_sub(self.next_segment_index.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Build the next standalone outbound Resource. The caller owns the
|
||||
/// returned segment and should request another only after the current one
|
||||
/// has completed or been terminally discarded.
|
||||
pub fn next_segment(
|
||||
&mut self,
|
||||
encrypt_fn: Option<&ResourceEncryptor<'_>>,
|
||||
) -> Result<Option<OutboundResource>, ResourceError> {
|
||||
if self.next_segment_index > self.total_segments {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let segment_index = self.next_segment_index;
|
||||
let segment_metadata = if segment_index == 1 {
|
||||
self.metadata.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let payload_limit = if segment_index == 1 {
|
||||
MAX_EFFICIENT_SIZE - self.metadata_wire_size
|
||||
} else {
|
||||
MAX_EFFICIENT_SIZE
|
||||
};
|
||||
let end = self
|
||||
.next_offset
|
||||
.saturating_add(payload_limit)
|
||||
.min(self.data.len());
|
||||
let chunk = self.data[self.next_offset..end].to_vec();
|
||||
|
||||
let mut resource = OutboundResource::with_options(
|
||||
chunk,
|
||||
self.auto_compress,
|
||||
segment_metadata,
|
||||
None,
|
||||
encrypt_fn,
|
||||
)?;
|
||||
resource.flags.split = true;
|
||||
resource.flags.is_response = self.is_response;
|
||||
resource.segment_index = segment_index;
|
||||
resource.total_segments = self.total_segments;
|
||||
resource.request_id = self.request_id.clone();
|
||||
resource.advertisement_data_size = self.data_size + self.metadata_wire_size;
|
||||
resource.original_hash = Some(self.original_hash);
|
||||
|
||||
self.next_offset = end;
|
||||
self.next_segment_index += 1;
|
||||
if self.next_segment_index > self.total_segments {
|
||||
// The current segment now owns its bytes. Release the complete
|
||||
// source allocation before it begins transferring.
|
||||
self.data = Vec::new();
|
||||
}
|
||||
Ok(Some(resource))
|
||||
}
|
||||
}
|
||||
|
||||
/// Inbound multi-segment resource coordinator: collects `InboundResource`
|
||||
/// segments and reassembles the original payload. Two ingest paths feed
|
||||
/// `assembled_segments`: `set_segment` + `assemble_segment` (unit tests) and
|
||||
@@ -1389,6 +1497,34 @@ impl OutboundTransfer {
|
||||
TransferAction::None
|
||||
}
|
||||
|
||||
/// Sender-side advertisement watchdog for request-driven runtimes.
|
||||
///
|
||||
/// 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.
|
||||
pub fn check_timeout(&mut self) -> TransferAction {
|
||||
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,
|
||||
);
|
||||
if self.started_at.elapsed() <= timeout {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
if self.retries < MAX_ADV_RETRIES {
|
||||
self.retries += 1;
|
||||
self.started_at = Instant::now();
|
||||
TransferAction::SendAdvertisement(self.create_advertisement())
|
||||
} else {
|
||||
self.resource.state = ResourceState::Failed;
|
||||
TransferAction::Failed("resource advertisement timed out".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume a hashmap-update frame from the receiver.
|
||||
///
|
||||
/// Wire layout:
|
||||
@@ -1549,8 +1685,7 @@ impl OutboundTransfer {
|
||||
// The collision guard widens the search window so out-of-order
|
||||
// part requests don't fall outside the scanned range when the
|
||||
// receiver's consecutive height lags ours.
|
||||
let guard_size =
|
||||
crate::resource_adv::collision_guard_size(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let guard_size = crate::resource_adv::collision_guard_size(rns_wire::constants::LINK_MDU);
|
||||
let search_start = self.receiver_min_consecutive_height;
|
||||
let search_end = (search_start + guard_size).min(self.resource.num_parts());
|
||||
|
||||
@@ -1597,7 +1732,7 @@ impl OutboundTransfer {
|
||||
};
|
||||
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
|
||||
// Python cancels if an exhausted request cursor is not aligned to
|
||||
// a hashmap segment boundary.
|
||||
@@ -1621,6 +1756,17 @@ impl OutboundTransfer {
|
||||
}
|
||||
}
|
||||
|
||||
// An empty hashmap means there is nothing to answer the receiver's
|
||||
// request with — cancel rather than emit a useless empty HMU (1.3.9).
|
||||
if hashmap_bytes.is_empty() {
|
||||
self.resource.state = ResourceState::Failed;
|
||||
actions.push(TransferAction::SendCancel(
|
||||
CancelType::Icl,
|
||||
self.resource.resource_hash,
|
||||
));
|
||||
return actions;
|
||||
}
|
||||
|
||||
// HMU wire layout: resource_hash(32) || msgpack([segment, hashmap]).
|
||||
let hmu_payload = {
|
||||
use rmpv::Value;
|
||||
@@ -1682,7 +1828,7 @@ impl OutboundTransfer {
|
||||
self.resource.random_hash.to_vec(),
|
||||
self.resource.flags,
|
||||
&self.resource.map_hashes,
|
||||
rns_wire::constants::ENCRYPTED_MDU,
|
||||
rns_wire::constants::LINK_MDU,
|
||||
);
|
||||
// `ResourceAdvertisement::new` defaults to single-segment metadata
|
||||
// (`segment_index = 1`, `total_segments = 1`, `original_hash =
|
||||
@@ -2118,23 +2264,38 @@ impl InboundTransfer {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
// Only process a hashmap update we actually solicited (1.3.9). An
|
||||
// unsolicited HMU is dropped rather than resetting the retry/activity
|
||||
// counters or injecting hashmap entries outside the request cycle.
|
||||
if !self.waiting_for_hmu {
|
||||
return TransferAction::None;
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return self.cancel();
|
||||
}
|
||||
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let Some(segment_start) = segment.checked_mul(hashmap_max_len) else {
|
||||
return self.cancel();
|
||||
};
|
||||
if segment_start >= self.resource.total_parts {
|
||||
return self.cancel();
|
||||
}
|
||||
|
||||
self.resource.state = ResourceState::Transferring;
|
||||
self.last_activity = Instant::now();
|
||||
self.retries_left = MAX_RETRIES;
|
||||
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
|
||||
// Parse hashes from the hashmap data and insert into our map_hashes.
|
||||
// `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
|
||||
.checked_mul(hashmap_max_len)
|
||||
.and_then(|base| base.checked_add(i))
|
||||
{
|
||||
let idx = match segment_start.checked_add(i) {
|
||||
Some(idx) if idx < self.resource.total_parts => idx,
|
||||
_ => break,
|
||||
};
|
||||
@@ -2597,6 +2758,31 @@ mod tests {
|
||||
assert!(ws.window_min > initial_min);
|
||||
}
|
||||
|
||||
// Regression: a very-slow demotion can clamp `window` below an already-raised `window_min`;
|
||||
// the next promoted grow must not underflow `window - window_min` (Python's signed comparison
|
||||
// is simply false there).
|
||||
#[test]
|
||||
fn window_grow_survives_demote_then_promote() {
|
||||
let mut w = WindowState::new();
|
||||
for _ in 0..6 {
|
||||
w.grow(1000);
|
||||
}
|
||||
assert_eq!((w.window, w.window_min, w.window_max), (10, 7, 10));
|
||||
for _ in 0..VERY_SLOW_RATE_THRESHOLD {
|
||||
w.grow(RATE_VERY_SLOW - 1);
|
||||
}
|
||||
assert_eq!(
|
||||
(w.window, w.window_min, w.window_max),
|
||||
(WINDOW_MAX_VERY_SLOW, 7, WINDOW_MAX_VERY_SLOW)
|
||||
);
|
||||
for _ in 0..FAST_RATE_THRESHOLD + 1 {
|
||||
w.grow(RATE_FAST + 1);
|
||||
}
|
||||
assert_eq!(w.window_max, WINDOW_MAX_FAST);
|
||||
assert_eq!(w.window, 5);
|
||||
assert_eq!(w.window_min, 7); // unchanged: window has not outgrown the band
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_link_resource_outbound_creation() {
|
||||
let link_id = [0xAA; 16];
|
||||
@@ -2721,6 +2907,47 @@ mod tests {
|
||||
assert!(matches!(action, TransferAction::SendPart(0, _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_advertisement_watchdog_retries() {
|
||||
let mut transfer = OutboundTransfer::new(
|
||||
b"retry advertisement".to_vec(),
|
||||
false,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
transfer.tick(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
|
||||
transfer.started_at = Instant::now() - Duration::from_secs(60);
|
||||
assert!(matches!(
|
||||
transfer.check_timeout(),
|
||||
TransferAction::SendAdvertisement(_)
|
||||
));
|
||||
assert_eq!(transfer.retries, 1);
|
||||
assert_eq!(transfer.resource.state, ResourceState::Advertised);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_advertisement_watchdog_fails_after_retry_limit() {
|
||||
let mut transfer = OutboundTransfer::new(
|
||||
b"failed advertisement".to_vec(),
|
||||
false,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.unwrap();
|
||||
transfer.tick();
|
||||
transfer.retries = MAX_ADV_RETRIES;
|
||||
transfer.started_at = Instant::now() - Duration::from_secs(60);
|
||||
|
||||
assert!(matches!(
|
||||
transfer.check_timeout(),
|
||||
TransferAction::Failed(_)
|
||||
));
|
||||
assert_eq!(transfer.resource.state, ResourceState::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_outbound_transfer_hmu_handling() {
|
||||
let data = b"small data".to_vec();
|
||||
@@ -2796,6 +3023,17 @@ mod tests {
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::TooLarge)));
|
||||
|
||||
let result = InboundResource::new(
|
||||
0,
|
||||
1024,
|
||||
1000,
|
||||
[0xAA; RANDOM_HASH_SIZE],
|
||||
[0xBB; 32],
|
||||
ResourceFlags::default(),
|
||||
Vec::new(),
|
||||
);
|
||||
assert!(matches!(result, Err(ResourceError::InvalidAdvertisement)));
|
||||
|
||||
// Same bound at the InboundResource layer directly.
|
||||
let result = InboundResource::new(
|
||||
usize::MAX,
|
||||
@@ -3230,12 +3468,91 @@ mod tests {
|
||||
assert_eq!(multi.segments[1].data.len(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lazy_multi_segment_materialises_only_on_demand() {
|
||||
let data = vec![0xA6; MAX_EFFICIENT_SIZE * 2 + 321];
|
||||
let mut lazy = LazyMultiSegmentOutbound::new(data.clone(), false).unwrap();
|
||||
|
||||
assert_eq!(lazy.total_segments, 3);
|
||||
assert_eq!(lazy.remaining_segments(), 3);
|
||||
|
||||
let first = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(first.segment_index, 1);
|
||||
assert_eq!(first.total_segments, 3);
|
||||
assert_eq!(first.data.len(), MAX_EFFICIENT_SIZE);
|
||||
assert_eq!(lazy.remaining_segments(), 2);
|
||||
|
||||
let second = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(second.segment_index, 2);
|
||||
assert_eq!(second.data.len(), MAX_EFFICIENT_SIZE);
|
||||
assert_eq!(lazy.remaining_segments(), 1);
|
||||
|
||||
let third = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert_eq!(third.segment_index, 3);
|
||||
assert_eq!(third.data.len(), 321);
|
||||
assert_eq!(lazy.remaining_segments(), 0);
|
||||
assert!(lazy.next_segment(None).unwrap().is_none());
|
||||
|
||||
let rebuilt: Vec<u8> = [first, second, third]
|
||||
.into_iter()
|
||||
.flat_map(|segment| segment.data)
|
||||
.collect();
|
||||
assert_eq!(rebuilt, data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lazy_multi_segment_preserves_metadata_and_request_flags() {
|
||||
let metadata = b"\x81\xa4name\xa8file.bin".to_vec();
|
||||
let request_id = vec![0x42; 16];
|
||||
let data = vec![0x5C; MAX_EFFICIENT_SIZE + 10];
|
||||
let mut lazy = LazyMultiSegmentOutbound::with_options(
|
||||
data,
|
||||
false,
|
||||
Some(metadata.clone()),
|
||||
Some(request_id.clone()),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let first = lazy.next_segment(None).unwrap().unwrap();
|
||||
let second = lazy.next_segment(None).unwrap().unwrap();
|
||||
assert!(first.flags.has_metadata);
|
||||
assert!(
|
||||
first
|
||||
.metadata
|
||||
.as_deref()
|
||||
.is_some_and(|wire| wire.ends_with(&metadata))
|
||||
);
|
||||
assert_eq!(first.metadata_size, metadata.len() + 3);
|
||||
assert!(!second.flags.has_metadata);
|
||||
assert_eq!(first.request_id, Some(request_id.clone()));
|
||||
assert_eq!(second.request_id, Some(request_id));
|
||||
assert!(first.flags.is_response);
|
||||
assert!(second.flags.is_response);
|
||||
assert_eq!(first.original_hash, second.original_hash);
|
||||
assert_eq!(
|
||||
first.advertisement_data_size,
|
||||
second.advertisement_data_size
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_outbound_too_large() {
|
||||
let data = vec![0; MAX_RESOURCE_SIZE + 1];
|
||||
assert!(MultiSegmentOutbound::new(data, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_plan_caps_metadata_induced_extra_segment() {
|
||||
let bounded_payload = MAX_EFFICIENT_SIZE * MAX_SEGMENTS;
|
||||
assert_eq!(required_segment_count(bounded_payload, 0), MAX_SEGMENTS);
|
||||
assert_eq!(required_segment_count(bounded_payload, 4), MAX_SEGMENTS + 1);
|
||||
assert_eq!(
|
||||
required_segment_count(MAX_RESOURCE_SIZE, 0),
|
||||
MAX_SEGMENTS + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multi_segment_cancel_all_fans_out() {
|
||||
// Python parity: head-cancel must tear down every follow-on segment.
|
||||
@@ -3903,7 +4220,7 @@ mod tests {
|
||||
let mut sender =
|
||||
OutboundTransfer::new(data.clone(), false, Duration::from_millis(100)).unwrap();
|
||||
assert!(
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU) > 1,
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU) > 1,
|
||||
"test requires a multi-entry hashmap segment"
|
||||
);
|
||||
|
||||
@@ -4132,14 +4449,14 @@ mod tests {
|
||||
assert_eq!(inbound.hashmap_height, initial_height);
|
||||
|
||||
// Build hashmap data for segment 0 with additional hashes
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let mut hashmap_bytes = Vec::new();
|
||||
let end = outbound.map_hashes.len().min(hashmap_max_len);
|
||||
for i in 0..end {
|
||||
hashmap_bytes.extend_from_slice(&outbound.map_hashes[i]);
|
||||
}
|
||||
|
||||
inbound.waiting_for_hmu = true;
|
||||
let action = inbound.hashmap_update(0, &hashmap_bytes);
|
||||
|
||||
// Should have extended map_hashes
|
||||
@@ -4151,14 +4468,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_rejects_out_of_range_segment() {
|
||||
// Wire-supplied `segment` must not grow map_hashes past total_parts.
|
||||
fn test_hashmap_update_ignores_unsolicited() {
|
||||
// 1.3.9: an HMU that was not solicited (waiting_for_hmu == false) is
|
||||
// dropped without touching transfer state.
|
||||
let data = vec![0u8; 2000];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.num_parts(),
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
@@ -4172,22 +4488,85 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Hostile segment index: would previously push ~segment*74 zero
|
||||
// entries into map_hashes. Must be ignored without growth or panic.
|
||||
inbound.hashmap_update(1_000_000, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
assert!(!inbound.waiting_for_hmu);
|
||||
let before = inbound.resource.map_hashes.len();
|
||||
let action = inbound.hashmap_update(0, &outbound.map_hashes[0]);
|
||||
assert!(matches!(action, TransferAction::None));
|
||||
assert_eq!(inbound.resource.map_hashes.len(), before);
|
||||
assert_ne!(inbound.resource.state, ResourceState::Failed);
|
||||
}
|
||||
|
||||
// Overflowing segment*hashmap_max_len must not panic either.
|
||||
inbound.hashmap_update(usize::MAX, &outbound.map_hashes[0]);
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
#[test]
|
||||
fn test_hashmap_update_empty_cancels() {
|
||||
// 1.3.9: a solicited but empty/degenerate HMU cancels the transfer and
|
||||
// emits a receiver cancel (RESOURCE_RCL).
|
||||
let data = vec![0u8; 2000];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
outbound.num_parts(),
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..2].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
inbound.waiting_for_hmu = true;
|
||||
let action = inbound.hashmap_update(0, &[]);
|
||||
assert!(matches!(
|
||||
action,
|
||||
TransferAction::SendCancel(CancelType::Rcl, _)
|
||||
));
|
||||
assert_eq!(inbound.resource.state, ResourceState::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_rejects_out_of_range_segment() {
|
||||
// Wire-supplied `segment` must not grow map_hashes past total_parts.
|
||||
let data = vec![0u8; 2000];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
|
||||
for segment in [1_000_000, usize::MAX] {
|
||||
let mut inbound = InboundTransfer::from_advertisement(
|
||||
total_parts,
|
||||
outbound.total_size,
|
||||
data.len(),
|
||||
outbound.random_hash,
|
||||
outbound.resource_hash,
|
||||
ResourceFlags {
|
||||
compressed: false,
|
||||
..Default::default()
|
||||
},
|
||||
outbound.map_hashes[..2].to_vec(),
|
||||
Duration::from_millis(100),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Hostile and overflowing segment indices must neither grow the
|
||||
// hashmap nor refresh the watchdog indefinitely.
|
||||
inbound.waiting_for_hmu = true;
|
||||
let action = inbound.hashmap_update(segment, &outbound.map_hashes[0]);
|
||||
assert!(matches!(
|
||||
action,
|
||||
TransferAction::SendCancel(CancelType::Rcl, _)
|
||||
));
|
||||
assert_eq!(inbound.resource.map_hashes.len(), 2);
|
||||
assert_eq!(inbound.resource.state, ResourceState::Failed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hashmap_update_second_segment_bounded_by_total_parts() {
|
||||
// Resource large enough that its hashmap spans >1 segment: segment 1
|
||||
// writes land, but never past total_parts even if overfull.
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let data = vec![0xCD; (hashmap_max_len + 12) * SDU];
|
||||
let outbound = OutboundResource::new(data.clone(), false, None).unwrap();
|
||||
let total_parts = outbound.num_parts();
|
||||
@@ -4215,6 +4594,7 @@ mod tests {
|
||||
overfull.extend_from_slice(&outbound.map_hashes[i]);
|
||||
}
|
||||
overfull.extend_from_slice(&[0xEE; MAPHASH_LEN * 8]);
|
||||
inbound.waiting_for_hmu = true;
|
||||
inbound.hashmap_update(1, &overfull);
|
||||
|
||||
assert_eq!(inbound.resource.map_hashes.len(), total_parts);
|
||||
@@ -4394,8 +4774,7 @@ mod tests {
|
||||
let mut request_data = Vec::new();
|
||||
request_data.push(HASHMAP_IS_EXHAUSTED);
|
||||
// last_map_hash -- use the hash at hashmap_max_len boundary
|
||||
let hashmap_max_len =
|
||||
crate::resource_adv::hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU);
|
||||
let hashmap_max_len = crate::resource_adv::hashmap_max_len(rns_wire::constants::LINK_MDU);
|
||||
let boundary_idx = hashmap_max_len.min(sender.resource.num_parts()) - 1;
|
||||
request_data.extend_from_slice(&sender.resource.map_hashes[boundary_idx]);
|
||||
request_data.extend_from_slice(&sender.resource.resource_hash);
|
||||
|
||||
@@ -289,8 +289,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_default_link_mdu_matches_python_hashmap_capacity() {
|
||||
assert_eq!(rns_wire::constants::ENCRYPTED_MDU, 431);
|
||||
assert_eq!(hashmap_max_len(rns_wire::constants::ENCRYPTED_MDU), 74);
|
||||
assert_eq!(rns_wire::constants::LINK_MDU, 431);
|
||||
assert_eq!(hashmap_max_len(rns_wire::constants::LINK_MDU), 74);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
# RatKey Hardware Status
|
||||
|
||||
RatKey hardware identity support is **desktop only** and experimental. The full
|
||||
desktop path is validated on a real YubiKey (5.7.4): provision (recoverable /
|
||||
hardware-only / import / restore), on-card sign + ECDH, in-app load into LXMF/RNS,
|
||||
PIN-prompt unlock, auto-lock timeout, lock-on-quit, and **attestation-chain
|
||||
verification against the device's real ATTEST output**. Pre-5.7 (TDES) management
|
||||
keys are implemented and unit-tested but await validation on a pre-5.7 device.
|
||||
|
||||
## Release scope: desktop only
|
||||
|
||||
Mobile is intentionally excluded from release. The `hardware` feature is off on
|
||||
iOS/Android (pcsc is desktop-only), the `hw_*` commands are
|
||||
`#[cfg(not(any(target_os = "android", target_os = "ios")))]`, and the frontend
|
||||
hides every hardware entry point on mobile (`isMobile()` gate in setup.js +
|
||||
identity.js).
|
||||
|
||||
## Mobile (deferred — needs a different model)
|
||||
|
||||
Desktop keeps the token plugged in and does every sign/ECDH on-card. That can't
|
||||
work over transient NFC (iOS CoreNFC is modal ~60s; Android IsoDep only while the
|
||||
tag is in-field; neither runs in the background). A messaging app used all day
|
||||
needs a **wrapped software session**: tap the key to unlock (on-card ECDH unwraps
|
||||
a software identity stored encrypted at rest, ideally in the Secure Enclave /
|
||||
StrongBox), operate in software for a configurable window (mirrors the desktop
|
||||
auto-lock setting), re-tap to refresh. This is a different security model than
|
||||
"key never leaves the token" and should be an explicit mode alongside
|
||||
hardware-only. The `PivTransport` seam is ready (`PivSession::new` takes any
|
||||
transport); a mobile loader belongs in `ratspeak-runtime`. Android NFC (IsoDep)
|
||||
is the tractable first transport.
|
||||
|
||||
### Recoverable software identities — DONE (2026-05-29, cross-platform)
|
||||
|
||||
The recoverable model generalized "hardware identity" → "recoverable identity,"
|
||||
with the YubiKey as one optional backing. All on every platform (the derivation
|
||||
+ vault are pure-Rust, gated behind a default `seed` feature in ratspeak-runtime
|
||||
that pulls `rns-ratkey` without pcsc):
|
||||
|
||||
- **Software seed-restore** (`ratspeak_runtime::derive_identity_key_from_phrase`,
|
||||
`restore_seed_identity` command): a 12-word phrase restores a software identity
|
||||
on any platform — the practical mobile recovery path. Folded into the app's
|
||||
**Import** flow (key *or* phrase), not a separate button.
|
||||
- **Mnemonic-derived-by-default** (`generate_recoverable_key`): new software
|
||||
identities are derived from a fresh BIP-39 mnemonic shown for backup at creation.
|
||||
Both `api_create_identity` (settings) and `api_setup_complete` (first-setup)
|
||||
produce them; legacy random identities keep raw-key export.
|
||||
`LxmfManager::create_identity` (random) stays for internal/tests.
|
||||
- **Recovery-phrase re-display** (`vault::store_plaintext_seed` /
|
||||
`has_stored_mnemonic` / `reveal_mnemonic`, `reveal_identity_mnemonic` command,
|
||||
software only): the phrase is persisted so it can be shown again. Its at-rest
|
||||
protection tracks the key's — a plaintext `identity.seed` sidecar when the
|
||||
identity is unprotected (crypto-equivalent to the already-plaintext `identity`
|
||||
key file), folded into the vault as a `mnemonic_token` (same KEK) once a passcode
|
||||
is set. The vault is authoritative when present, so reveal honors the passcode
|
||||
even if a stale sidecar survives the verify-before-delete window. Captured at
|
||||
create/import (both `api_create_identity`, `api_setup_complete`, and
|
||||
`restore_seed_identity`); hardware identities never store a phrase.
|
||||
- **Passcode at-rest encryption** (`vault.rs`): software identities can be sealed
|
||||
with a passcode — Argon2id(passcode,salt) → HKDF(info=params‖salt) binds the KDF
|
||||
params → 64-byte KEK → `rns_crypto::token` (AES-256-CBC + HMAC). Stored as
|
||||
`identity.enc`; param-tamper/wrong-passcode → auth failure (unit-tested). The
|
||||
launch unlock + auto-lock + lock-on-quit machinery is shared with the hardware
|
||||
PIN path (one "protected identity" state, a `kind` discriminator selects PIN vs
|
||||
passcode; the `hw_unlock`/`hardware_locked`/`hw_locked` wire names are retained).
|
||||
|
||||
Caveat documented to users: restore recovers the *identity*, not past message
|
||||
history (forward secrecy).
|
||||
|
||||
## Architecture (done)
|
||||
|
||||
- `PivTransport` is the platform seam: APDU bytes in, response bytes out.
|
||||
`PivSession<T>` builds every PIV operation on `apdu` over that seam and is
|
||||
transport-agnostic (compiles with no features).
|
||||
- `PcscTransport` (behind the `hardware` feature) is the desktop PC/SC
|
||||
implementation; `PivSession::<PcscTransport>::connect()` is the entry point.
|
||||
Mobile NFC/USB transports implement `PivTransport` from the application layer.
|
||||
- `HardwareIdentity` holds a `Box<dyn IdentityBackend>`, implemented by both
|
||||
`PivSession<T>` (real token, any transport) and `MockPivSession`.
|
||||
- `PivSession::lock()` / `HardwareIdentity::lock()` re-select the PIV applet to
|
||||
drop the on-card PIN cache (mechanism for app-side session timeout / lock-on-quit).
|
||||
|
||||
## Validated on hardware (YubiKey 5, firmware 5.7.4)
|
||||
|
||||
Full provision → verify → test loop with our own code, PIN-once + touch-never
|
||||
Ed25519 (9A) / X25519 (9D):
|
||||
|
||||
- **Management-key authentication** (witness/challenge, AES-192) — `hw provision`
|
||||
authenticates slot 9B and generates both keys on-device. Successful generate
|
||||
is proof of auth.
|
||||
- `parse_metadata_public_key` reads the correct pubkey from GET METADATA
|
||||
(confirmed against ykman-exported ground truth — the layout assumption held).
|
||||
- Ed25519 signing on slot 9A; signature verifies against the slot pubkey.
|
||||
- X25519 ECDH on slot 9D; shared secret symmetric with a software peer.
|
||||
- `HardwareIdentity` decrypt end-to-end (on-device ECDH → HKDF → AES token) — the
|
||||
same Ed25519-sign + X25519-ECDH + token-AES primitives LXMF uses, so live LXMF
|
||||
send/receive on a hardware identity routes through the card (serial 35284666).
|
||||
- The pubkey our provision records matches ykman's independent export byte-for-byte.
|
||||
- **Attestation chain verified against the device's real ATTEST output** (`hw
|
||||
attest`): both slot-9A/9D per-key certs chain through the slot-F9 device
|
||||
intermediate to a bundled, fingerprint-pinned new-PKI Yubico root. `hw provision`
|
||||
now captures + verifies the chain into the `.hwid`. The captured 5.7.4 certs are
|
||||
committed as a CI regression vector (`tests/fixtures/{9a_attest,f9_device}.der`).
|
||||
|
||||
## Still required before hardware RatKey is documented as supported
|
||||
|
||||
- **TDES management keys** are implemented (3DES EDE3 via the `des` crate, 8-byte
|
||||
block; `mgmt.rs` dispatches on the algorithm byte). A FIPS-81 known-answer test
|
||||
and a distinct-subkey round-trip cover the cipher. Pre-5.7 YubiKeys default to a
|
||||
TDES management key; the witness/challenge auth flow already drives its block
|
||||
size from `mgmt::block_len`, so it is ready — but not yet exercised against a
|
||||
physical pre-5.7 device.
|
||||
- A two-node **live LXMF message exchange** in the app on a hardware identity. The
|
||||
on-card crypto primitives are validated (above) and the runtime delegates
|
||||
sign/ECDH to the backend, but an end-to-end app round-trip between two peers is
|
||||
still a manual check.
|
||||
- Edge cases on a real device: disconnect mid-operation, wrong PIN / lockout,
|
||||
touch timeout (if touch is ever enabled), and the `from_hwid` key-mismatch guard.
|
||||
- Decide and document the ratchet policy for hardware identities. PIV cannot hold
|
||||
Reticulum ratchet private keys, so enforced-ratchet decrypt fails closed.
|
||||
- Add hardware-gated tests that are skipped by default but run when a device is
|
||||
explicitly selected by environment/config.
|
||||
|
||||
Until those items pass on real devices, CLI/UI surfaces must label hardware
|
||||
RatKey support as experimental.
|
||||
@@ -64,10 +64,10 @@ impl LocalKeyBackend for HardwareBackend {
|
||||
|
||||
fn lock(&self) {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
if let Ok(tx) = self.cmd_tx.lock()
|
||||
&& tx.send(Cmd::Lock { reply }).is_ok()
|
||||
{
|
||||
let _ = rx.recv();
|
||||
if let Ok(tx) = self.cmd_tx.lock() {
|
||||
if tx.send(Cmd::Lock { reply }).is_ok() {
|
||||
let _ = rx.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-runtime"
|
||||
description = "Core runtime, config parsing, and lifecycle for Reticulum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
@@ -32,3 +33,6 @@ serde = { workspace = true }
|
||||
subtle = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
nix = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -0,0 +1,28 @@
|
||||
# Reticulum runtime examples
|
||||
|
||||
These examples mirror the application-facing subjects in the upstream Python
|
||||
Reticulum examples while using explicit Rust runtime ownership.
|
||||
|
||||
Most networked examples have `server` and `client` modes:
|
||||
|
||||
```console
|
||||
cargo run -p rns-runtime --example link -- server
|
||||
cargo run -p rns-runtime --example link -- client <destination-hash> "hello"
|
||||
```
|
||||
|
||||
Pass `--config <directory>` to either mode to select a Reticulum config
|
||||
directory. Servers print their destination hash and announce once at startup.
|
||||
|
||||
The `ratchets` example is a local composition recipe because ratchet files and
|
||||
identity files are application-owned secrets:
|
||||
|
||||
```console
|
||||
cargo run -p rns-runtime --example ratchets -- identity.key ratchets.bin
|
||||
```
|
||||
|
||||
Use private, access-controlled paths for both files in a real application.
|
||||
|
||||
Python's `ExampleInterface.py` demonstrates runtime-loaded Python classes.
|
||||
Rust instead integrates third-party interfaces at compile time through
|
||||
`rns_interface::InterfaceHandle` and the runtime's interface factory. This is
|
||||
an intentional ownership and type-safety difference, not a wire-protocol gap.
|
||||
@@ -0,0 +1,66 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
|
||||
const ASPECT: &str = "example_utilities.announcesample.fruits";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut subscription = runtime
|
||||
.handle
|
||||
.subscribe_announces(Some(ASPECT.to_string()), false)
|
||||
.await?;
|
||||
let destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Announce destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
println!("Press enter to announce with app data; Ctrl-C stops");
|
||||
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
announce = subscription.recv() => {
|
||||
let Some(announce) = announce else { break };
|
||||
println!(
|
||||
"Observed {} app_data={}",
|
||||
hex::encode(announce.destination_hash),
|
||||
announce
|
||||
.app_data
|
||||
.as_deref()
|
||||
.map(String::from_utf8_lossy)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
line = lines.next_line() => {
|
||||
if line?.is_none() {
|
||||
break;
|
||||
}
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
app_data: Some(b"Peach".to_vec()),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await?;
|
||||
println!("Announced {}", hex::encode(destination.handle.destination_hash()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
subscription.close().await?;
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.broadcast";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let message = args
|
||||
.positional
|
||||
.first()
|
||||
.map_or("Hello Reticulum", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination = Destination::new(None, Direction::Out, DestType::Plain, ASPECT)?;
|
||||
|
||||
let sent = runtime
|
||||
.handle
|
||||
.send_to(
|
||||
&destination,
|
||||
message.as_bytes(),
|
||||
SendOptions {
|
||||
create_receipt: false,
|
||||
..SendOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
println!(
|
||||
"Broadcast {} to {}",
|
||||
hex::encode(sent.packet_hash),
|
||||
hex::encode(destination.hash)
|
||||
);
|
||||
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
|
||||
use rns_protocol::stream_data::StreamDataMessage;
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
const ASPECT: &str = "example_utilities.bufferexample";
|
||||
const STREAM_ID: u16 = 0;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Buffer destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
message = destination.events.channel_messages.recv() => {
|
||||
let Some(message) = message else { break };
|
||||
if message.msg_type != SMT_STREAM_DATA {
|
||||
continue;
|
||||
}
|
||||
let mut frame = StreamDataMessage::new(0, Vec::new(), false);
|
||||
frame.unpack(&message.payload)?;
|
||||
if frame.eof {
|
||||
destination
|
||||
.handle
|
||||
.send_channel(
|
||||
message.link_id,
|
||||
SMT_STREAM_DATA,
|
||||
StreamDataMessage::new(frame.stream_id, Vec::new(), true).pack(),
|
||||
)
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let text = String::from_utf8_lossy(&frame.data);
|
||||
println!("Received over Buffer: {text}");
|
||||
let reply = StreamDataMessage::new(
|
||||
frame.stream_id,
|
||||
format!("Received: {text}").into_bytes(),
|
||||
false,
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.send_channel(message.link_id, SMT_STREAM_DATA, reply.pack())
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Buffer", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "buffer-example").await?;
|
||||
let mut buffer = session
|
||||
.handle
|
||||
.channel()
|
||||
.create_bidirectional_buffer(STREAM_ID, STREAM_ID)
|
||||
.await?;
|
||||
|
||||
buffer.write_all(message.as_bytes()).await?;
|
||||
buffer.flush().await?;
|
||||
let expected_len = "Received: ".len() + message.len();
|
||||
let mut reply = vec![0; expected_len];
|
||||
tokio::time::timeout(Duration::from_secs(30), buffer.read_exact(&mut reply)).await??;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
buffer.shutdown().await?;
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.channelexample";
|
||||
const STRING_MESSAGE: u16 = 0x0101;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Channel destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
message = destination.events.channel_messages.recv() => {
|
||||
let Some(message) = message else { break };
|
||||
if message.msg_type == STRING_MESSAGE {
|
||||
println!(
|
||||
"Received on {}: {}",
|
||||
hex::encode(message.link_id),
|
||||
String::from_utf8_lossy(&message.payload),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.send_channel(message.link_id, STRING_MESSAGE, message.payload)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Channel", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "channel-example").await?;
|
||||
let channel = session.handle.channel();
|
||||
channel.register_message_type(STRING_MESSAGE).await?;
|
||||
|
||||
let (reply_tx, mut reply_rx) = tokio::sync::mpsc::channel(1);
|
||||
let handler = channel
|
||||
.add_message_handler(move |msg_type, payload| {
|
||||
if msg_type != STRING_MESSAGE {
|
||||
return false;
|
||||
}
|
||||
let _ = reply_tx.try_send(payload.to_vec());
|
||||
true
|
||||
})
|
||||
.await?;
|
||||
channel.send_raw(STRING_MESSAGE, message.as_bytes()).await?;
|
||||
|
||||
let reply = tokio::time::timeout(Duration::from_secs(30), reply_rx.recv())
|
||||
.await?
|
||||
.ok_or("Channel closed before the echo arrived")?;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
|
||||
channel.remove_message_handler(handler).await?;
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.echo";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
proof_strategy: ProofStrategy::ProveAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination("Echo destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.packets.recv() => {
|
||||
let Some(packet) = packet else { break };
|
||||
println!("Proved {} bytes: {}", packet.data.len(), String::from_utf8_lossy(&packet.data));
|
||||
}
|
||||
}
|
||||
}
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args.positional.get(2).map_or("Hello echo", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination =
|
||||
recall_outbound_destination(&runtime.handle, destination_hash, ASPECT).await?;
|
||||
let sent = runtime
|
||||
.handle
|
||||
.send_to(&destination, message.as_bytes(), SendOptions::default())
|
||||
.await?;
|
||||
let receipt = sent.receipt.ok_or("echo send did not create a receipt")?;
|
||||
let rtt = receipt.delivered().await?;
|
||||
println!("Delivered in {:.3} ms", rtt.as_secs_f64() * 1000.0);
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
mod support;
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.filetransfer.server";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let output_path = args.require(1, "new output file")?.to_string();
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"File-transfer destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
println!("The first completed transfer will be written to {output_path}");
|
||||
|
||||
let completed = tokio::select! {
|
||||
_ = runtime.shutdown.wait() => None,
|
||||
completed = destination.events.resource_completions.recv() => completed,
|
||||
};
|
||||
if let Some(completed) = completed {
|
||||
let mut output = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&output_path)?;
|
||||
output.write_all(&completed.data)?;
|
||||
output.sync_all()?;
|
||||
println!(
|
||||
"Wrote {} bytes to {} without replacing an existing file",
|
||||
completed.data.len(),
|
||||
output_path,
|
||||
);
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let input_path = Path::new(args.require(2, "input file")?);
|
||||
let input = File::open(input_path)?;
|
||||
let file_name = input_path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("resource")
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(
|
||||
&runtime.handle,
|
||||
destination_hash,
|
||||
false,
|
||||
"filetransfer-example",
|
||||
)
|
||||
.await?;
|
||||
let transfer = session
|
||||
.handle
|
||||
.send_resource(
|
||||
input,
|
||||
ResourceOptions {
|
||||
auto_compress: false,
|
||||
metadata: Some(file_name),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut progress = transfer.progress();
|
||||
let concluded = transfer.concluded();
|
||||
tokio::pin!(concluded);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = &mut concluded => {
|
||||
let receipt = result?;
|
||||
println!(
|
||||
"Transferred {} bytes as {}",
|
||||
receipt.data_size,
|
||||
hex::encode(receipt.resource_id),
|
||||
);
|
||||
break;
|
||||
}
|
||||
changed = progress.changed() => {
|
||||
changed?;
|
||||
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.identifyexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Identification destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
established = destination.events.links_established.recv() => {
|
||||
let Some(link_id) = established else { break };
|
||||
println!("Link {} established", hex::encode(link_id));
|
||||
}
|
||||
identified = destination.events.links_identified.recv() => {
|
||||
let Some((link_id, identity_hash)) = identified else { break };
|
||||
println!(
|
||||
"Link {} identified as {}",
|
||||
hex::encode(link_id),
|
||||
hex::encode(identity_hash),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, true, "identify-example").await?;
|
||||
println!(
|
||||
"Established and identified Link {}",
|
||||
hex::encode(session.handle.link_id())
|
||||
);
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.linkexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination("Link destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.link_packets.recv() => {
|
||||
let Some((data, link_id)) = packet else { break };
|
||||
println!("Received on {}: {}", hex::encode(link_id), String::from_utf8_lossy(&data));
|
||||
destination
|
||||
.handle
|
||||
.send_link_packet(link_id, data)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args.positional.get(2).map_or("Hello Link", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut session = connect(&runtime.handle, destination_hash, false, "link-example").await?;
|
||||
session
|
||||
.handle
|
||||
.send_packet(message.as_bytes().to_vec())
|
||||
.await?;
|
||||
|
||||
let reply = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
while let Some(event) = session.events.recv().await {
|
||||
if let LinkSessionEvent::Packet { data, .. } = event {
|
||||
return Some(data);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?
|
||||
.ok_or("Link closed before the echo arrived")?;
|
||||
println!("Reply: {}", String::from_utf8_lossy(&reply));
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.minimalsample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
proof_strategy: ProofStrategy::ProveAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
print_destination("Minimal destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
println!("Announced; waiting for packets (Ctrl-C to stop)");
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.packets.recv() => {
|
||||
let Some(packet) = packet else { break };
|
||||
println!("Received: {}", String::from_utf8_lossy(&packet.data));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
mod support;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.ratchet.echo.request";
|
||||
|
||||
fn load_or_create_identity(path: &Path) -> ExampleResult<Identity> {
|
||||
if path.exists() {
|
||||
return Ok(Identity::from_file(path)?);
|
||||
}
|
||||
let identity = Identity::new();
|
||||
identity.to_file(path)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
fn load_or_create_ring(path: &Path, identity: &Identity) -> ExampleResult<PersistentRatchetRing> {
|
||||
let mut ring = PersistentRatchetRing::open(path, identity)?;
|
||||
ring.ensure_current(identity)?;
|
||||
Ok(ring)
|
||||
}
|
||||
|
||||
fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
let identity_path = Path::new(args.require(0, "identity file")?);
|
||||
let ratchet_path = Path::new(args.require(1, "ratchet file")?);
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Forward-secret message", String::as_str);
|
||||
|
||||
let identity = load_or_create_identity(identity_path)?;
|
||||
let ring = load_or_create_ring(ratchet_path, &identity)?;
|
||||
let ratchet = ring
|
||||
.current_public_key()
|
||||
.ok_or("ratchet ring has no current key")?;
|
||||
|
||||
let mut inbound = Destination::new(Some(&identity), Direction::In, DestType::Single, ASPECT)?;
|
||||
inbound.enable_ratchets(true);
|
||||
inbound.set_local_ratchet(ratchet);
|
||||
let announce = inbound.announce_packet(
|
||||
&identity,
|
||||
Some(b"ratchet example"),
|
||||
inbound.get_ratchet_for_announce().as_ref(),
|
||||
false,
|
||||
None,
|
||||
0.0,
|
||||
)?;
|
||||
|
||||
let remote_identity = Identity::from_public_key(&identity.get_public_key())?;
|
||||
let mut outbound = Destination::new(
|
||||
Some(&remote_identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
ASPECT,
|
||||
)?;
|
||||
outbound.set_remote_ratchet(ratchet);
|
||||
let ciphertext = outbound.encrypt(
|
||||
message.as_bytes(),
|
||||
&remote_identity,
|
||||
outbound.remote_ratchet_pub.as_ref(),
|
||||
)?;
|
||||
let plaintext =
|
||||
inbound.decrypt_with_ratchets(&ciphertext, &identity, Some(ring.private_keys()))?;
|
||||
|
||||
println!("Destination: {}", hex::encode(inbound.hash));
|
||||
println!("Retained ratchets: {}", ring.len());
|
||||
println!("Signed announce: {} bytes", announce.len());
|
||||
println!("Decrypted: {}", String::from_utf8_lossy(&plaintext));
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.requestexample";
|
||||
const REQUEST_PATH: &str = "/echo";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
destination
|
||||
.handle
|
||||
.register_request_handler(
|
||||
REQUEST_PATH,
|
||||
AllowPolicy::AllowAll,
|
||||
Vec::new(),
|
||||
true,
|
||||
|request| {
|
||||
println!(
|
||||
"{} requested {} bytes on {}",
|
||||
hex::encode(request.link_id),
|
||||
request.data.len(),
|
||||
request.path,
|
||||
);
|
||||
RequestOutcome::Reply(request.data)
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination("Request destination", destination.handle.destination_hash());
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
runtime.shutdown.wait().await;
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello request", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "request-example").await?;
|
||||
let response = session
|
||||
.handle
|
||||
.request(
|
||||
REQUEST_PATH,
|
||||
message.as_bytes(),
|
||||
Some(Duration::from_secs(30)),
|
||||
)
|
||||
.await?;
|
||||
println!(
|
||||
"Response in {:.3} ms: {}",
|
||||
response.response_time.as_secs_f64() * 1000.0,
|
||||
String::from_utf8_lossy(&response.data),
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
mod support;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.resourceexample";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptAll,
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Resource destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
completed = destination.events.resource_completions.recv() => {
|
||||
let Some(completed) = completed else { break };
|
||||
println!(
|
||||
"Received {} bytes on {} as {}",
|
||||
completed.data.len(),
|
||||
hex::encode(completed.link_id),
|
||||
hex::encode(completed.resource_hash),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let message = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map_or("Hello Resource", String::as_str);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(&runtime.handle, destination_hash, false, "resource-example").await?;
|
||||
let transfer = session
|
||||
.handle
|
||||
.send_resource_bytes(
|
||||
message.as_bytes().to_vec(),
|
||||
ResourceOptions {
|
||||
auto_compress: true,
|
||||
metadata: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut progress = transfer.progress();
|
||||
let concluded = transfer.concluded();
|
||||
tokio::pin!(concluded);
|
||||
|
||||
let receipt = loop {
|
||||
tokio::select! {
|
||||
result = &mut concluded => break result?,
|
||||
changed = progress.changed() => {
|
||||
changed?;
|
||||
println!("Progress: {:.1}%", *progress.borrow() * 100.0);
|
||||
}
|
||||
}
|
||||
};
|
||||
println!(
|
||||
"Resource {} completed ({} bytes)",
|
||||
hex::encode(receipt.resource_id),
|
||||
receipt.data_size,
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
mod support;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
use support::*;
|
||||
|
||||
const ASPECT: &str = "example_utilities.speedtest";
|
||||
const DEFAULT_BYTES: usize = 2 * 1024 * 1024;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExampleResult {
|
||||
let args = ExampleArgs::parse()?;
|
||||
match args.require(0, "mode: server | client")? {
|
||||
"server" => server(args).await,
|
||||
"client" => client(args).await,
|
||||
other => Err(format!("unknown mode {other}; use server or client").into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn server(args: ExampleArgs) -> ExampleResult {
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let mut destination = register_single(
|
||||
&runtime.handle,
|
||||
Identity::new(),
|
||||
ASPECT,
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
print_destination(
|
||||
"Speed-test destination",
|
||||
destination.handle.destination_hash(),
|
||||
);
|
||||
destination
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await?;
|
||||
|
||||
let mut total = 0usize;
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = runtime.shutdown.wait() => break,
|
||||
packet = destination.events.link_packets.recv() => {
|
||||
let Some((data, _)) = packet else { break };
|
||||
total = total.saturating_add(data.len());
|
||||
if total >= DEFAULT_BYTES {
|
||||
let elapsed = started.elapsed().as_secs_f64();
|
||||
println!(
|
||||
"Received {total} bytes at {:.2} Mbit/s",
|
||||
(total as f64 * 8.0) / elapsed / 1_000_000.0,
|
||||
);
|
||||
total = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destination.close().await?;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn client(args: ExampleArgs) -> ExampleResult {
|
||||
let destination_hash = parse_destination_hash(args.require(1, "destination hash")?)?;
|
||||
let total_bytes = args
|
||||
.positional
|
||||
.get(2)
|
||||
.map(|value| value.parse::<usize>())
|
||||
.transpose()?
|
||||
.unwrap_or(DEFAULT_BYTES);
|
||||
let runtime = ExampleRuntime::start(args.config_dir.as_deref()).await?;
|
||||
let session = connect(
|
||||
&runtime.handle,
|
||||
destination_hash,
|
||||
false,
|
||||
"speedtest-example",
|
||||
)
|
||||
.await?;
|
||||
let chunk = vec![0xAA; session.handle.mdu()];
|
||||
let started = Instant::now();
|
||||
let mut sent = 0usize;
|
||||
|
||||
while sent < total_bytes {
|
||||
let count = (total_bytes - sent).min(chunk.len());
|
||||
session.handle.send_packet(chunk[..count].to_vec()).await?;
|
||||
sent += count;
|
||||
}
|
||||
let elapsed = started.elapsed().as_secs_f64();
|
||||
println!(
|
||||
"Queued {sent} bytes in {:.3}s ({:.2} Mbit/s)",
|
||||
elapsed,
|
||||
(sent as f64 * 8.0) / elapsed / 1_000_000.0,
|
||||
);
|
||||
|
||||
session.handle.close().await;
|
||||
runtime.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_runtime::lifecycle::install_signal_handlers;
|
||||
use rns_runtime::prelude::*;
|
||||
|
||||
pub type ExampleResult<T = ()> = Result<T, Box<dyn Error + Send + Sync>>;
|
||||
|
||||
pub struct ExampleArgs {
|
||||
pub config_dir: Option<String>,
|
||||
pub positional: Vec<String>,
|
||||
}
|
||||
|
||||
impl ExampleArgs {
|
||||
pub fn parse() -> ExampleResult<Self> {
|
||||
let mut config_dir = None;
|
||||
let mut positional = Vec::new();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "--config" {
|
||||
config_dir = Some(args.next().ok_or("--config requires a directory")?);
|
||||
} else {
|
||||
positional.push(arg);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
config_dir,
|
||||
positional,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn require(&self, index: usize, label: &str) -> ExampleResult<&str> {
|
||||
self.positional
|
||||
.get(index)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| format!("missing {label}").into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExampleRuntime {
|
||||
pub handle: ReticulumHandle,
|
||||
pub shutdown: ShutdownSignal,
|
||||
}
|
||||
|
||||
impl ExampleRuntime {
|
||||
pub async fn start(config_dir: Option<&str>) -> ExampleResult<Self> {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signals = install_signal_handlers(shutdown.clone());
|
||||
let handle = init(
|
||||
config_dir,
|
||||
None,
|
||||
shutdown.clone(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await?;
|
||||
Ok(Self { handle, shutdown })
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.handle.shutdown_and_wait().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_destination_hash(value: &str) -> ExampleResult<[u8; 16]> {
|
||||
let bytes = hex::decode(value)?;
|
||||
bytes
|
||||
.try_into()
|
||||
.map_err(|_| "destination hash must contain exactly 32 hexadecimal characters".into())
|
||||
}
|
||||
|
||||
pub async fn recall_outbound_destination(
|
||||
runtime: &ReticulumHandle,
|
||||
destination_hash: [u8; 16],
|
||||
app_name: &str,
|
||||
) -> ExampleResult<Destination> {
|
||||
let recalled = match runtime.recall(destination_hash).await? {
|
||||
Some(recalled) => recalled,
|
||||
None => {
|
||||
runtime
|
||||
.await_path(destination_hash, Duration::from_secs(15))
|
||||
.await?;
|
||||
runtime
|
||||
.recall(destination_hash)
|
||||
.await?
|
||||
.ok_or("destination identity was not learned from its announce")?
|
||||
}
|
||||
};
|
||||
let destination = Destination::new(
|
||||
Some(&recalled.identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
app_name,
|
||||
)?;
|
||||
if destination.hash != destination_hash {
|
||||
return Err(format!(
|
||||
"destination {} does not match application aspect {app_name}",
|
||||
hex::encode(destination_hash)
|
||||
)
|
||||
.into());
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
pub async fn connect(
|
||||
runtime: &ReticulumHandle,
|
||||
destination_hash: [u8; 16],
|
||||
identify: bool,
|
||||
label: &str,
|
||||
) -> ExampleResult<LinkSession> {
|
||||
let options = LinkConnectOptions {
|
||||
identify,
|
||||
client_label: label.to_string(),
|
||||
..LinkConnectOptions::default()
|
||||
};
|
||||
Ok(runtime
|
||||
.connect_link(destination_hash, Identity::new(), options)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn register_single(
|
||||
runtime: &ReticulumHandle,
|
||||
identity: Identity,
|
||||
app_name: &str,
|
||||
options: DestinationRuntimeOptions,
|
||||
) -> ExampleResult<RegisteredDestination> {
|
||||
Ok(runtime
|
||||
.register_destination(identity, app_name.to_string(), options)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub fn print_destination(label: &str, hash: [u8; 16]) {
|
||||
println!("{label}: {}", hex::encode(hash));
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
//! Async byte streams carried by a reliable Reticulum Link channel.
|
||||
//!
|
||||
//! The protocol framing and compression live in `rns-protocol`; this module
|
||||
//! wires them to the actor-owned [`LinkSessionChannelHandle`] and presents
|
||||
//! Tokio [`AsyncRead`] / [`AsyncWrite`] implementations.
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::task::{Context, Poll, Waker};
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_protocol::buffer::{MAX_CHUNK_LEN, StreamReader, StreamWriter};
|
||||
use rns_protocol::channel::ChannelError;
|
||||
use rns_protocol::channel_message::{MessageBase, SMT_STREAM_DATA};
|
||||
use rns_protocol::stream_data::{STREAM_ID_MAX, StreamDataMessage};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
use crate::link_session::{LinkSessionChannelError, LinkSessionChannelHandle};
|
||||
|
||||
/// Maximum unread data retained by the default channel Buffer reader.
|
||||
pub const DEFAULT_READER_CAPACITY: usize = 1024 * 1024;
|
||||
|
||||
/// Maximum time an orderly writer shutdown waits for channel headroom.
|
||||
pub const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
const CHANNEL_RETRY_INTERVAL: Duration = Duration::from_millis(10);
|
||||
const STREAM_HEADER_LEN: usize = 2;
|
||||
|
||||
type IoFuture = Pin<Box<dyn Future<Output = io::Result<()>> + Send + 'static>>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LinkSessionBufferError {
|
||||
#[error("stream id {0} exceeds the 14-bit Buffer stream-id range")]
|
||||
InvalidStreamId(u16),
|
||||
#[error("reader capacity must be greater than zero")]
|
||||
InvalidReaderCapacity,
|
||||
#[error("channel MDU {0} is too small for a Buffer frame")]
|
||||
ChannelMduTooSmall(usize),
|
||||
#[error(transparent)]
|
||||
Channel(#[from] LinkSessionChannelError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ReaderFailure {
|
||||
InvalidFrame,
|
||||
CapacityExceeded,
|
||||
}
|
||||
|
||||
impl ReaderFailure {
|
||||
fn into_io_error(self) -> io::Error {
|
||||
match self {
|
||||
Self::InvalidFrame => {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid channel Buffer frame")
|
||||
}
|
||||
Self::CapacityExceeded => io::Error::new(
|
||||
io::ErrorKind::OutOfMemory,
|
||||
"channel Buffer reader capacity exceeded",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ReaderState {
|
||||
stream_id: u16,
|
||||
reader: StreamReader,
|
||||
capacity: usize,
|
||||
failure: Option<ReaderFailure>,
|
||||
closed: bool,
|
||||
waker: Option<Waker>,
|
||||
}
|
||||
|
||||
impl ReaderState {
|
||||
fn wake(&mut self) -> Option<Waker> {
|
||||
self.waker.take()
|
||||
}
|
||||
|
||||
fn remember_waker(&mut self, waker: &Waker) {
|
||||
if self
|
||||
.waker
|
||||
.as_ref()
|
||||
.is_none_or(|current| !current.will_wake(waker))
|
||||
{
|
||||
self.waker = Some(waker.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read half of a channel-backed Reticulum Buffer stream.
|
||||
///
|
||||
/// Dropping the reader performs best-effort handler deregistration. Call
|
||||
/// [`Self::close`] when deterministic deregistration is required.
|
||||
pub struct LinkSessionBufferReader {
|
||||
channel: LinkSessionChannelHandle,
|
||||
handler_id: Option<rns_protocol::channel::HandlerId>,
|
||||
state: Arc<Mutex<ReaderState>>,
|
||||
}
|
||||
|
||||
impl LinkSessionBufferReader {
|
||||
pub fn stream_id(&self) -> u16 {
|
||||
self.state.lock().map(|state| state.stream_id).unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn available(&self) -> usize {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.reader.available())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn is_eof(&self) -> bool {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.reader.is_eof() || state.closed)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub async fn close(&mut self) -> Result<(), LinkSessionBufferError> {
|
||||
mark_reader_closed(&self.state);
|
||||
if let Some(handler_id) = self.handler_id.take() {
|
||||
let _ = self.channel.remove_message_handler(handler_id).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for LinkSessionBufferReader {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let mut state = match self.state.lock() {
|
||||
Ok(state) => state,
|
||||
Err(_) => {
|
||||
return Poll::Ready(Err(io::Error::other(
|
||||
"channel Buffer reader state is poisoned",
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(failure) = state.failure {
|
||||
return Poll::Ready(Err(failure.into_io_error()));
|
||||
}
|
||||
|
||||
if buffer.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
if let Some(data) = state.reader.read(buffer.remaining()) {
|
||||
buffer.put_slice(&data);
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
if state.closed || state.reader.is_done() {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
state.remember_waker(cx.waker());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LinkSessionBufferReader {
|
||||
fn drop(&mut self) {
|
||||
mark_reader_closed(&self.state);
|
||||
if let Some(handler_id) = self.handler_id.take() {
|
||||
self.channel.try_remove_message_handler(handler_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum WriterState {
|
||||
Open,
|
||||
Sending { accepted: usize, future: IoFuture },
|
||||
Closing { future: IoFuture },
|
||||
Closed,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Write half of a channel-backed Reticulum Buffer stream.
|
||||
///
|
||||
/// Writes are split and compressed by the protocol layer. Shutdown queues EOF
|
||||
/// only after all earlier writer frames have entered the reliable channel
|
||||
/// sequence and the channel has headroom for EOF.
|
||||
pub struct LinkSessionBufferWriter {
|
||||
channel: LinkSessionChannelHandle,
|
||||
writer: StreamWriter,
|
||||
state: WriterState,
|
||||
close_timeout: Duration,
|
||||
}
|
||||
|
||||
impl LinkSessionBufferWriter {
|
||||
pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.close_timeout = timeout;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
matches!(self.state, WriterState::Closed)
|
||||
}
|
||||
|
||||
fn start_write(&mut self, data: &[u8]) -> io::Result<usize> {
|
||||
let accepted = data.len().min(MAX_CHUNK_LEN);
|
||||
let messages = self
|
||||
.writer
|
||||
.write(&data[..accepted])
|
||||
.map_err(io::Error::other)?;
|
||||
self.state = WriterState::Sending {
|
||||
accepted,
|
||||
future: send_messages(self.channel.clone(), messages),
|
||||
};
|
||||
Ok(accepted)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for LinkSessionBufferWriter {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Open => {
|
||||
if buffer.is_empty() {
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
if let Err(error) = this.start_write(buffer) {
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
}
|
||||
WriterState::Sending { accepted, future } => {
|
||||
let accepted = *accepted;
|
||||
match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Open;
|
||||
return Poll::Ready(Ok(accepted));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
WriterState::Closing { .. } | WriterState::Closed => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"channel Buffer writer is closed",
|
||||
)));
|
||||
}
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => this.state = WriterState::Open,
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Open | WriterState::Closed => return Poll::Ready(Ok(())),
|
||||
WriterState::Closing { future } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Closed;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match &mut this.state {
|
||||
WriterState::Sending { future, .. } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => this.state = WriterState::Open,
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Open => {
|
||||
let eof = this.writer.close_simple();
|
||||
this.state = WriterState::Closing {
|
||||
future: drain_then_send_eof(this.channel.clone(), eof, this.close_timeout),
|
||||
};
|
||||
}
|
||||
WriterState::Closing { future } => match future.as_mut().poll(cx) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = WriterState::Closed;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
Poll::Ready(Err(error)) => {
|
||||
let message = error.to_string();
|
||||
this.state = WriterState::Failed(message);
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
},
|
||||
WriterState::Closed => return Poll::Ready(Ok(())),
|
||||
WriterState::Failed(message) => {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
message.clone(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bidirectional channel Buffer with independent receive and send stream IDs.
|
||||
pub struct LinkSessionBuffer {
|
||||
reader: LinkSessionBufferReader,
|
||||
writer: LinkSessionBufferWriter,
|
||||
}
|
||||
|
||||
impl LinkSessionBuffer {
|
||||
pub fn reader(&self) -> &LinkSessionBufferReader {
|
||||
&self.reader
|
||||
}
|
||||
|
||||
pub fn writer(&self) -> &LinkSessionBufferWriter {
|
||||
&self.writer
|
||||
}
|
||||
|
||||
pub async fn close_reader(&mut self) -> Result<(), LinkSessionBufferError> {
|
||||
self.reader.close().await
|
||||
}
|
||||
|
||||
pub fn into_split(self) -> (LinkSessionBufferReader, LinkSessionBufferWriter) {
|
||||
(self.reader, self.writer)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for LinkSessionBuffer {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().reader).poll_read(cx, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for LinkSessionBuffer {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buffer: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_write(cx, buffer)
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().writer).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl LinkSessionChannelHandle {
|
||||
pub async fn create_reader(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
|
||||
self.create_reader_with_capacity(stream_id, DEFAULT_READER_CAPACITY)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_reader_with_capacity(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
capacity: usize,
|
||||
) -> Result<LinkSessionBufferReader, LinkSessionBufferError> {
|
||||
validate_stream_id(stream_id)?;
|
||||
if capacity == 0 {
|
||||
return Err(LinkSessionBufferError::InvalidReaderCapacity);
|
||||
}
|
||||
|
||||
self.register_system_type(SMT_STREAM_DATA).await?;
|
||||
let state = Arc::new(Mutex::new(ReaderState {
|
||||
stream_id,
|
||||
reader: StreamReader::new(stream_id),
|
||||
capacity,
|
||||
failure: None,
|
||||
closed: false,
|
||||
waker: None,
|
||||
}));
|
||||
let weak_state = Arc::downgrade(&state);
|
||||
let handler_id = self
|
||||
.add_message_handler(move |msg_type, payload| {
|
||||
handle_stream_message(&weak_state, stream_id, msg_type, payload)
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(LinkSessionBufferReader {
|
||||
channel: self.clone(),
|
||||
handler_id: Some(handler_id),
|
||||
state,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_writer(
|
||||
&self,
|
||||
stream_id: u16,
|
||||
) -> Result<LinkSessionBufferWriter, LinkSessionBufferError> {
|
||||
validate_stream_id(stream_id)?;
|
||||
let max_data_len = self.mdu().saturating_sub(STREAM_HEADER_LEN);
|
||||
if max_data_len == 0 {
|
||||
return Err(LinkSessionBufferError::ChannelMduTooSmall(self.mdu()));
|
||||
}
|
||||
Ok(LinkSessionBufferWriter {
|
||||
channel: self.clone(),
|
||||
writer: StreamWriter::new(stream_id, max_data_len),
|
||||
state: WriterState::Open,
|
||||
close_timeout: DEFAULT_CLOSE_TIMEOUT,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn create_bidirectional_buffer(
|
||||
&self,
|
||||
receive_stream_id: u16,
|
||||
send_stream_id: u16,
|
||||
) -> Result<LinkSessionBuffer, LinkSessionBufferError> {
|
||||
validate_stream_id(receive_stream_id)?;
|
||||
validate_stream_id(send_stream_id)?;
|
||||
let reader = self.create_reader(receive_stream_id).await?;
|
||||
let writer = self.create_writer(send_stream_id)?;
|
||||
Ok(LinkSessionBuffer { reader, writer })
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_stream_id(stream_id: u16) -> Result<(), LinkSessionBufferError> {
|
||||
if stream_id > STREAM_ID_MAX {
|
||||
return Err(LinkSessionBufferError::InvalidStreamId(stream_id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mark_reader_closed(state: &Arc<Mutex<ReaderState>>) {
|
||||
let wake = state.lock().ok().and_then(|mut state| {
|
||||
state.closed = true;
|
||||
state.wake()
|
||||
});
|
||||
if let Some(waker) = wake {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_stream_message(
|
||||
weak_state: &Weak<Mutex<ReaderState>>,
|
||||
stream_id: u16,
|
||||
msg_type: u16,
|
||||
payload: &[u8],
|
||||
) -> bool {
|
||||
if msg_type != SMT_STREAM_DATA || payload.len() < STREAM_HEADER_LEN {
|
||||
return false;
|
||||
}
|
||||
let encoded_stream_id = u16::from_be_bytes([payload[0], payload[1]]) & STREAM_ID_MAX;
|
||||
if encoded_stream_id != stream_id {
|
||||
return false;
|
||||
}
|
||||
let Some(state) = weak_state.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut message = StreamDataMessage::new(0, Vec::new(), false);
|
||||
let decoded = message.unpack(payload);
|
||||
let wake = match state.lock() {
|
||||
Ok(mut state) => {
|
||||
if state.closed {
|
||||
return false;
|
||||
}
|
||||
if state.failure.is_some() {
|
||||
return true;
|
||||
} else if decoded.is_err() {
|
||||
state.failure = Some(ReaderFailure::InvalidFrame);
|
||||
} else if message.data.len() > state.capacity.saturating_sub(state.reader.available()) {
|
||||
state.failure = Some(ReaderFailure::CapacityExceeded);
|
||||
} else {
|
||||
state.reader.feed(&message);
|
||||
}
|
||||
state.wake()
|
||||
}
|
||||
Err(_) => return true,
|
||||
};
|
||||
if let Some(waker) = wake {
|
||||
waker.wake();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn send_messages(channel: LinkSessionChannelHandle, messages: Vec<StreamDataMessage>) -> IoFuture {
|
||||
Box::pin(async move {
|
||||
for message in messages {
|
||||
let msg_type = message.msg_type();
|
||||
let payload = message.pack();
|
||||
loop {
|
||||
match channel.send_raw(msg_type, payload.clone()).await {
|
||||
Ok(_) => break,
|
||||
Err(LinkSessionChannelError::Channel(ChannelError::NotReady)) => {
|
||||
tokio::time::sleep(CHANNEL_RETRY_INTERVAL).await;
|
||||
}
|
||||
Err(error) => return Err(io::Error::other(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn drain_then_send_eof(
|
||||
channel: LinkSessionChannelHandle,
|
||||
eof: StreamDataMessage,
|
||||
close_timeout: Duration,
|
||||
) -> IoFuture {
|
||||
Box::pin(async move {
|
||||
tokio::time::timeout(close_timeout, send_messages(channel, vec![eof]))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"timed out draining channel Buffer writer",
|
||||
)
|
||||
})?
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn reader_state(stream_id: u16, capacity: usize) -> Arc<Mutex<ReaderState>> {
|
||||
Arc::new(Mutex::new(ReaderState {
|
||||
stream_id,
|
||||
reader: StreamReader::new(stream_id),
|
||||
capacity,
|
||||
failure: None,
|
||||
closed: false,
|
||||
waker: None,
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_routes_only_the_matching_stream() {
|
||||
let state = reader_state(7, 128);
|
||||
let weak = Arc::downgrade(&state);
|
||||
|
||||
let wrong = StreamDataMessage::new(8, b"wrong".to_vec(), false).pack();
|
||||
assert!(!handle_stream_message(&weak, 7, SMT_STREAM_DATA, &wrong));
|
||||
assert_eq!(state.lock().unwrap().reader.available(), 0);
|
||||
|
||||
let matching = StreamDataMessage::new(7, b"hello".to_vec(), true).pack();
|
||||
assert!(handle_stream_message(&weak, 7, SMT_STREAM_DATA, &matching));
|
||||
let mut state = state.lock().unwrap();
|
||||
assert_eq!(state.reader.read_all().unwrap(), b"hello");
|
||||
assert!(state.reader.is_done());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_fails_closed_at_reader_capacity() {
|
||||
let state = reader_state(1, 4);
|
||||
let weak = Arc::downgrade(&state);
|
||||
let oversized = StreamDataMessage::new(1, b"12345".to_vec(), false).pack();
|
||||
|
||||
assert!(handle_stream_message(&weak, 1, SMT_STREAM_DATA, &oversized));
|
||||
let state = state.lock().unwrap();
|
||||
assert!(matches!(
|
||||
state.failure,
|
||||
Some(ReaderFailure::CapacityExceeded)
|
||||
));
|
||||
assert_eq!(state.reader.available(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handler_reports_invalid_compressed_payload() {
|
||||
let state = reader_state(2, 128);
|
||||
let weak = Arc::downgrade(&state);
|
||||
let mut malformed = (0x4000_u16 | 2).to_be_bytes().to_vec();
|
||||
malformed.extend_from_slice(b"not bzip2");
|
||||
|
||||
assert!(handle_stream_message(&weak, 2, SMT_STREAM_DATA, &malformed));
|
||||
assert!(matches!(
|
||||
state.lock().unwrap().failure,
|
||||
Some(ReaderFailure::InvalidFrame)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_the_full_stream_id_range() {
|
||||
assert!(validate_stream_id(STREAM_ID_MAX).is_ok());
|
||||
assert!(matches!(
|
||||
validate_stream_id(STREAM_ID_MAX + 1),
|
||||
Err(LinkSessionBufferError::InvalidStreamId(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
//! App-facing ownership for an inbound SINGLE destination.
|
||||
//!
|
||||
//! Python binds Destination construction, transport registration, Link
|
||||
//! handling, and callbacks to process-global state. This facade keeps those
|
||||
//! responsibilities explicit: one registration owns one responder
|
||||
//! [`LinkManager`], exposes bounded event receivers, and deregisters when
|
||||
//! closed.
|
||||
|
||||
use rns_identity::destination::{
|
||||
AllowPolicy, DefaultAppData, DestType, Destination, DestinationError, Direction, ProofStrategy,
|
||||
};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
use rns_protocol::channel::ChannelError;
|
||||
use rns_protocol::channel_message::{ChannelMessageError, MessageBase};
|
||||
use rns_protocol::resource_adv::ResourceAdvertisement;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
use crate::link_manager::{
|
||||
ChannelSendError, ChannelSendReceipt, DestinationAnnounceOptions, DestinationControlError,
|
||||
DestinationRequest, LinkChannelMessage, LinkManager, LinkManagerCommand, LinkPacketProof,
|
||||
LinkPacketSendReceipt, LinkPayloadSendReceipt, LinkResourceEvent, LinkResourceProof,
|
||||
LinkResourceSendReceipt, LinkSendError, RequestOutcome, ResourceCompletion,
|
||||
};
|
||||
|
||||
const DEFAULT_EVENT_CAPACITY: usize = 128;
|
||||
const COMMAND_CAPACITY: usize = 256;
|
||||
|
||||
type ResourceAcceptCallback = dyn Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DestinationRuntimeOptions {
|
||||
pub proof_strategy: ProofStrategy,
|
||||
pub accepts_links: bool,
|
||||
pub resource_strategy: ResourceStrategy,
|
||||
pub event_capacity: usize,
|
||||
/// Announce app data used whenever an announce (including a path
|
||||
/// response) carries none explicitly.
|
||||
pub default_app_data: Option<Vec<u8>>,
|
||||
/// Per-advertisement acceptance policy consulted when
|
||||
/// `resource_strategy` is `AcceptApp`.
|
||||
pub resource_accept: Option<ResourceAcceptPolicy>,
|
||||
/// Synchronous LinkIdentify gate; returning false closes the link.
|
||||
pub identity_gate: Option<IdentityGatePolicy>,
|
||||
/// User Channel message types registered before the manager starts.
|
||||
pub channel_message_types: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Default for DestinationRuntimeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
proof_strategy: ProofStrategy::ProveNone,
|
||||
accepts_links: true,
|
||||
resource_strategy: ResourceStrategy::AcceptNone,
|
||||
event_capacity: DEFAULT_EVENT_CAPACITY,
|
||||
default_app_data: None,
|
||||
resource_accept: None,
|
||||
identity_gate: None,
|
||||
channel_message_types: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clonable per-advertisement inbound Resource acceptance policy.
|
||||
#[derive(Clone)]
|
||||
pub struct ResourceAcceptPolicy(Arc<ResourceAcceptCallback>);
|
||||
|
||||
impl ResourceAcceptPolicy {
|
||||
pub fn new(
|
||||
policy: impl Fn([u8; 16], &ResourceAdvertisement) -> bool + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self(Arc::new(policy))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ResourceAcceptPolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("ResourceAcceptPolicy")
|
||||
}
|
||||
}
|
||||
|
||||
/// Clonable synchronous LinkIdentify gate, consulted before any later
|
||||
/// resource advertisement can race the admission decision.
|
||||
#[derive(Clone)]
|
||||
pub struct IdentityGatePolicy(Arc<dyn Fn([u8; 16], [u8; 16]) -> bool + Send + Sync>);
|
||||
|
||||
impl IdentityGatePolicy {
|
||||
pub fn new(gate: impl Fn([u8; 16], [u8; 16]) -> bool + Send + Sync + 'static) -> Self {
|
||||
Self(Arc::new(gate))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for IdentityGatePolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("IdentityGatePolicy")
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent forward-secrecy settings for a live inbound destination.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DestinationRatchetOptions {
|
||||
/// Signed Python-compatible ratchet-ring file.
|
||||
pub path: PathBuf,
|
||||
/// Reject packets encrypted only to the base identity key.
|
||||
pub enforce: bool,
|
||||
}
|
||||
|
||||
impl DestinationRatchetOptions {
|
||||
/// Use `path` with ratchet enforcement disabled.
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
enforce: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DestinationPacket {
|
||||
pub data: Vec<u8>,
|
||||
pub raw: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Event receivers owned by one registered destination. All are bounded by
|
||||
/// `event_capacity` except `link_packets`: inbound link data is proved to the
|
||||
/// peer on receipt, so its local delivery is lossless and must be drained.
|
||||
pub struct DestinationEvents {
|
||||
pub packets: mpsc::Receiver<DestinationPacket>,
|
||||
pub links_established: mpsc::Receiver<[u8; 16]>,
|
||||
pub links_identified: mpsc::Receiver<([u8; 16], [u8; 16])>,
|
||||
pub link_packets: mpsc::UnboundedReceiver<(Vec<u8>, [u8; 16])>,
|
||||
pub link_packet_proofs: mpsc::Receiver<LinkPacketProof>,
|
||||
pub resource_completions: mpsc::Receiver<ResourceCompletion>,
|
||||
pub resource_proofs: mpsc::Receiver<LinkResourceProof>,
|
||||
pub resource_events: mpsc::Receiver<LinkResourceEvent>,
|
||||
pub channel_messages: mpsc::Receiver<LinkChannelMessage>,
|
||||
pub links_closed: mpsc::Receiver<[u8; 16]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DestinationRuntimeError {
|
||||
#[error(transparent)]
|
||||
Destination(#[from] DestinationError),
|
||||
#[error(transparent)]
|
||||
Control(#[from] DestinationControlError),
|
||||
#[error(transparent)]
|
||||
LinkSend(#[from] LinkSendError),
|
||||
#[error(transparent)]
|
||||
ChannelSend(#[from] ChannelSendError),
|
||||
#[error(transparent)]
|
||||
Channel(#[from] ChannelError),
|
||||
#[error("destination event capacity must be greater than zero")]
|
||||
InvalidEventCapacity,
|
||||
#[error("destination manager is no longer available")]
|
||||
ManagerUnavailable,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DestinationHandle {
|
||||
destination_hash: [u8; 16],
|
||||
app_name: String,
|
||||
command_tx: mpsc::Sender<LinkManagerCommand>,
|
||||
}
|
||||
|
||||
impl DestinationHandle {
|
||||
pub fn destination_hash(&self) -> [u8; 16] {
|
||||
self.destination_hash
|
||||
}
|
||||
|
||||
pub fn app_name(&self) -> &str {
|
||||
&self.app_name
|
||||
}
|
||||
|
||||
pub async fn announce(
|
||||
&self,
|
||||
options: DestinationAnnounceOptions,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::AnnounceWith {
|
||||
options,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_accepts_links(&self, accepts: bool) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SetAcceptsLinks {
|
||||
accepts,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set or clear the default app data used whenever an announce (including
|
||||
/// a path response) carries none explicitly.
|
||||
pub async fn set_default_app_data(
|
||||
&self,
|
||||
app_data: Option<Vec<u8>>,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SetDefaultAppData {
|
||||
app_data,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn register_request_handler<F>(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
allow: AllowPolicy,
|
||||
allowed_list: Vec<[u8; 16]>,
|
||||
auto_compress: bool,
|
||||
handler: F,
|
||||
) -> Result<bool, DestinationRuntimeError>
|
||||
where
|
||||
F: Fn(DestinationRequest) -> RequestOutcome + Send + 'static,
|
||||
{
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::RegisterRequestHandler {
|
||||
path: path.into(),
|
||||
allow,
|
||||
allowed_list,
|
||||
auto_compress,
|
||||
handler: Box::new(handler),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn deregister_request_handler(
|
||||
&self,
|
||||
path: impl Into<String>,
|
||||
) -> Result<bool, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::DeregisterRequestHandler {
|
||||
path: path.into(),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn send_link_packet(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
) -> Result<LinkPacketSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkPacket {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_link_resource(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkResourceSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkResource {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
auto_compress,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_link_payload(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
payload: impl Into<Vec<u8>>,
|
||||
auto_compress: bool,
|
||||
) -> Result<LinkPayloadSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendLinkPayload {
|
||||
link_id,
|
||||
payload: payload.into(),
|
||||
auto_compress,
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn send_channel(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
msg_type: u16,
|
||||
payload: impl Into<Vec<u8>>,
|
||||
) -> Result<ChannelSendReceipt, DestinationRuntimeError> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::SendChannelMessage {
|
||||
link_id,
|
||||
message: Box::new(RawChannelMessage {
|
||||
msg_type,
|
||||
payload: payload.into(),
|
||||
}),
|
||||
result_tx: Some(result_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
Ok(result_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)??)
|
||||
}
|
||||
|
||||
pub async fn close_link(
|
||||
&self,
|
||||
link_id: [u8; 16],
|
||||
reason: CloseReason,
|
||||
send_teardown: bool,
|
||||
) -> Result<(), DestinationRuntimeError> {
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::CloseLink {
|
||||
link_id,
|
||||
reason,
|
||||
send_teardown,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) -> Result<(), DestinationRuntimeError> {
|
||||
self.command_tx
|
||||
.send(LinkManagerCommand::Shutdown)
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns one live inbound destination and its responder Link manager.
|
||||
pub struct RegisteredDestination {
|
||||
pub handle: DestinationHandle,
|
||||
pub events: DestinationEvents,
|
||||
stopped_rx: Option<oneshot::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl RegisteredDestination {
|
||||
pub async fn register(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
Self::register_inner(transport_tx, identity, app_name, options, None).await
|
||||
}
|
||||
|
||||
/// Register a live destination whose announce rotation and inbound
|
||||
/// decryption are backed by one verified persistent ratchet ring.
|
||||
pub async fn register_ratcheted(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
ratchet_options: DestinationRatchetOptions,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
Self::register_inner(
|
||||
transport_tx,
|
||||
identity,
|
||||
app_name,
|
||||
options,
|
||||
Some(ratchet_options),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn register_inner(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
identity: Identity,
|
||||
app_name: impl Into<String>,
|
||||
options: DestinationRuntimeOptions,
|
||||
ratchet_options: Option<DestinationRatchetOptions>,
|
||||
) -> Result<Self, DestinationRuntimeError> {
|
||||
if options.event_capacity == 0 {
|
||||
return Err(DestinationRuntimeError::InvalidEventCapacity);
|
||||
}
|
||||
let app_name = app_name.into();
|
||||
let destination =
|
||||
Destination::new(Some(&identity), Direction::In, DestType::Single, &app_name)?;
|
||||
let destination_hash = destination.hash;
|
||||
let (delivery_tx, delivery_rx) = mpsc::channel(options.event_capacity);
|
||||
|
||||
let mut manager = LinkManager::with_destination(
|
||||
transport_tx.clone(),
|
||||
delivery_rx,
|
||||
&identity,
|
||||
&app_name,
|
||||
identity.get_signing_key(),
|
||||
);
|
||||
if let Some(ratchet_options) = ratchet_options {
|
||||
manager.enable_persistent_ratchets(ratchet_options.path, ratchet_options.enforce)?;
|
||||
}
|
||||
manager.set_resource_strategy(options.resource_strategy);
|
||||
manager.set_use_implicit_proof(true);
|
||||
if let Some(policy) = options.resource_accept.clone() {
|
||||
manager.set_resource_accept_handler(move |link_id, adv| (policy.0)(link_id, adv));
|
||||
}
|
||||
if let Some(gate) = options.identity_gate.clone() {
|
||||
manager.set_link_identity_gate(move |link_id, identity| (gate.0)(link_id, identity));
|
||||
}
|
||||
for msg_type in &options.channel_message_types {
|
||||
manager.register_channel_message_type(*msg_type)?;
|
||||
}
|
||||
let owned_destination = manager
|
||||
.destination_mut()
|
||||
.ok_or(DestinationControlError::DestinationUnavailable)?;
|
||||
owned_destination.set_proof_strategy(options.proof_strategy);
|
||||
owned_destination.set_accepts_links(options.accepts_links);
|
||||
if let Some(app_data) = options.default_app_data.clone() {
|
||||
owned_destination.set_default_app_data(DefaultAppData::Static(app_data));
|
||||
}
|
||||
|
||||
transport_tx
|
||||
.send(TransportMessage::RegisterDestination {
|
||||
hash: destination_hash,
|
||||
app_name: app_name.clone(),
|
||||
delivery_tx: Some(delivery_tx),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
|
||||
let capacity = options.event_capacity;
|
||||
let (packet_tx, packets) = mpsc::channel(capacity);
|
||||
owned_destination.set_packet_callback(Box::new(move |data, raw| {
|
||||
let _ = packet_tx.try_send(DestinationPacket {
|
||||
data: data.to_vec(),
|
||||
raw: raw.to_vec(),
|
||||
});
|
||||
}));
|
||||
|
||||
let (links_established_tx, links_established) = mpsc::channel(capacity);
|
||||
let (links_identified_tx, links_identified) = mpsc::channel(capacity);
|
||||
let (link_packets_tx, link_packets) = mpsc::unbounded_channel();
|
||||
let (link_packet_proofs_tx, link_packet_proofs) = mpsc::channel(capacity);
|
||||
let (resource_completions_tx, resource_completions) = mpsc::channel(capacity);
|
||||
let (resource_proofs_tx, resource_proofs) = mpsc::channel(capacity);
|
||||
let (resource_events_tx, resource_events) = mpsc::channel(capacity);
|
||||
let (channel_messages_tx, channel_messages) = mpsc::channel(capacity);
|
||||
let (links_closed_tx, links_closed) = mpsc::channel(capacity);
|
||||
manager.set_link_established_channel(links_established_tx);
|
||||
manager.set_link_identified_channel(links_identified_tx);
|
||||
manager.set_link_packet_channel(link_packets_tx);
|
||||
manager.set_link_packet_proof_channel(link_packet_proofs_tx);
|
||||
manager.set_resource_completion_channel(resource_completions_tx);
|
||||
manager.set_outbound_resource_proof_channel(resource_proofs_tx);
|
||||
manager.set_resource_event_channel(resource_events_tx);
|
||||
manager.set_channel_message_channel(channel_messages_tx);
|
||||
manager.set_link_closed_channel(links_closed_tx);
|
||||
|
||||
let (command_tx, command_rx) = mpsc::channel(COMMAND_CAPACITY);
|
||||
let (stopped_tx, stopped_rx) = oneshot::channel();
|
||||
let manager_transport_tx = transport_tx;
|
||||
tokio::spawn(async move {
|
||||
manager.run_with_commands(command_rx).await;
|
||||
let _ = manager_transport_tx
|
||||
.send(TransportMessage::DeregisterDestination {
|
||||
hash: destination_hash,
|
||||
})
|
||||
.await;
|
||||
let _ = stopped_tx.send(());
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
handle: DestinationHandle {
|
||||
destination_hash,
|
||||
app_name,
|
||||
command_tx,
|
||||
},
|
||||
events: DestinationEvents {
|
||||
packets,
|
||||
links_established,
|
||||
links_identified,
|
||||
link_packets,
|
||||
link_packet_proofs,
|
||||
resource_completions,
|
||||
resource_proofs,
|
||||
resource_events,
|
||||
channel_messages,
|
||||
links_closed,
|
||||
},
|
||||
stopped_rx: Some(stopped_rx),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn close(mut self) -> Result<(), DestinationRuntimeError> {
|
||||
self.handle.shutdown().await?;
|
||||
if let Some(stopped_rx) = self.stopped_rx.take() {
|
||||
stopped_rx
|
||||
.await
|
||||
.map_err(|_| DestinationRuntimeError::ManagerUnavailable)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RegisteredDestination {
|
||||
fn drop(&mut self) {
|
||||
let command = LinkManagerCommand::Shutdown;
|
||||
match self.handle.command_tx.try_send(command) {
|
||||
Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
|
||||
Err(mpsc::error::TrySendError::Full(command)) => {
|
||||
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
|
||||
let command_tx = self.handle.command_tx.clone();
|
||||
runtime.spawn(async move {
|
||||
let _ = command_tx.send(command).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RawChannelMessage {
|
||||
msg_type: u16,
|
||||
payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl MessageBase for RawChannelMessage {
|
||||
fn msg_type(&self) -> u16 {
|
||||
self.msg_type
|
||||
}
|
||||
|
||||
fn pack(&self) -> Vec<u8> {
|
||||
self.payload.clone()
|
||||
}
|
||||
|
||||
fn unpack(&mut self, raw: &[u8]) -> Result<(), ChannelMessageError> {
|
||||
self.payload = raw.to_vec();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::link_session::{LinkSession, LinkSessionConfig, LinkSessionEvent};
|
||||
use rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN;
|
||||
use rns_transport::actor::TransportActor;
|
||||
use rns_transport::messages::TransportMessage;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn register_applies_policy_options_and_rejects_reserved_channel_types() {
|
||||
let identity = Identity::new();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
|
||||
let reserved = RegisteredDestination::register(
|
||||
transport_tx.clone(),
|
||||
identity.clone(),
|
||||
"example.runtime.policies",
|
||||
DestinationRuntimeOptions {
|
||||
channel_message_types: vec![SYSTEM_MESSAGE_TYPE_MIN],
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(reserved, Err(DestinationRuntimeError::Channel(_))));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"a reserved channel type must fail before transport registration"
|
||||
);
|
||||
|
||||
let registration = RegisteredDestination::register(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime.policies",
|
||||
DestinationRuntimeOptions {
|
||||
resource_strategy: ResourceStrategy::AcceptApp,
|
||||
resource_accept: Some(ResourceAcceptPolicy::new(|_, _| false)),
|
||||
identity_gate: Some(IdentityGatePolicy::new(|_, _| true)),
|
||||
channel_message_types: vec![0x0100],
|
||||
default_app_data: Some(b"policy app data".to_vec()),
|
||||
..DestinationRuntimeOptions::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("valid policy options must register");
|
||||
registration.close().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn registration_announces_and_deregisters_exact_destination() {
|
||||
let identity = Identity::new();
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
let registration = RegisteredDestination::register(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime",
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::RegisterDestination { hash, .. }) if hash == destination_hash
|
||||
));
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
app_data: Some(b"hello".to_vec()),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::Outbound(_)) | Some(TransportMessage::OutboundAttached { .. })
|
||||
));
|
||||
|
||||
registration.close().await.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn link_session_connects_to_destination_on_same_transport_actor() {
|
||||
let (actor, transport_tx) = TransportActor::new();
|
||||
let actor_task = tokio::spawn(actor.run());
|
||||
let server_identity = Identity::new();
|
||||
let server_public_key = server_identity.get_public_key();
|
||||
let mut registration = RegisteredDestination::register(
|
||||
transport_tx.clone(),
|
||||
server_identity,
|
||||
"example.runtime.loopback",
|
||||
DestinationRuntimeOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
let client_identity = Identity::new();
|
||||
let expected_client = client_identity.hash;
|
||||
|
||||
let mut session = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
LinkSession::connect(
|
||||
transport_tx.clone(),
|
||||
client_identity,
|
||||
LinkSessionConfig {
|
||||
destination_hash,
|
||||
remote_public_key: server_public_key,
|
||||
hops: 1,
|
||||
establishment_timeout: Duration::from_secs(2),
|
||||
client_label: "test.same-actor-link".into(),
|
||||
identify: true,
|
||||
track_phy_stats: false,
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("same-actor Link establishment timed out")
|
||||
.expect("same-actor Link establishment failed");
|
||||
let link_id = session.handle.link_id();
|
||||
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.links_established.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(link_id)
|
||||
);
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.links_identified.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some((link_id, expected_client))
|
||||
);
|
||||
|
||||
session
|
||||
.handle
|
||||
.send_packet(b"client to server".to_vec())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
registration.events.link_packets.recv()
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Some((b"client to server".to_vec(), link_id))
|
||||
);
|
||||
|
||||
registration
|
||||
.handle
|
||||
.send_link_packet(link_id, b"server to client".to_vec())
|
||||
.await
|
||||
.unwrap();
|
||||
let received = tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
if let Some(LinkSessionEvent::Packet { data, .. }) = session.events.recv().await {
|
||||
break data;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(received, b"server to client");
|
||||
|
||||
session.handle.close().await;
|
||||
registration.close().await.unwrap();
|
||||
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
actor_task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ratcheted_registration_advertises_and_decrypts_owned_ring() {
|
||||
let identity = Identity::new();
|
||||
let app_name = "example.runtime.ratcheted";
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("reticulum_runtime_ratchets_{}", identity.hexhash()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ratchet_path = dir.join("ratchets");
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(16);
|
||||
|
||||
let mut registration = RegisteredDestination::register_ratcheted(
|
||||
transport_tx,
|
||||
identity.clone(),
|
||||
app_name,
|
||||
DestinationRuntimeOptions::default(),
|
||||
DestinationRatchetOptions {
|
||||
path: ratchet_path.clone(),
|
||||
enforce: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let destination_hash = registration.handle.destination_hash();
|
||||
let delivery_tx = match transport_rx.recv().await.unwrap() {
|
||||
TransportMessage::RegisterDestination {
|
||||
hash,
|
||||
delivery_tx: Some(delivery_tx),
|
||||
..
|
||||
} => {
|
||||
assert_eq!(hash, destination_hash);
|
||||
delivery_tx
|
||||
}
|
||||
other => panic!("expected destination registration, got {other:?}"),
|
||||
};
|
||||
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let announce_raw = match transport_rx.recv().await.unwrap() {
|
||||
TransportMessage::Outbound(request) => request.raw,
|
||||
TransportMessage::OutboundAttached { request, .. } => request.raw,
|
||||
other => panic!("expected ratcheted announce, got {other:?}"),
|
||||
};
|
||||
let (announce_header, _) = rns_wire::header::PacketHeader::unpack(&announce_raw).unwrap();
|
||||
assert_eq!(
|
||||
announce_header.flags.packet_type,
|
||||
rns_wire::flags::PacketType::Announce
|
||||
);
|
||||
assert!(announce_header.flags.context_flag);
|
||||
|
||||
let ratchet = rns_identity::ratchet::RatchetRing::load_verified(&ratchet_path, &identity)
|
||||
.unwrap()
|
||||
.ring()
|
||||
.current_public_key()
|
||||
.unwrap();
|
||||
let mut wrong_ratchet = ratchet;
|
||||
wrong_ratchet[0] ^= 0xFF;
|
||||
assert!(matches!(
|
||||
registration
|
||||
.handle
|
||||
.announce(DestinationAnnounceOptions {
|
||||
ratchet: Some(wrong_ratchet),
|
||||
..DestinationAnnounceOptions::default()
|
||||
})
|
||||
.await,
|
||||
Err(DestinationRuntimeError::Control(
|
||||
DestinationControlError::ManagedRatchetMismatch
|
||||
))
|
||||
));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"a mismatched managed ratchet must not be advertised"
|
||||
);
|
||||
|
||||
let public_identity = Identity::from_public_key(&identity.get_public_key()).unwrap();
|
||||
let mut outbound = Destination::new(
|
||||
Some(&public_identity),
|
||||
Direction::Out,
|
||||
DestType::Single,
|
||||
app_name,
|
||||
)
|
||||
.unwrap();
|
||||
outbound.set_remote_ratchet(ratchet);
|
||||
let ciphertext = outbound
|
||||
.encrypt(
|
||||
b"forward secret",
|
||||
&public_identity,
|
||||
outbound.remote_ratchet_pub.as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
let packet = rns_wire::packet::Packet::new(
|
||||
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::Data,
|
||||
},
|
||||
hops: 0,
|
||||
transport_id: None,
|
||||
destination_hash,
|
||||
context: rns_wire::context::PacketContext::None,
|
||||
},
|
||||
ciphertext,
|
||||
)
|
||||
.unwrap();
|
||||
delivery_tx
|
||||
.send(
|
||||
rns_transport::link_messages::DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(packet.raw),
|
||||
interface_id: 1,
|
||||
metrics: rns_transport::link_messages::PacketMetrics::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let delivered = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
registration.events.packets.recv(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(delivered.data, b"forward secret");
|
||||
|
||||
registration.close().await.unwrap();
|
||||
assert!(matches!(
|
||||
transport_rx.recv().await,
|
||||
Some(TransportMessage::DeregisterDestination { hash }) if hash == destination_hash
|
||||
));
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_ratchet_setup_does_not_leak_transport_registration() {
|
||||
let identity = Identity::new();
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"reticulum_runtime_missing_ratchets_{}",
|
||||
identity.hexhash()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let ratchet_path = root.join("missing").join("ratchets");
|
||||
let (transport_tx, mut transport_rx) = mpsc::channel(4);
|
||||
|
||||
let result = RegisteredDestination::register_ratcheted(
|
||||
transport_tx,
|
||||
identity,
|
||||
"example.runtime.ratchet-failure",
|
||||
DestinationRuntimeOptions::default(),
|
||||
DestinationRatchetOptions::new(ratchet_path),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(DestinationRuntimeError::Control(
|
||||
DestinationControlError::RatchetPersistence(_)
|
||||
))
|
||||
));
|
||||
assert!(
|
||||
transport_rx.try_recv().is_err(),
|
||||
"failed local setup must not register a destination with transport"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,64 @@
|
||||
//! Reticulum runtime: config, lifecycle, RPC, and the [`reticulum::ReticulumHandle`]
|
||||
//! that user code holds. Python reference: `RNS/Reticulum.py`.
|
||||
|
||||
pub mod buffer_stream;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod destination_runtime;
|
||||
pub mod interface_factory;
|
||||
mod interface_registry;
|
||||
pub mod jobs;
|
||||
pub mod lifecycle;
|
||||
pub mod link_client;
|
||||
pub mod link_manager;
|
||||
pub mod link_session;
|
||||
pub mod platform;
|
||||
pub mod probe;
|
||||
pub mod remote_management;
|
||||
pub mod remote_management_schema;
|
||||
pub mod resource_source;
|
||||
pub mod reticulum;
|
||||
pub mod rncp;
|
||||
pub mod rnsh;
|
||||
pub mod rpc;
|
||||
pub mod rpc_server;
|
||||
|
||||
/// Common application-facing types for Reticulum programs.
|
||||
///
|
||||
/// This is additive convenience; module-qualified paths remain supported.
|
||||
pub mod prelude {
|
||||
pub use crate::destination_runtime::{
|
||||
DestinationEvents, DestinationHandle, DestinationPacket, DestinationRatchetOptions,
|
||||
DestinationRuntimeError, DestinationRuntimeOptions, IdentityGatePolicy,
|
||||
RegisteredDestination, ResourceAcceptPolicy,
|
||||
};
|
||||
pub use crate::lifecycle::ShutdownSignal;
|
||||
pub use crate::link_manager::{DestinationAnnounceOptions, DestinationRequest, RequestOutcome};
|
||||
pub use crate::link_session::{
|
||||
LinkSession, LinkSessionChannelError, LinkSessionChannelHandle, LinkSessionCloseReason,
|
||||
LinkSessionError, LinkSessionEvent, LinkSessionHandle, LinkSessionResourceError,
|
||||
LinkSessionResourceOffer, LinkSessionResponse,
|
||||
};
|
||||
pub use crate::resource_source::{ResourceOptions, ResourceSource};
|
||||
pub use crate::reticulum::{
|
||||
AnnounceSubscription, ControlError, InitOptions, InterfaceStats, LinkConnectError,
|
||||
LinkConnectOptions, OutboundPacket, PacketReceiptHandle, PacketReceiptStatus,
|
||||
RNodeReadinessError, RNodeRuntimeLookupError, RNodeRuntimeObserver, RNodeRuntimeSpawnError,
|
||||
RecalledDestination, ReceiptError, ReticulumError, ReticulumHandle, SendError, SendOptions,
|
||||
SendResult, SpawnedRNodeRuntime, StartupRNodeRuntime, init, init_with_options,
|
||||
init_with_options_and_rnode_startup_options,
|
||||
};
|
||||
pub use rns_identity::destination::{
|
||||
AllowPolicy, DestType, Destination, DestinationPacketError, DestinationPacketOptions,
|
||||
Direction, PackedDestinationPacket, ProofStrategy,
|
||||
};
|
||||
pub use rns_identity::identity::Identity;
|
||||
pub use rns_identity::ratchet::PersistentRatchetRing;
|
||||
pub use rns_interface::rnode::{
|
||||
RNodeCapabilityAdmissionError, RNodeCapabilityAdmissionFailureClass, RNodeCapabilityState,
|
||||
RNodeConfigurationState, RNodeDetectionState, RNodeFirmwareCompatibility,
|
||||
RNodeObservedRadioState, RNodeRuntimePhase, RNodeRuntimeReason, RNodeRuntimeSnapshot,
|
||||
RNodeSpawnError, RNodeStartupOptions, RNodeTransmitFlowState, RNodeTransportClass,
|
||||
};
|
||||
pub use rns_link::link::{CloseReason, ResourceStrategy};
|
||||
}
|
||||
@@ -32,10 +32,15 @@ impl ShutdownSignal {
|
||||
}
|
||||
|
||||
pub async fn wait(&self) {
|
||||
if self.is_triggered() {
|
||||
return;
|
||||
loop {
|
||||
let notified = self.notify.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.is_triggered() {
|
||||
return;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
self.notify.notified().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,33 +80,50 @@ impl Default for ExitHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a Ctrl-C (SIGINT) handler that trips `shutdown`. Returned receiver
|
||||
/// yields once on signal for await-based callers.
|
||||
/// Install process-signal handlers that trip `shutdown`. On Unix this covers
|
||||
/// both SIGINT and SIGTERM; other platforms use the runtime's Ctrl-C handler.
|
||||
/// The returned receiver yields once on the first signal for await-based
|
||||
/// callers.
|
||||
///
|
||||
/// On unix the OS-level registration happens synchronously in this call — a
|
||||
/// handler registered inside a spawned task only takes effect once that task
|
||||
/// is first polled, leaving a window where SIGINT kills the process via the
|
||||
/// is first polled, leaving a window where a signal kills the process via the
|
||||
/// default disposition.
|
||||
pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let shutdown_clone = shutdown.clone();
|
||||
|
||||
#[cfg(unix)]
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
|
||||
Ok(mut sigint) => {
|
||||
tokio::spawn(async move {
|
||||
sigint.recv().await;
|
||||
signal_shutdown(shutdown_clone, tx).await;
|
||||
});
|
||||
{
|
||||
let shutdown_clone = shutdown.clone();
|
||||
let tx_clone = tx.clone();
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) {
|
||||
Ok(mut sigint) => {
|
||||
tokio::spawn(async move {
|
||||
sigint.recv().await;
|
||||
signal_shutdown(shutdown_clone, tx_clone, "SIGINT");
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
|
||||
spawn_ctrl_c_handler(shutdown.clone(), tx.clone());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGINT registration failed; falling back to ctrl_c");
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
|
||||
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
Ok(mut sigterm) => {
|
||||
tokio::spawn(async move {
|
||||
sigterm.recv().await;
|
||||
signal_shutdown(shutdown, tx, "SIGTERM");
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "SIGTERM registration failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
spawn_ctrl_c_handler(shutdown_clone, tx);
|
||||
spawn_ctrl_c_handler(shutdown, tx);
|
||||
|
||||
rx
|
||||
}
|
||||
@@ -109,14 +131,14 @@ pub fn install_signal_handlers(shutdown: ShutdownSignal) -> mpsc::Receiver<()> {
|
||||
fn spawn_ctrl_c_handler(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tokio::spawn(async move {
|
||||
tokio::signal::ctrl_c().await.ok();
|
||||
signal_shutdown(shutdown, tx).await;
|
||||
signal_shutdown(shutdown, tx, "Ctrl-C");
|
||||
});
|
||||
}
|
||||
|
||||
async fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>) {
|
||||
tracing::info!("received shutdown signal");
|
||||
fn signal_shutdown(shutdown: ShutdownSignal, tx: mpsc::Sender<()>, signal: &'static str) {
|
||||
tracing::info!(signal, "received shutdown signal");
|
||||
shutdown.trigger();
|
||||
let _ = tx.send(()).await;
|
||||
let _ = tx.try_send(());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -171,4 +193,13 @@ mod tests {
|
||||
signal.wait().await;
|
||||
assert!(signal.is_triggered());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_shutdown_wait_after_trigger() {
|
||||
let signal = ShutdownSignal::new();
|
||||
signal.trigger();
|
||||
tokio::time::timeout(std::time::Duration::from_millis(50), signal.wait())
|
||||
.await
|
||||
.expect("pre-triggered shutdown wait must return");
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::timeout;
|
||||
|
||||
use rns_crypto::ed25519::Ed25519PublicKey;
|
||||
@@ -17,7 +17,9 @@ use rns_link::link::{CloseReason, Link};
|
||||
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};
|
||||
use rns_transport::messages::{
|
||||
AnnounceHandlerEvent, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LinkClientError {
|
||||
@@ -70,27 +72,36 @@ impl LinkClient {
|
||||
let dest_hash =
|
||||
Destination::hash_from_name_and_identity(app_name, Some(&remote_transport_hash));
|
||||
|
||||
// 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?;
|
||||
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?;
|
||||
self.send_msg(TransportMessage::RequestPath {
|
||||
destination_hash: dest_hash,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let pubkey = wait_for_pubkey(&mut ann_rx, dest_hash, time_remaining(deadline)?).await?;
|
||||
let _ = self
|
||||
.transport_tx
|
||||
.try_send(TransportMessage::DeregisterAnnounceHandler {
|
||||
aspect_filter: Some(app_name.to_string()),
|
||||
});
|
||||
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 (mut link, request_data) = Link::new_initiator(dest_hash, hops);
|
||||
let link_id = link.link_id;
|
||||
@@ -197,6 +208,58 @@ 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 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> {
|
||||
let link_id = link.link_id;
|
||||
let Some(teardown_data) = link.teardown(CloseReason::InitiatorClosed) else {
|
||||
@@ -479,17 +542,37 @@ async fn wait_for_response(
|
||||
let Some(transfer) = inbound_resources.get_mut(&rh) else {
|
||||
continue;
|
||||
};
|
||||
if let TransferAction::SendRequest(req) =
|
||||
transfer.hashmap_update(segment, &hashmap)
|
||||
{
|
||||
send_link_data(
|
||||
transport_tx,
|
||||
link,
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&req,
|
||||
true,
|
||||
)?;
|
||||
match transfer.hashmap_update(segment, &hashmap) {
|
||||
TransferAction::SendRequest(req) => {
|
||||
send_link_data(
|
||||
transport_tx,
|
||||
link,
|
||||
link_id,
|
||||
rns_wire::context::PacketContext::ResourceReq,
|
||||
&req,
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
// Empty/invalid HMU cancels the transfer (RESOURCE_RCL, 1.3.9).
|
||||
TransferAction::SendCancel(cancel_type, resource_hash) => {
|
||||
let context = match cancel_type {
|
||||
rns_protocol::resource::CancelType::Icl => {
|
||||
rns_wire::context::PacketContext::ResourceIcl
|
||||
}
|
||||
rns_protocol::resource::CancelType::Rcl => {
|
||||
rns_wire::context::PacketContext::ResourceRcl
|
||||
}
|
||||
};
|
||||
send_link_data(
|
||||
transport_tx,
|
||||
link,
|
||||
link_id,
|
||||
context,
|
||||
&resource_hash,
|
||||
true,
|
||||
)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rns_wire::context::PacketContext::LinkClose
|
||||
@@ -653,6 +736,62 @@ 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];
|
||||
|
||||
+5967
-722
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -20,6 +20,9 @@ use rns_wire::flags::{DestinationType, HeaderType, PacketFlags, PacketType, Tran
|
||||
use rns_wire::hash::packet_hash_pair;
|
||||
use rns_wire::header::PacketHeader;
|
||||
|
||||
/// Python rnprobe `DEFAULT_TIMEOUT`.
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ProbeError {
|
||||
#[error("timed out waiting for path to destination")]
|
||||
@@ -82,7 +85,9 @@ pub async fn spawn_probe_responder(
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = event_rx.recv().await {
|
||||
let (raw, interface_id) = match event {
|
||||
DestinationEvent::InboundPacket { raw, interface_id } => (raw, interface_id),
|
||||
DestinationEvent::InboundPacket {
|
||||
raw, interface_id, ..
|
||||
} => (raw, interface_id),
|
||||
DestinationEvent::AnnounceRequested(request) => {
|
||||
let raw = match destination.announce_packet(
|
||||
identity.as_ref(),
|
||||
@@ -132,6 +137,9 @@ pub async fn spawn_probe_responder(
|
||||
if header.flags.packet_type != PacketType::Data {
|
||||
continue;
|
||||
}
|
||||
if !destination.should_prove(&raw) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (full_hash, trunc_hash) = packet_hash_pair(&raw, header.flags.header_type);
|
||||
let proof_payload = match identity.prove(&full_hash, implicit) {
|
||||
@@ -239,13 +247,15 @@ impl Drop for DeliveryProofWaiter {
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` waits mirror Python rnprobe: `DEFAULT_TIMEOUT +
|
||||
/// get_first_hop_timeout(dest)`, resolved fresh at each wait.
|
||||
pub async fn probe_once(
|
||||
transport_tx: mpsc::Sender<TransportMessage>,
|
||||
dest_hash: [u8; 16],
|
||||
app_name: &str,
|
||||
size: usize,
|
||||
proof_wait: Duration,
|
||||
path_wait: Duration,
|
||||
proof_wait: Option<Duration>,
|
||||
path_wait: Option<Duration>,
|
||||
use_implicit_proof: bool,
|
||||
) -> Result<ProbeOutcome, ProbeError> {
|
||||
if size > MTU {
|
||||
@@ -277,6 +287,11 @@ pub async fn probe_once(
|
||||
.await
|
||||
.map_err(|_| ProbeError::TransportClosed)?;
|
||||
|
||||
let path_wait = match path_wait {
|
||||
Some(d) => d,
|
||||
None => default_probe_wait(&transport_tx, dest_hash).await?,
|
||||
};
|
||||
|
||||
let (await_tx, await_rx) = oneshot::channel();
|
||||
transport_tx
|
||||
.send(TransportMessage::AwaitPath {
|
||||
@@ -340,6 +355,12 @@ pub async fn probe_once(
|
||||
|
||||
let (full_hash, trunc_hash) = packet_hash_pair(&raw, HeaderType::Header1);
|
||||
|
||||
// Per probe, like Python's per-packet `timeout or DEFAULT_TIMEOUT + fht`.
|
||||
let proof_wait = match proof_wait {
|
||||
Some(d) => d,
|
||||
None => default_probe_wait(&transport_tx, dest_hash).await?,
|
||||
};
|
||||
|
||||
// trunc_hash keys `receipt_table`; unique msg_id filters fan-out.
|
||||
let msg_id = format!(
|
||||
"probe.{}.{:x}",
|
||||
@@ -350,6 +371,8 @@ pub async fn probe_once(
|
||||
.send(TransportMessage::RegisterReceipt {
|
||||
truncated_hash: trunc_hash,
|
||||
full_hash,
|
||||
destination_hash: dest_hash,
|
||||
destination_public_key: pubkey,
|
||||
msg_id: msg_id.clone(),
|
||||
timeout: Some(proof_wait + Duration::from_secs(1)),
|
||||
})
|
||||
@@ -404,6 +427,17 @@ pub async fn probe_once(
|
||||
})
|
||||
}
|
||||
|
||||
async fn default_probe_wait(
|
||||
tx: &mpsc::Sender<TransportMessage>,
|
||||
dest: [u8; 16],
|
||||
) -> Result<Duration, ProbeError> {
|
||||
let first_hop = match query(tx, TransportQuery::FirstHopTimeout { dest }).await? {
|
||||
TransportQueryResponse::FloatResult(Some(t)) => t,
|
||||
_ => rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT,
|
||||
};
|
||||
Ok(Duration::from_secs_f64(DEFAULT_TIMEOUT_SECS + first_hop))
|
||||
}
|
||||
|
||||
pub fn parse_dest_hash(hex_str: &str) -> Result<[u8; 16], ProbeError> {
|
||||
let bytes = hex::decode(hex_str.trim()).map_err(|_| ProbeError::InvalidName)?;
|
||||
<[u8; 16]>::try_from(bytes.as_slice()).map_err(|_| ProbeError::InvalidName)
|
||||
@@ -569,6 +603,7 @@ mod tests {
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(raw),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -702,6 +737,7 @@ mod tests {
|
||||
.send(DestinationEvent::InboundPacket {
|
||||
raw: bytes::Bytes::from(raw),
|
||||
interface_id: 0,
|
||||
metrics: Default::default(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -266,6 +266,7 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
|
||||
txs: e.tx_rate,
|
||||
announce_queue: e.announce_queue,
|
||||
clients: e.clients,
|
||||
blocked_ips: e.blocked_ips,
|
||||
ifac_signature: None,
|
||||
ifac_size,
|
||||
ifac_netname: None,
|
||||
@@ -350,6 +351,7 @@ mod tests {
|
||||
txs: 0,
|
||||
announce_queue: None,
|
||||
clients: None,
|
||||
blocked_ips: None,
|
||||
ifac_signature: None,
|
||||
ifac_size: None,
|
||||
ifac_netname: None,
|
||||
@@ -376,9 +378,67 @@ mod tests {
|
||||
.any(|(k, _)| k.as_str() == Some("interfaces"));
|
||||
assert!(has_interfaces, "stats dict has 'interfaces' key");
|
||||
|
||||
let interface_map = stats_map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("interfaces"))
|
||||
.and_then(|(_, value)| value.as_array())
|
||||
.and_then(|interfaces| interfaces.first())
|
||||
.and_then(rmpv::Value::as_map)
|
||||
.expect("first interface is a map");
|
||||
assert!(
|
||||
!interface_map
|
||||
.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ips")),
|
||||
"absent aggregate count is omitted"
|
||||
);
|
||||
assert_eq!(arr[1].as_u64(), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_response_serializes_only_aggregate_blocked_ip_count() {
|
||||
let stats = schema::InterfaceStats {
|
||||
name: "Backbone".to_string(),
|
||||
short_name: "Backbone".to_string(),
|
||||
hash: None,
|
||||
type_: "Interface".to_string(),
|
||||
rxb: 0,
|
||||
txb: 0,
|
||||
incoming_announce_frequency: 0.0,
|
||||
outgoing_announce_frequency: 0.0,
|
||||
incoming_pr_frequency: 0.0,
|
||||
outgoing_pr_frequency: 0.0,
|
||||
held_announces: 0,
|
||||
burst_active: false,
|
||||
burst_activated: 0.0,
|
||||
pr_burst_active: false,
|
||||
pr_burst_activated: 0.0,
|
||||
status: true,
|
||||
mode: 0x01,
|
||||
bitrate: Some(1_000_000),
|
||||
rxs: 0,
|
||||
txs: 0,
|
||||
announce_queue: None,
|
||||
clients: Some(2),
|
||||
blocked_ips: Some(3),
|
||||
ifac_signature: None,
|
||||
ifac_size: None,
|
||||
ifac_netname: None,
|
||||
};
|
||||
let encoded = rmp_serde::to_vec_named(&stats).unwrap();
|
||||
let decoded: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
|
||||
let map = decoded.as_map().expect("interface stats are a map");
|
||||
assert_eq!(
|
||||
map.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("blocked_ips"))
|
||||
.and_then(|(_, value)| value.as_u64()),
|
||||
Some(3)
|
||||
);
|
||||
assert!(
|
||||
!map.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ip_list"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_response_is_list_of_dicts() {
|
||||
let entry = schema::PathEntry {
|
||||
@@ -484,6 +544,7 @@ mod tests {
|
||||
pr_burst_active: true,
|
||||
pr_burst_activated: 1_700_000_002.0,
|
||||
clients: None,
|
||||
blocked_ips: Some(3),
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
@@ -611,6 +672,16 @@ mod tests {
|
||||
.1
|
||||
.as_bool();
|
||||
assert_eq!(pr_burst_active, Some(true));
|
||||
let blocked_ips = iface_map
|
||||
.iter()
|
||||
.find(|(key, _)| key.as_str() == Some("blocked_ips"))
|
||||
.and_then(|(_, value)| value.as_u64());
|
||||
assert_eq!(blocked_ips, Some(3));
|
||||
assert!(
|
||||
!iface_map
|
||||
.iter()
|
||||
.any(|(key, _)| key.as_str() == Some("blocked_ip_list"))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
|
||||
@@ -53,6 +53,8 @@ pub struct InterfaceStats {
|
||||
pub announce_queue: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub clients: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub blocked_ips: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", with = "bytes_opt")]
|
||||
pub ifac_signature: Option<Vec<u8>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
//! Bounded-memory sources for Link Resource transfers.
|
||||
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_link::key_derivation::LinkKeys;
|
||||
use rns_protocol::resource::{
|
||||
MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, OutboundResource, OutboundTransfer,
|
||||
ResourceError,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Seekable source accepted by the high-level Resource API.
|
||||
pub trait ResourceSource: Read + Seek + Send {}
|
||||
|
||||
impl<T> ResourceSource for T where T: Read + Seek + Send {}
|
||||
|
||||
/// Sender options shared by byte and streaming Resource sources.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ResourceOptions {
|
||||
pub auto_compress: bool,
|
||||
pub metadata: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ResourceSourceError {
|
||||
#[error("resource source I/O failed: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
#[error("resource source exceeds the supported {MAX_RESOURCE_SIZE}-byte limit")]
|
||||
TooLarge,
|
||||
#[error("resource metadata leaves no valid bounded segment plan")]
|
||||
TooManySegments,
|
||||
#[error("resource preparation failed: {0}")]
|
||||
Protocol(#[from] ResourceError),
|
||||
}
|
||||
|
||||
pub(crate) struct PreparedResourceSegment {
|
||||
pub transfer: OutboundTransfer,
|
||||
pub logical_hash: [u8; 32],
|
||||
pub segment_index: usize,
|
||||
pub total_segments: usize,
|
||||
pub data_size: usize,
|
||||
pub segment_data_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) enum ResourcePurpose {
|
||||
#[default]
|
||||
Ordinary,
|
||||
Request([u8; 16]),
|
||||
}
|
||||
|
||||
impl ResourcePurpose {
|
||||
fn apply(self, resource: &mut OutboundResource) {
|
||||
if let Self::Request(request_id) = self {
|
||||
resource.flags.is_request = true;
|
||||
resource.request_id = Some(request_id.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum PreparedResourceSource {
|
||||
Single {
|
||||
data: Option<Vec<u8>>,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
},
|
||||
Split {
|
||||
source: Box<dyn ResourceSource>,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
data_size: usize,
|
||||
metadata_wire_size: usize,
|
||||
original_hash: [u8; 32],
|
||||
total_segments: usize,
|
||||
next_segment: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl PreparedResourceSource {
|
||||
pub(crate) fn prepare<S>(
|
||||
source: S,
|
||||
options: ResourceOptions,
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
Self::prepare_with_purpose(source, options, ResourcePurpose::Ordinary)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_request<S>(
|
||||
source: S,
|
||||
request_id: [u8; 16],
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
Self::prepare_with_purpose(
|
||||
source,
|
||||
ResourceOptions::default(),
|
||||
ResourcePurpose::Request(request_id),
|
||||
)
|
||||
}
|
||||
|
||||
fn prepare_with_purpose<S>(
|
||||
mut source: S,
|
||||
options: ResourceOptions,
|
||||
purpose: ResourcePurpose,
|
||||
) -> Result<Self, ResourceSourceError>
|
||||
where
|
||||
S: ResourceSource + 'static,
|
||||
{
|
||||
let data_size = source.seek(SeekFrom::End(0))?;
|
||||
if data_size > MAX_RESOURCE_SIZE as u64 {
|
||||
return Err(ResourceSourceError::TooLarge);
|
||||
}
|
||||
source.seek(SeekFrom::Start(0))?;
|
||||
let data_size = data_size as usize;
|
||||
let metadata_wire_size = options
|
||||
.metadata
|
||||
.as_ref()
|
||||
.map(|metadata| 3usize.saturating_add(metadata.len()))
|
||||
.unwrap_or(0);
|
||||
|
||||
if metadata_wire_size.saturating_add(data_size) <= MAX_EFFICIENT_SIZE {
|
||||
let mut data = Vec::with_capacity(data_size);
|
||||
source.read_to_end(&mut data)?;
|
||||
return Ok(Self::Single {
|
||||
data: Some(data),
|
||||
options,
|
||||
purpose,
|
||||
});
|
||||
}
|
||||
|
||||
if metadata_wire_size > MAX_EFFICIENT_SIZE {
|
||||
return Err(ResourceSourceError::Protocol(
|
||||
ResourceError::MetadataTooLarge,
|
||||
));
|
||||
}
|
||||
let first_payload_size = MAX_EFFICIENT_SIZE - metadata_wire_size;
|
||||
let first_len = data_size.min(first_payload_size);
|
||||
let remaining = data_size.saturating_sub(first_len);
|
||||
let total_segments = 1 + remaining.div_ceil(MAX_EFFICIENT_SIZE);
|
||||
if total_segments > MAX_SEGMENTS {
|
||||
return Err(ResourceSourceError::TooManySegments);
|
||||
}
|
||||
|
||||
let random_hash: [u8; 4] = rns_crypto::random::random_bytes(4)
|
||||
.try_into()
|
||||
.expect("fixed random-hash length");
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let read = source.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..read]);
|
||||
}
|
||||
hasher.update(random_hash);
|
||||
let original_hash = hasher.finalize().into();
|
||||
source.seek(SeekFrom::Start(0))?;
|
||||
|
||||
Ok(Self::Split {
|
||||
source: Box::new(source),
|
||||
options,
|
||||
purpose,
|
||||
data_size,
|
||||
metadata_wire_size,
|
||||
original_hash,
|
||||
total_segments,
|
||||
next_segment: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn next_segment(
|
||||
&mut self,
|
||||
keys: &LinkKeys,
|
||||
rtt: Duration,
|
||||
) -> Result<Option<PreparedResourceSegment>, ResourceSourceError> {
|
||||
let encrypt = |plaintext: &[u8]| {
|
||||
rns_link::encryption::link_encrypt(keys, plaintext)
|
||||
.unwrap_or_else(|_| plaintext.to_vec())
|
||||
};
|
||||
|
||||
match self {
|
||||
Self::Single {
|
||||
data,
|
||||
options,
|
||||
purpose,
|
||||
} => {
|
||||
let Some(data) = data.take() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let data_size = data.len();
|
||||
let resource = OutboundResource::with_options(
|
||||
data,
|
||||
options.auto_compress,
|
||||
options.metadata.take(),
|
||||
None,
|
||||
Some(&encrypt),
|
||||
)?;
|
||||
let mut resource = resource;
|
||||
purpose.apply(&mut resource);
|
||||
let logical_hash = resource.resource_hash;
|
||||
Ok(Some(PreparedResourceSegment {
|
||||
transfer: OutboundTransfer::from_prebuilt(resource, rtt),
|
||||
logical_hash,
|
||||
segment_index: 1,
|
||||
total_segments: 1,
|
||||
data_size,
|
||||
segment_data_size: data_size,
|
||||
}))
|
||||
}
|
||||
Self::Split {
|
||||
source,
|
||||
options,
|
||||
purpose,
|
||||
data_size,
|
||||
metadata_wire_size,
|
||||
original_hash,
|
||||
total_segments,
|
||||
next_segment,
|
||||
} => {
|
||||
if *next_segment >= *total_segments {
|
||||
return Ok(None);
|
||||
}
|
||||
let segment_index = *next_segment + 1;
|
||||
let metadata = if segment_index == 1 {
|
||||
options.metadata.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let segment_metadata_wire_size = metadata
|
||||
.as_ref()
|
||||
.map(|value| 3usize.saturating_add(value.len()))
|
||||
.unwrap_or(0);
|
||||
let payload_limit = if segment_index == 1 {
|
||||
MAX_EFFICIENT_SIZE - segment_metadata_wire_size
|
||||
} else {
|
||||
MAX_EFFICIENT_SIZE
|
||||
};
|
||||
let mut data = vec![0u8; payload_limit];
|
||||
let mut filled = 0;
|
||||
while filled < data.len() {
|
||||
let read = source.read(&mut data[filled..])?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
filled += read;
|
||||
}
|
||||
data.truncate(filled);
|
||||
|
||||
let mut resource = OutboundResource::with_options(
|
||||
data,
|
||||
options.auto_compress,
|
||||
metadata,
|
||||
None,
|
||||
Some(&encrypt),
|
||||
)?;
|
||||
purpose.apply(&mut resource);
|
||||
resource.flags.split = true;
|
||||
resource.segment_index = segment_index;
|
||||
resource.total_segments = *total_segments;
|
||||
resource.original_hash = Some(*original_hash);
|
||||
resource.advertisement_data_size = data_size.saturating_add(*metadata_wire_size);
|
||||
let segment_data_size = resource.data.len();
|
||||
*next_segment += 1;
|
||||
|
||||
Ok(Some(PreparedResourceSegment {
|
||||
transfer: OutboundTransfer::from_prebuilt(resource, rtt),
|
||||
logical_hash: *original_hash,
|
||||
segment_index,
|
||||
total_segments: *total_segments,
|
||||
data_size: *data_size,
|
||||
segment_data_size,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Cursor;
|
||||
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
use rns_link::constants::MODE_AES256_CBC;
|
||||
use rns_link::key_derivation::LinkKeys;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn test_keys() -> LinkKeys {
|
||||
let local = X25519PrivateKey::generate();
|
||||
let remote = X25519PrivateKey::generate();
|
||||
LinkKeys::derive(&local, &remote.public_key(), &[0xA5; 16], MODE_AES256_CBC).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_source_prepares_one_segment() {
|
||||
let mut prepared = PreparedResourceSource::prepare(
|
||||
Cursor::new(b"small resource".to_vec()),
|
||||
ResourceOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let segment = prepared
|
||||
.next_segment(&test_keys(), Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(segment.total_segments, 1);
|
||||
assert_eq!(segment.segment_index, 1);
|
||||
assert_eq!(segment.data_size, b"small resource".len());
|
||||
assert_eq!(
|
||||
segment.logical_hash,
|
||||
segment.transfer.resource.resource_hash
|
||||
);
|
||||
assert!(
|
||||
prepared
|
||||
.next_segment(&test_keys(), Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_source_is_read_one_segment_at_a_time() {
|
||||
let data = vec![0x5A; MAX_EFFICIENT_SIZE + 17];
|
||||
let mut prepared =
|
||||
PreparedResourceSource::prepare(Cursor::new(data.clone()), ResourceOptions::default())
|
||||
.unwrap();
|
||||
let keys = test_keys();
|
||||
let first = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let second = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(first.total_segments, 2);
|
||||
assert_eq!(second.total_segments, 2);
|
||||
assert_eq!(first.logical_hash, second.logical_hash);
|
||||
assert_eq!(first.transfer.resource.segment_index, 1);
|
||||
assert_eq!(second.transfer.resource.segment_index, 2);
|
||||
assert_eq!(second.transfer.resource.data.len(), 17);
|
||||
assert_eq!(first.data_size, data.len());
|
||||
assert!(
|
||||
prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_source_marks_every_segment_with_request_id() {
|
||||
let request_id = [0x42; 16];
|
||||
let data = vec![0xA5; MAX_EFFICIENT_SIZE + 17];
|
||||
let mut prepared =
|
||||
PreparedResourceSource::prepare_request(Cursor::new(data), request_id).unwrap();
|
||||
let keys = test_keys();
|
||||
|
||||
for expected_segment in 1..=2 {
|
||||
let segment = prepared
|
||||
.next_segment(&keys, Duration::from_millis(100))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(segment.segment_index, expected_segment);
|
||||
assert!(segment.transfer.resource.flags.is_request);
|
||||
assert!(!segment.transfer.resource.flags.is_response);
|
||||
assert_eq!(
|
||||
segment.transfer.resource.request_id.as_deref(),
|
||||
Some(request_id.as_slice())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8754
-429
File diff suppressed because it is too large.
Load diff
@@ -33,6 +33,13 @@ pub const FETCH_PATH_NAME: &str = "fetch_file";
|
||||
|
||||
pub const DEFAULT_RNCP_APP_NAME: &str = "rncp.receive";
|
||||
|
||||
/// Python sends the final Resource proof before it runs the receiver-side
|
||||
/// conclusion callback that materialises the file. Keep the Link alive for a
|
||||
/// short, bounded settlement window after a valid proof so an immediate
|
||||
/// teardown cannot race that callback and turn a proven Resource into
|
||||
/// `FAILED` on a loaded peer.
|
||||
const RNCP_POST_PROOF_SETTLE: Duration = Duration::from_millis(250);
|
||||
|
||||
pub fn default_rncp_app_name() -> &'static str {
|
||||
DEFAULT_RNCP_APP_NAME
|
||||
}
|
||||
@@ -639,6 +646,10 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
|
||||
completed_parts += segment_parts;
|
||||
}
|
||||
|
||||
if transfer_result.is_ok() {
|
||||
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 {
|
||||
@@ -1565,4 +1576,9 @@ mod tests {
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::LinkClose);
|
||||
assert!(responder.receive_teardown(&raw[offset..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_rncp_send_retains_python_receiver_settlement_window() {
|
||||
assert_eq!(RNCP_POST_PROOF_SETTLE, Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
+270
-19
@@ -23,9 +23,9 @@ use rns_link::link::{CloseReason, Link};
|
||||
use rns_protocol::channel::{ChannelError, LinkChannel};
|
||||
use rns_protocol::channel_message::MessageBase;
|
||||
use rns_protocol::rnsh::{
|
||||
CommandExitedMessage, ErrorMessage, ExecuteCommandMessage, NoopMessage, PROTOCOL_VERSION,
|
||||
RnshMessage, RnshStreamDataMessage, STREAM_ID_STDERR, STREAM_ID_STDIN, STREAM_ID_STDOUT,
|
||||
VersionInfoMessage, WindowSizeMessage,
|
||||
CommandExitedMessage, ErrorMessage, ExecuteCommandMessage, MESSAGE_TYPES, NoopMessage,
|
||||
PROTOCOL_VERSION, RnshMessage, RnshStreamDataMessage, STREAM_ID_STDERR, STREAM_ID_STDIN,
|
||||
STREAM_ID_STDOUT, VersionInfoMessage, WindowSizeMessage,
|
||||
};
|
||||
use rns_transport::link_messages::DestinationEvent;
|
||||
use rns_transport::messages::{
|
||||
@@ -171,6 +171,9 @@ async fn run_rnsh_listener_inner(
|
||||
RNSH_APP_NAME,
|
||||
Some(signing_key),
|
||||
);
|
||||
for msg_type in MESSAGE_TYPES {
|
||||
link_mgr.register_channel_message_type(msg_type)?;
|
||||
}
|
||||
|
||||
let announce_tx = transport_tx.clone();
|
||||
let announce_packet = build_announce_packet(&cfg.identity, RNSH_APP_NAME)?;
|
||||
@@ -209,27 +212,50 @@ async fn run_rnsh_listener_inner(
|
||||
tokio::select! {
|
||||
maybe_link = established_rx.recv() => {
|
||||
let Some(link_id) = maybe_link else { break };
|
||||
sessions.insert(link_id, ListenerSession::new(cfg.allow_all));
|
||||
// or_insert (not insert) so a rare identification processed ahead
|
||||
// of this establishment event is never clobbered.
|
||||
sessions.entry(link_id).or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
}
|
||||
maybe_identified = identified_rx.recv() => {
|
||||
let Some((link_id, identity_hash)) = maybe_identified else { break };
|
||||
let allowed = listener_allowed_identities(&cfg);
|
||||
if cfg.allow_all || allowed.contains(&identity_hash) {
|
||||
let session = sessions.entry(link_id).or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
session.authorized = true;
|
||||
session.remote_identity_hash = Some(identity_hash);
|
||||
session.state = ListenerState::WaitVersion;
|
||||
// Identification is a legitimate session creator (it may race
|
||||
// ahead of the establishment event), so create-or-get here.
|
||||
let session = sessions
|
||||
.entry(link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
// First-identification-wins: only a freshly-established
|
||||
// (WaitIdent) authenticated session may be authorized and
|
||||
// advanced — a repeat identification cannot regress a session
|
||||
// that has already moved on.
|
||||
if session.state == ListenerState::WaitIdent {
|
||||
session.authorized = true;
|
||||
session.remote_identity_hash = Some(identity_hash);
|
||||
session.state = ListenerState::WaitVersion;
|
||||
} else if cfg.allow_all && session.remote_identity_hash.is_none() {
|
||||
// allow_all sessions start authorized in WaitVersion;
|
||||
// record the first identity without regressing state.
|
||||
session.remote_identity_hash = Some(identity_hash);
|
||||
}
|
||||
} else {
|
||||
// Denial is terminal: mark the session Closed so a message that
|
||||
// lands before CloseLink completes cannot resurrect it.
|
||||
let session = sessions
|
||||
.entry(link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
session.authorized = false;
|
||||
session.state = ListenerState::Closed;
|
||||
send_manager_message(
|
||||
&command_tx,
|
||||
link_id,
|
||||
ErrorMessage::new(Some("Identity is not allowed.".into()), true, None),
|
||||
).await?;
|
||||
let _ = command_tx.send(LinkManagerCommand::CloseLink {
|
||||
link_id,
|
||||
reason: CloseReason::DestinationClosed,
|
||||
send_teardown: true,
|
||||
}).await;
|
||||
// Keep the already-closed session around just long enough
|
||||
// for the peer to receive the protocol-level denial. The
|
||||
// channel-message gate drops every subsequent message, so
|
||||
// this grace period cannot advance or run the session.
|
||||
close_link_after_error(command_tx.clone(), link_id);
|
||||
}
|
||||
}
|
||||
maybe_closed = closed_rx.recv() => {
|
||||
@@ -371,7 +397,9 @@ pub async fn rnsh_client_execute(
|
||||
let session_keys = link
|
||||
.session_keys()
|
||||
.ok_or_else(|| RnshError::LinkCrypto("no session keys".into()))?;
|
||||
let mut channel = LinkChannel::new_encrypted(link_id, link.rtt_secs(), session_keys);
|
||||
let mut channel =
|
||||
LinkChannel::new_encrypted_with_mdu(link_id, link.rtt_secs(), link.mdu, session_keys);
|
||||
register_rnsh_message_types(&mut channel)?;
|
||||
link.mark_channel_created();
|
||||
let mut pending_messages = VecDeque::new();
|
||||
let mut stdout = Vec::new();
|
||||
@@ -481,6 +509,13 @@ pub async fn rnsh_client_execute(
|
||||
})
|
||||
}
|
||||
|
||||
fn register_rnsh_message_types(channel: &mut LinkChannel) -> Result<(), ChannelError> {
|
||||
for msg_type in MESSAGE_TYPES {
|
||||
channel.register_message_type(msg_type)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pending_has_remote_terminal(pending_messages: &VecDeque<RnshMessage>) -> bool {
|
||||
pending_messages.iter().any(|message| {
|
||||
matches!(
|
||||
@@ -727,6 +762,8 @@ enum ListenerState {
|
||||
WaitVersion,
|
||||
WaitCommand,
|
||||
Running,
|
||||
/// Terminal: the session was denied or torn down. No message can advance it.
|
||||
Closed,
|
||||
}
|
||||
|
||||
struct ListenerSession {
|
||||
@@ -991,11 +1028,14 @@ async fn handle_listener_channel_message(
|
||||
sessions: &mut HashMap<[u8; 16], ListenerSession>,
|
||||
msg: LinkChannelMessage,
|
||||
) -> Result<(), RnshError> {
|
||||
let session = sessions
|
||||
.entry(msg.link_id)
|
||||
.or_insert_with(|| ListenerSession::new(cfg.allow_all));
|
||||
// Sessions are created only on link establishment or on an allowed
|
||||
// identification — a stray channel message must never fabricate one.
|
||||
let Some(session) = sessions.get_mut(&msg.link_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if !session.authorized {
|
||||
// Drop everything on an unauthorized or terminally-closed session.
|
||||
if !session.authorized || session.state == ListenerState::Closed {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -1003,6 +1043,7 @@ async fn handle_listener_channel_message(
|
||||
.map_err(|e| RnshError::Channel(e.to_string()))?;
|
||||
|
||||
match session.state {
|
||||
ListenerState::Closed => Ok(()),
|
||||
ListenerState::WaitIdent => Ok(()),
|
||||
ListenerState::WaitVersion => match decoded {
|
||||
RnshMessage::VersionInfo(version) => {
|
||||
@@ -1500,7 +1541,7 @@ async fn send_client_channel_data(
|
||||
raw.extend_from_slice(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(raw.len());
|
||||
link.record_tx(data.len());
|
||||
transport_tx
|
||||
.send(TransportMessage::Outbound(OutboundRequest {
|
||||
raw: Bytes::from(raw),
|
||||
@@ -1515,6 +1556,7 @@ async fn resend_timed_out_client_channel_messages(
|
||||
link: &mut Link,
|
||||
channel: &mut LinkChannel,
|
||||
) -> Result<(), RnshError> {
|
||||
channel.update_rtt(link.rtt_secs());
|
||||
for sequence in channel.timed_out_sequences() {
|
||||
let Some(data) = channel.timeout(sequence)? else {
|
||||
continue;
|
||||
@@ -1957,6 +1999,21 @@ mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn rnsh_channel_registration_accepts_every_protocol_type() {
|
||||
let mut channel = LinkChannel::new([0xA2; 16], 0.1);
|
||||
register_rnsh_message_types(&mut channel).unwrap();
|
||||
|
||||
for (sequence, msg_type) in MESSAGE_TYPES.into_iter().enumerate() {
|
||||
let mut envelope = Vec::with_capacity(6);
|
||||
envelope.extend_from_slice(&msg_type.to_be_bytes());
|
||||
envelope.extend_from_slice(&(sequence as u16).to_be_bytes());
|
||||
envelope.extend_from_slice(&0u16.to_be_bytes());
|
||||
let received = channel.receive_data(&envelope).unwrap();
|
||||
assert_eq!(received, vec![(msg_type, Vec::new())]);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_ack_manager(
|
||||
mut rx: mpsc::Receiver<LinkManagerCommand>,
|
||||
messages: Arc<Mutex<Vec<RnshMessage>>>,
|
||||
@@ -2169,4 +2226,198 @@ mod tests {
|
||||
let _ = std::fs::remove_file(&pid_path);
|
||||
assert!(!process_exists(pid), "child process survived session drop");
|
||||
}
|
||||
|
||||
fn unique_marker(tag: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!(
|
||||
"rnsh-adv-{tag}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
))
|
||||
}
|
||||
|
||||
// Authenticated listener whose default command creates `marker` if it ever
|
||||
// reaches process spawn. The attacker identity is absent from the allow-list.
|
||||
fn marker_listener_config(marker: &std::path::Path) -> RnshListenerConfig {
|
||||
RnshListenerConfig {
|
||||
identity: Identity::new(),
|
||||
command: vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
format!("touch '{}'", marker.display()),
|
||||
],
|
||||
allow_all: false,
|
||||
allowed: Vec::new(),
|
||||
allowed_identity_files: Vec::new(),
|
||||
allow_remote_command: false,
|
||||
remote_command_as_args: false,
|
||||
announce_period: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn version_channel_msg(link_id: [u8; 16]) -> LinkChannelMessage {
|
||||
let msg = VersionInfoMessage::new(RNSH_SOFTWARE_VERSION);
|
||||
LinkChannelMessage {
|
||||
link_id,
|
||||
msg_type: msg.msg_type(),
|
||||
payload: msg.pack(),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_command_channel_msg(link_id: [u8; 16]) -> LinkChannelMessage {
|
||||
// Empty cmdline + headless pipes: selects the listener's default command.
|
||||
let msg =
|
||||
ExecuteCommandMessage::new(None, true, true, true, None, None, None, None, None, None);
|
||||
LinkChannelMessage {
|
||||
link_id,
|
||||
msg_type: msg.msg_type(),
|
||||
payload: msg.pack(),
|
||||
}
|
||||
}
|
||||
|
||||
// The 1.3.9 rnsh flaw: a rejected identity ignores the fatal error, then
|
||||
// sends VersionInfo + ExecuteCommand and reaches command execution. A denied
|
||||
// (terminal Closed) session must drop both and never spawn the command.
|
||||
#[tokio::test]
|
||||
async fn adversarial_denied_session_never_runs_command() {
|
||||
let marker = unique_marker("denied");
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
let cfg = marker_listener_config(&marker);
|
||||
let (command_tx, command_rx) = mpsc::channel(64);
|
||||
let messages = Arc::new(Mutex::new(Vec::new()));
|
||||
spawn_ack_manager(command_rx, messages.clone());
|
||||
|
||||
let link_id = [0x55; 16];
|
||||
let mut sessions = HashMap::new();
|
||||
let mut denied = ListenerSession::new(false);
|
||||
denied.state = ListenerState::Closed; // denial marks the session terminal
|
||||
sessions.insert(link_id, denied);
|
||||
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
version_channel_msg(link_id),
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
execute_command_channel_msg(link_id),
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
|
||||
assert!(
|
||||
!marker.exists(),
|
||||
"denied session must never run the listener command"
|
||||
);
|
||||
assert_eq!(sessions.get(&link_id).unwrap().state, ListenerState::Closed);
|
||||
assert!(
|
||||
!messages
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|m| matches!(m, RnshMessage::VersionInfo(_))),
|
||||
"denied session must not answer VersionInfo"
|
||||
);
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
}
|
||||
|
||||
// Same attack against a session that identified with an unallowed identity but
|
||||
// was never authorized (still WaitIdent). Every message is dropped at the gate.
|
||||
#[tokio::test]
|
||||
async fn adversarial_unauthorized_session_never_runs_command() {
|
||||
let marker = unique_marker("unauth");
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
let cfg = marker_listener_config(&marker);
|
||||
let (command_tx, command_rx) = mpsc::channel(64);
|
||||
let messages = Arc::new(Mutex::new(Vec::new()));
|
||||
spawn_ack_manager(command_rx, messages.clone());
|
||||
|
||||
let link_id = [0x56; 16];
|
||||
let mut sessions = HashMap::new();
|
||||
// Unauthorized authenticated session: authorized=false, WaitIdent.
|
||||
sessions.insert(link_id, ListenerSession::new(false));
|
||||
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
version_channel_msg(link_id),
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
execute_command_channel_msg(link_id),
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
|
||||
assert!(
|
||||
!marker.exists(),
|
||||
"unauthorized session must never run the listener command"
|
||||
);
|
||||
let session = sessions.get(&link_id).unwrap();
|
||||
assert!(!session.authorized);
|
||||
assert_eq!(session.state, ListenerState::WaitIdent);
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
}
|
||||
|
||||
// Positive control: an authorized session in WaitCommand DOES run the command,
|
||||
// proving the harness can reach process spawn — so the negative results above
|
||||
// are due to authorization, not an impotent test setup.
|
||||
#[tokio::test]
|
||||
async fn positive_control_authorized_session_runs_command() {
|
||||
let marker = unique_marker("authed");
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
let cfg = marker_listener_config(&marker);
|
||||
let (command_tx, command_rx) = mpsc::channel(64);
|
||||
let messages = Arc::new(Mutex::new(Vec::new()));
|
||||
spawn_ack_manager(command_rx, messages.clone());
|
||||
|
||||
let link_id = [0x57; 16];
|
||||
let mut sessions = HashMap::new();
|
||||
let mut authed = ListenerSession::new(false);
|
||||
authed.authorized = true;
|
||||
authed.remote_identity_hash = Some([0xAB; 16]);
|
||||
authed.state = ListenerState::WaitCommand;
|
||||
sessions.insert(link_id, authed);
|
||||
|
||||
handle_listener_channel_message(
|
||||
&command_tx,
|
||||
&cfg,
|
||||
&mut sessions,
|
||||
execute_command_channel_msg(link_id),
|
||||
)
|
||||
.await
|
||||
.expect("handler ok");
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while Instant::now() < deadline && !marker.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
assert!(
|
||||
marker.exists(),
|
||||
"authorized session must run the listener command (positive control)"
|
||||
);
|
||||
assert_eq!(
|
||||
sessions.get(&link_id).unwrap().state,
|
||||
ListenerState::Running
|
||||
);
|
||||
|
||||
drop(sessions); // reap the spawned child
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
}
|
||||
}
|
||||
+598
-337
File diff suppressed because it is too large.
Load diff
@@ -165,6 +165,7 @@ fn bind_abstract_unix_listener(_name: &str) -> std::io::Result<tokio::net::UnixL
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn display_socket_path(path: &str) -> String {
|
||||
if let Some(rest) = path.strip_prefix('\0') {
|
||||
format!("\\0{rest}")
|
||||
@@ -220,16 +221,56 @@ async fn handle_rpc_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const TRANSPORT_QUERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum TransportQueryFailure {
|
||||
SendTimedOut,
|
||||
ChannelClosed,
|
||||
ResponseTimedOut,
|
||||
ResponseClosed,
|
||||
}
|
||||
|
||||
impl TransportQueryFailure {
|
||||
fn description(self) -> &'static str {
|
||||
match self {
|
||||
Self::SendTimedOut => "request enqueue timed out",
|
||||
Self::ChannelClosed => "query channel is closed",
|
||||
Self::ResponseTimedOut => "response timed out",
|
||||
Self::ResponseClosed => "response channel closed without an answer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_failure_response(
|
||||
operation: &'static str,
|
||||
failure: TransportQueryFailure,
|
||||
) -> RpcResponse {
|
||||
RpcResponse::Error(format!(
|
||||
"transport actor failed {operation}: {}",
|
||||
failure.description()
|
||||
))
|
||||
}
|
||||
|
||||
fn unexpected_transport_response(operation: &'static str) -> RpcResponse {
|
||||
RpcResponse::Error(format!(
|
||||
"transport actor returned an unexpected response to {operation}"
|
||||
))
|
||||
}
|
||||
|
||||
fn invalid_request_hash(kind: &'static str) -> RpcResponse {
|
||||
RpcResponse::Error(format!("invalid {kind} hash in RPC request"))
|
||||
}
|
||||
|
||||
/// 5 s cap so a wedged actor can't hold a client open indefinitely.
|
||||
async fn query_transport(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
query: rns_transport::messages::TransportQuery,
|
||||
) -> Option<rns_transport::messages::TransportQueryResponse> {
|
||||
) -> Result<rns_transport::messages::TransportQueryResponse, TransportQueryFailure> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let budget = std::time::Duration::from_secs(5);
|
||||
let started = std::time::Instant::now();
|
||||
match tokio::time::timeout(
|
||||
budget,
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::Rpc {
|
||||
query,
|
||||
response_tx: tx,
|
||||
@@ -238,45 +279,57 @@ async fn query_transport(
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return None,
|
||||
Err(_) => return None,
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
let remaining = TRANSPORT_QUERY_BUDGET
|
||||
.checked_sub(started.elapsed())
|
||||
.ok_or(TransportQueryFailure::ResponseTimedOut)?;
|
||||
match tokio::time::timeout(remaining, rx).await {
|
||||
Ok(Ok(response)) => Ok(response),
|
||||
Ok(Err(_)) => Err(TransportQueryFailure::ResponseClosed),
|
||||
Err(_) => Err(TransportQueryFailure::ResponseTimedOut),
|
||||
}
|
||||
let remaining = budget.checked_sub(started.elapsed())?;
|
||||
tokio::time::timeout(remaining, rx)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|r| r.ok())
|
||||
}
|
||||
|
||||
async fn request_path(
|
||||
transport_tx: &mpsc::Sender<TransportMessage>,
|
||||
destination_hash: [u8; 16],
|
||||
timeout_secs: Option<f64>,
|
||||
) -> bool {
|
||||
) -> Result<bool, TransportQueryFailure> {
|
||||
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
|
||||
if transport_tx
|
||||
.send(TransportMessage::RequestPath { destination_hash })
|
||||
.await
|
||||
.is_err()
|
||||
match tokio::time::timeout(
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::RequestPath { destination_hash }),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return false;
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
|
||||
let (reply, rx) = tokio::sync::oneshot::channel();
|
||||
if transport_tx
|
||||
.send(TransportMessage::AwaitPath {
|
||||
match tokio::time::timeout(
|
||||
TRANSPORT_QUERY_BUDGET,
|
||||
transport_tx.send(TransportMessage::AwaitPath {
|
||||
dest: destination_hash,
|
||||
reply,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return false;
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(_)) => return Err(TransportQueryFailure::ChannelClosed),
|
||||
Err(_) => return Err(TransportQueryFailure::SendTimedOut),
|
||||
}
|
||||
|
||||
match tokio::time::timeout(wait, rx).await {
|
||||
Ok(Ok(found)) => found,
|
||||
_ => false,
|
||||
Ok(Ok(found)) => Ok(found),
|
||||
Ok(Err(_)) => Err(TransportQueryFailure::ResponseClosed),
|
||||
// This is the caller-selected path-discovery deadline, so an intact
|
||||
// actor that simply did not discover a path reports `false`.
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,10 +339,19 @@ async fn process_rpc_request(
|
||||
) -> RpcResponse {
|
||||
use rns_transport::messages::{TransportQuery, TransportQueryResponse};
|
||||
|
||||
macro_rules! authoritative_query {
|
||||
($query:expr, $operation:literal) => {
|
||||
match query_transport(transport_tx, $query).await {
|
||||
Ok(response) => response,
|
||||
Err(failure) => return transport_failure_response($operation, failure),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match request {
|
||||
RpcRequest::GetPathTable { max_hops } => {
|
||||
match query_transport(transport_tx, TransportQuery::GetPathTable).await {
|
||||
Some(TransportQueryResponse::PathTable(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetPathTable, "path table query") {
|
||||
TransportQueryResponse::PathTable(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.filter(|e| max_hops.is_none_or(|max| e.hops <= max))
|
||||
@@ -304,12 +366,12 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::PathTable(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::PathTable(Vec::new()),
|
||||
_ => unexpected_transport_response("path table query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetInterfaceStats => {
|
||||
match query_transport(transport_tx, TransportQuery::GetInterfaceStats).await {
|
||||
Some(TransportQueryResponse::InterfaceStats(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetInterfaceStats, "interface stats query") {
|
||||
TransportQueryResponse::InterfaceStats(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::InterfaceStatEntry {
|
||||
@@ -335,6 +397,7 @@ async fn process_rpc_request(
|
||||
pr_burst_active: e.pr_burst_active,
|
||||
pr_burst_activated: e.pr_burst_activated,
|
||||
clients: e.clients,
|
||||
blocked_ips: e.blocked_ips,
|
||||
announce_rate_target: e.announce_rate_target,
|
||||
announce_rate_grace: e.announce_rate_grace,
|
||||
announce_rate_penalty: e.announce_rate_penalty,
|
||||
@@ -345,14 +408,12 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::InterfaceStats(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::Error(
|
||||
"transport actor did not answer interface stats query".to_string(),
|
||||
),
|
||||
_ => unexpected_transport_response("interface stats query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetRateTable => {
|
||||
match query_transport(transport_tx, TransportQuery::GetRateTable).await {
|
||||
Some(TransportQueryResponse::RateTable(entries)) => {
|
||||
match authoritative_query!(TransportQuery::GetRateTable, "rate table query") {
|
||||
TransportQueryResponse::RateTable(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::RateTableEntry {
|
||||
@@ -366,106 +427,111 @@ async fn process_rpc_request(
|
||||
.collect();
|
||||
RpcResponse::RateTable(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::RateTable(Vec::new()),
|
||||
_ => unexpected_transport_response("rate table query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetLinkCount => {
|
||||
match query_transport(transport_tx, TransportQuery::GetLinkCount).await {
|
||||
Some(TransportQueryResponse::IntResult(n)) => RpcResponse::IntResult(n),
|
||||
_ => RpcResponse::IntResult(0),
|
||||
match authoritative_query!(TransportQuery::GetLinkCount, "link count query") {
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("link count query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetNextHopIfName { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetNextHopIfName { dest: d },
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::StringResult(s)) => {
|
||||
RpcResponse::StringResult(s)
|
||||
}
|
||||
_ => RpcResponse::StringResult(None),
|
||||
}
|
||||
}
|
||||
None => RpcResponse::StringResult(None),
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetNextHopIfName { dest },
|
||||
"next-hop interface query"
|
||||
) {
|
||||
TransportQueryResponse::StringResult(name) => RpcResponse::StringResult(name),
|
||||
_ => unexpected_transport_response("next-hop interface query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetNextHop { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(transport_tx, TransportQuery::GetNextHop { dest: d })
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::HashResult(h)) => {
|
||||
RpcResponse::HashResult(h.map(|a| a.to_vec()))
|
||||
}
|
||||
_ => RpcResponse::HashResult(None),
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::GetNextHop { dest }, "next-hop query") {
|
||||
TransportQueryResponse::HashResult(hash) => {
|
||||
RpcResponse::HashResult(hash.map(|hash| hash.to_vec()))
|
||||
}
|
||||
None => RpcResponse::HashResult(None),
|
||||
_ => unexpected_transport_response("next-hop query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash,
|
||||
timeout_secs,
|
||||
} => match hash_to_array(&destination_hash) {
|
||||
Some(dest) => {
|
||||
RpcResponse::BoolResult(request_path(transport_tx, dest, timeout_secs).await)
|
||||
} => {
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match request_path(transport_tx, dest, timeout_secs).await {
|
||||
Ok(found) => RpcResponse::BoolResult(found),
|
||||
Err(failure) => transport_failure_response("path request", failure),
|
||||
}
|
||||
None => RpcResponse::BoolResult(false),
|
||||
},
|
||||
}
|
||||
RpcRequest::DropPath { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
if let Some(d) = dest {
|
||||
let _ = query_transport(transport_tx, TransportQuery::DropPath { dest: d }).await;
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::DropPath { dest }, "path drop") {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("path drop"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::DropPathTable => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropPathTable).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
match authoritative_query!(TransportQuery::DropPathTable, "path table drop") {
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("path table drop"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropRecentAnnounces => {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
|
||||
match authoritative_query!(TransportQuery::DropRecentAnnounces, "recent announces drop")
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
TransportQueryResponse::IntResult(n) => RpcResponse::IntResult(n),
|
||||
_ => unexpected_transport_response("recent announces drop"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::DropAnnounceQueues => {
|
||||
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
|
||||
RpcResponse::Ok
|
||||
match authoritative_query!(TransportQuery::DropAnnounceQueues, "announce queue drop") {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("announce queue drop"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetBlackholedIdentities => {
|
||||
match query_transport(transport_tx, TransportQuery::GetBlackholedIdentities).await {
|
||||
Some(TransportQueryResponse::BlackholeList(entries)) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::BlackholeEntry {
|
||||
identity_hash: e.identity_hash.to_vec(),
|
||||
source: e.source.map(|source| source.to_vec()),
|
||||
// Wire compat: `until` is absolute expiry (created + ttl);
|
||||
// permanent entries report `None`.
|
||||
until: e.ttl.map(|t| e.created + t),
|
||||
reason: Some(
|
||||
e.reason_label
|
||||
.unwrap_or_else(|| e.reason.as_str().to_string()),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
RpcResponse::BlackholeList(rpc_entries)
|
||||
}
|
||||
_ => RpcResponse::BlackholeList(Vec::new()),
|
||||
RpcRequest::GetBlackholedIdentities => match authoritative_query!(
|
||||
TransportQuery::GetBlackholedIdentities,
|
||||
"blackholed identity query"
|
||||
) {
|
||||
TransportQueryResponse::BlackholeList(entries) => {
|
||||
let rpc_entries = entries
|
||||
.into_iter()
|
||||
.map(|e| rpc::BlackholeEntry {
|
||||
identity_hash: e.identity_hash.to_vec(),
|
||||
source: e.source.map(|source| source.to_vec()),
|
||||
// Wire compat: `until` is absolute expiry (created + ttl);
|
||||
// permanent entries report `None`.
|
||||
until: e.ttl.map(|t| e.created + t),
|
||||
reason: Some(
|
||||
e.reason_label
|
||||
.unwrap_or_else(|| e.reason.as_str().to_string()),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
RpcResponse::BlackholeList(rpc_entries)
|
||||
}
|
||||
_ => unexpected_transport_response("blackholed identity query"),
|
||||
},
|
||||
RpcRequest::IsBlackholed { identity_hash } => {
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::IsBlackholed { hash },
|
||||
"blackhole status query"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("blackhole status query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::BlackholeIdentity {
|
||||
@@ -473,149 +539,154 @@ async fn process_rpc_request(
|
||||
until,
|
||||
reason,
|
||||
} => {
|
||||
if let Some(h) = hash_to_array(&identity_hash) {
|
||||
// `until` (absolute unix ts) → relative TTL; past timestamps
|
||||
// clamp to ~0 so the entry expires on the next maintenance tick.
|
||||
let ttl = until.map(|u| {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
(u - now).max(0.001)
|
||||
});
|
||||
let reason_enum = reason
|
||||
.as_deref()
|
||||
.map(rns_transport::blackhole::BlackholeReason::parse)
|
||||
.unwrap_or_default();
|
||||
let _ = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::BlackholeIdentity {
|
||||
hash: h,
|
||||
ttl,
|
||||
reason: reason_enum,
|
||||
reason_label: reason,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
// `until` (absolute unix ts) → relative TTL; past timestamps
|
||||
// clamp to ~0 so the entry expires on the next maintenance tick.
|
||||
let ttl = until.map(|until| {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs_f64();
|
||||
(until - now).max(0.001)
|
||||
});
|
||||
let reason_enum = reason
|
||||
.as_deref()
|
||||
.map(rns_transport::blackhole::BlackholeReason::parse)
|
||||
.unwrap_or_default();
|
||||
match authoritative_query!(
|
||||
TransportQuery::BlackholeIdentity {
|
||||
hash,
|
||||
ttl,
|
||||
reason: reason_enum,
|
||||
reason_label: reason,
|
||||
},
|
||||
"identity blackhole"
|
||||
) {
|
||||
TransportQueryResponse::Ok => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("identity blackhole"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::UnblackholeIdentity { identity_hash } => {
|
||||
if let Some(h) = hash_to_array(&identity_hash) {
|
||||
let _ = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::UnblackholeIdentity { hash: h },
|
||||
)
|
||||
.await;
|
||||
let Some(hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::UnblackholeIdentity { hash },
|
||||
"identity unblackhole"
|
||||
) {
|
||||
// Python's mutation response is success-shaped even when the
|
||||
// identity was not present; the typed actor result proves the
|
||||
// mutation was authoritatively processed.
|
||||
TransportQueryResponse::BoolResult(_) => RpcResponse::Ok,
|
||||
_ => unexpected_transport_response("identity unblackhole"),
|
||||
}
|
||||
RpcResponse::Ok
|
||||
}
|
||||
RpcRequest::GetFirstHopTimeout { destination_hash } => {
|
||||
let dest = hash_to_array(&destination_hash);
|
||||
match dest {
|
||||
Some(d) => {
|
||||
match query_transport(transport_tx, TransportQuery::FirstHopTimeout { dest: d })
|
||||
.await
|
||||
{
|
||||
Some(TransportQueryResponse::FloatResult(v)) => RpcResponse::FloatResult(v),
|
||||
_ => RpcResponse::FloatResult(None),
|
||||
}
|
||||
}
|
||||
None => RpcResponse::FloatResult(None),
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::FirstHopTimeout { dest },
|
||||
"first-hop timeout query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("first-hop timeout query"),
|
||||
}
|
||||
}
|
||||
RpcRequest::GetPacketRssi { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketRssi { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketRssi { packet_hash },
|
||||
"packet RSSI query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet RSSI query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::GetPacketSnr { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketSnr { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketSnr { packet_hash },
|
||||
"packet SNR query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet SNR query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::GetPacketQ { packet_hash } => {
|
||||
if let Some(hash) = packet_hash_to_array(&packet_hash) {
|
||||
if let Some(TransportQueryResponse::FloatResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::GetPacketQ { packet_hash: hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::FloatResult(v);
|
||||
}
|
||||
let Some(packet_hash) = packet_hash_to_array(&packet_hash) else {
|
||||
return invalid_request_hash("packet");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::GetPacketQ { packet_hash },
|
||||
"packet quality query"
|
||||
) {
|
||||
TransportQueryResponse::FloatResult(value) => RpcResponse::FloatResult(value),
|
||||
_ => unexpected_transport_response("packet quality query"),
|
||||
}
|
||||
RpcResponse::FloatResult(None)
|
||||
}
|
||||
RpcRequest::DropAllVia { transport_hash } => {
|
||||
if let Some(next_hop) = hash_to_array(&transport_hash) {
|
||||
if let Some(TransportQueryResponse::IntResult(n)) =
|
||||
query_transport(transport_tx, TransportQuery::DropAllVia { next_hop }).await
|
||||
{
|
||||
return RpcResponse::IntResult(n);
|
||||
}
|
||||
let Some(next_hop) = hash_to_array(&transport_hash) else {
|
||||
return invalid_request_hash("transport");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::DropAllVia { next_hop },
|
||||
"drop all via transport"
|
||||
) {
|
||||
TransportQueryResponse::IntResult(count) => RpcResponse::IntResult(count),
|
||||
_ => unexpected_transport_response("drop all via transport"),
|
||||
}
|
||||
RpcResponse::IntResult(0)
|
||||
}
|
||||
RpcRequest::UseDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::UseDestination { dest }).await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(TransportQuery::UseDestination { dest }, "destination use") {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination use"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::RetainDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::RetainDestination { dest }).await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::RetainDestination { dest },
|
||||
"destination retention"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination retention"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::RetainIdentity { identity_hash } => {
|
||||
if let Some(identity_hash) = hash_to_array(&identity_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) = query_transport(
|
||||
transport_tx,
|
||||
TransportQuery::RetainIdentity { identity_hash },
|
||||
)
|
||||
.await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(identity_hash) = hash_to_array(&identity_hash) else {
|
||||
return invalid_request_hash("identity");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::RetainIdentity { identity_hash },
|
||||
"identity retention"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("identity retention"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
RpcRequest::UnretainDestination { destination_hash } => {
|
||||
if let Some(dest) = hash_to_array(&destination_hash) {
|
||||
if let Some(TransportQueryResponse::BoolResult(v)) =
|
||||
query_transport(transport_tx, TransportQuery::UnretainDestination { dest })
|
||||
.await
|
||||
{
|
||||
return RpcResponse::BoolResult(v);
|
||||
}
|
||||
let Some(dest) = hash_to_array(&destination_hash) else {
|
||||
return invalid_request_hash("destination");
|
||||
};
|
||||
match authoritative_query!(
|
||||
TransportQuery::UnretainDestination { dest },
|
||||
"destination release"
|
||||
) {
|
||||
TransportQueryResponse::BoolResult(value) => RpcResponse::BoolResult(value),
|
||||
_ => unexpected_transport_response("destination release"),
|
||||
}
|
||||
RpcResponse::BoolResult(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -644,6 +715,70 @@ fn packet_hash_to_array(hash: &[u8]) -> Option<[u8; 32]> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn all_rpc_requests() -> Vec<RpcRequest> {
|
||||
vec![
|
||||
RpcRequest::GetPathTable { max_hops: Some(5) },
|
||||
RpcRequest::GetInterfaceStats,
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetNextHopIfName {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetNextHop {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetFirstHopTimeout {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkCount,
|
||||
RpcRequest::GetPacketRssi {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketSnr {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketQ {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetBlackholedIdentities,
|
||||
RpcRequest::IsBlackholed {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropAllVia {
|
||||
transport_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
until: Some(99999.0),
|
||||
reason: Some("test".to_string()),
|
||||
},
|
||||
RpcRequest::UnblackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UseDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rpc_server_bind_and_shutdown() {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
@@ -743,6 +878,81 @@ mod tests {
|
||||
shutdown.trigger();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_listener_returns_errors_when_transport_actor_is_closed() {
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
drop(rx);
|
||||
let rpc_key = b"closed_actor_key".to_vec();
|
||||
let port = spawn_test_rpc_server(rpc_key.clone(), tx, shutdown.clone()).await;
|
||||
|
||||
for request in all_rpc_requests() {
|
||||
let response = rpc_client_request(port, &rpc_key, request).await;
|
||||
assert!(
|
||||
matches!(response, RpcResponse::Error(_)),
|
||||
"closed transport actor must produce an RPC error, got {response:?}"
|
||||
);
|
||||
}
|
||||
|
||||
shutdown.trigger();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transport_query_reports_closed_send_and_response_channels() {
|
||||
let (closed_tx, closed_rx) = mpsc::channel(1);
|
||||
drop(closed_rx);
|
||||
assert!(matches!(
|
||||
query_transport(
|
||||
&closed_tx,
|
||||
rns_transport::messages::TransportQuery::GetLinkCount
|
||||
)
|
||||
.await,
|
||||
Err(TransportQueryFailure::ChannelClosed)
|
||||
));
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { response_tx, .. }) = rx.recv().await else {
|
||||
panic!("expected transport RPC query");
|
||||
};
|
||||
drop(response_tx);
|
||||
});
|
||||
assert!(matches!(
|
||||
query_transport(&tx, rns_transport::messages::TransportQuery::GetLinkCount).await,
|
||||
Err(TransportQueryFailure::ResponseClosed)
|
||||
));
|
||||
responder.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn transport_query_reports_enqueue_and_response_timeouts() {
|
||||
let (full_tx, full_rx) = mpsc::channel(1);
|
||||
full_tx.send(TransportMessage::Shutdown).await.unwrap();
|
||||
assert!(matches!(
|
||||
query_transport(
|
||||
&full_tx,
|
||||
rns_transport::messages::TransportQuery::GetLinkCount
|
||||
)
|
||||
.await,
|
||||
Err(TransportQueryFailure::SendTimedOut)
|
||||
));
|
||||
drop(full_rx);
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let responder = tokio::spawn(async move {
|
||||
let Some(TransportMessage::Rpc { response_tx, .. }) = rx.recv().await else {
|
||||
panic!("expected transport RPC query");
|
||||
};
|
||||
let _response_tx = response_tx;
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
assert!(matches!(
|
||||
query_transport(&tx, rns_transport::messages::TransportQuery::GetLinkCount).await,
|
||||
Err(TransportQueryFailure::ResponseTimedOut)
|
||||
));
|
||||
responder.abort();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_rpc_server_accepts_python_multiprocessing_client() {
|
||||
if std::process::Command::new("python3")
|
||||
@@ -763,6 +973,8 @@ mod tests {
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
|
||||
// Python >=1.3.4 clients speak umsgpack over send_bytes/recv_bytes
|
||||
// (commit a2ef9782); frames hardcoded so the test needs no msgpack module.
|
||||
let script = r#"
|
||||
import multiprocessing.connection
|
||||
import sys
|
||||
@@ -770,17 +982,17 @@ import sys
|
||||
port = int(sys.argv[1])
|
||||
authkey = bytes.fromhex(sys.argv[2])
|
||||
conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey)
|
||||
conn.send({"get": "link_count"})
|
||||
resp = conn.recv()
|
||||
conn.send_bytes(bytes.fromhex("81a3676574aa6c696e6b5f636f756e74")) # {"get": "link_count"}
|
||||
resp = conn.recv_bytes()
|
||||
conn.close()
|
||||
if resp != 0:
|
||||
raise SystemExit(f"unexpected response: {resp!r}")
|
||||
if resp != b"\x00":
|
||||
raise SystemExit(f"unexpected response: {resp.hex()}")
|
||||
conn = multiprocessing.connection.Client(("127.0.0.1", port), authkey=authkey)
|
||||
conn.send({"get": "interface_stats"})
|
||||
resp = conn.recv()
|
||||
conn.send_bytes(bytes.fromhex("81a3676574af696e746572666163655f7374617473")) # {"get": "interface_stats"}
|
||||
resp = conn.recv_bytes()
|
||||
conn.close()
|
||||
if not isinstance(resp, dict) or "interfaces" not in resp:
|
||||
raise SystemExit(f"unexpected interface_stats response: {resp!r}")
|
||||
if b"\xaainterfaces" not in resp:
|
||||
raise SystemExit(f"unexpected interface_stats response: {resp.hex()}")
|
||||
"#;
|
||||
let output = std::process::Command::new("python3")
|
||||
.arg("-c")
|
||||
@@ -813,6 +1025,9 @@ if not isinstance(resp, dict) or "interfaces" not in resp:
|
||||
|
||||
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
|
||||
// is needed.
|
||||
let script = r#"
|
||||
import multiprocessing.connection
|
||||
import sys
|
||||
@@ -822,10 +1037,10 @@ authkey = bytes.fromhex(sys.argv[2])
|
||||
listener = multiprocessing.connection.Listener(("127.0.0.1", port), authkey=authkey)
|
||||
print("READY", flush=True)
|
||||
conn = listener.accept()
|
||||
call = conn.recv()
|
||||
if call != {"get": "link_count"}:
|
||||
raise SystemExit(f"unexpected call: {call!r}")
|
||||
conn.send(7)
|
||||
call = conn.recv_bytes()
|
||||
if call != bytes.fromhex("81a3676574aa6c696e6b5f636f756e74"): # {"get": "link_count"}
|
||||
raise SystemExit(f"unexpected call: {call.hex()}")
|
||||
conn.send_bytes(b"\x07") # 7
|
||||
conn.close()
|
||||
listener.close()
|
||||
"#;
|
||||
@@ -892,63 +1107,7 @@ listener.close()
|
||||
let (actor, tx) = rns_transport::actor::TransportActor::new();
|
||||
tokio::spawn(actor.run());
|
||||
|
||||
let requests = vec![
|
||||
RpcRequest::GetPathTable { max_hops: Some(5) },
|
||||
RpcRequest::GetInterfaceStats,
|
||||
RpcRequest::GetRateTable,
|
||||
RpcRequest::GetNextHopIfName {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetNextHop {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RequestPath {
|
||||
destination_hash: vec![0; 16],
|
||||
timeout_secs: Some(0.01),
|
||||
},
|
||||
RpcRequest::GetFirstHopTimeout {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::GetLinkCount,
|
||||
RpcRequest::GetPacketRssi {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketSnr {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetPacketQ {
|
||||
packet_hash: vec![0; 32],
|
||||
},
|
||||
RpcRequest::GetBlackholedIdentities,
|
||||
RpcRequest::DropPath {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropAllVia {
|
||||
transport_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::DropPathTable,
|
||||
RpcRequest::DropRecentAnnounces,
|
||||
RpcRequest::DropAnnounceQueues,
|
||||
RpcRequest::BlackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
until: Some(99999.0),
|
||||
reason: Some("test".to_string()),
|
||||
},
|
||||
RpcRequest::UnblackholeIdentity {
|
||||
identity_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UseDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::RetainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
RpcRequest::UnretainDestination {
|
||||
destination_hash: vec![0; 16],
|
||||
},
|
||||
];
|
||||
|
||||
for req in requests {
|
||||
for req in all_rpc_requests() {
|
||||
let resp = process_rpc_request(req, &tx).await;
|
||||
assert!(
|
||||
!matches!(resp, RpcResponse::Error(_)),
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "rns-tools"
|
||||
description = "Rust CLI utilities for Reticulum (rnsd-rs, rnstatus-rs, etc.)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
autobins = false
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
|
||||
};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
|
||||
use rns_tools::RETICULUM_COMPAT_VERSION;
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -197,7 +197,7 @@ fn load_or_create_identity(
|
||||
pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
if args.version {
|
||||
println!("rncp-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rncp-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
if args.phy_rates {
|
||||
@@ -213,10 +213,13 @@ pub(crate) async fn main() {
|
||||
0 => tracing::Level::WARN,
|
||||
_ => tracing::Level::ERROR,
|
||||
};
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(level)
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&config_dir),
|
||||
true,
|
||||
std::io::stderr,
|
||||
);
|
||||
|
||||
if args.fetch {
|
||||
run_fetch(args).await;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Base256 armored encoding for rsg/rsm data.
|
||||
//!
|
||||
//! Python ref: 1.3.8 `RNS/__init__.py` `b256`/`b256rep`/`b256_to_bytes` (commit
|
||||
//! 855ef7bf). Upstream marks the glyph table experimental ("likely to change") —
|
||||
//! this is the 1.3.8 snapshot; re-check on upstream release sweeps.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// One glyph per byte value 0x00..=0xFF, in upstream table order
|
||||
/// (Latin/numerals, Greek, Cyrillic, Armenian, Elder Futhark, Katakana,
|
||||
/// Shavian, Ol Chiki, Gothic & Deseret).
|
||||
const B256_GLYPHS: &str = "abcdefghijklmnopqrstuvxyzæø01234\
|
||||
ABCDEFGHIJKLMNOPQRSTUWXYZÆØ56789\
|
||||
αβγδεζηθικλμνξπρστφχψωΓΔΘΛΞΠΣΦΨΩ\
|
||||
БДЖЗИЛПЦЧШЩЪЫЭЮЯбджзилпцчшщъыэюя\
|
||||
ԱԲԳԴԵԶԷԸԹԺԻԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՎՐՑՒՔՖ\
|
||||
ᚠᚢᚦᚱᚹᚺᚾᛈᛇᛉᛊᛏᛒᛖᛗᛟ\
|
||||
イウオカキケサシスセタチテトナヌ\
|
||||
ネヒフヘホマミムメモヤラリルレワ\
|
||||
𐑐𐑑𐑒𐑔𐑕𐑗𐑙𐑳𐑶𐑸𐑹𐑺𐑻𐑽𐑾𐑿\
|
||||
᱑᱕᱘᱙ᱚᱝᱟᱣᱦᱨᱬᱭᱰᱳᱶᱷ\
|
||||
𐌳𐌸𐌾𐐀𐐁𐐂𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏";
|
||||
|
||||
static B256: LazyLock<Vec<char>> = LazyLock::new(|| {
|
||||
let table: Vec<char> = B256_GLYPHS.chars().collect();
|
||||
assert_eq!(table.len(), 256, "b256 glyph table must hold 256 entries");
|
||||
table
|
||||
});
|
||||
|
||||
static B256_INDEX: LazyLock<HashMap<char, u8>> = LazyLock::new(|| {
|
||||
B256.iter()
|
||||
.enumerate()
|
||||
.map(|(index, glyph)| (*glyph, index as u8))
|
||||
.collect()
|
||||
});
|
||||
|
||||
pub fn b256rep(data: &[u8]) -> String {
|
||||
data.iter().map(|byte| B256[*byte as usize]).collect()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn b256_to_bytes(input: &str) -> Result<Vec<u8>, String> {
|
||||
input
|
||||
.chars()
|
||||
.map(|glyph| {
|
||||
B256_INDEX
|
||||
.get(&glyph)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("Could not decode base256: invalid glyph {glyph:?}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Generated by running the verbatim 1.3.8 RNS/__init__.py b256 helpers over
|
||||
// bytes(range(256)) — proves the table copy is glyph-for-glyph faithful.
|
||||
const PYTHON_138_ALL_BYTES: &str = "abcdefghijklmnopqrstuvxyzæø01234ABCDEFGHIJKLMNOPQRSTUWXYZÆØ56789αβγδεζηθικλμνξπρστφχψωΓΔΘΛΞΠΣΦΨΩБДЖЗИЛПЦЧШЩЪЫЭЮЯбджзилпцчшщъыэюяԱԲԳԴԵԶԷԸԹԺԻԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՎՐՑՒՔՖᚠᚢᚦᚱᚹᚺᚾᛈᛇᛉᛊᛏᛒᛖᛗᛟイウオカキケサシスセタチテトナヌネヒフヘホマミムメモヤラリルレワ𐑐𐑑𐑒𐑔𐑕𐑗𐑙𐑳𐑶𐑸𐑹𐑺𐑻𐑽𐑾𐑿᱑᱕᱘᱙ᱚᱝᱟᱣᱦᱨᱬᱭᱰᱳᱶᱷ𐌳𐌸𐌾𐐀𐐁𐐂𐐆𐐇𐐈𐐉𐐊𐐋𐐌𐐍𐐎𐐏";
|
||||
|
||||
#[test]
|
||||
fn matches_python_138_table() {
|
||||
let all_bytes: Vec<u8> = (0..=255u8).collect();
|
||||
assert_eq!(b256rep(&all_bytes), PYTHON_138_ALL_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_all_byte_values() {
|
||||
let all_bytes: Vec<u8> = (0..=255u8).collect();
|
||||
let encoded = b256rep(&all_bytes);
|
||||
assert_eq!(b256_to_bytes(&encoded).unwrap(), all_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_rejects_unknown_glyph() {
|
||||
assert!(b256_to_bytes("ab!").is_err());
|
||||
// 'w' and 'V' are deliberately absent from the upstream table.
|
||||
assert!(b256_to_bytes("w").is_err());
|
||||
assert!(b256_to_bytes("V").is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,524 @@
|
||||
//! RSM metadata embedding: ConfigObj-subset INI parsing plus the Validator
|
||||
//! subset used for `--meta-spec` (string/integer/float/boolean with min/max/
|
||||
//! default; unknown checks fail validation, matching upstream behavior where
|
||||
//! Validator returns a failed result for unrecognized check names).
|
||||
//!
|
||||
//! Python ref: 1.3.8 `RNS/Utilities/rnid.py:566-586` (`rsg_meta_from_file`,
|
||||
//! commit f0824fd7) with `RNS/vendor/configobj.py` + `RNS/vendor/validate.py`.
|
||||
//! Like upstream, spec check expressions containing commas are unusable: the
|
||||
//! INI list division splits them before check parsing (upstream raises inside
|
||||
//! Validator; here it is a validation error on the same rnid error path).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum MetaValue {
|
||||
Str(String),
|
||||
List(Vec<String>),
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct MetaSection {
|
||||
pub scalars: Vec<(String, MetaValue)>,
|
||||
pub sections: Vec<(String, MetaSection)>,
|
||||
}
|
||||
|
||||
impl MetaSection {
|
||||
fn scalar_mut(&mut self, key: &str) -> Option<&mut MetaValue> {
|
||||
self.scalars
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
fn has_scalar(&self, key: &str) -> bool {
|
||||
self.scalars.iter().any(|(k, _)| k == key)
|
||||
}
|
||||
|
||||
fn has_section(&self, name: &str) -> bool {
|
||||
self.sections.iter().any(|(k, _)| k == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load and parse a metadata file, optionally validating against a spec file.
|
||||
/// Mirrors `rsg_meta_from_file` (1.3.8 rnid.py:566-575).
|
||||
pub fn rsg_meta_from_file(
|
||||
path: &Path,
|
||||
spec_path: Option<&Path>,
|
||||
) -> Result<Vec<(String, Value)>, String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
let mut meta = parse_ini(&content)?;
|
||||
if let Some(spec_path) = spec_path {
|
||||
let spec_content = std::fs::read_to_string(spec_path).map_err(|e| e.to_string())?;
|
||||
let spec = parse_ini(&spec_content)?;
|
||||
validate_section(&mut meta, &spec)
|
||||
.map_err(|_| "Metadata did not pass spec validation".to_string())?;
|
||||
}
|
||||
Ok(section_to_values(&meta))
|
||||
}
|
||||
|
||||
/// Convert a parsed section to ordered `(key, msgpack value)` pairs, scalars
|
||||
/// first then subsections — the same ordering ConfigObj `.dict()` yields.
|
||||
pub fn section_to_values(section: &MetaSection) -> Vec<(String, Value)> {
|
||||
let mut out = Vec::with_capacity(section.scalars.len() + section.sections.len());
|
||||
for (key, value) in §ion.scalars {
|
||||
out.push((key.clone(), meta_value_to_rmpv(value)));
|
||||
}
|
||||
for (name, sub) in §ion.sections {
|
||||
let entries = section_to_values(sub)
|
||||
.into_iter()
|
||||
.map(|(k, v)| (Value::from(k.as_str()), v))
|
||||
.collect();
|
||||
out.push((name.clone(), Value::Map(entries)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn meta_value_to_rmpv(value: &MetaValue) -> Value {
|
||||
match value {
|
||||
MetaValue::Str(s) => Value::from(s.as_str()),
|
||||
MetaValue::List(items) => {
|
||||
Value::Array(items.iter().map(|s| Value::from(s.as_str())).collect())
|
||||
}
|
||||
MetaValue::Int(i) => Value::from(*i),
|
||||
MetaValue::Float(f) => Value::F64(*f),
|
||||
MetaValue::Bool(b) => Value::Boolean(*b),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_ini(content: &str) -> Result<MetaSection, String> {
|
||||
let mut root = MetaSection::default();
|
||||
let mut path: Vec<String> = Vec::new();
|
||||
|
||||
for (index, raw_line) in content.lines().enumerate() {
|
||||
let line_num = index + 1;
|
||||
let line = raw_line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if line.starts_with('[') {
|
||||
let depth = line.chars().take_while(|&c| c == '[').count();
|
||||
let closing = line.chars().rev().take_while(|&c| c == ']').count();
|
||||
if depth != closing || line.len() < depth + closing {
|
||||
return Err(format!("line {line_num}: malformed section header"));
|
||||
}
|
||||
let name = unquote(line[depth..line.len() - closing].trim());
|
||||
if name.is_empty() {
|
||||
return Err(format!("line {line_num}: empty section name"));
|
||||
}
|
||||
if depth > path.len() + 1 {
|
||||
return Err(format!("line {line_num}: section nested too deep"));
|
||||
}
|
||||
path.truncate(depth - 1);
|
||||
let parent = section_for_path(&mut root, &path);
|
||||
if parent.has_section(&name) || parent.has_scalar(&name) {
|
||||
return Err(format!("line {line_num}: duplicate section name"));
|
||||
}
|
||||
parent.sections.push((name.clone(), MetaSection::default()));
|
||||
path.push(name);
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(eq_pos) = line.find('=') else {
|
||||
return Err(format!("line {line_num}: unrecognized line"));
|
||||
};
|
||||
let key = unquote(line[..eq_pos].trim());
|
||||
if key.is_empty() {
|
||||
return Err(format!("line {line_num}: empty key"));
|
||||
}
|
||||
let value =
|
||||
parse_value(line[eq_pos + 1..].trim()).map_err(|e| format!("line {line_num}: {e}"))?;
|
||||
let section = section_for_path(&mut root, &path);
|
||||
if section.has_scalar(&key) || section.has_section(&key) {
|
||||
return Err(format!("line {line_num}: duplicate keyword name"));
|
||||
}
|
||||
section.scalars.push((key, value));
|
||||
}
|
||||
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
fn section_for_path<'a>(root: &'a mut MetaSection, path: &[String]) -> &'a mut MetaSection {
|
||||
let mut current = root;
|
||||
for name in path {
|
||||
let index = current
|
||||
.sections
|
||||
.iter()
|
||||
.position(|(k, _)| k == name)
|
||||
.expect("section path always points at existing sections");
|
||||
current = &mut current.sections[index].1;
|
||||
}
|
||||
current
|
||||
}
|
||||
|
||||
/// ConfigObj value semantics: inline comments outside quotes are stripped;
|
||||
/// commas outside quotes divide the value into a list of strings; a lone
|
||||
/// comma is the empty-list marker; members are unquoted.
|
||||
fn parse_value(input: &str) -> Result<MetaValue, String> {
|
||||
let stripped = strip_inline_comment(input);
|
||||
let trimmed = stripped.trim();
|
||||
if trimmed.starts_with("\"\"\"") || trimmed.starts_with("'''") {
|
||||
return Err("multiline values are not supported".to_string());
|
||||
}
|
||||
if trimmed == "," {
|
||||
return Ok(MetaValue::List(Vec::new()));
|
||||
}
|
||||
|
||||
let members = split_unquoted_commas(trimmed)?;
|
||||
if members.len() == 1 {
|
||||
return Ok(MetaValue::Str(unquote(members[0].trim())));
|
||||
}
|
||||
|
||||
let mut items = Vec::new();
|
||||
for (index, member) in members.iter().enumerate() {
|
||||
let member = member.trim();
|
||||
if member.is_empty() {
|
||||
if index == members.len() - 1 {
|
||||
continue; // trailing comma
|
||||
}
|
||||
return Err("empty list member".to_string());
|
||||
}
|
||||
items.push(unquote(member));
|
||||
}
|
||||
Ok(MetaValue::List(items))
|
||||
}
|
||||
|
||||
fn strip_inline_comment(input: &str) -> &str {
|
||||
let mut quote: Option<char> = None;
|
||||
for (pos, ch) in input.char_indices() {
|
||||
match quote {
|
||||
Some(q) if ch == q => quote = None,
|
||||
None if ch == '\'' || ch == '"' => quote = Some(ch),
|
||||
None if ch == '#' => return &input[..pos],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
input
|
||||
}
|
||||
|
||||
fn split_unquoted_commas(input: &str) -> Result<Vec<&str>, String> {
|
||||
let mut members = Vec::new();
|
||||
let mut quote: Option<char> = None;
|
||||
let mut start = 0;
|
||||
for (pos, ch) in input.char_indices() {
|
||||
match quote {
|
||||
Some(q) if ch == q => quote = None,
|
||||
None if ch == '\'' || ch == '"' => quote = Some(ch),
|
||||
None if ch == ',' => {
|
||||
members.push(&input[start..pos]);
|
||||
start = pos + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if quote.is_some() {
|
||||
return Err("unterminated quote".to_string());
|
||||
}
|
||||
members.push(&input[start..]);
|
||||
Ok(members)
|
||||
}
|
||||
|
||||
fn unquote(token: &str) -> String {
|
||||
let bytes = token.as_bytes();
|
||||
if bytes.len() >= 2 {
|
||||
let first = bytes[0];
|
||||
if (first == b'\'' || first == b'"') && bytes[bytes.len() - 1] == first {
|
||||
return token[1..token.len() - 1].to_string();
|
||||
}
|
||||
}
|
||||
token.to_string()
|
||||
}
|
||||
|
||||
/// Walk the spec, coercing matching meta values in place. Missing keys take
|
||||
/// the check's `default` when present and fail validation otherwise; unknown
|
||||
/// check names fail; keys absent from the spec pass through untouched.
|
||||
fn validate_section(meta: &mut MetaSection, spec: &MetaSection) -> Result<(), ()> {
|
||||
for (key, check) in &spec.scalars {
|
||||
let MetaValue::Str(check) = check else {
|
||||
// A list here means the check expression contained commas, which
|
||||
// ConfigObj list division splits before Validator ever runs.
|
||||
return Err(());
|
||||
};
|
||||
let check = parse_check(check)?;
|
||||
match meta.scalar_mut(key) {
|
||||
Some(value) => *value = apply_check(&check, value)?,
|
||||
None => {
|
||||
let default = check.default.as_ref().ok_or(())?;
|
||||
let coerced = apply_check(&check, &MetaValue::Str(default.clone()))?;
|
||||
meta.scalars.push((key.clone(), coerced));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, sub_spec) in &spec.sections {
|
||||
if !meta.has_section(name) {
|
||||
meta.sections.push((name.clone(), MetaSection::default()));
|
||||
}
|
||||
let sub = meta
|
||||
.sections
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k == name)
|
||||
.map(|(_, v)| v)
|
||||
.expect("section ensured above");
|
||||
validate_section(sub, sub_spec)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Check {
|
||||
name: String,
|
||||
min: Option<String>,
|
||||
max: Option<String>,
|
||||
default: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_check(expr: &str) -> Result<Check, ()> {
|
||||
let expr = expr.trim();
|
||||
let (name, arg) = match expr.find('(') {
|
||||
Some(open) => {
|
||||
if !expr.ends_with(')') {
|
||||
return Err(());
|
||||
}
|
||||
(
|
||||
expr[..open].trim(),
|
||||
Some(expr[open + 1..expr.len() - 1].trim()),
|
||||
)
|
||||
}
|
||||
None => (expr, None),
|
||||
};
|
||||
let mut check = Check {
|
||||
name: name.to_string(),
|
||||
min: None,
|
||||
max: None,
|
||||
default: None,
|
||||
};
|
||||
if let Some(arg) = arg.filter(|a| !a.is_empty()) {
|
||||
match arg.split_once('=') {
|
||||
Some((kw, value)) => match kw.trim() {
|
||||
"min" => check.min = Some(unquote(value.trim())),
|
||||
"max" => check.max = Some(unquote(value.trim())),
|
||||
"default" => check.default = Some(unquote(value.trim())),
|
||||
_ => return Err(()),
|
||||
},
|
||||
// Single positional argument is `min` (validate.py `('min', 'max')`).
|
||||
None => check.min = Some(unquote(arg)),
|
||||
}
|
||||
}
|
||||
Ok(check)
|
||||
}
|
||||
|
||||
fn apply_check(check: &Check, value: &MetaValue) -> Result<MetaValue, ()> {
|
||||
match check.name.as_str() {
|
||||
"string" => {
|
||||
let MetaValue::Str(s) = value else {
|
||||
return Err(());
|
||||
};
|
||||
let min = parse_bound_int(&check.min)?;
|
||||
let max = parse_bound_int(&check.max)?;
|
||||
let len = s.chars().count() as i64;
|
||||
if min.is_some_and(|m| len < m) || max.is_some_and(|m| len > m) {
|
||||
return Err(());
|
||||
}
|
||||
Ok(MetaValue::Str(s.clone()))
|
||||
}
|
||||
"integer" => {
|
||||
let MetaValue::Str(s) = value else {
|
||||
return Err(());
|
||||
};
|
||||
let parsed: i64 = s.trim().parse().map_err(|_| ())?;
|
||||
let min = parse_bound_int(&check.min)?;
|
||||
let max = parse_bound_int(&check.max)?;
|
||||
if min.is_some_and(|m| parsed < m) || max.is_some_and(|m| parsed > m) {
|
||||
return Err(());
|
||||
}
|
||||
Ok(MetaValue::Int(parsed))
|
||||
}
|
||||
"float" => {
|
||||
let MetaValue::Str(s) = value else {
|
||||
return Err(());
|
||||
};
|
||||
let parsed: f64 = s.trim().parse().map_err(|_| ())?;
|
||||
let min = parse_bound_float(&check.min)?;
|
||||
let max = parse_bound_float(&check.max)?;
|
||||
if min.is_some_and(|m| parsed < m) || max.is_some_and(|m| parsed > m) {
|
||||
return Err(());
|
||||
}
|
||||
Ok(MetaValue::Float(parsed))
|
||||
}
|
||||
"boolean" => {
|
||||
if check.min.is_some() || check.max.is_some() {
|
||||
return Err(());
|
||||
}
|
||||
let MetaValue::Str(s) = value else {
|
||||
return Err(());
|
||||
};
|
||||
match s.to_lowercase().as_str() {
|
||||
"on" | "1" | "true" | "yes" => Ok(MetaValue::Bool(true)),
|
||||
"off" | "0" | "false" | "no" => Ok(MetaValue::Bool(false)),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bound_int(bound: &Option<String>) -> Result<Option<i64>, ()> {
|
||||
bound
|
||||
.as_ref()
|
||||
.map(|s| s.trim().parse().map_err(|_| ()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn parse_bound_float(bound: &Option<String>) -> Result<Option<f64>, ()> {
|
||||
bound
|
||||
.as_ref()
|
||||
.map(|s| s.trim().parse().map_err(|_| ()))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_and_validate(ini: &str, spec: &str) -> Result<MetaSection, ()> {
|
||||
let mut meta = parse_ini(ini).map_err(|_| ())?;
|
||||
let spec = parse_ini(spec).map_err(|_| ())?;
|
||||
validate_section(&mut meta, &spec)?;
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_scalars_lists_and_nested_sections_in_order() {
|
||||
// Semantics cross-checked against the vendored ConfigObj: comment
|
||||
// stripping, quote handling, list division, trailing comma.
|
||||
let meta = parse_ini(concat!(
|
||||
"title = Test Release\n",
|
||||
"tags = alpha, beta, gamma\n",
|
||||
"empty =\n",
|
||||
"quoted = \"hello # world\"\n",
|
||||
"inline = value # trailing comment\n",
|
||||
"single_item_list = one,\n",
|
||||
"[origin]\n",
|
||||
"name = Origins\n",
|
||||
"[[nested]]\n",
|
||||
"deep = yes\n",
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
meta.scalars,
|
||||
vec![
|
||||
("title".into(), MetaValue::Str("Test Release".into())),
|
||||
(
|
||||
"tags".into(),
|
||||
MetaValue::List(vec!["alpha".into(), "beta".into(), "gamma".into()])
|
||||
),
|
||||
("empty".into(), MetaValue::Str(String::new())),
|
||||
("quoted".into(), MetaValue::Str("hello # world".into())),
|
||||
("inline".into(), MetaValue::Str("value".into())),
|
||||
(
|
||||
"single_item_list".into(),
|
||||
MetaValue::List(vec!["one".into()])
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(meta.sections.len(), 1);
|
||||
let (name, origin) = &meta.sections[0];
|
||||
assert_eq!(name, "origin");
|
||||
assert_eq!(
|
||||
origin.scalars,
|
||||
vec![("name".into(), MetaValue::Str("Origins".into()))]
|
||||
);
|
||||
assert_eq!(origin.sections[0].0, "nested");
|
||||
assert_eq!(
|
||||
origin.sections[0].1.scalars,
|
||||
vec![("deep".into(), MetaValue::Str("yes".into()))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicates_and_bad_nesting() {
|
||||
assert!(parse_ini("a = 1\na = 2\n").is_err());
|
||||
assert!(parse_ini("[s]\n[s]\n").is_err());
|
||||
assert!(parse_ini("[[deep]]\n").is_err());
|
||||
assert!(parse_ini("no equals sign\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_coerces_types_and_fills_defaults() {
|
||||
let meta = parse_and_validate(
|
||||
"name = pkg\nversion = 7\nweight = 2.5\nactive = yes\n",
|
||||
"name = string(max=64)\nversion = integer(max=100)\nweight = float(min=0)\nactive = boolean\nextra = string(default=filled)\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
meta.scalars,
|
||||
vec![
|
||||
("name".into(), MetaValue::Str("pkg".into())),
|
||||
("version".into(), MetaValue::Int(7)),
|
||||
("weight".into(), MetaValue::Float(2.5)),
|
||||
("active".into(), MetaValue::Bool(true)),
|
||||
("extra".into(), MetaValue::Str("filled".into())),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_failures_match_upstream_validator() {
|
||||
// Out of range.
|
||||
assert!(parse_and_validate("version = 200\n", "version = integer(max=100)\n").is_err());
|
||||
// Missing key without default.
|
||||
assert!(parse_and_validate("name = pkg\n", "name = string\ncount = integer\n").is_err());
|
||||
// Unknown check name.
|
||||
assert!(parse_and_validate("name = pkg\n", "name = ip_addr_list\n").is_err());
|
||||
// Comma'd check expressions break upstream too (list division).
|
||||
assert!(parse_and_validate("version = 7\n", "version = integer(1, 100)\n").is_err());
|
||||
// Non-boolean value for boolean check.
|
||||
assert!(parse_and_validate("active = maybe\n", "active = boolean\n").is_err());
|
||||
// Single positional argument is min.
|
||||
assert!(parse_and_validate("version = 3\n", "version = integer(5)\n").is_err());
|
||||
assert!(parse_and_validate("version = 7\n", "version = integer(5)\n").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_validates_nested_sections_and_ignores_extra_keys() {
|
||||
let meta = parse_and_validate(
|
||||
"extra = untouched\n[sec]\nport = 8\n",
|
||||
"[sec]\nport = integer\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
meta.scalars,
|
||||
vec![("extra".into(), MetaValue::Str("untouched".into()))]
|
||||
);
|
||||
assert_eq!(
|
||||
meta.sections[0].1.scalars,
|
||||
vec![("port".into(), MetaValue::Int(8))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_to_ordered_msgpack_values() {
|
||||
let meta = parse_ini("title = t\ntags = a, b\n[origin]\nname = o\n").unwrap();
|
||||
let values = section_to_values(&meta);
|
||||
assert_eq!(values[0], ("title".to_string(), Value::from("t")));
|
||||
assert_eq!(
|
||||
values[1],
|
||||
(
|
||||
"tags".to_string(),
|
||||
Value::Array(vec![Value::from("a"), Value::from("b")])
|
||||
)
|
||||
);
|
||||
let (key, origin) = &values[2];
|
||||
assert_eq!(key, "origin");
|
||||
assert_eq!(
|
||||
origin,
|
||||
&Value::Map(vec![(Value::from("name"), Value::from("o"))])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,8 @@ pub struct ValidatedRsg {
|
||||
pub signer_hash: [u8; 16],
|
||||
pub file_hash: [u8; 32],
|
||||
pub public_key: [u8; 64],
|
||||
/// Full envelope meta map, for `--meta` display (Python signed_data["meta"]).
|
||||
pub meta: Vec<(Value, Value)>,
|
||||
}
|
||||
|
||||
struct ParsedEnvelope {
|
||||
@@ -72,19 +74,34 @@ struct ParsedEnvelope {
|
||||
file_hash: [u8; 32],
|
||||
signer_hash: [u8; 16],
|
||||
public_key: [u8; 64],
|
||||
meta: Vec<(Value, Value)>,
|
||||
}
|
||||
|
||||
pub fn is_legacy_format(rsg_data: &[u8]) -> bool {
|
||||
rsg_data.len() == SIG_LEN
|
||||
}
|
||||
|
||||
pub fn create_rsg<R: Read>(signer_identity: &Identity, message: R) -> Result<Vec<u8>, RsgError> {
|
||||
/// Python ref: 1.3.8 rnid.py:488-516 create_rsg. With `embed` the message
|
||||
/// bytes are packed into the envelope under "message"; `meta` keys not
|
||||
/// already present are merged into the envelope meta map (rnid.py:501-503).
|
||||
pub fn create_rsg<R: Read>(
|
||||
signer_identity: &Identity,
|
||||
mut message: R,
|
||||
embed: bool,
|
||||
meta: Option<&[(String, Value)]>,
|
||||
) -> Result<Vec<u8>, RsgError> {
|
||||
if !signer_identity.has_private_key() {
|
||||
return Err(RsgError::MissingPrivateKey);
|
||||
}
|
||||
|
||||
let file_hash = sha256_reader(message)?;
|
||||
let envelope = encode_envelope(signer_identity, file_hash)?;
|
||||
let (file_hash, embedded) = if embed {
|
||||
let mut data = Vec::new();
|
||||
message.read_to_end(&mut data)?;
|
||||
(rns_crypto::sha::sha256(&data), Some(data))
|
||||
} else {
|
||||
(sha256_reader(message)?, None)
|
||||
};
|
||||
let envelope = encode_envelope(signer_identity, file_hash, embedded.as_deref(), meta)?;
|
||||
let signature = signer_identity
|
||||
.sign(&envelope)
|
||||
.ok_or(RsgError::MissingPrivateKey)?;
|
||||
@@ -95,6 +112,17 @@ pub fn create_rsg<R: Read>(signer_identity: &Identity, message: R) -> Result<Vec
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// TODO(rngit): Python 1.3.8 rnid.py:588-600 also hosts check_release_rsm_structure,
|
||||
// the canonical release-manifest validator consumed only by rngit/server.py.
|
||||
// Excluded per the rngit/release-manifest stub policy; a Rust rngit must port it.
|
||||
|
||||
/// Decode the msgpack envelope after the 64-byte signature without any
|
||||
/// validation. Python ref: 1.3.8 rnid.py:413-419 extract_signed_rsg_data.
|
||||
pub fn extract_signed_rsg_data(rsg_data: &[u8]) -> Option<Value> {
|
||||
let envelope = rsg_data.get(SIG_LEN..)?;
|
||||
rmpv::decode::read_value(&mut Cursor::new(envelope)).ok()
|
||||
}
|
||||
|
||||
pub fn create_raw_signature<R: Read>(
|
||||
signer_identity: &Identity,
|
||||
mut message: R,
|
||||
@@ -163,6 +191,7 @@ pub fn validate_rsg<R: Read>(
|
||||
signer_hash: parsed.signer_hash,
|
||||
file_hash: parsed.file_hash,
|
||||
public_key: parsed.public_key,
|
||||
meta: parsed.meta,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -198,20 +227,42 @@ fn sha256_reader<R: Read>(mut reader: R) -> Result<[u8; 32], RsgError> {
|
||||
Ok(hasher.finalize().into())
|
||||
}
|
||||
|
||||
fn encode_envelope(identity: &Identity, file_hash: [u8; 32]) -> Result<Vec<u8>, RsgError> {
|
||||
let meta = Value::Map(vec![
|
||||
// Envelope layout matches Python 1.3.8 byte-for-byte: top-level key order
|
||||
// hashtype, hash, meta, [message]; meta order signer, pubkey, then merged
|
||||
// keys. The meta.note field is no longer emitted (dropped upstream in
|
||||
// 1.2.8/1.3.2, commits a2193b9f/22ab5c29).
|
||||
fn encode_envelope(
|
||||
identity: &Identity,
|
||||
file_hash: [u8; 32],
|
||||
message: Option<&[u8]>,
|
||||
meta: Option<&[(String, Value)]>,
|
||||
) -> Result<Vec<u8>, RsgError> {
|
||||
let mut meta_entries = vec![
|
||||
(Value::from("signer"), Value::Binary(identity.hash.to_vec())),
|
||||
(
|
||||
Value::from("pubkey"),
|
||||
Value::Binary(identity.get_public_key().to_vec()),
|
||||
),
|
||||
(Value::from("note"), Value::Nil),
|
||||
]);
|
||||
let envelope = Value::Map(vec![
|
||||
];
|
||||
if let Some(meta) = meta {
|
||||
for (key, value) in meta {
|
||||
let present = meta_entries
|
||||
.iter()
|
||||
.any(|(k, _)| value_as_str(k) == Some(key.as_str()));
|
||||
if !present {
|
||||
meta_entries.push((Value::from(key.as_str()), value.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut entries = vec![
|
||||
(Value::from("hashtype"), Value::from(HASH_TYPE_SHA256)),
|
||||
(Value::from("hash"), Value::Binary(file_hash.to_vec())),
|
||||
(Value::from("meta"), meta),
|
||||
]);
|
||||
(Value::from("meta"), Value::Map(meta_entries)),
|
||||
];
|
||||
if let Some(message) = message {
|
||||
entries.push((Value::from("message"), Value::Binary(message.to_vec())));
|
||||
}
|
||||
let envelope = Value::Map(entries);
|
||||
let mut buf = Vec::new();
|
||||
rmpv::encode::write_value(&mut buf, &envelope).map_err(|e| RsgError::Msgpack(e.to_string()))?;
|
||||
Ok(buf)
|
||||
@@ -244,15 +295,15 @@ fn parse_envelope(envelope: &[u8]) -> Result<ParsedEnvelope, RsgError> {
|
||||
.and_then(value_as_bytes)
|
||||
.and_then(slice_to_array::<64>)
|
||||
.ok_or(RsgError::InvalidEnvelope("missing or invalid meta.pubkey"))?;
|
||||
if map_get(meta_map, "note").is_none() {
|
||||
return Err(RsgError::InvalidEnvelope("missing meta.note"));
|
||||
}
|
||||
// meta.note is neither required nor emitted since upstream 1.2.8/1.3.2;
|
||||
// envelopes still carrying it (incl. note:nil) remain accepted.
|
||||
|
||||
Ok(ParsedEnvelope {
|
||||
hashtype,
|
||||
file_hash,
|
||||
signer_hash,
|
||||
public_key,
|
||||
meta: meta_map.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -342,7 +393,7 @@ mod tests {
|
||||
#[test]
|
||||
fn validates_new_rsg_with_embedded_signer() {
|
||||
let identity = Identity::new();
|
||||
let rsg = create_rsg(&identity, message()).unwrap();
|
||||
let rsg = create_rsg(&identity, message(), false, None).unwrap();
|
||||
assert!(!is_legacy_format(&rsg));
|
||||
|
||||
let validated = validate_rsg(&rsg, message(), None).unwrap();
|
||||
@@ -354,7 +405,7 @@ mod tests {
|
||||
#[test]
|
||||
fn validates_new_rsg_with_required_hash() {
|
||||
let identity = Identity::new();
|
||||
let rsg = create_rsg(&identity, message()).unwrap();
|
||||
let rsg = create_rsg(&identity, message(), false, None).unwrap();
|
||||
|
||||
let validated =
|
||||
validate_rsg(&rsg, message(), Some(RequiredSigner::Hash(identity.hash))).unwrap();
|
||||
@@ -365,7 +416,7 @@ mod tests {
|
||||
fn rejects_wrong_required_hash() {
|
||||
let identity = Identity::new();
|
||||
let other = Identity::new();
|
||||
let rsg = create_rsg(&identity, message()).unwrap();
|
||||
let rsg = create_rsg(&identity, message(), false, None).unwrap();
|
||||
|
||||
let err =
|
||||
validate_rsg(&rsg, message(), Some(RequiredSigner::Hash(other.hash))).unwrap_err();
|
||||
@@ -375,12 +426,141 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_modified_message() {
|
||||
let identity = Identity::new();
|
||||
let rsg = create_rsg(&identity, message()).unwrap();
|
||||
let rsg = create_rsg(&identity, message(), false, None).unwrap();
|
||||
|
||||
let err = validate_rsg(&rsg, b"modified".as_slice(), None).unwrap_err();
|
||||
assert!(matches!(err, RsgError::HashMismatch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn created_envelope_omits_note_field() {
|
||||
let identity = Identity::new();
|
||||
let rsg = create_rsg(&identity, message(), false, None).unwrap();
|
||||
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsg) else {
|
||||
panic!("envelope must decode to a map");
|
||||
};
|
||||
let Some(Value::Map(meta)) = map_get(&map, "meta").cloned() else {
|
||||
panic!("meta must be a map");
|
||||
};
|
||||
let keys: Vec<_> = meta.iter().filter_map(|(k, _)| value_as_str(k)).collect();
|
||||
assert_eq!(keys, ["signer", "pubkey"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_envelope_with_legacy_note_field() {
|
||||
// Python <=1.3.1 emitted meta.note (note:None shim) — stays accepted.
|
||||
let identity = Identity::new();
|
||||
let envelope = pack_value(envelope_value(
|
||||
Some(Value::from(HASH_TYPE_SHA256)),
|
||||
Some(Value::Binary(rns_crypto::sha::sha256(message()).to_vec())),
|
||||
Some(meta_value(
|
||||
Some(Value::Binary(identity.hash.to_vec())),
|
||||
Some(Value::Binary(identity.get_public_key().to_vec())),
|
||||
Some(Value::Nil),
|
||||
)),
|
||||
));
|
||||
let rsg = signed_rsg(&identity, envelope);
|
||||
|
||||
let validated = validate_rsg(&rsg, message(), None).unwrap();
|
||||
assert_eq!(validated.signer_hash, identity.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embeds_message_and_merges_meta() {
|
||||
let identity = Identity::new();
|
||||
let meta = vec![
|
||||
("title".to_string(), Value::from("t")),
|
||||
// Reserved keys must not be overridden by merged meta.
|
||||
("signer".to_string(), Value::from("bogus")),
|
||||
];
|
||||
let rsg = create_rsg(&identity, message(), true, Some(&meta)).unwrap();
|
||||
|
||||
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsg) else {
|
||||
panic!("envelope must decode to a map");
|
||||
};
|
||||
assert_eq!(
|
||||
map_get(&map, "message").and_then(value_as_bytes),
|
||||
Some(message())
|
||||
);
|
||||
let Some(Value::Map(meta_map)) = map_get(&map, "meta").cloned() else {
|
||||
panic!("meta must be a map");
|
||||
};
|
||||
let keys: Vec<_> = meta_map
|
||||
.iter()
|
||||
.filter_map(|(k, _)| value_as_str(k))
|
||||
.collect();
|
||||
assert_eq!(keys, ["signer", "pubkey", "title"]);
|
||||
assert_eq!(
|
||||
map_get(&meta_map, "signer").and_then(value_as_bytes),
|
||||
Some(identity.hash.as_slice())
|
||||
);
|
||||
|
||||
// The embedded message validates against the envelope hash.
|
||||
let validated = validate_rsg(&rsg, message(), None).unwrap();
|
||||
assert_eq!(validated.signer_hash, identity.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_returns_none_on_bad_envelope() {
|
||||
assert!(extract_signed_rsg_data(&[0u8; 10]).is_none());
|
||||
let mut rsg = vec![0u8; SIG_LEN];
|
||||
rsg.extend_from_slice(&[0xd9, 0x20]);
|
||||
assert!(extract_signed_rsg_data(&rsg).is_none());
|
||||
}
|
||||
|
||||
// Fixture generated by running the VERBATIM Python 1.3.8 rnid.py create_rsg
|
||||
// (git show 1.3.8:RNS/Utilities/rnid.py) with embed=True over MESSAGE using
|
||||
// the identity below (vendored umsgpack + RNS Identity from pip rns).
|
||||
const FIXTURE_PRV_HEX: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f";
|
||||
const FIXTURE_MESSAGE: &str = "Hello Reticulum 1.3.8 signed message test.\nSecond line æø.";
|
||||
const FIXTURE_RSM_HEX: &str = "266bce756d1873e4b44113fd24bd57c9c8e78dc25b5acd109e9417b045a5d736520049307a49293c13b432a5899065374060fe8b97d7ef4228e40c7bdcafbf0384a86861736874797065a6736861323536a468617368c420322779176317ebc50102a216a56a68d41c8e9aa1c849f4d4eded5c31ba542795a46d65746182a67369676e6572c410aca31af0441d81dbec71e82da0b4b5f5a67075626b6579c4408f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7a76d657373616765c43c48656c6c6f205265746963756c756d20312e332e38207369676e6564206d65737361676520746573742e0a5365636f6e64206c696e6520c3a6c3b82e";
|
||||
|
||||
fn fixture_identity() -> Identity {
|
||||
Identity::from_private_key(&hex::decode(FIXTURE_PRV_HEX).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
// Same generator, embed=False: a plain note-less .rsg as Python >=1.3.2
|
||||
// emits it (rsg-note-field-drop).
|
||||
const FIXTURE_RSG_HEX: &str = "804718b7b983d4d555035627aab086d91ecddea89eaf7c75aa72b5275038b478c5db2c105841a8aa06c18dc6b84a2638694937a9b649a3a06ed1d4ba3127800083a86861736874797065a6736861323536a468617368c420322779176317ebc50102a216a56a68d41c8e9aa1c849f4d4eded5c31ba542795a46d65746182a67369676e6572c410aca31af0441d81dbec71e82da0b4b5f5a67075626b6579c4408f40c5adb68f25624ae5b214ea767a6ec94d829d3d7b5e1ad1ba6f3e2138285f29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7";
|
||||
|
||||
#[test]
|
||||
fn embedded_message_rsm_is_byte_exact_with_python_138() {
|
||||
let identity = fixture_identity();
|
||||
let rsg = create_rsg(&identity, FIXTURE_MESSAGE.as_bytes(), true, None).unwrap();
|
||||
assert_eq!(hex::encode(&rsg), FIXTURE_RSM_HEX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_rsg_is_byte_exact_with_python_138_and_cross_validates() {
|
||||
let identity = fixture_identity();
|
||||
let rsg = create_rsg(&identity, FIXTURE_MESSAGE.as_bytes(), false, None).unwrap();
|
||||
assert_eq!(hex::encode(&rsg), FIXTURE_RSG_HEX);
|
||||
|
||||
// Python >=1.3.2 note-less output is accepted by the Rust validator.
|
||||
let python_rsg = hex::decode(FIXTURE_RSG_HEX).unwrap();
|
||||
let validated = validate_rsg(&python_rsg, FIXTURE_MESSAGE.as_bytes(), None).unwrap();
|
||||
assert_eq!(validated.signer_hash, identity.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_python_138_created_rsm() {
|
||||
let rsm = hex::decode(FIXTURE_RSM_HEX).unwrap();
|
||||
let identity = fixture_identity();
|
||||
|
||||
let Some(Value::Map(map)) = extract_signed_rsg_data(&rsm) else {
|
||||
panic!("fixture envelope must decode to a map");
|
||||
};
|
||||
let embedded = map_get(&map, "message")
|
||||
.and_then(value_as_bytes)
|
||||
.expect("fixture must embed a message");
|
||||
assert_eq!(embedded, FIXTURE_MESSAGE.as_bytes());
|
||||
|
||||
let validated =
|
||||
validate_rsg(&rsm, embedded, Some(RequiredSigner::Hash(identity.hash))).unwrap();
|
||||
assert_eq!(validated.signer_hash, identity.hash);
|
||||
assert_eq!(validated.public_key, identity.get_public_key());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_legacy_raw_signature() {
|
||||
let identity = Identity::new();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,8 @@
|
||||
//! RNode platform, product and firmware model tables.
|
||||
//! RNode platform, product and firmware model metadata.
|
||||
//!
|
||||
//! Radio families and numeric operating limits belong to
|
||||
//! `rns_interface::rnode_capabilities`; this tool-local table contains only
|
||||
//! metadata needed to plan firmware operations.
|
||||
|
||||
pub const PLATFORM_AVR: u8 = 0x90;
|
||||
pub const PLATFORM_ESP32: u8 = 0x80;
|
||||
@@ -32,439 +36,61 @@ pub const MODEL_B9_TCXO: u8 = 0x09;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ModelInfo {
|
||||
pub model: u8,
|
||||
pub min_frequency: u32,
|
||||
pub max_frequency: u32,
|
||||
pub max_tx_power: u8,
|
||||
pub band_label: &'static str,
|
||||
pub firmware_filename: Option<&'static str>,
|
||||
pub radio: &'static str,
|
||||
}
|
||||
|
||||
pub const MODELS: &[ModelInfo] = &[
|
||||
model(
|
||||
0xA4,
|
||||
410000000,
|
||||
525000000,
|
||||
14,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware.hex"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA9,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware.hex"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xA1,
|
||||
410000000,
|
||||
525000000,
|
||||
22,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_t3s3.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xA6,
|
||||
820000000,
|
||||
1020000000,
|
||||
22,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_t3s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xA5,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_t3s3_sx127x.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xAA,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_t3s3_sx127x.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xAC,
|
||||
2400000000,
|
||||
2500000000,
|
||||
20,
|
||||
"2.4 - 2.5 GHz",
|
||||
Some("rnode_firmware_t3s3_sx1280_pa.zip"),
|
||||
"SX1280",
|
||||
),
|
||||
model(
|
||||
0xA2,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_ng21.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA7,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware_ng21.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xA3,
|
||||
410000000,
|
||||
525000000,
|
||||
17,
|
||||
"410 - 525 MHz",
|
||||
Some("rnode_firmware_ng20.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xA8,
|
||||
820000000,
|
||||
1020000000,
|
||||
17,
|
||||
"820 - 1020 MHz",
|
||||
Some("rnode_firmware_ng20.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xB3,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v20.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xB8,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v20.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xB4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v21.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xB9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v21.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
MODEL_B4_TCXO,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v21_tcxo.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
MODEL_B9_TCXO,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v21_tcxo.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xBA,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_lora32v10.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xBB,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_lora32v10.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xC4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec32v2.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xC9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v2.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xC5,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec32v3.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xCA,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xC8,
|
||||
860000000,
|
||||
930000000,
|
||||
28,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec32v4pa.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xC6,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_heltec_t114.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xC7,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_heltec_t114.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xE4,
|
||||
420000000,
|
||||
520000000,
|
||||
17,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam.zip"),
|
||||
"SX1278",
|
||||
),
|
||||
model(
|
||||
0xE9,
|
||||
850000000,
|
||||
950000000,
|
||||
17,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam.zip"),
|
||||
"SX1276",
|
||||
),
|
||||
model(
|
||||
0xD4,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tdeck.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xD9,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tdeck.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xDB,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam_supreme.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xDC,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam_supreme.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xE3,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_tbeam_sx1262.zip"),
|
||||
"SX1268",
|
||||
),
|
||||
model(
|
||||
0xE8,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_tbeam_sx1262.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x11,
|
||||
430000000,
|
||||
510000000,
|
||||
22,
|
||||
"430 - 510 MHz",
|
||||
Some("rnode_firmware_rak4631.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x12,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 MHz",
|
||||
Some("rnode_firmware_rak4631.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x13,
|
||||
430000000,
|
||||
510000000,
|
||||
22,
|
||||
"430 - 510 MHz",
|
||||
Some("rnode_firmware_rak4631_sx1280.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0x14,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 MHz",
|
||||
Some("rnode_firmware_rak4631_sx1280.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0x16,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"430 - 510 Mhz",
|
||||
Some("rnode_firmware_techo.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x17,
|
||||
779000000,
|
||||
928000000,
|
||||
22,
|
||||
"779 - 928 Mhz",
|
||||
Some("rnode_firmware_techo.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0x21,
|
||||
820000000,
|
||||
960000000,
|
||||
22,
|
||||
"820 - 960 MHz",
|
||||
Some("rnode_firmware_opencom_xl.zip"),
|
||||
"SX1262 + SX1280",
|
||||
),
|
||||
model(
|
||||
0xDE,
|
||||
420000000,
|
||||
520000000,
|
||||
22,
|
||||
"420 - 520 MHz",
|
||||
Some("rnode_firmware_xiao_esp32s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xDD,
|
||||
850000000,
|
||||
950000000,
|
||||
22,
|
||||
"850 - 950 MHz",
|
||||
Some("rnode_firmware_xiao_esp32s3.zip"),
|
||||
"SX1262",
|
||||
),
|
||||
model(
|
||||
0xFE,
|
||||
100000000,
|
||||
1100000000,
|
||||
17,
|
||||
"(Band capabilities unknown)",
|
||||
None,
|
||||
"Unknown",
|
||||
),
|
||||
model(
|
||||
0xFF,
|
||||
100000000,
|
||||
1100000000,
|
||||
14,
|
||||
"(Band capabilities unknown)",
|
||||
None,
|
||||
"Unknown",
|
||||
),
|
||||
model(0xA4, Some("rnode_firmware.hex")),
|
||||
model(0xA9, Some("rnode_firmware.hex")),
|
||||
model(0xA1, Some("rnode_firmware_t3s3.zip")),
|
||||
model(0xA6, Some("rnode_firmware_t3s3.zip")),
|
||||
model(0xA5, Some("rnode_firmware_t3s3_sx127x.zip")),
|
||||
model(0xAA, Some("rnode_firmware_t3s3_sx127x.zip")),
|
||||
model(0xAC, Some("rnode_firmware_t3s3_sx1280_pa.zip")),
|
||||
model(0xA2, Some("rnode_firmware_ng21.zip")),
|
||||
model(0xA7, Some("rnode_firmware_ng21.zip")),
|
||||
model(0xA3, Some("rnode_firmware_ng20.zip")),
|
||||
model(0xA8, Some("rnode_firmware_ng20.zip")),
|
||||
model(0xB3, Some("rnode_firmware_lora32v20.zip")),
|
||||
model(0xB8, Some("rnode_firmware_lora32v20.zip")),
|
||||
model(0xB4, Some("rnode_firmware_lora32v21.zip")),
|
||||
model(0xB9, Some("rnode_firmware_lora32v21.zip")),
|
||||
model(MODEL_B4_TCXO, Some("rnode_firmware_lora32v21_tcxo.zip")),
|
||||
model(MODEL_B9_TCXO, Some("rnode_firmware_lora32v21_tcxo.zip")),
|
||||
model(0xBA, Some("rnode_firmware_lora32v10.zip")),
|
||||
model(0xBB, Some("rnode_firmware_lora32v10.zip")),
|
||||
model(0xC4, Some("rnode_firmware_heltec32v2.zip")),
|
||||
model(0xC9, Some("rnode_firmware_heltec32v2.zip")),
|
||||
model(0xC5, Some("rnode_firmware_heltec32v3.zip")),
|
||||
model(0xCA, Some("rnode_firmware_heltec32v3.zip")),
|
||||
model(0xC8, Some("rnode_firmware_heltec32v4pa.zip")),
|
||||
model(0xC6, Some("rnode_firmware_heltec_t114.zip")),
|
||||
model(0xC7, Some("rnode_firmware_heltec_t114.zip")),
|
||||
model(0xE4, Some("rnode_firmware_tbeam.zip")),
|
||||
model(0xE9, Some("rnode_firmware_tbeam.zip")),
|
||||
model(0xD4, Some("rnode_firmware_tdeck.zip")),
|
||||
model(0xD9, Some("rnode_firmware_tdeck.zip")),
|
||||
model(0xDB, Some("rnode_firmware_tbeam_supreme.zip")),
|
||||
model(0xDC, Some("rnode_firmware_tbeam_supreme.zip")),
|
||||
model(0xE3, Some("rnode_firmware_tbeam_sx1262.zip")),
|
||||
model(0xE8, Some("rnode_firmware_tbeam_sx1262.zip")),
|
||||
model(0x11, Some("rnode_firmware_rak4631.zip")),
|
||||
model(0x12, Some("rnode_firmware_rak4631.zip")),
|
||||
model(0x13, Some("rnode_firmware_rak4631_sx1280.zip")),
|
||||
model(0x14, Some("rnode_firmware_rak4631_sx1280.zip")),
|
||||
model(0x16, Some("rnode_firmware_techo.zip")),
|
||||
model(0x17, Some("rnode_firmware_techo.zip")),
|
||||
model(0x21, Some("rnode_firmware_opencom_xl.zip")),
|
||||
model(0xDE, Some("rnode_firmware_xiao_esp32s3.zip")),
|
||||
model(0xDD, Some("rnode_firmware_xiao_esp32s3.zip")),
|
||||
model(0xFE, None),
|
||||
model(0xFF, None),
|
||||
];
|
||||
|
||||
const fn model(
|
||||
model: u8,
|
||||
min_frequency: u32,
|
||||
max_frequency: u32,
|
||||
max_tx_power: u8,
|
||||
band_label: &'static str,
|
||||
firmware_filename: Option<&'static str>,
|
||||
radio: &'static str,
|
||||
) -> ModelInfo {
|
||||
const fn model(model: u8, firmware_filename: Option<&'static str>) -> ModelInfo {
|
||||
ModelInfo {
|
||||
model,
|
||||
min_frequency,
|
||||
max_frequency,
|
||||
max_tx_power,
|
||||
band_label,
|
||||
firmware_filename,
|
||||
radio,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -480,28 +106,6 @@ pub fn normalize_eeprom_model(model: u8) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn product_name(product: u8) -> Option<&'static str> {
|
||||
Some(match product {
|
||||
PRODUCT_RNODE => "RNode",
|
||||
PRODUCT_HMBRW => "Hombrew RNode",
|
||||
PRODUCT_TBEAM => "LilyGO T-Beam",
|
||||
PRODUCT_TBEAM_S_V1 => "LilyGO T-Beam Supreme",
|
||||
PRODUCT_TDECK => "LilyGO T-Deck",
|
||||
PRODUCT_T32_10 => "LilyGO LoRa32 v1.0",
|
||||
PRODUCT_T32_20 => "LilyGO LoRa32 v2.0",
|
||||
PRODUCT_T32_21 => "LilyGO LoRa32 v2.1",
|
||||
PRODUCT_H32_V2 => "Heltec LoRa32 v2",
|
||||
PRODUCT_H32_V3 => "Heltec LoRa32 v3",
|
||||
PRODUCT_H32_V4 => "Heltec LoRa32 v4",
|
||||
PRODUCT_TECHO => "LilyGO T-Echo",
|
||||
PRODUCT_RAK4631 => "RAK4631",
|
||||
PRODUCT_OPENCOM_XL => "openCom XL",
|
||||
PRODUCT_HELTEC_T114 => "Heltec Mesh Node T114",
|
||||
PRODUCT_XIAO_S3 => "Seeed XIAO ESP32S3 Wio-SX1262",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn platform_name(platform: u8) -> Option<&'static str> {
|
||||
Some(match platform {
|
||||
PLATFORM_AVR => "AVR",
|
||||
@@ -526,7 +130,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_table_matches_upstream_shape() {
|
||||
fn model_table_retains_only_firmware_planning_metadata() {
|
||||
assert_eq!(MODELS.len(), 45);
|
||||
assert_eq!(
|
||||
model_info(0xA4).unwrap().firmware_filename,
|
||||
@@ -537,7 +141,7 @@ mod tests {
|
||||
Some("rnode_firmware_t3s3_sx1280_pa.zip")
|
||||
);
|
||||
assert_eq!(model_info(0xFE).unwrap().firmware_filename, None);
|
||||
assert_eq!(model_info(0xFF).unwrap().max_tx_power, 14);
|
||||
assert_eq!(model_info(0xFF).unwrap().firmware_filename, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -548,8 +152,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_match_upstream_spellings() {
|
||||
assert_eq!(product_name(PRODUCT_HMBRW), Some("Hombrew RNode"));
|
||||
fn platform_and_mcu_names_match_upstream_spellings() {
|
||||
assert_eq!(platform_name(PLATFORM_ESP32), Some("ESP32"));
|
||||
assert_eq!(mcu_name(MCU_NRF52), Some("Nordic Semiconductor nRF52840"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Side-effect-free command planning for the bounded `rnodeconf` slice.
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use rns_interface::{rnode, rnode_admin};
|
||||
|
||||
use super::{Args, frame};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DevicePlan {
|
||||
pub mutation: Option<MutationPlan>,
|
||||
pub read_only: Vec<rnode_admin::AdminFrame>,
|
||||
pub show_psk: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MutationPlan {
|
||||
Tnc(rnode::RNodeRadioSettings),
|
||||
Normal,
|
||||
}
|
||||
|
||||
impl DevicePlan {
|
||||
pub fn build(args: &Args) -> Result<Self, String> {
|
||||
validate_conflicts(args)?;
|
||||
validate_wifi_inputs(args)?;
|
||||
|
||||
if args.show_psk && !args.config {
|
||||
return Err("--show-psk requires --config".to_string());
|
||||
}
|
||||
|
||||
let radio = plan_radio(args)?;
|
||||
reject_unverified_mutations(args)?;
|
||||
|
||||
let mutation = if args.normal {
|
||||
Some(MutationPlan::Normal)
|
||||
} else {
|
||||
radio.map(MutationPlan::Tnc)
|
||||
};
|
||||
|
||||
let mut read_only = Vec::new();
|
||||
if args.info {
|
||||
read_only.extend(rnode_admin::detect_sequence());
|
||||
read_only.push(rnode_admin::eeprom_read_frame());
|
||||
}
|
||||
if args.config {
|
||||
read_only.push(frame(rnode::CMD_CFG_READ, &[0]));
|
||||
}
|
||||
if args.eeprom_dump || args.eeprom_backup {
|
||||
read_only.push(rnode_admin::eeprom_read_frame());
|
||||
}
|
||||
if args.get_target_firmware_hash {
|
||||
read_only.push(frame(rnode::CMD_HASHES, &[1]));
|
||||
}
|
||||
if args.get_firmware_hash {
|
||||
read_only.push(frame(rnode::CMD_HASHES, &[2]));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
mutation,
|
||||
read_only,
|
||||
show_psk: args.show_psk,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.mutation.is_none() && self.read_only.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_conflicts(args: &Args) -> Result<(), String> {
|
||||
if args.normal && args.tnc {
|
||||
return Err("--normal conflicts with --tnc".to_string());
|
||||
}
|
||||
|
||||
let bluetooth_flags = [args.bluetooth_on, args.bluetooth_off, args.bluetooth_pair]
|
||||
.into_iter()
|
||||
.filter(|enabled| *enabled)
|
||||
.count();
|
||||
if bluetooth_flags > 1 {
|
||||
return Err(
|
||||
"--bluetooth-on, --bluetooth-off and --bluetooth-pair are mutually exclusive"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
if args.ia_enable && args.ia_disable {
|
||||
return Err("--ia-enable conflicts with --ia-disable".to_string());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plan_radio(args: &Args) -> Result<Option<rnode::RNodeRadioSettings>, String> {
|
||||
let fields = [
|
||||
args.freq.is_some(),
|
||||
args.bandwidth.is_some(),
|
||||
args.spreading_factor.is_some(),
|
||||
args.coding_rate.is_some(),
|
||||
args.tx_power.is_some(),
|
||||
];
|
||||
let any = fields.iter().any(|present| *present);
|
||||
let all = fields.iter().all(|present| *present);
|
||||
|
||||
if any && !args.tnc {
|
||||
return Err("RF settings are only allowed as a complete --tnc tuple".to_string());
|
||||
}
|
||||
if args.tnc && !all {
|
||||
return Err(
|
||||
"--tnc requires --freq, --bw, --sf, --cr and --txp as a complete tuple".to_string(),
|
||||
);
|
||||
}
|
||||
if !args.tnc {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let settings = rnode::RNodeRadioSettings::new(
|
||||
args.freq.expect("tuple completeness checked"),
|
||||
args.bandwidth.expect("tuple completeness checked"),
|
||||
args.spreading_factor.expect("tuple completeness checked"),
|
||||
args.coding_rate.expect("tuple completeness checked"),
|
||||
args.tx_power.expect("tuple completeness checked"),
|
||||
);
|
||||
settings
|
||||
.validate()
|
||||
.map_err(|error| format!("invalid {}: {error}", error.field()))?;
|
||||
Ok(Some(settings))
|
||||
}
|
||||
|
||||
fn validate_wifi_inputs(args: &Args) -> Result<(), String> {
|
||||
if let Some(mode) = args.wifi.as_deref() {
|
||||
match mode.to_ascii_lowercase().as_str() {
|
||||
"off" | "none" | "station" | "sta" | "ap" | "accesspoint" | "access_point" => {}
|
||||
_ => 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(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(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());
|
||||
}
|
||||
}
|
||||
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}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reject_unverified_mutations(args: &Args) -> Result<(), String> {
|
||||
let bluetooth = args.bluetooth_on || args.bluetooth_off || args.bluetooth_pair;
|
||||
let wifi = args.wifi.is_some()
|
||||
|| args.channel.is_some()
|
||||
|| args.ssid.is_some()
|
||||
|| args.psk.is_some()
|
||||
|| args.ip.is_some()
|
||||
|| args.nm.is_some();
|
||||
let display = args.display.is_some()
|
||||
|| args.timeout.is_some()
|
||||
|| args.rotation.is_some()
|
||||
|| args.display_addr.is_some()
|
||||
|| args.recondition_display
|
||||
|| args.neopixel.is_some();
|
||||
let interference_avoidance = args.ia_enable || args.ia_disable;
|
||||
|
||||
let mut unsupported = Vec::new();
|
||||
if bluetooth {
|
||||
unsupported.push("Bluetooth");
|
||||
}
|
||||
if wifi {
|
||||
unsupported.push("WiFi");
|
||||
}
|
||||
if display {
|
||||
unsupported.push("display");
|
||||
}
|
||||
if interference_avoidance {
|
||||
unsupported.push("interference-avoidance");
|
||||
}
|
||||
if unsupported.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{} mutations are not yet safely supported",
|
||||
unsupported.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn plan(args: &[&str]) -> Result<DevicePlan, String> {
|
||||
let args = Args::parse_from(std::iter::once("rnodeconf").chain(args.iter().copied()));
|
||||
DevicePlan::build(&args)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_builds_typed_tnc_and_preserves_radio_order() {
|
||||
let plan = plan(&[
|
||||
"--tnc",
|
||||
"--freq",
|
||||
"868000000",
|
||||
"--bw",
|
||||
"125000",
|
||||
"--sf",
|
||||
"7",
|
||||
"--cr",
|
||||
"5",
|
||||
"--txp",
|
||||
"14",
|
||||
"fake",
|
||||
])
|
||||
.unwrap();
|
||||
let MutationPlan::Tnc(settings) = plan.mutation.unwrap() else {
|
||||
panic!("expected TNC plan");
|
||||
};
|
||||
let frames =
|
||||
rnode_admin::decode_frames(&rnode::build_radio_configuration_sequence(&settings));
|
||||
assert_eq!(
|
||||
frames.iter().map(|frame| frame.command).collect::<Vec<_>>(),
|
||||
vec![
|
||||
rnode::CMD_RADIO_STATE,
|
||||
rnode::CMD_FREQUENCY,
|
||||
rnode::CMD_BANDWIDTH,
|
||||
rnode::CMD_SF,
|
||||
rnode::CMD_CR,
|
||||
rnode::CMD_TXPOWER,
|
||||
rnode::CMD_RADIO_STATE,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_rejects_conflicts_and_incomplete_or_detached_rf_tuples() {
|
||||
assert!(plan(&["--normal", "--tnc", "fake"]).is_err());
|
||||
assert!(plan(&["--bluetooth-on", "--bluetooth-off", "fake"]).is_err());
|
||||
assert!(plan(&["--ia-enable", "--ia-disable", "fake"]).is_err());
|
||||
assert!(plan(&["--tnc", "--freq", "868000000", "fake"]).is_err());
|
||||
assert!(plan(&["--freq", "868000000", "fake"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planner_rejects_generic_ranges_before_a_session_can_be_opened() {
|
||||
let result = plan(&[
|
||||
"--tnc",
|
||||
"--freq",
|
||||
"136999999",
|
||||
"--bw",
|
||||
"125000",
|
||||
"--sf",
|
||||
"7",
|
||||
"--cr",
|
||||
"5",
|
||||
"--txp",
|
||||
"14",
|
||||
"fake",
|
||||
]);
|
||||
assert!(result.unwrap_err().contains("invalid frequency"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_wifi_is_rejected_before_unsupported_mutation_gate() {
|
||||
assert!(
|
||||
plan(&["--wifi", "bogus", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("WiFi mode")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--channel", "0", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("channel")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--ip", "999.1.1.1", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("IP address")
|
||||
);
|
||||
assert!(
|
||||
plan(&["--psk", "short", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("PSK")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unacknowledged_mutation_families_fail_closed() {
|
||||
for args in [
|
||||
&["--bluetooth-on", "fake"][..],
|
||||
&["--wifi", "off", "fake"][..],
|
||||
&["--display", "10", "fake"][..],
|
||||
&["--ia-enable", "fake"][..],
|
||||
] {
|
||||
assert!(plan(args).unwrap_err().contains("not yet safely supported"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_psk_is_only_a_config_output_permission() {
|
||||
assert!(
|
||||
plan(&["--show-psk", "fake"])
|
||||
.unwrap_err()
|
||||
.contains("requires --config")
|
||||
);
|
||||
let plan = plan(&["--config", "--show-psk", "fake"]).unwrap();
|
||||
assert_eq!(plan.read_only.len(), 1);
|
||||
assert_eq!(plan.read_only[0].command, rnode::CMD_CFG_READ);
|
||||
assert!(
|
||||
plan.read_only
|
||||
.iter()
|
||||
.all(|frame| frame.command != rnode::CMD_WIFI_PSK)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Framing and deadline ownership for staged RNode administration sessions.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Read, Write};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rns_interface::{kiss, rnode_admin};
|
||||
|
||||
/// Small transaction surface used by the mutation executor and deterministic
|
||||
/// tests. Implementations must preserve inbound framing state between calls.
|
||||
pub trait FrameSession {
|
||||
fn send(&mut self, frame: &rnode_admin::AdminFrame) -> Result<(), String>;
|
||||
|
||||
/// Return the next complete frame, or `None` once `deadline` expires.
|
||||
fn receive_until(
|
||||
&mut self,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<rnode_admin::AdminFrame>, String>;
|
||||
}
|
||||
|
||||
pub struct SerialFrameSession {
|
||||
port: Box<dyn serialport::SerialPort>,
|
||||
inbox: FrameInbox,
|
||||
}
|
||||
|
||||
impl SerialFrameSession {
|
||||
pub fn new(port: Box<dyn serialport::SerialPort>) -> Self {
|
||||
Self {
|
||||
port,
|
||||
inbox: FrameInbox::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameSession for SerialFrameSession {
|
||||
fn send(&mut self, frame: &rnode_admin::AdminFrame) -> Result<(), String> {
|
||||
let encoded = rnode_admin::encode_frame(frame.command, &frame.payload);
|
||||
self.port
|
||||
.write_all(&encoded)
|
||||
.map_err(|error| format!("serial write failed: {error}"))?;
|
||||
self.port
|
||||
.flush()
|
||||
.map_err(|error| format!("serial flush failed: {error}"))
|
||||
}
|
||||
|
||||
fn receive_until(
|
||||
&mut self,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<rnode_admin::AdminFrame>, String> {
|
||||
if let Some(frame) = self.inbox.pop() {
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
|
||||
let mut buffer = [0u8; 512];
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(now);
|
||||
let read_timeout = remaining.min(Duration::from_millis(100));
|
||||
self.port
|
||||
.set_timeout(read_timeout)
|
||||
.map_err(|error| format!("could not set serial read timeout: {error}"))?;
|
||||
|
||||
match self.port.read(&mut buffer) {
|
||||
Ok(0) => {}
|
||||
Ok(count) => {
|
||||
self.inbox.feed(&buffer[..count]);
|
||||
if let Some(frame) = self.inbox.pop() {
|
||||
return Ok(Some(frame));
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(error) => return Err(format!("serial read failed: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FrameInbox {
|
||||
deframer: kiss::RawKissDeframer,
|
||||
frames: VecDeque<rnode_admin::AdminFrame>,
|
||||
}
|
||||
|
||||
impl FrameInbox {
|
||||
fn feed(&mut self, bytes: &[u8]) {
|
||||
self.frames.extend(
|
||||
self.deframer
|
||||
.feed(bytes)
|
||||
.into_iter()
|
||||
.map(|(command, payload)| rnode_admin::AdminFrame { command, payload }),
|
||||
);
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<rnode_admin::AdminFrame> {
|
||||
self.frames.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rns_interface::{kiss, rnode};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_deframer_survives_fragmented_and_escaped_input_across_stages() {
|
||||
let first =
|
||||
rnode_admin::encode_frame(rnode::CMD_CFG_READ, &[0x11, kiss::FEND, 0x22, kiss::FESC]);
|
||||
let second = rnode_admin::encode_frame(rnode::CMD_FREQUENCY, &868_000_000u32.to_be_bytes());
|
||||
let split = first.len() - 2;
|
||||
let mut inbox = FrameInbox::default();
|
||||
|
||||
inbox.feed(&first[..3]);
|
||||
assert!(inbox.pop().is_none());
|
||||
inbox.feed(&first[3..split]);
|
||||
assert!(inbox.pop().is_none());
|
||||
inbox.feed(&first[split..]);
|
||||
assert_eq!(
|
||||
inbox.pop(),
|
||||
Some(rnode_admin::AdminFrame {
|
||||
command: rnode::CMD_CFG_READ,
|
||||
payload: vec![0x11, kiss::FEND, 0x22, kiss::FESC],
|
||||
})
|
||||
);
|
||||
|
||||
for chunk in second.chunks(2) {
|
||||
inbox.feed(chunk);
|
||||
}
|
||||
assert_eq!(inbox.pop(), rnode_admin::decode_frames(&second).pop());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbox_queues_multiple_frames_without_reframing_between_reads() {
|
||||
let mut wire = rnode_admin::encode_frame(rnode::CMD_READY, &[1]);
|
||||
wire.extend(rnode_admin::encode_frame(rnode::CMD_RADIO_STATE, &[1]));
|
||||
let mut inbox = FrameInbox::default();
|
||||
inbox.feed(&wire);
|
||||
|
||||
assert_eq!(inbox.pop().unwrap().command, rnode::CMD_READY);
|
||||
assert_eq!(inbox.pop().unwrap().command, rnode::CMD_RADIO_STATE);
|
||||
assert!(inbox.pop().is_none());
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ const REMOTE_TIMEOUT_SECS: u64 = 30;
|
||||
const REMOTE_HOPS: u8 = 8;
|
||||
const MGMT_APP: &str = "rnstransport.remote.management";
|
||||
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
|
||||
use rns_tools::RETICULUM_COMPAT_VERSION;
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -130,7 +130,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnpath-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnpath-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -139,7 +139,13 @@ pub(crate) async fn main() -> ExitCode {
|
||||
1 => tracing::Level::INFO,
|
||||
_ => tracing::Level::DEBUG,
|
||||
};
|
||||
tracing_subscriber::fmt().with_max_level(level).init();
|
||||
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&config_dir),
|
||||
true,
|
||||
std::io::stdout,
|
||||
);
|
||||
|
||||
if args.blackholed_list {
|
||||
return run_remote_blackhole_list(args).await;
|
||||
@@ -188,6 +194,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
config_dir,
|
||||
rpc_key,
|
||||
timeout: std::time::Duration::from_secs(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS)),
|
||||
explicit_timeout: args.timeout.map(std::time::Duration::from_secs),
|
||||
};
|
||||
|
||||
// First matching branch wins when multiple action flags are passed.
|
||||
@@ -267,6 +274,8 @@ struct ClientCtx {
|
||||
config_dir: PathBuf,
|
||||
rpc_key: Vec<u8>,
|
||||
timeout: std::time::Duration,
|
||||
/// `-w` as given; `None` means path requests wait `PATH_REQUEST_TIMEOUT`.
|
||||
explicit_timeout: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
async fn request(ctx: &ClientCtx, req: &RpcRequest) -> Result<RpcResponse, LocalRpcFailure> {
|
||||
@@ -772,12 +781,17 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
|
||||
let mut next_hop = next_hop;
|
||||
let mut iface = iface;
|
||||
if next_hop.is_none() && path_entry.is_none() {
|
||||
let timeout_secs = ctx.timeout.as_secs_f64().max(0.1);
|
||||
// Python rnpath defaults -w to Transport.PATH_REQUEST_TIMEOUT.
|
||||
let timeout_secs = ctx
|
||||
.explicit_timeout
|
||||
.map(|d| d.as_secs_f64())
|
||||
.unwrap_or(rns_transport::constants::PATH_REQUEST_TIMEOUT)
|
||||
.max(0.1);
|
||||
let req = RpcRequest::RequestPath {
|
||||
destination_hash: dest.to_vec(),
|
||||
timeout_secs: Some(timeout_secs),
|
||||
};
|
||||
let rpc_timeout = ctx.timeout + std::time::Duration::from_secs(1);
|
||||
let rpc_timeout = std::time::Duration::from_secs_f64(timeout_secs + 1.0);
|
||||
let found = match request_with_timeout(ctx, &req, rpc_timeout).await {
|
||||
Ok(RpcResponse::BoolResult(found)) => found,
|
||||
Ok(other) => {
|
||||
|
||||
@@ -12,8 +12,7 @@ use rns_runtime::probe::{
|
||||
};
|
||||
|
||||
const DEFAULT_PROBE_SIZE: usize = 16;
|
||||
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
|
||||
use rns_tools::RETICULUM_COMPAT_VERSION;
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -65,7 +64,7 @@ struct Args {
|
||||
pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
if args.version {
|
||||
println!("rnprobe-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnprobe-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -82,10 +81,13 @@ pub(crate) async fn main() {
|
||||
1 => tracing::Level::INFO,
|
||||
_ => tracing::Level::DEBUG,
|
||||
};
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(level)
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&config_dir),
|
||||
true,
|
||||
std::io::stderr,
|
||||
);
|
||||
|
||||
let full_name = args
|
||||
.full_name
|
||||
@@ -103,9 +105,9 @@ pub(crate) async fn main() {
|
||||
};
|
||||
|
||||
let size = args.size.unwrap_or(DEFAULT_PROBE_SIZE);
|
||||
let timeout = Duration::from_secs_f64(args.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS));
|
||||
// None = Python default: 12 s + first-hop timeout, resolved per wait.
|
||||
let timeout = args.timeout.map(Duration::from_secs_f64);
|
||||
let wait = Duration::from_secs_f64(args.wait.max(0.0));
|
||||
let path_wait = timeout;
|
||||
|
||||
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
|
||||
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
|
||||
@@ -143,7 +145,7 @@ pub(crate) async fn main() {
|
||||
&full_name,
|
||||
size,
|
||||
timeout,
|
||||
path_wait,
|
||||
timeout,
|
||||
handle.should_use_implicit_proof(),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -7,23 +7,36 @@ use std::path::{Path, PathBuf};
|
||||
use clap::Parser;
|
||||
use tracing_subscriber::fmt::MakeWriter;
|
||||
|
||||
use rns_tools::RETICULUM_COMPAT_VERSION;
|
||||
use rns_tools::{RETICULUM_COMPAT_VERSION, RS_RETICULUM_VERSION};
|
||||
const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024;
|
||||
const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config file.
|
||||
|
||||
[reticulum]
|
||||
enable_transport = No
|
||||
share_instance = Yes
|
||||
enable_transport = no
|
||||
share_instance = yes
|
||||
instance_name = default
|
||||
|
||||
# Interval in minutes at which remote blackhole sources
|
||||
# are updated. Defaults to one hour.
|
||||
# blackhole_update_interval = 60
|
||||
|
||||
# When not running as a transport node, force the same,
|
||||
# static transport identity at every instance start.
|
||||
# Defaults to a new identity per start if transport is
|
||||
# disabled.
|
||||
# static_transport_identity = no
|
||||
|
||||
[logging]
|
||||
loglevel = 4
|
||||
|
||||
# You can disable timestamp inclusion in logs.
|
||||
# logtimestamps = no
|
||||
|
||||
[interfaces]
|
||||
|
||||
[[Default Interface]]
|
||||
type = AutoInterface
|
||||
enabled = Yes
|
||||
enabled = yes
|
||||
|
||||
[[UDP Interface]]
|
||||
type = UDPInterface
|
||||
@@ -60,7 +73,7 @@ bandwidth = 125000
|
||||
txpower = 7
|
||||
spreadingfactor = 8
|
||||
codingrate = 5
|
||||
flow_control = False
|
||||
flow_control = false
|
||||
|
||||
[[Packet Radio KISS Interface]]
|
||||
type = KISSInterface
|
||||
@@ -112,7 +125,7 @@ struct Args {
|
||||
#[arg(short = 'q', long, action = clap::ArgAction::Count)]
|
||||
quiet: u8,
|
||||
|
||||
/// Run as service and log to <configdir>/logfile.
|
||||
/// Run as service and log to `<configdir>/logfile`.
|
||||
#[arg(short = 's', long)]
|
||||
service: bool,
|
||||
|
||||
@@ -134,7 +147,7 @@ pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnsd-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnsd-rs {RS_RETICULUM_VERSION}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -151,6 +164,7 @@ pub(crate) async fn main() {
|
||||
config_loglevel + args.verbose as i32 - args.quiet as i32
|
||||
};
|
||||
let level = tracing_level(verbosity);
|
||||
let log_timestamps = rns_tools::config_log_timestamps(&config_dir);
|
||||
|
||||
if args.service {
|
||||
if let Err(e) = fs::create_dir_all(&config_dir) {
|
||||
@@ -168,16 +182,12 @@ pub(crate) async fn main() {
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(level)
|
||||
.with_writer(LogFileWriter::new(log_path))
|
||||
.with_ansi(false)
|
||||
.init();
|
||||
rns_tools::init_tracing(level, log_timestamps, false, LogFileWriter::new(log_path));
|
||||
} else {
|
||||
tracing_subscriber::fmt().with_max_level(level).init();
|
||||
rns_tools::init_tracing(level, log_timestamps, true, std::io::stdout);
|
||||
}
|
||||
|
||||
tracing::info!("rnsd-rs {RETICULUM_COMPAT_VERSION} starting");
|
||||
tracing::info!("rnsd-rs {RS_RETICULUM_VERSION} starting");
|
||||
|
||||
let shutdown = rns_runtime::lifecycle::ShutdownSignal::new();
|
||||
let _signal_rx = rns_runtime::lifecycle::install_signal_handlers(shutdown.clone());
|
||||
@@ -199,6 +209,7 @@ pub(crate) async fn main() {
|
||||
}
|
||||
|
||||
shutdown.wait().await;
|
||||
handle.shutdown_and_wait().await;
|
||||
tracing::info!("rnsd-rs shutting down");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -215,7 +226,7 @@ async fn run_interactive_shell(handle: rns_runtime::reticulum::ReticulumHandle)
|
||||
let mut stdout = io::stdout();
|
||||
let _ = writeln!(
|
||||
stdout,
|
||||
"rnsd-rs {RETICULUM_COMPAT_VERSION} interactive console"
|
||||
"rnsd-rs {RS_RETICULUM_VERSION} interactive console"
|
||||
);
|
||||
let _ = writeln!(
|
||||
stdout,
|
||||
|
||||
@@ -23,7 +23,8 @@ use rns_runtime::rnsh::{
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
const RNS_VERSION: &str = "1.2.5";
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
|
||||
const APP_NAME: &str = "rnsh";
|
||||
const DEFAULT_SERVICE_NAME: &str = "default";
|
||||
@@ -86,7 +87,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
|
||||
async fn run(mut args: Args) -> ExitCode {
|
||||
if args.version {
|
||||
println!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
|
||||
println!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -123,7 +124,7 @@ async fn run_listener(args: Args) -> ExitCode {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
init_logging(args.verbose, args.quiet);
|
||||
init_logging(args.verbose, args.quiet, args.config.as_deref());
|
||||
|
||||
let handle = match start_reticulum(args.config.as_deref(), shutdown.clone()).await {
|
||||
Ok(handle) => handle,
|
||||
@@ -178,7 +179,7 @@ async fn run_initiator(args: Args) -> ExitCode {
|
||||
// Register before any slow init so an early SIGINT exits cleanly.
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let _signal_rx = install_signal_handlers(shutdown.clone());
|
||||
init_logging(args.verbose, args.quiet);
|
||||
init_logging(args.verbose, args.quiet, args.config.as_deref());
|
||||
|
||||
let destination = match args.destination.as_deref().and_then(parse_hash16) {
|
||||
Some(hash) => hash,
|
||||
@@ -266,17 +267,20 @@ async fn start_reticulum(
|
||||
rns_runtime::reticulum::init(config, None, shutdown, is_foreground).await
|
||||
}
|
||||
|
||||
fn init_logging(verbose: u8, quiet: u8) {
|
||||
fn init_logging(verbose: u8, quiet: u8, config_dir: Option<&Path>) {
|
||||
let level = match (verbose as i32) - (quiet as i32) {
|
||||
n if n >= 2 => tracing::Level::DEBUG,
|
||||
1 => tracing::Level::INFO,
|
||||
0 => tracing::Level::WARN,
|
||||
_ => tracing::Level::ERROR,
|
||||
};
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_max_level(level)
|
||||
.with_writer(std::io::stderr)
|
||||
.try_init();
|
||||
let resolved = resolve_config_dir(config_dir.and_then(|path| path.to_str()));
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&resolved),
|
||||
true,
|
||||
std::io::stderr,
|
||||
);
|
||||
}
|
||||
|
||||
fn terminal_window_size() -> (Option<u32>, Option<u32>, Option<u32>, Option<u32>) {
|
||||
@@ -878,8 +882,8 @@ mod tests {
|
||||
#[test]
|
||||
fn version_string_uses_rust_command_name() {
|
||||
assert_eq!(
|
||||
format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
|
||||
"rnsh-rs 1.2.5 (protocol 0.2.0)"
|
||||
format!("rnsh-rs {RS_RETICULUM_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
|
||||
format!("rnsh-rs {} (protocol 0.2.0)", env!("CARGO_PKG_VERSION"))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const DEFAULT_TIMEOUT_SECS: u64 = 5;
|
||||
const REMOTE_TIMEOUT_SECS: u64 = 30;
|
||||
const REMOTE_HOPS: u8 = 8;
|
||||
const MGMT_APP: &str = "rnstransport.remote.management";
|
||||
use rns_tools::RETICULUM_COMPAT_VERSION;
|
||||
use rns_tools::RS_RETICULUM_VERSION;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
@@ -125,7 +125,7 @@ pub(crate) async fn main() -> ExitCode {
|
||||
let args = Args::parse();
|
||||
|
||||
if args.version {
|
||||
println!("rnstatus-rs {RETICULUM_COMPAT_VERSION}");
|
||||
println!("rnstatus-rs {RS_RETICULUM_VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if let Err(e) = validate_args(&args) {
|
||||
@@ -140,7 +140,13 @@ pub(crate) async fn main() -> ExitCode {
|
||||
1 => tracing::Level::INFO,
|
||||
_ => tracing::Level::DEBUG,
|
||||
};
|
||||
tracing_subscriber::fmt().with_max_level(level).init();
|
||||
let config_dir = rns_runtime::platform::resolve_config_dir(args.config.as_deref());
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&config_dir),
|
||||
true,
|
||||
std::io::stdout,
|
||||
);
|
||||
|
||||
if args.monitor {
|
||||
run_monitor(args).await
|
||||
@@ -152,21 +158,38 @@ pub(crate) async fn main() -> ExitCode {
|
||||
}
|
||||
|
||||
async fn run_monitor(args: Args) -> ExitCode {
|
||||
let interval = Duration::from_secs_f64(args.monitor_interval.max(0.1));
|
||||
// Python 1.3.8 rnstatus.py:714-744 (commit 32389002): one RNS instance and
|
||||
// one remote destination live across refreshes; only the request repeats.
|
||||
let session = if args.remote.is_some() {
|
||||
match RemoteSession::open(&args).await {
|
||||
Ok(s) => Some(s),
|
||||
Err(code) => return code,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
loop {
|
||||
let started = std::time::Instant::now();
|
||||
print!("\x1b[2J\x1b[H");
|
||||
let exit = if args.remote.is_some() {
|
||||
run_remote_once(&args).await
|
||||
} else {
|
||||
run_local_once(&args).await
|
||||
let exit = match &session {
|
||||
Some(session) => session.query_and_print(&args).await,
|
||||
None => run_local_once(&args).await,
|
||||
};
|
||||
if exit != ExitCode::SUCCESS {
|
||||
if let Some(session) = &session {
|
||||
session.shutdown.trigger();
|
||||
}
|
||||
return exit;
|
||||
}
|
||||
tokio::time::sleep(interval).await;
|
||||
tokio::time::sleep(monitor_sleep(args.monitor_interval, started.elapsed())).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.3.8 rnstatus.py:742-744: sleep `max(interval - render time, 0.2)`.
|
||||
fn monitor_sleep(interval_secs: f64, elapsed: Duration) -> Duration {
|
||||
Duration::from_secs_f64((interval_secs - elapsed.as_secs_f64()).max(0.2))
|
||||
}
|
||||
|
||||
async fn run_local(args: Args) -> ExitCode {
|
||||
run_local_once(&args).await
|
||||
}
|
||||
@@ -342,8 +365,8 @@ enum SortKey {
|
||||
|
||||
fn validate_args(args: &Args) -> Result<(), String> {
|
||||
parse_sort_key(args.sort.as_deref()).map(|_| ())?;
|
||||
if args.monitor_interval <= 0.0 {
|
||||
return Err("--monitor-interval must be greater than 0".to_string());
|
||||
if !(args.monitor_interval > 0.0 && args.monitor_interval.is_finite()) {
|
||||
return Err("--monitor-interval must be a finite number greater than 0".to_string());
|
||||
}
|
||||
if (args.discovered || args.discovered_details) && args.remote.is_some() {
|
||||
return Err(
|
||||
@@ -396,6 +419,32 @@ fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Python 1.3.8 rnstatus.py:421-427 mode string table (unknown modes render "Full").
|
||||
fn mode_display_name(mode: &str) -> &'static str {
|
||||
match mode {
|
||||
"AccessPoint" | "Access Point" => "Access Point",
|
||||
"PointToPoint" | "Point-to-Point" => "Point-to-Point",
|
||||
"Roaming" => "Roaming",
|
||||
"Boundary" => "Boundary",
|
||||
"Gateway" => "Gateway",
|
||||
"Internal" => "Internal",
|
||||
_ => "Full",
|
||||
}
|
||||
}
|
||||
|
||||
/// Same table keyed on the numeric mode carried by remote /status responses.
|
||||
fn remote_mode_display_name(mode: u64) -> &'static str {
|
||||
match mode {
|
||||
0x02 => "Point-to-Point",
|
||||
0x03 => "Access Point",
|
||||
0x04 => "Roaming",
|
||||
0x05 => "Boundary",
|
||||
0x06 => "Gateway",
|
||||
0x07 => "Internal",
|
||||
_ => "Full",
|
||||
}
|
||||
}
|
||||
|
||||
fn visible_by_default(name: &str) -> bool {
|
||||
!(name.starts_with("LocalInterface[")
|
||||
|| name.starts_with("TCPInterface[Client")
|
||||
@@ -472,13 +521,16 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
let status = if entry.online { "Up" } else { "Down" };
|
||||
println!(" {}", entry.name);
|
||||
println!(" Status : {status}");
|
||||
println!(" Mode : {}", entry.mode);
|
||||
println!(" Mode : {}", mode_display_name(&entry.mode));
|
||||
println!(" Role : {}", entry.role);
|
||||
println!(" Bitrate : {}", format::pretty_speed(entry.bitrate));
|
||||
println!(" MTU : {} B", entry.mtu);
|
||||
if let Some(clients) = entry.clients {
|
||||
println!(" Clients : {clients}");
|
||||
}
|
||||
if let Some(blocked) = blocked_count_text(entry.blocked_ips) {
|
||||
println!(" Blocked : {blocked}");
|
||||
}
|
||||
if entry.ifac_size > 0 {
|
||||
println!(" IFAC : {} bits", entry.ifac_size * 8);
|
||||
}
|
||||
@@ -567,7 +619,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"blocked_ips\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
|
||||
json_str(&e.name),
|
||||
e.online,
|
||||
json_str(&e.mode),
|
||||
@@ -591,6 +643,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
|
||||
e.pr_burst_active,
|
||||
e.pr_burst_activated,
|
||||
opt_u64_json(e.clients),
|
||||
opt_u64_json(e.blocked_ips),
|
||||
opt_f64_json(e.announce_rate_target),
|
||||
opt_u32_json(e.announce_rate_grace),
|
||||
opt_f64_json(e.announce_rate_penalty),
|
||||
@@ -866,85 +919,105 @@ fn unix_now_secs() -> u64 {
|
||||
}
|
||||
|
||||
async fn run_remote(args: Args) -> ExitCode {
|
||||
run_remote_once(&args).await
|
||||
let session = match RemoteSession::open(&args).await {
|
||||
Ok(s) => s,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let exit = session.query_and_print(&args).await;
|
||||
session.shutdown.trigger();
|
||||
exit
|
||||
}
|
||||
|
||||
async fn run_remote_once(args: &Args) -> ExitCode {
|
||||
let remote_hex = args.remote.as_deref().expect("checked in main");
|
||||
let remote_hash = match hash::parse_dest_hash(remote_hex) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: --remote: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
/// Remote-management state reused across monitor refreshes: one runtime,
|
||||
/// one identity, one client — only the /status request repeats.
|
||||
struct RemoteSession {
|
||||
remote_hash: [u8; 16],
|
||||
client: LinkClient,
|
||||
shutdown: ShutdownSignal,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
let identity_path = match args.identity.as_ref() {
|
||||
Some(p) => p.clone(),
|
||||
None => {
|
||||
eprintln!("rnstatus-rs: --remote requires --identity <path>.");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let identity = match rns_identity::identity::Identity::from_file(&identity_path) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"rnstatus-rs: could not load identity from {}: {e:?}",
|
||||
identity_path.display()
|
||||
);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
impl RemoteSession {
|
||||
async fn open(args: &Args) -> Result<Self, ExitCode> {
|
||||
let remote_hex = args.remote.as_deref().expect("checked in main");
|
||||
let remote_hash = match hash::parse_dest_hash(remote_hex) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: --remote: {e}");
|
||||
return Err(ExitCode::from(2));
|
||||
}
|
||||
};
|
||||
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let foreground = Arc::new(AtomicBool::new(true));
|
||||
let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: failed to initialize Reticulum runtime: {e:?}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let identity_path = match args.identity.as_ref() {
|
||||
Some(p) => p.clone(),
|
||||
None => {
|
||||
eprintln!("rnstatus-rs: --remote requires --identity <path>.");
|
||||
return Err(ExitCode::from(2));
|
||||
}
|
||||
};
|
||||
let identity = match rns_identity::identity::Identity::from_file(&identity_path) {
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"rnstatus-rs: could not load identity from {}: {e:?}",
|
||||
identity_path.display()
|
||||
);
|
||||
return Err(ExitCode::from(1));
|
||||
}
|
||||
};
|
||||
|
||||
let timeout = Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS));
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let foreground = Arc::new(AtomicBool::new(true));
|
||||
let handle = match init(args.config.as_deref(), None, shutdown.clone(), foreground).await {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: failed to initialize Reticulum runtime: {e:?}");
|
||||
return Err(ExitCode::from(1));
|
||||
}
|
||||
};
|
||||
|
||||
// Wire format: msgpack 1-tuple `(include_link_count,)`.
|
||||
let payload = match rmp_serde::to_vec(&(args.link_stats,)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: msgpack encode failed: {e}");
|
||||
shutdown.trigger();
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let client = LinkClient::new(handle.transport_tx.clone(), identity);
|
||||
let response_bytes = match client
|
||||
.query(
|
||||
Ok(Self {
|
||||
remote_hash,
|
||||
MGMT_APP,
|
||||
"/status",
|
||||
payload,
|
||||
REMOTE_HOPS,
|
||||
timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: remote query failed: {}", remote_err(&e));
|
||||
shutdown.trigger();
|
||||
return match e {
|
||||
LinkClientError::Timeout(_) => ExitCode::from(124),
|
||||
_ => ExitCode::from(1),
|
||||
};
|
||||
}
|
||||
};
|
||||
client: LinkClient::new(handle.transport_tx.clone(), identity),
|
||||
shutdown,
|
||||
timeout: Duration::from_secs(args.timeout.unwrap_or(REMOTE_TIMEOUT_SECS)),
|
||||
})
|
||||
}
|
||||
|
||||
let exit = print_remote_status(&response_bytes, args);
|
||||
shutdown.trigger();
|
||||
exit
|
||||
async fn query_and_print(&self, args: &Args) -> ExitCode {
|
||||
// Wire format: msgpack 1-tuple `(include_link_count,)`.
|
||||
let payload = match rmp_serde::to_vec(&(args.link_stats,)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: msgpack encode failed: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let response_bytes = match self
|
||||
.client
|
||||
.query(
|
||||
self.remote_hash,
|
||||
MGMT_APP,
|
||||
"/status",
|
||||
payload,
|
||||
REMOTE_HOPS,
|
||||
self.timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
eprintln!("rnstatus-rs: remote query failed: {}", remote_err(&e));
|
||||
return match e {
|
||||
LinkClientError::Timeout(_) => ExitCode::from(124),
|
||||
_ => ExitCode::from(1),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
print_remote_status(&response_bytes, args)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -968,6 +1041,7 @@ struct RemoteInterface {
|
||||
pr_burst_active: bool,
|
||||
pr_burst_activated: f64,
|
||||
clients: Option<u64>,
|
||||
blocked_ips: Option<u64>,
|
||||
announce_rate_target: Option<f64>,
|
||||
announce_rate_grace: Option<u32>,
|
||||
announce_rate_penalty: Option<f64>,
|
||||
@@ -1068,7 +1142,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
print!(",");
|
||||
}
|
||||
print!(
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"blocked_ips\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
|
||||
json_str(&iface.name),
|
||||
iface.online,
|
||||
iface.mode,
|
||||
@@ -1091,6 +1165,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
iface.pr_burst_active,
|
||||
iface.pr_burst_activated,
|
||||
opt_u64_json(iface.clients),
|
||||
opt_u64_json(iface.blocked_ips),
|
||||
opt_f64_json(iface.announce_rate_target),
|
||||
opt_u32_json(iface.announce_rate_grace),
|
||||
opt_f64_json(iface.announce_rate_penalty),
|
||||
@@ -1115,11 +1190,14 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
|
||||
let status = if iface.online { "Up" } else { "Down" };
|
||||
println!(" {}", iface.name);
|
||||
println!(" Status : {status}");
|
||||
println!(" Mode : 0x{:02x}", iface.mode);
|
||||
println!(" Mode : {}", remote_mode_display_name(iface.mode));
|
||||
println!(" Bitrate : {}", format::pretty_speed(iface.bitrate));
|
||||
if let Some(clients) = iface.clients {
|
||||
println!(" Clients : {clients}");
|
||||
}
|
||||
if let Some(blocked) = blocked_count_text(iface.blocked_ips) {
|
||||
println!(" Blocked : {blocked}");
|
||||
}
|
||||
if args.announce_stats {
|
||||
if let Some(queued) = iface.announce_queue {
|
||||
if queued > 0 {
|
||||
@@ -1215,6 +1293,7 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
|
||||
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
|
||||
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
|
||||
clients: map_u64(m, "clients"),
|
||||
blocked_ips: map_u64(m, "blocked_ips"),
|
||||
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
|
||||
announce_rate_grace: map_u64(m, "announce_rate_grace")
|
||||
.map(|v| v.min(u32::MAX as u64) as u32),
|
||||
@@ -1328,6 +1407,12 @@ fn opt_u64_json(value: Option<u64>) -> String {
|
||||
.unwrap_or_else(|| "null".to_string())
|
||||
}
|
||||
|
||||
fn blocked_count_text(blocked_ips: Option<u64>) -> Option<String> {
|
||||
let count = blocked_ips.filter(|count| *count > 0)?;
|
||||
let noun = if count == 1 { "IP" } else { "IPs" };
|
||||
Some(format!("{count} {noun}"))
|
||||
}
|
||||
|
||||
fn opt_u32_json(value: Option<u32>) -> String {
|
||||
value
|
||||
.map(|v| v.to_string())
|
||||
@@ -1432,6 +1517,7 @@ mod tests {
|
||||
0.0
|
||||
},
|
||||
clients: None,
|
||||
blocked_ips: None,
|
||||
announce_rate_target: None,
|
||||
announce_rate_grace: None,
|
||||
announce_rate_penalty: None,
|
||||
@@ -1497,6 +1583,85 @@ mod tests {
|
||||
assert_eq!(iface.burst_activated, 0.0);
|
||||
assert!(!iface.pr_burst_active);
|
||||
assert_eq!(iface.pr_burst_activated, 0.0);
|
||||
assert_eq!(iface.blocked_ips, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_status_parser_accepts_only_scalar_blocked_count() {
|
||||
let iface = remote_interface_from_map(&[
|
||||
(rmpv::Value::from("name"), rmpv::Value::from("BackboneIf")),
|
||||
(rmpv::Value::from("blocked_ips"), rmpv::Value::from(2)),
|
||||
(
|
||||
rmpv::Value::from("blocked_ip_list"),
|
||||
rmpv::Value::Array(vec![
|
||||
rmpv::Value::from("198.51.100.2"),
|
||||
rmpv::Value::from("203.0.113.7"),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
|
||||
assert_eq!(iface.blocked_ips, Some(2));
|
||||
assert_eq!(blocked_count_text(iface.blocked_ips), Some("2 IPs".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_count_text_omits_empty_counts_and_pluralizes() {
|
||||
assert_eq!(blocked_count_text(None), None);
|
||||
assert_eq!(blocked_count_text(Some(0)), None);
|
||||
assert_eq!(blocked_count_text(Some(1)), Some("1 IP".into()));
|
||||
assert_eq!(blocked_count_text(Some(2)), Some("2 IPs".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_display_names_match_python_138_table() {
|
||||
assert_eq!(mode_display_name("Full"), "Full");
|
||||
assert_eq!(mode_display_name("PointToPoint"), "Point-to-Point");
|
||||
assert_eq!(mode_display_name("AccessPoint"), "Access Point");
|
||||
assert_eq!(mode_display_name("Roaming"), "Roaming");
|
||||
assert_eq!(mode_display_name("Boundary"), "Boundary");
|
||||
assert_eq!(mode_display_name("Gateway"), "Gateway");
|
||||
assert_eq!(mode_display_name("Internal"), "Internal");
|
||||
// Python rnstatus.py:427 falls back to "Full" for unknown modes.
|
||||
assert_eq!(mode_display_name("Bogus"), "Full");
|
||||
|
||||
assert_eq!(remote_mode_display_name(0x01), "Full");
|
||||
assert_eq!(remote_mode_display_name(0x02), "Point-to-Point");
|
||||
assert_eq!(remote_mode_display_name(0x03), "Access Point");
|
||||
assert_eq!(remote_mode_display_name(0x04), "Roaming");
|
||||
assert_eq!(remote_mode_display_name(0x05), "Boundary");
|
||||
assert_eq!(remote_mode_display_name(0x06), "Gateway");
|
||||
assert_eq!(remote_mode_display_name(0x07), "Internal");
|
||||
assert_eq!(remote_mode_display_name(0x08), "Full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_sleep_compensates_render_time_with_floor() {
|
||||
// Python rnstatus.py:742-744: max(interval - elapsed, 0.2).
|
||||
assert_eq!(
|
||||
monitor_sleep(1.0, Duration::from_millis(250)),
|
||||
Duration::from_secs_f64(0.75)
|
||||
);
|
||||
assert_eq!(
|
||||
monitor_sleep(1.0, Duration::from_secs(5)),
|
||||
Duration::from_secs_f64(0.2)
|
||||
);
|
||||
assert_eq!(
|
||||
monitor_sleep(0.05, Duration::ZERO),
|
||||
Duration::from_secs_f64(0.2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_interval_must_be_finite_positive() {
|
||||
let mut args = test_args();
|
||||
args.monitor_interval = 0.0;
|
||||
assert!(validate_args(&args).is_err());
|
||||
args.monitor_interval = f64::INFINITY;
|
||||
assert!(validate_args(&args).is_err());
|
||||
args.monitor_interval = f64::NAN;
|
||||
assert!(validate_args(&args).is_err());
|
||||
args.monitor_interval = 0.5;
|
||||
assert!(validate_args(&args).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user